Skip to content

Documentation from Jutul.jl ​

JutulDarcy.jl builds upon Jutul.jl, which takes care of the heavy lifting in terms of meshes, discretizations and solvers. You can use JutulDarcy.jl without knowing the inner workings of Jutul.jl, but if you want to dive under the hood the Jutul.jl manual and Jutul.jl docstrings may be useful.

We include the docstrings here for your convenience:

Jutul.AMGPreconditioner Type
julia
AMGPreconditioner(method = :hmis; kwargs...)

Jutul preconditioner wrapper for the backend-portable algebraic multigrid implementation in the internal KAPreconditioners module. The default uses HMIS coarsening with an ILU(0) smoother. The supported compatibility methods are :hmis, :aggregation, and :ruge_stuben. They default to Extended+i, piecewise-constant, and classical interpolation, respectively.

The other options of the AMG preconditioner correspond to the fields of AMGOptions and control various aspects of the multigrid hierarchy, such as the coarsening strategy, interpolation method, smoother configuration, and cycle type. These are not a public API and are subject to change without notice or major version bump.

aggressive_levels defaults to zero. A positive value applies a HYPRE-style second coarsening pass on that many levels, starting with the finest. RS/HMIS use two-stage Extended+i interpolation on those levels, composing fine-to-first coarse interpolation with partial interpolation to the final coarse set.

theta defaults to 0.25 for :ruge_stuben and 0.5 for :hmis. second_pass overrides the classical RS second pass when the method is Ruge-Stuben. The shared strength_type can be :signed_fallback (default), :signed, or :absolute. aggressive_num_paths (default 1) controls the second strength graph for RS/HMIS. aggressive_interpolation accepts an TwoStageExtendedIInterpolation(...) configuration with independent factor and product truncation and row limits. Explicit ExtendedIInterpolation(...) selects the legacy distance-two path. See AMGOptions for these settings.

With reuse=:partial_operators or :partial_sparsity, n_levels_partial_keep controls how many leading levels retain their symbolic structure (default 3). n_partial_keep can shorten that prefix at the first level whose matrix size is below the specified value. Its default of -1 disables the size limit. The remaining levels rebuild their symbolic data on each full update.

source
Jutul.AbstractGlobalObjective Type

Abstract type for objective as a global objective function on the form:

julia
F(model, state0, states, step_infos, forces, input_data)

Note that if substeps are enabled by setting output_substates=true in the simulator setup, the length of forces and states will be dynamic and of equal length to step_infos. If you want to recover the state at a specific step, you can reason about :step field of the corresponding entry in the step_infos array.

source
Jutul.AbstractJutulObjective Type

Abstract type for Jutul objectives.

source
Jutul.AbstractSumObjective Type

Abstract type for objective as a sum of function values on the form:

julia
F(model, state, dt, step_info, forces)

evaluated for each step. This means that the objective is a sum of all of these values. If you want to only depend on a single step, you can look up the the step_info[:step] information to verify that you are operating on the correct step.

source
Jutul.AbstractTerminationCriterion Type

Abstract type for termination criteria for steady-state time-stepping simulations.

Subtypes should implement the method

julia
timestepping_is_done(C::AbstractTerminationCriterion, simulator, states, substates, reports, solve_recorder)

that returns a Bool indicating whether the time-stepping should terminate.

source
Jutul.BlockJacobianPositions Type

Logical alignment matrix storing only the first scalar position of each block.

source
Jutul.BlockMajorLayout Type

Same as EntityMajorLayout, but the system is a sparse matrix where each entry is a small dense matrix.

For a test system with primary variables P, S and equations E1, E2 and two cells this will give a diagonal of length 2: [(∂E1/∂p)₁ (∂E1/∂S)₁ ; (∂E2/∂p)₁ (∂E2/∂S)₁] [(∂E1/∂p)₂ (∂E1/∂S)₂ ; (∂E2/∂p)₂ (∂E2/∂S)₂]

source
Jutul.BoundaryFaces Type

Entity for faces on the boundary (faces that are only connected to a single Cells)

source
Jutul.CartesianMesh Type
julia
CartesianMesh(dims, [Δ, [origin]])

Create a Cartesian mesh with dimensions specified by the Tuple dims.

Arguments

  • dims::Tuple: Number of grid cells in each direction. For example, (nx, ny) will give a 2D grids with nx cells in the x-direction.

  • Δ::Tuple=Tuple(ones(length(dims))): Equal length to dims. First option: A

Tuple of scalars where each entry is the length of each cell in that direction. For example, specifying (Δx, Δy) for a uniform grid with each grid cell having area ofΔx*Δy. Second option: ATuple` of vectors where each entry contains the cell sizes in the direction.

  • origin=zeros(length(dims)): The origin of the first corner in the grid.

Examples

Generate a uniform 3D mesh that discretizes a domain of 2 by 3 by 5 units with 3 by 5 by 2 cells:

julia
julia> CartesianMesh((3, 5, 2), (2.0, 3.0, 5.0))
CartesianMesh (3D) with 3x5x2=30 cells

Generate a non-uniform 2D mesh:

julia
julia> CartesianMesh((2, 3), ([1.0, 2.0], [0.1, 3.0, 2.5]))
CartesianMesh (2D) with 2x3x1=6 cells
source
Jutul.Cells Type

Entity for Cells (closed volumes with averaged properties for a finite-volume solver)

source
Jutul.CoarseMesh Method
julia
CoarseMesh(G::JutulMesh, p)

Construct a coarse mesh from a given JutulMesh that can be converted to an UnstructuredMesh instance. The second argument p should be a partition Vector with one entry per cell in the original grid that assigns that cell to a coarse block. Should be one-indexed and the numbering should be sequential and contain at least one fine cell for each coarse index. This is tested by the function.

source
Jutul.CompactAutoDiffCache Type

Cache that holds an AD vector/matrix together with their positions.

source
Jutul.DataDomain Method
julia
DataDomain(domain::JutulDomain; property1 = p1, property2 = p2, ...)

A wrapper around a domain that allows for storing of entity-associated data.

Example:

julia
# Grid with 6 cells and 7 interior faces
g = CartesianMesh((2, 3))
d = DataDomain(g)
d[:cell_vec] = rand(6) #ok, same as:
d[:cell_vec, Cells()] = rand(6) #ok
d[:cell_vec, Faces()] = rand(6) #not ok!
d[:face_vec, Faces()] = rand(7) #ok!
# Can also add general arrays if last dimension == entity dimension
d[:cell_vec, Cells()] = rand(10, 3, 6) #ok
# Can add general data too, but needs to be specified
d[:not_on_face_or_cell, nothing] = rand(3) # also ok
source
Jutul.DefaultContext Type

Default CPU context. See secondary_scheme for secondary-variable scheduling.

source
Jutul.DeviceExecutionMode Type
julia
DeviceExecutionMode

Execution policy for a submodel in a backend-resident MultiModel.

  • SolveFullyOnDevice: variables, equations, assembly and the linear system reside on the device.

  • AssembleOnDevice: variables and equations are evaluated on the host, then synchronized to preallocated device storage for linear-system assembly. Cross terms with another AssembleOnDevice model are evaluated on the host and copied to the device. Cross terms with a SolveFullyOnDevice model are evaluated on the device after synchronizing the host model's state.

  • NothingOnDevice: variables, equations, assembly and the linear system remain on the host.

source
Jutul.DiscretizedDomain Type
julia
DiscretizedDomain(domain, disc = nothing)

A type for a discretized domain of some other domain or mesh. May contain one or more discretizations as-needed to write equations.

source
Jutul.EndTimeTerminationCriterion Type
julia
EndTimeTerminationCriterion(end_time)

A termination criterion that stops time-stepping when the global time reaches end_time.

source
Jutul.EntityCounter Type

Immutable entity-count lookup used by backend-adapted domains.

source
Jutul.EntityMajorLayout Type

Equations are grouped by entity, listing all equations and derivatives for entity 1 before proceeding to entity 2 etc.

For a test system with primary variables P, S and equations E1, E2 and two cells this will give the following ordering on the diagonal: (∂E1/∂p)₁, (∂E2/∂S)₁, (∂E1/∂p)₂, (∂E2/∂S)₂

source
Jutul.EquationMajorLayout Type

Equations are stored sequentially in rows, derivatives of same type in columns:

For a test system with primary variables P, S and equations E1, E2 and two cells this will give the following ordering on the diagonal: (∂E1/∂p)₁, (∂E1/∂p)₂, (∂E2/∂S)₁, (∂E2/∂S)₂

source
Jutul.EquationSet Type

Set of a variable where equations are defined

source
Jutul.FaceMap Type

Struct that contains mappings for a set of faces that are made up of nodes and are part of cells.

source
Jutul.Faces Type

Entity for Faces (intersection between pairs of Cells)

source
Jutul.FastAssemblyData Method
julia
FastAssemblyData(mesh::UnstructuredMesh)

Set up data structures for fast assembly of of discretizations. This includes geometric information such as cell volumes, face areas, and normals, as well as connectivity information such as which faces belong to which cells and which nodes belong to which faces. The data is stored in a way that is optimized for fast access with statically sized vectors for vectors and points.

source
Jutul.FlowDiscretization Type

Discretization of kgradp + upwind

source
Jutul.FractionVariables Type

Abstract type for fraction variables (vector variables that sum up to unity over each entity).

By default, these are limited to the [0, 1] range through maximum_value and minimum_value default implementations.

source
Jutul.FusedEquationAssemblyStorage Type

Data retained in place of the cell half-face flux cache when TPFA fluxes are evaluated as part of equation assembly.

source
Jutul.GenericKrylov Type
julia
GenericKrylov(solver = :gmres; preconditioner = nothing; <kwarg>)

Solver that wraps Krylov.jl with support for preconditioning.

source
Jutul.GlobalSet Type

The global set of variables

source
Jutul.GroupWisePreconditioner Type

Multi-model preconditioners

source
Jutul.HalfFaces Type

Entity for half-faces (face associated with a single Cells)

source
Jutul.HelperSimulator Method
julia
HelperSimulator(model::M, T = Float64; state0 = setup_state(model), executor::E = Jutul.default_executor()) where {M, E}

Construct a helper simulator that can be used to compute the residuals and/or accumulation terms for a given type T. Useful for coupling Jutul to other solvers and types of automatic differentiation.

source
Jutul.ILUZeroPreconditioner Type

ILU(0) preconditioner on CPU

source
Jutul.ImmutableJutulStorage Type

Immutable storage whose named fields and value types are fully specialized.

source
Jutul.IndirectionMap Type

IndirectionMap(vals::Vector{V}, pos::Vector{Int}) where V

Create a indirection map that encodes a variable length dense vector.

pos is assumed to be a Vector{Int} of length n+1 where n is the number of dense vectors that is encoded. The vals array holds the entries for vector i in the range pos[i]:(pos[i+1]-1) for fast lookup. Indexing into the indirection map with index k will give a view into the values for vector k.

source
Jutul.IndirectionMap Method
julia
imap = IndirectionMap(vec_of_vec::Vector{V}) where V

Create indirection map for a variable length dense vector that is represented as a Vector of Vectors.

source
Jutul.JacobiPreconditioner Type

Damped Jacobi preconditioner on CPU

source
Jutul.JutulAutoDiffCache Type

An AutoDiffCache is a type that holds both a set of AD values and a map into some global Jacobian.

source
Jutul.JutulCase Type
julia
JutulCase(model, dt = [1.0], forces = setup_forces(model); state0 = nothing, parameters = nothing, kwarg...)

Set up a structure that holds the complete specification of a simulation case.

source
Jutul.JutulConfig Type

JutulConfig(name = nothing)

A configuration object that acts like a Dict{Symbol,Any} but contains additional data to limit the valid keys and values to those added by add_option!

source
Jutul.JutulContext Type

Abstract type for the context Jutul should execute in (matrix formats, memory allocation, etc.)

source
Jutul.JutulDiscretization Type
julia
d = disc(i, Cells())

Ask discretization for entry i when discretizing some equation on the chosen entity (e.g. Cells)

source
Jutul.JutulDiscretization Type

Abstract type for a Jutul discretization

source
Jutul.JutulDomain Type

Abstract type for domains where equations can be defined

source
Jutul.JutulEntity Type

Super-type for all entities where JutulVariables can be defined.

source
Jutul.JutulEquation Type

Abstract type for all residual equations

source
Jutul.JutulForce Type

Abstract type for driving forces

source
Jutul.JutulMatrixLayout Type

Abstract type for matrix layouts. A layout determines how primary variables and equations are ordered in a sparse matrix representation. Note that this is different from the matrix format itself as it concerns the ordering itself: For example, if all equations for a single cell come in sequence, or if a single equation is given for all entities before the next equation is written.

Different layouts does not change the solution of the system, but different linear solvers support different layouts.

source
Jutul.JutulMesh Type

A mesh is a type of domain that has been discretized. Abstract subtype.

source
Jutul.JutulStorage Type

Mutable, unspecialized storage backed by JUTUL_OUTPUT_TYPE.

source
Jutul.JutulSystem Type

Abstract type for the physical system to be solved.

source
Jutul.JutulVariables Type

Abstract type for all variables in Jutul.

A variable is associated with a JutulEntity through the associated_entity function. A variable is local to that entity, and cannot depend on other entities. Variables are used by models to define:

  • primary variables: Sometimes referred to as degrees of freedom, primary unknowns or solution variables

  • parameters: Static quantities that impact the solution

  • secondary variables: Can be computed from a combination of other primary and secondary variables and parameters.

source
Jutul.KASmootherPreconditioner Type
julia
KASmootherPreconditioner(config = KAPreconditioners.SPAI0())

Wrap a backend-portable smoother in Jutul's preconditioner lifecycle. A symbol (:spai0, :gauss_seidel, :ilu0, :dilu, or :vendor_ilu) can be supplied instead of a smoother config.

source
Jutul.LUPreconditioner Type

Full LU factorization as preconditioner (intended for smaller subsystems)

source
Jutul.LUSolver Type
julia
LUSolver(; reuse_memory = true, check = true, max_size = 50000)

Direct solver that calls lu directly. Direct solvers are highly accurate, but are costly in terms of memory usage and execution speed for larger systems.

source
Jutul.LimitByFailedTimestepSelector Type
julia
sel = LimitByFailedTimestepSelector(num = 10, factor = 0.9)

Limit the timestep by the shortest of num failed timesteps, reducing the timestep by factor multiplied by the shortest failed timestep. If no time-steps failed during the last num steps, the timestep is not changed.

source
Jutul.MRSTWrapMesh Type
julia
MRSTWrapMesh(G, N = nothing)

Mesh that adapts an exported MRST mesh to the Jutul interface. G is assumed to be read directly from file using MAT.matread. The raw exported grid can be found under the data field.

source
Jutul.MultiModel Type
julia
MultiModel(models)
MultiModel(models, :SomeLabel)

A model variant made up of named, fully realized SimulationModel instances. models should be a NamedTuple or Dict{Symbol, JutulModel}. The group_execution keyword sets one DeviceExecutionMode per submodel, in the same order as models and groups. Within each linear-system group, all submodels must either use NothingOnDevice, or use any combination of AssembleOnDevice and SolveFullyOnDevice.

source
Jutul.NoEntity Type

An entity for something that isn't associated with an entity

source
Jutul.NoTerminationCriterion Type
julia
NoTerminationCriterion()

A termination criterion that never terminates prematurely, leaving all timesteps to be executed.

source
Jutul.Nodes Type

Entity for Nodes (intersection between multiple Faces)

source
Jutul.ParallelCSRContext Type
julia
ParallelCSRContext()
# 5 threads (provided that Julia was started at least --threads=5)
ParalellCSRContext(5)
# Use @threads :static for the threaded loops
ParalellCSRContext(thread_type = :threads_static)
# Use batch threading for the threaded loops
ParalellCSRContext(thread_type = :batch)
# Use serial loops for the threaded loops
ParalellCSRContext(thread_type = :serial)

A context that uses a CSR sparse matrix format together with threads. See secondary_scheme for secondary-variable scheduling.

source
Jutul.SPAI0Preconditioner Type

Sparse Approximate Inverse preconditioner of lowest order – SPAI(0)

source
Jutul.SPU Type

Single-point upwinding.

source
Jutul.ScalarVariable Type

Abstract type for scalar variables (one entry per entity, e.g. pressure or temperature in each cell of a model)

source
Jutul.SimulationModel Method
julia
SimulationModel(domain, system; <kwarg>)

Instantiate a model for a given system discretized on the domain.

source
Jutul.SimulationModel Method
julia
SimulationModel(g::JutulMesh, system; discretization = nothing, kwarg...)

Type that defines a simulation model - everything needed to solve the discrete equations.

The minimal setup requires a JutulMesh that defines topology together with a JutulSystem that imposes physical laws.

source
Jutul.Simulator Method
julia
Simulator(model; <kwarg>)

Set up a simulator object for a model that can be used by simulate!. To avoid manually instantiating the simulator, the non-mutating simulate interface can be used instead.

source
Jutul.SparsityTracingWrapper Method
julia
SparsityTracingWrapper(x::AbstractArray{T, N}) where {T, N}

Create a sparsity tracing wrapper for a numeric array. This wrapped array produces outputs that have the same value as the wrapped type, but contains a SparsityTracing seeded value with seed equal to the column index (if matrix) or linear index (if vector).

source
Jutul.TPFA Type

Two-point flux approximation.

source
Jutul.TwoPointFiniteVolumeGeometry Type
julia
TwoPointFiniteVolumeGeometry(neighbors, areas, volumes, normals, cell_centers, face_centers)

Store two-point geometry information for a given list of neighbors specified as a 2 by n matrix where n is the number of faces such that face i connectes cells N[1, i] and N[2, i].

The two-point finite-volume geometry contains the minimal set of geometry information required to compute standard finite-volume discretizations.

source
Jutul.UnstructuredMesh Method
julia
UnstructuredMesh(g::CartesianMesh)

Convert CartesianMesh instance to unstructured grid. Note that the mesh must be 2D and 3D for a 1-to-1 conversion. 1D meshes are implicitly converted to 2D.

source
Jutul.VariableSet Type

Set of a variable where variables are defined

source
Jutul.VectorVariables Type

Abstract type for vector variables (more than one entry per entity, for example saturations or displacements)

source
Jutul.WrappedGlobalObjective Type
julia
WrappedGlobalObjective(objective)

A global (in time) objective that wraps a function/callable. This type automatically wraps functions/callable structs that are passed to the optimization interface if they have the sum signature (five arguments).

source
Jutul.WrappedSumObjective Type
julia
WrappedSumObjective(objective)

An objective that is a sum of function values, evaluated for each step, defined by a function. This type automatically wraps functions/callable structs that are passed to the optimization interface if they have the sum signature (five arguments).

source
Jutul.absolute_increment_limit Method

Absolute allowable change for variable during a nonlinear update.

source
Jutul.add_option! Function
julia
add_option!(opts::JutulConfig, :my_cool_option, 3, "My option has this brief description")

Add an option to existing JutulConfig structure. Additional currently undocumented keyword arguments can be used to restrict valid types and values.

source
Jutul.align_to_jacobian! Method

Update an equation so that it knows where to store its derivatives in the Jacobian representation.

source
Jutul.align_to_jacobian! Method

Update positions of law's derivatives in global Jacobian

source
Jutul.allocate_array_ad Method
julia
allocate_array_ad(v::AbstractMatrix, ...)

Convert matrix to AD matrix.

source
Jutul.allocate_array_ad Method
julia
allocate_array_ad(v::AbstractVector, ...)

Convert vector to AD vector.

source
Jutul.allocate_array_ad Method
julia
allocate_array_ad(n[, m]; <keyword arguments>)

Allocate vector or matrix as AD with optionally provided context and a specified non-zero on the diagonal.

Arguments

  • n::Integer: number of entries in vector, or number of rows if m is given.

  • m::Integer: number of rows (optional)

Keyword arguments

  • npartials = 1: Number of partials derivatives to allocate for each element

  • diag_pos = nothing: Indices of where to put entities on the diagonal (if any)

Other keyword arguments are passed onto get_ad_entity_scalar.

Examples:

Allocate a vector with a single partial:

julia
julia> allocate_array_ad(2)
2-element Vector{ForwardDiff.Dual{nothing, Float64, 1}}:
 Dual{nothing}(0.0,0.0)
 Dual{nothing}(0.0,0.0)

Allocate a vector with two partials, and set the first to one:

julia
julia> allocate_array_ad(2, diag_pos = 1, npartials = 2)
2-element Vector{ForwardDiff.Dual{nothing, Float64, 2}}:
 Dual{nothing}(0.0,1.0,0.0)
 Dual{nothing}(0.0,1.0,0.0)

Set up a matrix with two partials, where the first column has partials [1, 0] and the second [0, 1]:

julia
julia> allocate_array_ad(2, 2, diag_pos = [1, 2], npartials = 2)
2×2 Matrix{ForwardDiff.Dual{nothing, Float64, 2}}:
 Dual{nothing}(0.0,1.0,0.0)  Dual{nothing}(0.0,1.0,0.0)
 Dual{nothing}(0.0,0.0,1.0)  Dual{nothing}(0.0,0.0,1.0)
source
Jutul.apply! Method

Trivial / identity preconditioner with size for use in subsystems.

source
Jutul.apply_forces! Method

Apply a set of forces to all equations. Equations that don't support a given force will just ignore them, thanks to the power of multiple dispatch.

source
Jutul.apply_forces_to_equation! Method
julia
apply_forces_to_equation!(diag_part, storage, model, eq, eq_s, force, time)

Update an equation with the effect of a force. The default behavior for any force we do not know about is to assume that the force does not impact this particular equation.

source
Jutul.apply_ka_amg! Function

Apply a KernelAbstractions algebraic multigrid hierarchy.

source
Jutul.apply_ka_smoother! Function

Apply a KernelAbstractions smoother.

source
Jutul.as_value Method

Create a mapped array that produces only the values when indexed.

Only useful for AD arrays, otherwise it does nothing.

source
Jutul.associated_entity Method

Return the domain entity the equation is associated with

source
Jutul.associated_entity Method

The entity a variable is associated with, and can hold partial derivatives with respect to.

source
Jutul.backend_copyto! Method
julia
backend_copyto!(destination, source)

Copy compatible simulation storage from host evaluation buffers to backend buffers. Unsupported metadata is deliberately left unchanged by default.

source
Jutul.cartesian_partition Function
julia
cartesian_partition(D::DataDomain, coarse_dims, ptype = :centroids)

Perform Cartesian partition in centroid or IJK space.

Examples

Generate 5x5x5 partition based on points (suitable for unstructured meshes)

julia
mesh = CartesianMesh((50, 50, 1))
p_pts = Jutul.cartesian_partition(domain, (5, 5, 5), :centroids)

Generate 5x5x5 partition based on IJK indices (suitable for logically Cartesian meshes)

julia
mesh = CartesianMesh((50, 50, 1))
p_ijk = Jutul.cartesian_partition(domain, (5, 5, 5), :ijk)
source
Jutul.cell_dims Method
julia
cell_dims(g, pos)::Tuple

Get physical cell dimensions of cell with index pos for grid g.

source
Jutul.cell_index Method
julia
cell_index(g, pos)

Get linear (scalar) index of mesh cell from provided IJK tuple pos.

source
Jutul.cells_inside_bounding_box Method
julia
cells_inside_bounding_box(G::UnstructuredMesh, low_bb, high_bb; algorithm = :box, atol = 0.01)
source
Jutul.check_amgcl_availability Method
julia
check_amgcl_availability(; throw = true)

Check if AMGCLWrap extension is available. If throw=true this wil be an error, otherwise a Boolean indicating if the extension is available will be returned.

source
Jutul.check_lbfgsb_availability Method
julia
check_lbfgsb_availability(; throw = true)

Check if LBFGSB.jl extension is available. If throw=true this wil be an error, otherwise a Boolean indicating if the extension is available will be returned.

source
Jutul.check_plotting_availability Method
julia
check_plotting_availability(; throw = true, interactive = false)

Check if plotting through at least one Makie backend is available in the Julia session (after package has been loaded by for example using GLMakie). The argument throw can be used to control if this function acts as a programmatic check (throw=false) there the return value indicates availability, or if an error message is to be printed telling the user how to get plotting working (throw=true)

An additional check for specifically interactive plots can also be added.

source
Jutul.compress_timesteps Function
julia
compress_timesteps(timesteps, forces = nothing; max_step = Inf)

Compress a set of timesteps and forces to the largest possible steps that still covers the same interval and changes forces at exactly the same points in time, while being limited to a maximum size of max_step.

source
Jutul.compress_timesteps Method
julia
compress_timesteps(case::JutulCase; max_step = Inf)

Compress time steps for a Jutul case. See compress_timesteps for the general case.

source
Jutul.compute_boundary_trans Method
julia
compute_boundary_trans(d::DataDomain, perm)

Compute the boundary half face transmissibilities for perm. The input perm can either be the symbol of some data defined on Cells(), a vector of numbers for each cell or a matrix with number of columns equal to the number of cells.

source
Jutul.compute_face_trans Method

compute_face_trans(g::DataDomain, perm)

Compute face trans for the interior faces. The input perm can either be the symbol of some data defined on Cells(), a vector of numbers for each cell or a matrix with number of columns equal to the number of cells.

source
Jutul.compute_half_face_trans Method
julia
compute_half_face_trans(g::DataDomain, perm)

Compute half-face trans for the interior faces. The input perm can either be the symbol of some data defined on Cells(), a vector of numbers for each cell or a matrix with number of columns equal to the number of cells.

source
Jutul.convergence_criterion Method
julia
convergence_criterion(model, storage, eq, eq_s, r; dt = 1)

Get the convergence criterion values for a given equation. Can be checked against the corresponding tolerances.

Arguments

  • model: model that generated the current equation.

  • storage: global simulator storage.

  • eq::JutulEquation: equation implementation currently being checked

  • eq_s: storage for eq where values are contained.

  • r: the local residual part corresponding to this model, as a matrix with column index equaling entity index

source
Jutul.convert_from_si Method
julia
convert_from_si(value, unit_name::Union{Symbol, String})

Convert value from SI representation to the unit in unit_symbol.

Examples

julia
julia> convert_from_si(3600.0, :hour) # Get 3600 s represented as hours
1.0
source
Jutul.convert_state_ad Function

Convert a state containing variables as arrays of doubles to a state where those arrays contain the same value as Dual types. The dual type is currently taken from ForwardDiff.

source
Jutul.convert_to_si Function
julia
convert_to_si(value, unit_name::String)

Convert value to SI representation from value in the unit given by unit_symbol.

Available units

You can get a list of all available units via Jutul.available_units(). The values in Jutul itself are:

A, BTU, British thermal unit, Da, F, Gal, J, K, Kelvin, L, N, Pa, R, Rankine, Standard barrel, W, amp, ampere, atm, atmosphere, bar, btu, dalton, darcy, day, dyn, dyne, farad, feet, ft, g, gal, gallon_us, gram, hour, in, inch, joule, kelvin, kg, kilogram, l, lb, lbf, liter, litre, m, meter, minute, mol, newton, pascal, poise, pound, pound-force, psi, rankine, s, second, site, stb, tonne, usgal, watt, year.

In addition units can be prefixed with standard SI prefixes. Available prefixes are:

quetta, ronna, yotta, zetta, exa, peta, tera, giga, mega, kilo, hecto, deca, deci, centi, milli, micro, nano, pico, femto, atto, zepto, yocto, ronto, quecto.

This utility can also handle composite units, e.g. "kilometer/hour" or "meter/second^2". Note that relative temperature units (Celsius and Fahrenheit) must be converted to absolute units (Kelvin or Rankine) before being used in composite units.

Examples

julia
julia> convert_to_si(1.0, :hour) # Get 1 hour represented as seconds
3600.0
julia> convert_to_si(5.0, "kilometer/hour") # Get 5 kilometers per hour represented as seconds
1.3888888888888888
julia> convert_to_si(1.0, "milligram") # Get 1 milligram represented as kilograms
1.0e-6
source
Jutul.coord_offset Method

Lower corner for one dimension, without any transforms applied

source
Jutul.data_domain_to_parameters_gradient Method
julia
data_domain_to_parameters_gradient(model, parameter_gradient; dp_dd = missing, config = nothing)

Make a data_domain copy that contains the gradient of some objective with respect to the fields in the data_domain, assuming that the parameters were initialized directly from the data_domain via (setup_parameters)[@ref].

source
Jutul.declare_pattern Method

Give out source, target arrays of equal length for a given equation attached to the given model.

source
Jutul.declare_sparsity Function

Give out I, J arrays of equal length for a given equation attached to the given model.

source
Jutul.degrees_of_freedom_per_entity Method

Number of independent primary variables / degrees of freedom per computational entity.

source
Jutul.descalarize_primary_variable! Function
julia
descalarize_primary_variable!(dest_array, model, V, var::Jutul.ScalarVariable, index)

Descalarize a primary variable, overwriting dest_array at entity index. The AD status of entries in dest_array will be retained.

source
Jutul.descalarize_primary_variables! Function
julia
descalarize_primary_variables!(state, model, V, pvars::NamedTuple = (; pairs(model.primary_variables)...), ind = eachindex(V))

Replace values in state by the scalarized values found in V.

source
Jutul.dim Method
julia
dim(g)::Integer

Get the dimension of a mesh.

source
Jutul.evaluate_all_secondary_variables Function
julia
evaluate_all_secondary_variables(model, state, parameters = setup_parameters(x))

Convenience function to get a state with all secondary variables evaluated given a model and a state (not 100% necessarily efficiently).

source
Jutul.evaluation_state Method
julia
state = evaluation_state(storage)

Get the evaluation state (at the end of the current timestep) from the simulator storage.

source
Jutul.evaluation_state Method
julia
state = evaluation_state(s::JutulSimulator)

Get the state from a simulator for use during equation assembly.

source
Jutul.evaluation_state0 Method
julia
state = evaluation_state0(storage)

Get the evaluation state at the previous timestep from the simulator storage.

source
Jutul.evaluation_state0 Method
julia
state = evaluation_state(s::JutulSimulator)

Get the state at the previous step from a simulator for use during equation assembly.

source
Jutul.expand_to_ministeps Method
julia
substates, dt, report_index = expand_to_ministeps(states, reports)

Get states and timesteps at the finest stored resolution. Output lengths depend on if output_substates option to simulator was enabled.

source
Jutul.expand_to_ministeps Method
julia
substates, dt, report_index = expand_to_ministeps(result::SimResult)

Get states and timesteps at the finest stored resolution. Output lengths depend on if output_substates option to simulator was enabled.

source
Jutul.export_mesh_vtu Function
julia
export_mesh_vtu(mesh, filename; point_data = NamedTuple(), cell_data = NamedTuple())

Export a Jutul UnstructuredMesh to VTK unstructured format (.vtu). Requires the WriteVTK.jl package to be loaded.

Examples

julia
using WriteVTK
export_mesh_vtu(mesh, "output.vtu")
export_mesh_vtu(mesh, "output.vtu"; cell_data = (pressure = p,))
source
Jutul.extra_debug_output! Method
julia
extra_debug_output!(report, storage, model, config, iteration, dt)

Add extra debug output to report during a nonlinear iteration.

source
Jutul.extract_submesh Method
julia
extract_submesh(g::UnstructuredMesh, cells)

Extract a subgrid for a given mesh and a iterable of cells to keep.

source
Jutul.extrude_mesh Method
julia
extrude_mesh(m2d::UnstructuredMesh, nlayers)
extrude_mesh(m2d::UnstructuredMesh, [1, 2, 5, 10])

Extrude a 2D mesh into a 3D mesh by adding layers of cells in the z-direction. The number of layers can be specified as an integer or as an array of depths. The depths must be in increasing order.

source
Jutul.face_area_vector Method
julia
face_area_vector(node_points, nodes, center)

Area-weighted normal of a face, oriented by the node ordering (consistent with the normals used in segment_face_intersections!).

source
Jutul.face_average Method
julia
face_average(F, tpfa)

Compute the arithmetic average of F(left) and F(right) across a face.

source
Jutul.factorize_linear_system Method

Create a factorization for a linear-system block.

source
Jutul.find_enclosing_cell Method
julia
find_enclosing_cell(G::UnstructuredMesh{D}, pt::SVector{D, T},
    normals::AbstractVector{SVector{D, T}},
    face_centroids::AbstractVector{SVector{D, T}},
    boundary_normals::AbstractVector{SVector{D, T}},
    boundary_centroids::AbstractVector{SVector{D, T}},
    cells = 1:number_of_cells(G)
) where {D, T}

Find enclosing cell of a point. This can be a bit expensive for larger meshes. Recommended to use the more high level find_enclosing_cells instead.

source
Jutul.find_enclosing_cells Method
julia
find_enclosing_cells(G, traj; geometry = tpfv_geometry(G), extra_out = false)

Find the cell indices of cells in the mesh G that are intersected by a given piecewise linear trajectory traj. traj can be either a matrix with equal number of columns as dimensions in G (i.e. three columns for 3D) or a Vector of SVector instances with the same length.

The cells are returned in the order they are first visited when traversing the trajectory from the first to the last point.

The search is done by computing the intersections between each segment of the trajectory and the faces of the mesh. The crossing direction at each face determines which cell the trajectory enters, so that each part of the trajectory between two consecutive face intersections can be assigned to a single cell. A uniform background grid of buckets is used to limit the number of faces that must be checked for each segment.

The optional argument geometry is used to define the centroids and normals used in the calculations. You can precompute this if you need to perform many searches.

If extra_out = true, the function returns (cells, extra) where extra is a Dict with the following per-cell entries (ordered as cells):

  • :lengths: Length of the trajectory inside the cell.

  • :direction: Mean direction of the trajectory inside the cell, scaled so that direction .* lengths is the vector sum of the subsegments inside the cell.

  • :normed_direction: The vector sum of the subsegments divided by the dimensions of the cell.

  • :centroids: Length-weighted centroid of the subsegments inside the cell.

use_boundary is by default set to false. If set to true, the boundary normals from the geometry are used to determine if the trajectory enters or exits the mesh at a boundary face. This requires that the boundary normals are oriented outwards, which is currently not the case for all meshes from downstream packages. Otherwise, the vector from the cell centroid to the boundary face centroid is used.

atol is the tolerance used when checking if faces are inside the bounding box of the trajectory.

cells can be used to limit the search to a subset of cells in the mesh. By default all cells are used. Faces between a cell in the subset and a cell outside it are treated as boundary faces.

The keyword arguments n and limit_box are retained for backwards compatibility and have no effect.

source
Jutul.full_cell Method

Inner cell to local cell (full set)

source
Jutul.get_1d_interpolator Method
julia
get_1d_interpolator(xs, ys; <keyword arguments>)

Get a 1D interpolator F(x) ≈ y for a table xs, ys that by default does constant extrapolation

Arguments

  • xs: sorted list of parameter points.

  • ys: list of function values with equal length to xs

  • method=LinearInterpolant: constructor for the interpolation. Defaults to LinearInterpolant which does simple linear interpolation.

  • cap_endpoints = true: Add values so that the endpoints are capped (constant extrapolation). Otherwise, the extrapolation will match the method.

  • cap_start = cap_endpoints: Fine-grained version of cap_endpoints for the start of the interval only (extrapolation for x < xs[1])

  • cap_end = cap_endpoints:Fine-grained version of cap_endpoints for the end of the interval only (extrapolation for x > xs[end])

Additional keyword arguments are passed onto the interpolator constructor.

source
Jutul.get_2d_interpolator Method
julia
get_2d_interpolator(xs, ys, fs; method = BilinearInterpolant, cap_endpoints = true)

For xs of length nx and ys of length ny generate a 2D interpolation for values given as a nx by ny matrix. By default cap_endpoints=true, and constant extrapolation is used. Fine-grined control over extrapolation can be achieved by setting the keywords arguments cap_x = (cap_low_x, cap_high_x) and analogously for cap_y.

source
Jutul.get_ad_entity_scalar Method
julia
get_ad_entity_scalar(v::Real, npartials, diag_pos = nothing; <keyword_arguments>)

Get scalar with partial derivatives as AD instance.

Arguments

  • v::Real: Value of AD variable.

  • npartials: Number of partial derivatives each AD instance holds.

  • diag_pos = nothing: Position(s) of where to set 1 as the partial derivative instead of zero.

Keyword arguments

  • tag = nothing: Tag for AD instance. Two AD values of the different tag cannot interoperate to avoid perturbation confusion (see ForwardDiff documentation).
source
Jutul.get_dependencies Method

Get dependencies of variable when viewed as a secondary variable. Normally autogenerated with @jutul_secondary

source
Jutul.get_diagonal_entries Method
julia
get_diagonal_entries(eq::JutulEquation, eq_s)

Get the diagonal entries of a cache, i.e. the entries where entity type and index equals that of the governing equation.

Note: Be very careful about modifications to this array, as this is a view into the internal AD buffers and it is very easy to create inconsistent Jacobians.

source
Jutul.get_entity_tag Method
julia
get_entity_tag(basetag, entity)

Combine a base tag (which can be nothing) with a entity to get a tag that captures base tag + entity tag for use with AD initialization.

source
Jutul.get_entries Method

Get entries of autodiff cache. Entries are AD vectors that hold values and derivatives.

source
Jutul.get_entries Method

Get the entries of the main autodiff cache for an equation.

Note: This only gets the .equation field's entries.

source
Jutul.get_mesh_entity_tag Method
julia
get_mesh_entity_tag(met::JutulMesh, entity::JutulEntity, tag_group::Symbol, tag_value = missing; throw = true)

Get the indices tagged for entity in group tag_group, optionally for the specific tag_value. If ismissing(tag_value), the Dict containing the tag group will be returned.

source
Jutul.get_parameters Method
julia
get_parameters(model::SimulationModel)

Get the parameter definitions (as OrderedDict) for a given model.

Parameters are defined as static values in a forward simulation that combine with the primary variables to compute secondary variables and model equations.

source
Jutul.get_primary_variable_ordered_entities Method
julia
get_primary_variable_ordered_entities(model::SimulationModel)

Get only the entities where primary variables are present, sorted by their order in the primary variables.

source
Jutul.get_primary_variables Method
julia
get_primary_variables(model::SimulationModel)

Get the primary variable definitions (as OrderedDict) for a given model.

Primary variables are sometimes referred to as solution variables or primary unknowns. The set of primary variables completely determines the state of the system together with the parameters.

source
Jutul.get_secondary_variables Method
julia
get_secondary_variables(model::SimulationModel)

Get the secondary variable definitions (as OrderedDict) for a given model.

Secondary variables are variables that can be computed from the primary variables together with the parameters.

source
Jutul.get_sparse_arguments Method
julia
get_sparse_arguments(storage, model)

Get the [SparsePattern]@ref for the Jacobian matrix of a given simulator storage and corresponding model.

source
Jutul.get_tstr Function
julia
get_tstr(dT, lim = 3)

Get formatted time string of dT given in seconds, limited to lim number of units.

source
Jutul.get_variable Method
julia
get_variable(model::SimulationModel, name::Symbol)

Get implementation of variable or parameter with name name for the model.

source
Jutul.get_variables Method
julia
get_variables(model::SimulationModel)

Get all variable definitions (as OrderedDict) for a given model.

This is the union of get_secondary_variables and get_primary_variables.

source
Jutul.get_variables_and_parameters Method
julia
get_variables_and_parameters(model::SimulationModel)

Get all variable definitions (as OrderedDict) for a given model.

This is the union of get_secondary_variables, get_primary_variables and get_parameters.

source
Jutul.global_cell Method

Local cell -> global cell (full set)

source
Jutul.global_face Method

Local face -> global face (full set)

source
Jutul.gradient Method
julia
gradient(X::AbstractMatrix, i, tpfa::TPFA)

Compute the gradient of row i of cell-centered matrix X across a face.

source
Jutul.gradient Method
julia
gradient(X::AbstractVector, tpfa::TPFA)

Compute the gradient of cell-centered values X across a face: X[right] - X[left].

source
Jutul.gradient Method
julia
gradient(F, tpfa::TPFA)

Compute the gradient using a function handle F(cell) across a face.

source
Jutul.initialize_context! Method

Initialize context when setting up a model

source
Jutul.initialize_extra_state_fields! Method
julia
initialize_extra_state_fields!(state, model::JutulModel)

Add model-dependent changing variables that need to be in state, but are never AD variables themselves (for example status flags).

source
Jutul.initialize_storage! Method
julia
initialize_storage!(storage, model::JutulModel; initialize_state0 = true)

Initialize the already allocated storage at the beginning of a simulation. Use this to e.g. set up extra stuff in state0 needed for initializing the simulation loop.

source
Jutul.initialize_variable_value Method

Initializer for the value of non-scalar primary variables

source
Jutul.interior_cell Method

Local cell in full set -> inner cell (or zero)

source
Jutul.interpolation_constant_lookup Function
julia
interpolation_constant_lookup(X, constant_dx = missing)

Generate a lookup table for linear interpolation when dx is evenly spaced.

Note: Setting constant_dx=true can lead to incorrect interpolations if the data is not evenly spaced.

source
Jutul.jutul_message Function
julia
jutul_message("Jutul", "Hello, world!", color = :light_blue)

Print a line with a colored prefix. The prefix is colored with the color argument. The fancy argument controls whether the output is colored or not.

source
Jutul.jutul_output_path Function
julia
pth = jutul_output_path(name = missing; subfolder = "jutul", basedir = missing, create = true)

Get path for output. The final path will be found in /basedir/<subfolder/name. If subfolder=missing, the path will be set to /basedir/name instead. name will be autogenerated if not provided.

Pass the optional input create = false to avoid making the directory. To globally set the default output dir, set ENV["JUTUL_OUTPUT_PATH"]``to your desiredbasedir``.

source
Jutul.jutul_table_format_with_data_hlines Method
julia
jutul_table_format_with_data_hlines(tf::TextTableFormat, hlines)

Return a copy of tf with horizontal lines drawn after the data rows in hlines. PrettyTables v3 carries horizontal_lines_at_data_rows inside the immutable TextTableFormat, so this folds the old v2 body_hlines argument into the format.

source
Jutul.linear_timestep_selection Function
julia
linear_timestep_selection(x, x0, x1, dt0, dt1)

Produce linear estimate of timestep dt for some value x from observed observations. If the observations have the same x or dt values, a simple scaling based on the x1 value is used.

source
Jutul.load_balanced_endpoint Method
julia
load_balanced_endpoint(block_index, nvals, nblocks)

Endpoint for interval block_index that subdivides nvals into nblocks in a load balanced manner. This is done by adding one element to the first set of blocks whenever possible.

source
Jutul.load_balanced_interval Method
julia
load_balanced_interval(b, n, m)

Create UnitRange for block b ∈ [1, m] for interval of total length n, dividing each block into a load balanced interval.

Example

We have the interval 1:10 and want to divide it into 3 blocks. The first block will have 4 elements, the second will have 3, and the third will have 3.

julia


<Badge type="info" class="source-link" text="source"><a href="https://github.com/sintefmath/Jutul.jl/blob/v0.5.6/src/partitioning.jl#L331-L348" target="_blank" rel="noreferrer">source</a></Badge>

</details>

<details class='jldocstring custom-block' open>
<summary><a id='Jutul.local_ad-Tuple{Any, Any, Any}' href='#Jutul.local_ad-Tuple{Any, Any, Any}'><span class="jlbinding">Jutul.local_ad</span></a> <Badge type="info" class="jlObjectType jlMethod" text="Method" /></summary>



```julia
local_ad(state::T, index::I, ad_tag::∂T) where {T, I<:Integer, ∂T}

Create local_ad for state for index I of AD tag of type ad_tag

source
Jutul.local_cell Method

Global cell -> local cell (full set)

source
Jutul.local_face Method

Global face -> local face (full set)

source
Jutul.local_residual_view Method
julia
local_residual_view(r_buf, model, eq, equation_offset)

Get a matrix view of the residual so that, independent of ordering, the column index corresponds to the entity index for the given equation eq starting at equation_offset in the global residual buffer r_buf.

source
Jutul.matrix_row_view Method
julia
matrix_row_view(matrix, row)

Return a row view. Transposes and real adjoints use their parent's column directly, keeping reductions over EquationMajorLayout residuals on the array's original backend.

source
Jutul.maximum_value Method

Upper (inclusive) limit for variable.

source
Jutul.maybe_convert_evaluation_state Method
julia
maybe_convert_evaluation_state(state::ImmutableJutulStorage, context)

Backend hook for constructing a pre-converted, isbits state mirror used as a kernel argument. Return nothing when the ordinary state can be used directly.

source
Jutul.merge_step_report_errors Method
julia
merge_step_report_errors(data; fn = max)

Merge step reports errors of the same type using a pair wise reduction (default: max)

source
Jutul.mesh_from_gmsh Function
julia
G = mesh_from_gmsh(pth)
G = mesh_from_gmsh()
G = mesh_from_gmsh(pth; verbose = true)

Parse a Gmsh file and return a Jutul UnstructuredMesh (in 3D only). Requires the Gmsh.jl package to be loaded. If no path is provided in pth it is assumed that you are managing the Gmsh state manually and it will use the current selected mesh inside Gmsh. Please note that Gmsh is GPL licensed unless you have obtained another type of license from the authors.

source
Jutul.minimum_value Method

Lower (inclusive) limit for variable.

source
Jutul.model_accumulation! Function
julia
model_accumulation!(acc, sim::HelperSimulator, x, dt = 1.0;
    forces = setup_forces(sim.model),
    update_secondary = true,
    kwarg...
)

Compute the accumulation term into Vector acc.

source
Jutul.model_residual! Function
julia
model_residual!(r, sim, x, x0 = missing, dt = 1.0;
    forces = setup_forces(sim.model),
    include_accumulation = true,
    kwarg...
)

Fill in the model residual into Vector r.

source
Jutul.model_residual Method
julia
model_residual(sim::HelperSimulator, x, y = missing; kwarg...)

Out of place version of model_residual!

source
Jutul.number_of_boundary_faces Function
julia
number_of_boundary_faces(g)

Get the number of boundary/exterior faces in a mesh.

source
Jutul.number_of_cells Method
julia
number_of_cells(g)::Integer

Get the number of cells in a mesh.

source
Jutul.number_of_cells Method
julia
number_of_cells(D::Union{DataDomain, DiscretizedDomain})

Get the number of cells in a DataDomain or DiscretizedDomain.

source
Jutul.number_of_degrees_of_freedom Method

Total number of degrees of freedom for a model, over all primary variables and all entities.

source
Jutul.number_of_entities Method

Get the number of entities (e.g. the number of cells) that the equation is defined on.

source
Jutul.number_of_entities Method

Number of entities (e.g. Cells, Faces) a variable is defined on. By default, each primary variable exists on all cells of a discretized domain

source
Jutul.number_of_entities Method

Get number of entities a cache is defined on.

source
Jutul.number_of_entities Method

Number of entities for vector stored in state (just the number of elements)

source
Jutul.number_of_entities Method

Number of entities for matrix stored in state (convention is number of columns)

source
Jutul.number_of_equations Method

Get the total number of equations on the domain of model.

source
Jutul.number_of_equations_per_entity Method
julia
n = number_of_equations_per_entity(model::JutulModel, eq::JutulEquation)

Get the number of equations per entity. For example, mass balance of two components will have two equations per grid cell (= entity)

source
Jutul.number_of_faces Method
julia
number_of_faces(g)::Integer

Get the number of faces in a mesh.

source
Jutul.number_of_faces Method
julia
number_of_faces(D::Union{DataDomain, DiscretizedDomain})

Get the number of faces in a DataDomain or DiscretizedDomain.

source
Jutul.number_of_half_faces Method
julia
number_of_half_faces(D::Union{DataDomain, DiscretizedDomain})

Get the number of half-faces in a DataDomain or DiscretizedDomain.

source
Jutul.number_of_partials_per_entity Method
julia
number_of_partials_per_entity(model::SimulationModel, entity::JutulEntity)

Get the number of local partial derivatives per entity in a model for a given JutulEntity. This is the sum of degrees_of_freedom_per_entity for all primary variables defined on entity.

source
Jutul.number_of_values Function

Total number of values for a model, for a given type of variables over all entities

source
Jutul.numerical_eltype Method
julia
numerical_eltype(x::AbstractArray{T}) where T

Get the numerical eltype (i.e. the inner type of the element type that could potentially be AD)

source
Jutul.numerical_type Method
julia
numerical_type(::T) where T

Get the numerical eltype (i.e. the inner type of the element type that could potentially be AD). This function should be overloaded if you have a custom type that wraps a numeric/potentially AD type.

source
Jutul.optimization_step_info Method
julia
optimization_step_info(step::Int, time::Real, dt; kwarg...)

Optimization step information is normally not set up manually, but the output from this function will be passed to objective functions as step_info. This function is a Dict with the following fields:

Fields

  • :time - The time at the end of the step. To get time at the start of the step, use step_info[:time] - step_info[:dt]

  • :dt - The time step size for this step.

  • :step - The step number, starting at 1. Not that this is the report step, and multiple step_info entries could have the same step if substeps are used.

  • :Nstep - The total number of steps in the simulation.

  • :substep - The substep number, starting at 1. This is used to indicate that multiple steps are taken within a single step.

  • :substep_global - The global substep number, starting at 1 and will not reset between global steps.

  • :Nsubstep_global - The total number of substeps in the simulation.

  • :total_time - The total time of the simulation (i.e. time at the final step and substep)

source
Jutul.parameters_jacobian_wrt_data_domain Method
julia
parameters_jacobian_wrt_data_domain(model; copy = true, config = nothing)

Compute the (sparse) Jacobian of parameters with respect to data_domain values (i.e. floating point values). Optionally, config can be passed to allow vectorize_variables to only include a subset of the parameters.

source
Jutul.partition Function
julia
partition(N::AbstractMatrix, num_coarse, weights = ones(size(N, 2)); partitioner = MetisPartitioner(), groups = nothing, n = maximum(N), group_by_weights = false, buffer_group = true)

Partition based on neighborship (with optional groups kept contigious after partitioning)

source
Jutul.partition_hypergraph Function
julia
partition_hypergraph(g, n::Int, partitioner = MetisPartitioner(); expand = true)

Partition a hypergraph from setup_partitioner_hypergraph using a given partitioner. If the optional expand parameter is set to true the result will be expanded to the full graph (i.e. where groups are not condensed).

source
Jutul.physical_representation Method
julia
physical_representation(x)

Get the physical representation of an object. The physical representation is usually some kind of mesh or domain that represents a physical domain.

source
Jutul.physical_representation Method
julia
physical_representation(x::DataDomain)

Get the underlying physical representation (domain or mesh) that is wrapped.

source
Jutul.physical_representation Method
julia
physical_representation(x::DiscretizedDomain)

Get the underlying physical representation (domain or mesh) that was discretized.

source
Jutul.physical_representation Method
julia
physical_representation(m::SimulationModel)

Get the underlying physical representation for the model (domain or mesh)

source
Jutul.pick_next_timestep Method
julia
pick_next_timestep(sel::IterationTimestepSelector, sim, config, dt_prev, dT, forces, reports, current_reports, step_index, new_step)

Pick the next time-step for IterationTimestepSelector. This function uses the number of iterations from previous timesteps to estimate the relationship between the last and the new time step.

source
Jutul.plot_cell_data! Method
julia
plot_cell_data!(ax, mesh, data; kwarg...)

Mutating version of plot_cell_data that plots into an existing Makie Axis

source
Jutul.plot_cell_data Method
julia
plot_cell_data(mesh::JutulMesh, data::Vector; kwarg...)
plot_cell_data(mesh, data;
    cells = nothing,
    faces = nothing,
    boundaryfaces = nothing
)

Plot cell-wise values (as a vector) on the mesh. Optionally, indices cells, faces or boundaryfaces can be passed to limit the plotting to a specific selection of entities.

source
Jutul.plot_explorer Method
julia
plot_explorer(mesh::JutulMesh)
plot_explorer(d::DataDomain)
plot_explorer(mesh, static::Dict)
plot_explorer(mesh, static::Dict, dynamic::Vector{Dict})
plot_explorer(mesh, static = somedict, dynamic = vectorofdicts)
plot_explorer(mesh, static = somedict, dynamic = vectorofdicts, sens = sensdict)

An interactive 3D plot of a mesh with static and dynamic data that is well suited for interactive exploration and full screen usage. It also has prettier defaults than plot_interactive and is the recommended way to quickly visualize a mesh and its data. This plotter supports static data (via the static argument), dynamic data (via the dynamic argument), and sensitivity data (via the sens argument, plotted using a special colormap).

source
Jutul.plot_interactive Method
julia
plot_interactive(mesh, vector_of_dicts; kwarg...)

Launch an interactive plot of a mesh with the given vector_of_dicts (or just a dict). Each dict can have cell data either as vectors (one value per cell) or matrices (one column per cell). For 3D plots, use axis_view = :default|:xz|:yz|:xy to set the initial camera preset programmatically.

source
Jutul.plot_mesh! Method
julia
plot_mesh!(ax, mesh)

Mutating version of plot_mesh that plots into an existing Makie Axis instance.

source
Jutul.plot_mesh Method
julia
plot_mesh(mesh)
plot_mesh(mesh;
    cells = nothing,
    faces = nothing,
    boundaryfaces = nothing,
    outer = false,
    color = :lightblue,
)

Plot a mesh with uniform colors. Optionally, indices cells, faces or boundaryfaces can be passed to limit the plotting to a specific selection of entities.

source
Jutul.plot_mesh_edges! Method
julia
plot_mesh_edges!(ax, mesh; kwarg...)

Plot the edges of all cells on the exterior of a mesh into existing Makie Axis ax.

source
Jutul.plot_mesh_edges Method
julia
plot_mesh_edges(mesh; kwarg...)

Plot the edges of all cells on the exterior of a mesh.

source
Jutul.prepare_backend_transfer! Method
julia
prepare_backend_transfer!(storage, model)

Application hook for refreshing host-side numeric buffers immediately before they are copied to a backend mirror.

source
Jutul.prepare_host_transfer! Method
julia
prepare_host_transfer!(backend, value)

Backend hook called during simulator transfer for host buffers that will be copied to or from the backend repeatedly. Backends can use this hook to pin or otherwise optimize the host allocation. The default implementation is a no-op.

source
Jutul.prepare_step_storage Method
julia
prepare_step_storage(storage, model, ::Missing)

Initialize storage for prepare_step_handler.

source
Jutul.process_partition Function
julia
p = process_partition(g::JutulMesh, partition; weights = missing)
p = process_partition(N::Vector{Tuple{Int, Int}}, partition; weights = missing)
p = process_partition(N::Matrix{Int}, partition; weights = missing)

Perform processing of partition on mesh or neighborship to make sure that all coarse blocks in the partition are connected. Optionally, weights can be passed that will be used to remove connections with weights that are zero (or within floating point precision of zero).

The resulting partition vector will be a copy and will have additional coarse blocks inserted when blocks were split into two or more components.

julia
g = CartesianMesh((5,))
p = [1, 1, 2, 1, 1] # Block 1 is disconnected!
process_partition(g, p)
source
Jutul.read_results Method

states, reports = read_results(pth; read_states = true, read_reports = true)

Read results from a given output_path provded to simulate or simulator_config.

source
Jutul.refactorize_linear_system! Method

Refresh an existing factorization for a linear-system block.

source
Jutul.relative_increment_limit Method

Relative allowable change for variable during a nonlinear update. A variable with value |x| and relative limit 0.2 cannot change more than |x|*0.2.

source
Jutul.replace_variables! Method
julia
replace_variables!(model, throw = true, varname = vardef, varname2 = vardef2)

Replace one or more variables that already exists in the model (primary, secondary or parameters) with a new definition.

Arguments

  • model: instance where variables is to be replaced

  • varname=vardef::JutulVariables: replace variable with varname by vardef

  • throw=true: throw an error if the named variable definition is not found in primary or secondary, otherwise silently return the model.

source
Jutul.scalarize_primary_variable Method
julia
scalarize_primary_variable(model, source_vec, var::Jutul.ScalarVariable, index)

Scalarize a primary variable. For scalars, this means getting the value itself.

source
Jutul.scalarize_primary_variables Function
julia
scalarize_primary_variables(model, state, pvars = model.primary_variables)

Create a vector where each entry corresponds to a tuple of values that minimally defines the given variables. All variables must belong to the same type of entity. This is checked by this function.

source
Jutul.scalarize_primary_variables! Method
julia
scalarize_primary_variables!(V::Vector{T}, model, state, pvars::NamedTuple) where T

Scalarize into array. See scalarize_primary_variables for more details.

source
Jutul.scalarized_primary_variable_type Function
julia
scalarized_primary_variable_type(model, var::Jutul.ScalarVariable)

Get the type of a scalarized numerical variable (=Float64 for variables that are already represented as scalars)

source
Jutul.secondary_scheme Method
julia
secondary_scheme(model)
secondary_scheme(context::JutulContext)

Select how secondary variables are evaluated. The model method defaults to its context and can be specialized for application models. CPU contexts accept the secondary_scheme keyword with these values:

  • :flat (default): one contiguous batch per worker.

  • :fused: evaluate all variables of each entity on cache-sized tiles, using minbatch(context) entities per tile. Dependencies must be entity-local.

  • :strided: spread up to four batches per worker across the entities to balance spatially uneven property costs.

The non-default schemes use host evaluation; device kernels retain :flat.

source
Jutul.segment_face_intersections! Method
julia
segment_face_intersections!(hits, a, d, node_points, nodes, center)

Find all intersections between the segment a + t*d for t in [0, 1] and the face defined by nodes, and push (t, cosθ) to hits where cosθ is the cosine of the angle between d and the local face normal at the intersection (oriented by the node ordering of the face). In 3D, the face is triangulated as a fan around center, and a segment can intersect a non-planar face more than once. Segments that are parallel to the face are not considered intersecting.

source
Jutul.segment_intersects_box Method
julia
segment_intersects_box(a, d, lo, hi, atol)

Slab test: Check if the segment a + t*d for t in [0, 1] intersects the axis-aligned box [lo - atol, hi + atol].

source
Jutul.set_default_tolerances Method
julia
set_default_tolerances(model)

Set default tolerances for the nonlinear convergence check of the governing equations.

source
Jutul.set_parameters! Method
julia
set_parameters!(model, parname = pardef)

Set a parameter with name varname to the definition vardef (adding if it does not exist)

source
Jutul.set_primary_variables! Method
julia
set_primary_variables!(model, varname = vardef)
set_primary_variables!(model, varname1 = vardef1, varname2 = vardef2)

Set a primary variable with name varname to the definition vardef (adding if it does not exist)

source
Jutul.set_secondary_variables! Method
julia
set_secondary_variables!(model, varname = vardef)
set_secondary_variables!(model, varname1 = vardef1, varname2 = vardef2)

Set a secondary variable with name varname to the definition vardef (adding if it does not exist)

source
Jutul.setup_adjoint_storage Method
julia
setup_adjoint_storage(model; state0 = setup_state(model), parameters = setup_parameters(model))

Set up storage for use with solve_adjoint_sensitivities!.

source
Jutul.setup_cross_term_storage_extra! Method

Application hook for preallocating cross-term-specific storage.

source
Jutul.setup_forces Method
julia
setup_forces(model::JutulModel; force_name = force_value)

Set up forces for a given model. Keyword arguments varies depending on what the model supports.

source
Jutul.setup_ka_amg Function

Set up a KernelAbstractions algebraic multigrid hierarchy.

source
Jutul.setup_ka_smoother Function

Set up a KernelAbstractions smoother.

source
Jutul.setup_parameter_optimization Method
julia
setup_parameter_optimization(model, state0, param, dt, forces, G, opt_cfg = optimization_config(model, param);
    grad_type = :adjoint,
    config = nothing,
    print = 1,
    copy_case = true,
    param_obj = false,
    strict = false,
    kwarg...
)

Set up function handles for optimizing the case defined by the inputs to simulate together with a per-timestep objective function G. The objective function should fit the format described in AbstractGlobalObjective or AbstractSumObjective.

Generally calling either of the functions will mutate the data Dict. The options are:

  • F_o(x): evaluate objective

  • dF_o(dFdx, x): evaluate gradient of objective, mutating dFdx (may trigger evaluation of F_o)

  • F_and_dF(F, dFdx, x): evaluate F and/or dF. If nothing is passed for an entry, the corresponding entry is skipped.

Missing forward ministep states warn by default; set strict = true to reject these inputs when evaluating an adjoint gradient.

source
Jutul.setup_parameters Method
julia
setup_parameters(model::JutulModel; name = value)

Set up a parameter storage for a given model with values for the parameter defined in the model.

Arguments

  • name=value: The name of the parameter together with the value(s) of the parameter.

A scalar (or short vector of the right size for VectorVariables) will be repeated over the entire domain, while a vector (or matrix for VectorVariables) with length (number of columns for VectorVariables) equal to the entity count (for example, number of cells for a cell variable) will be used directly.

source
Jutul.setup_partitioner_hypergraph Method
julia
setup_partitioner_hypergraph(N::Matrix{Int};
    num_nodes::Int = maximum(N),
    num_edges::Int = size(N, 2),
    node_weights::Vector{Int} = ones(Int, num_nodes),
    edge_weights::Vector{Int} = ones(Int, num_edges),
    groups = [Int[]]
)

Set up a hypergraph structure for a given neighborship matrix. N should be a matrix with two rows, with one pair of cells in each column. Optionally node and edge weights can be provided. If a list of groups are provided, these nodes will be accumulated together in the hypergraph.

source
Jutul.setup_state! Function
julia
setup_state!(state, model::JutulModel, init_values::AbstractDict = Dict())

Initialize primary variables and other state fields, given initial values as a Dict

source
Jutul.setup_state Method
julia
setup_state(model::JutulModel, name1 = value1, name2 = value2)

Set up a state for a given model with values for the primary variables defined in the model. Normally all primary variables must be initialized in this way.

Arguments

  • name=value: The name of the primary variable together with the value(s) used to initialize the primary variable.

A scalar (or short vector of the right size for VectorVariables) will be repeated over the entire domain, while a vector (or matrix for VectorVariables) with length (number of columns for VectorVariables) equal to the entity count (for example, number of cells for a cell variable) will be used directly.

Note: You likely want to overload [setup_state!]@ref for a custom model instead of setup_state

source
Jutul.setup_state_and_parameters Method
julia
state, prm = setup_state_and_parameters(model, init)

Simultaneously set up state and parameters from a single init file (typically a Dict containing values that might either be initial values or parameters)

source
Jutul.setup_storage! Method
julia
setup_storage!(storage, model::JutulModel; setup_linearized_system = true,
                                                setup_equations = true,
                                                state0 = setup_state(model),
                                                parameters = setup_parameters(model),
                                                tag = nothing,
                                                state0_ad = false,
                                                state_ad = true,
                                                kwarg...)

Allocate storage for a given model. The storage consists of all dynamic quantities used in the simulation. The default implementation allocates properties, equations and linearized system.

source
Jutul.setup_storage Method
julia
setup_storage(model::JutulModel; kwarg...)

Allocate storage for the model. You should overload setup_storage! if you have a custom definition.

source
Jutul.si_unit Method
julia
si_unit(u::Union{String, Symbol})

Get the multiplicative SI unit conversion factor for a single unit. The return value is given so that x*si_unit(:name) will convert x to the SI representation of the unit with the given name. Composite units are also supported via strings, e.g. si_unit("feet^3/second").

Examples

julia
julia> si_unit(:day) # Get days represented as seconds
86400.0
source
Jutul.si_units Method
julia
u1_val = si_units(u1)
meter = si_units(:meter)
meter, hour = si_units(:meter, :hour)

Get multiplicative SI unit conversion factors for multiple units simultaneously. The return value will be a Tuple of values, one for each input argument. Each input arguments can be either a String a Symbol.

Examples

julia
julia> meter, hour = si_units(:meter, :hour)
(1.0, 3600.0)
source
Jutul.simulate! Method
julia
simulate!(sim::JutulSimulator, timesteps;
    forces = nothing,
    config = nothing,
    initialize = true,
    restart = nothing,
    state0 = nothing,
    parameters = nothing,
    states = Vector{JUTUL_OUTPUT_TYPE}(),
    reports = [],
    kwarg...
)

Non-allocating (or perhaps less allocating) version of simulate!.

Arguments

  • initialize=true: Perform internal updates as if this is the first time

  • states, reports: Pre-allocated output containers. Defaults are fresh empty vectors. Supply your own to retain partial output when simulate! throws mid-loop (e.g. from a post_ministep_hook).

See also simulate for additional supported input arguments.

source
Jutul.simulate Method
julia
simulate(state0, model, timesteps, parameters = setup_parameters(model))
simulate(state0, model, timesteps, info_level = 3)
simulate(state0, model, timesteps; <keyword arguments>)

Simulate a set of timesteps with model for the given initial state0 and optionally specific parameters. Additional keyword arguments are passed onto simulator_config and simulate!. This interface is primarily for convenience, as all storage for the simulator is allocated upon use and discared upon return. If you want to perform multiple simulations with the same model it is advised to instead instantiate Simulator and combine it with simulate!.

Arguments

  • state0::Dict: initial state, typically created using setup_state for the model in use.

  • model::JutulModel: model that describes the discretized system to solve, for example SimulationModel or MultiModel.

  • timesteps: Vector of desired report steps. The simulator will perform time integration until sum(timesteps). You can also provide a single step in place of a vector. is reached, providing outputs at the end of each report step. If a Inf value is provided as any of the time-steps, the simulator will either perform an infinite step (if no max_timestep is provided) or the simulator will perform timestepping forever until the termination criterion is met. If you pass Inf and no termination criterion is provided, the simulator will error.

  • parameters=setup_parameters(model): Optional overrides the default parameters for the model.

  • forces=nothing: Either nothing (for no forces), a single set of forces from setup_forces(model) or a Vector of such forces with equal length to timesteps.

  • restart=nothing: If an integer is provided, the simulation will attempt to restart from that step. Requires that output_path is provided here or in the config.

  • config=simulator_config(model): Configuration object that holds many fine grained settings for output, linear solver, time-steps, outputs etc.

Additional arguments are passed onto simulator_config.

See also simulate!, Simulator, SimulationModel, simulator_config.

source
Jutul.simulate Method
julia
simulate(state0, sim::JutulSimulator, timesteps; parameters = nothing, kwarg...)

Simulate a set of timesteps with simulator for the given initial state0 and optionally specific parameters.

source
Jutul.simulator_config Method
julia
simulator_config(sim; info_level = 3, linear_solver = GenericKrylov())

Set up a simulator configuration object that can be passed onto simulate!.

There are many options available to configure a given simulator. The best way to get an overview of these possible configuration options is to instatiate the config without any arguments and inspecting the resulting table by calling simulator_config(sim) in the REPL.

source
Jutul.solve_adjoint_forces Method
julia
solve_adjoint_forces(case::JutulCase, res::SimResult, G)

Solve the adjoint equations for the forces in case given the simulation result res and the objective function G.

source
Jutul.solve_adjoint_sensitivities! Method
julia
solve_adjoint_sensitivities!(∇G, storage, states, state0, timesteps, G; forces)

Non-allocating version of solve_adjoint_sensitivities.

source
Jutul.solve_adjoint_sensitivities Method
julia
solve_adjoint_sensitivities(model, states, reports_or_timesteps, G; extra_timing = false, state0 = setup_state(model), forces = setup_forces(model), raw_output = false, kwarg...)

Compute sensitivities of model parameter with name target for objective function G.

The objective function is at the moment assumed to be a sum over all states on the form: obj = Σₙ G(model, state, dt_n, n, forces_for_step_n)

Solves the adjoint equations: For model equations F the gradient with respect to parameters p is ∇ₚG = Σₙ (∂Fₙ / ∂p)ᵀ λₙ where n ∈ [1, N]. Given Lagrange multipliers λₙ from the adjoint equations (∂Fₙ / ∂xₙ)ᵀ λₙ = - (∂J / ∂xₙ)ᵀ - (∂Fₙ₊₁ / ∂xₙ)ᵀ λₙ₊₁ where the last term is omitted for step n = N and G is the objective function.

Reports should contain one successful ministep per stored state. Missing ministep states produce a warning by default; set strict = true to throw an ArgumentError instead. For subdivided report steps, simulate with output_substates = true and pass a SimResult to the case overload, or explicitly expand states, timesteps and forces with expand_to_ministeps before calling this method.

source
Jutul.solve_numerical_sensitivities Method
julia
solve_numerical_sensitivities(model, states, reports, G, target;
                                            forces = setup_forces(model),
                                            state0 = setup_state(model),
                                            parameters = setup_parameters(model),
                                            epsilon = 1e-8)

Compute sensitivities of model parameter with name target for objective function G.

This method uses numerical perturbation and is primarily intended for testing of solve_adjoint_sensitivities.

source
Jutul.solve_timestep! Method
julia
solve_timestep!(sim, dT, forces, max_its, config; <keyword arguments>)

Internal function for solving a single time-step with fixed driving forces.

Arguments

  • sim: Simulator instance.

  • dT: time-step to be solved

  • forces: Driving forces for the time-step

  • max_its: Maximum number of steps/Newton iterations.

  • config: Configuration for solver (typically output from simulator_config).

Note: This function is exported for fine-grained simulation workflows. The general simulate interface is both easier to use and performs additional validation.

source
Jutul.subvariable Method
julia
subvariable(var, map)

Get subvariable of Jutul variable

source
Jutul.successful_reports Function
julia
successful_reports(reports; step = length(reports), n = 1)

Get last n successful reports starting at the end of step and reversing backwards until n values have been found. n can be set to Inf to produce all successful reports.

source
Jutul.successful_reports Function
julia
successful_reports(old_reports, current_reports, step_index, n = 1)

Get the n last successful solve reports from all previous reports (old_reports) and the current ministep set. You can optionally provide a function that replaces the default definition of success=r->r[:success].

source
Jutul.synchronize Method

Synchronize backend after allocations.

Some backends may require notification that storage has been allocated.

source
Jutul.synchronize_cross_term_states! Method
julia
synchronize_cross_term_states!(storage, model; state, state0, parameters)

Queue the state required by mixed AssembleOnDevice and SolveFullyOnDevice cross terms. Returns true when a device-to-host copy must finish before evaluating host cross terms.

source
Jutul.synchronize_host_equations! Method
julia
synchronize_host_equations!(storage, model)

Queue host-evaluated equations for backend assembly after host equation updates, forces, and boundary conditions have completed.

source
Jutul.timestepping_is_done Method
julia
timestepping_is_done(C::AbstractTerminationCriterion, simulator, states, substates, reports, solve_recorder)

Check whether time-stepping should terminate according to the criterion C. Subtypes of AbstractTerminationCriterion should implement this method.

The arguements are:

  • simulator: The simulator executing the time-stepping. The simulator holds the current state after a converged time step (can be accessed in the standard output format by get_output_state(simulator))

  • states: The current states of the simulation (up to the current report step)

  • substates: The current substates of the simulation for the current report step. May be missing if output_substates is false.

  • reports: The reports so far in the simulation.

  • solve_recorder: The solve recorder holding information about the current time, etc. You can get the current time with get_current_time(solve_recorder, :global).

source
Jutul.tpfv_geometry Function
julia
tpfv_geometry(g)

Generate two-point finite-volume geometry for a given grid, if supported.

See also TwoPointFiniteVolumeGeometry.

source
Jutul.transfer Method

Transfer v to the representation expected by a given context.

For the defalt context, the transfer function does nothing. For other context such as the CUDA version, it may convert integers and floats to other types (e.g. Float32) and Arrays to CuArrays.

You will likely have to implement some transfer operators for your own types if you want to simulate with a non-default context.

source
Jutul.transfer_cross_term_evaluation! Method
julia
transfer_cross_term_evaluation!(storage, model)

Transfer cross terms evaluated on the host to their preallocated backend storage. The transfer is queued after all cross-term forces have been applied.

source
Jutul.transfer_csr_to_backend Method

Copy a CPU CSR matrix to the backend used by a reference CSR matrix.

source
Jutul.transfer_entities! Method
julia
transfer_entities!(disc::DiscretizedDomain, data::DataDomain)

Add any entities present in data but missing from disc into disc.entities. Entities already present must have matching counts.

source
Jutul.transfer_to_backend Function
julia
transfer_to_backend(simulator, backend; kwargs...)

Transfer an initialized simulator to an execution backend. Backend modules implement this interface for the contexts they support.

source
Jutul.two_point_potential_drop Method

Two-point potential drop with gravity (generic)

source
Jutul.unsafe_reinterpret Method
julia
unsafe_reinterpret(Vt, v, n)

Unsafely reinterpret v as a n length vector of value type Vt

source
Jutul.update_before_step! Methodsource
Jutul.update_before_step_multimodel_backend! Method
julia
update_before_step_multimodel_backend!(storage, model,
    backend_storage, backend_model, submodel, dt, forces, label; kwarg...)

Backend-aware variant of update_before_step_multimodel!. storage and model are the selected evaluation view, while backend_storage and backend_model are the simulator's preallocated backend objects. The default implementation delegates to the ordinary hook.

source
Jutul.update_cross_terms! Method
julia
update_cross_terms!(storage, model, dt;
    targets = submodels_symbols(model),
    sources = submodels_symbols(model), do_sync = true)

Evaluate matching cross terms and synchronize the multimodel backend by default. Pass do_sync=false when the caller will synchronize after launching additional backend work.

source
Jutul.update_equation! Method

Update equation based on currently stored properties

source
Jutul.update_equations! Function
julia
update_equations!(storage, model, dt = nothing)

Update the governing equations using the current set of primary variables, parameters and secondary variables. Does not fill linearized system.

source
Jutul.update_equations_and_apply_forces! Method
julia
update_equations_and_apply_forces!(storage, model, dt, forces;
    time = NaN, do_sync = true)

Update the model equations and apply boundary conditions and forces. Does not fill linearized system. By default the model backend is synchronized after evaluation. Pass do_sync=false when a later evaluation boundary will synchronize it.

source
Jutul.update_ka_amg! Function

Update an existing KernelAbstractions algebraic multigrid hierarchy.

source
Jutul.update_ka_smoother! Function

Update an existing KernelAbstractions smoother.

source
Jutul.update_linearized_system! Function
julia
update_linearized_system!(storage, model::JutulModel; <keyword arguments>)

Update the linearized system with the current set of equations.

source
Jutul.update_linearized_system_equation! Method

Update a linearized system based on the values and derivatives in the equation.

source
Jutul.update_parameter_before_step! Method
julia
update_parameter_before_step!(prm_val, prm, storage, model, dt, forces)

Update parameters before time-step. Used for hysteretic parameters.

source
Jutul.update_secondary_variable! Function

Update a secondary variable. Normally autogenerated with @jutul_secondary

source
Jutul.update_state_dependents! Method
julia
update_state_dependents!(storage, model, dt, forces; time = NaN, update_secondary = true)

Perform updates of everything that depends on the state: A full linearization for the current primary variables.

This includes properties, governing equations and the linearized system itself.

source
Jutul.update_values! Method
julia
update_values!(x, dx)

Replace values (for non-Real types, direct assignment)

source
Jutul.update_values! Method
julia
update_values!(x, dx)

Replace values of x in-place by y, leaving x with the values of y and the partials of x.

source
Jutul.upwind Method
julia
upwind(upw::SPU, X::AbstractArray, q)

Single-point upwinding: index into array X at the upwind cell.

source
Jutul.upwind Method
julia
upwind(upw::SPU, F, q)

Single-point upwinding: evaluate F(cell) at the upwind cell.

source
Jutul.upwind Method
julia
upwind(upw::SPU, m::AbstractArray{<:SCT.Dual}, q)

Adjoint pattern tracking overload: touches both cells so the sparsity tracker sees the full dependency pattern.

source
Jutul.value Method
julia
value(d::Dict)

Call value on all elements of some Dict.

source
Jutul.value Method

Take value of AD.

source
Jutul.values_per_entity Method

Number of values held by a primary variable. Normally this is equal to the number of degrees of freedom, but some special primary variables are most conveniently defined by having N values and N-1 independent variables.

source
Jutul.variable_scale Method

Define a "typical" numerical value for a variable to scale the linear system entries.

source
Jutul.vectorize_variables Function
julia
vectorize_variables(model, state_or_prm, type_or_map = :primary; config = nothing, T = Float64)

Vectorize (flatten) the variables in state_or_prm according to the mapping given by type_or_map. The result is a vector of type T. Optionally, config can be passed to allow for variable exclusion, lumping or scaling.

The vectorized variables are stored in canonical order (i.e., all values for each variable are stored contiguously). For example, a model with variables p, x where p is scalar and x has two components a, b per entity will be stored as

julia
[p_1, p_2, ..., p_N, x_a_1, x_a_1, ..., x_a_N, x_b_1, x_b_2, ..., x_b_N]

where N is the number of entities.

source
Jutul.write_reports_to_mat_format Function
julia
write_reports_to_mat_format(reports::Vector, path = jutul_output_path(); name = "report", config = missing, verbose = false)

Write the reports to MAT files named "report_1", "report_2", ... to the given path.

source
Jutul.@jutul_secondary Macro

Designate the function as updating a secondary variable.

A generic evaluator is then defined, together with a function for getting the dependencies of that function upon the state. This is most easily documented with an example. If we define the following function annotated with the macro when updating the array containing the values of MyVarType realized for some model:

julia
@jutul_secondary function some_fn!(target, var::MyVarType, model, a, b, c, ix)
    for i in ix
        target[i] = a[i] + b[i] / c[i]
    end
end

The purpose of the macro is to translate this into two functions. The first defines for the dependencies of the function with respect to the fields of the state (primary variables, secondary variables and parameters):

julia
function get_dependencies(var::MyVarType, model)
   return (:a, :b, :c)
end

The second function defines a generic version that takes in state, and automatically expands the set of dependencies into getfield calls.

julia
function update_secondary_variable!(array_target, var::MyVarType, model, state, ix)
    some_fn!(array_target, var, model, state.a, state.b, state.c, ix)
end

Note that the input names of arguments 4 to end-1 matter, as these will be fetched from state, exactly as written.

source
Jutul.@si_str Macro
julia
si"kg/meter"

A string macro to convert unit strings to SI conversion factors. Convenience function for si_unit.

Examples

julia
julia> si"day" # Get days represented as seconds
86400.0
julia> si"kilometer/hour" # Get kilometers per hour represented as seconds
0.2777777777777778
julia> si"3.14*kilometer/hour" # Get 3.14 kilometers per hour represented as seconds
0.8722222222222222
julia> si"100gram + 0.1kilogram" # Get 100 grams + 0.1 kilogram represented as kilograms
0.2
source
Jutul.ConvergenceMonitors.ConvergenceMonitorRelaxation Method
julia
ConvergenceMonitorRelaxation(; w_min = 0.1, dw = 0.2, dw_increase = nothing, dw_decrease = nothing, w_max = 1.0)

Relaxation strategy based on convergence monitoring. Requires that the simulation has been configured with a ConvergenceMonitorCuttingCriterion so that the convergence status is available in the reports. See corresponding iplementation of select_nonlinear_relaxation_model below for details.

source
Jutul.ConvergenceMonitors.compute_contraction_factor Method
julia
compute_contraction_factor(r, N)

Compute contraction factor from a number of Newton iterate distances from convergence (defined with a user-prescribed distance metric). For more than two iterates, the contraction factor is estimated using least-squares assuming the iterates follow a geometric series: rₙ = Θⁿr₀. The function also computes the target contraction factor under this assumption assuming N iterations left.

source
Jutul.ConvergenceMonitors.compute_distance Method
julia
compute_distance(report; distance_function = r -> scaled_residual_norm(r), mapping = v -> maximum(v))

Compute distance from convergence using a user-defined distance function, and optionally apply a mapping to the distance. The function returns the distance and the names of equation residual norms used in the distance computation.

source
Jutul.ConvergenceMonitors.flatten_dict Function
julia
flatten_dict(input_dict::Dict, separator::String = ".", trail = [])

Flatten a dict of dicts into a vector of values and a vector of names. The names are on the format "key1<separator>key2<separator>key3" and the values are the corresponding values in the dict.

source
Jutul.ConvergenceMonitors.get_model_residuals Method
julia
get_model_residuals(report)

Get all residual norms for all equations of a model from a nonlinear iteration report, scaled by their respective toelrances. The function returns a dict of dicts with the residual norms for each equation on the form

julia
residuals[equation_type][equation][norm] = res/tol
source
Jutul.ConvergenceMonitors.get_multimodel_residuals Method
julia
get_multimodel_residuals(report)

Get all residual norms for all equations of all models from a nonlinear iteration report, scaled by their respective toelrances. The function returns a dict of dicts with the residual norms for each equation on the form

julia
residuals[model][equation_type][equation][norm] = res/tol
source
Jutul.ConvergenceMonitors.make_report Method
julia
make_report(θ, θ_target, oscillation, status)

Utility for generating a report from the convergence monitor.

source
Jutul.ConvergenceMonitors.nonconverged_equations Method
julia
nonconverged_equations(report)

Compute distance to convergence as non-converged equations, e.g., 1.0 for non-converged and 0.0 for converged. The final distance is typically taken as the sum of the output from this function.

source
Jutul.ConvergenceMonitors.oscillation Function
julia
oscillation(contraction_factors, tol)

Check if the contraction factors are oscillating. The function checks if the contraction factors are oscillating by checking if the last three contraction factors are below a user-defined tolerance defining "slow" convergece. The function returns true if the contraction factors are oscillating, and false otherwise. If less than three contraction factors are provided, the function returns false.

source
Jutul.ConvergenceMonitors.print_convergence_status Method
julia
print_convergence_status(cc::ConvergenceMonitorCuttingCriterion, it, it0)

Utility for printing the status of the convergence monitor.

source
Jutul.ConvergenceMonitors.process_name Method
julia
process_name(name)

Process a names to be suibale as dictionary keys.

source
Jutul.ConvergenceMonitors.reset! Method
julia
reset!(cc::ConvergenceMonitorCuttingCriterion, template, max_iter)

Utility for resetting convergence monitor cutting criterion.

source
Jutul.ConvergenceMonitors.scaled_residual_norm Method
julia
scaled_residual_norm(report)

Compute distance to convergence as the residual norm of the equations scaled by their respective tolerances.

source
Jutul.ConvergenceMonitors.set_convergence_monitor_cutting_criterion! Method
julia
set_convergence_monitor_cutting_criterion!(config; max_nonlinear_iterations = 50, kwargs...)

Utility for setting ConvergenceMonitorCuttingCriterion to the simulator config. The function also adjusts the maximum number of nonlinear iterations (to 50 by default).

source
Jutul.ConvergenceMonitors.set_convergence_monitor_relaxation! Method
julia
set_convergence_monitor_relaxation!(config; max_nonlinear_iterations = 50, convergence_monitor_args = NamedTuple(), relaxation_args...)

Utility for setting ConvergenceMonitorRelaxation to the simulator config. This function also sets the a ConvergenceMonitorCuttingCriterion to the config – see set_convergence_monitor_cutting_criterion!.

source
Jutul.cutting_criterion Method
julia
Jutul.cutting_criterion(cc::ConvergenceMonitorCuttingCriterion, sim, dt, forces, it, max_iter, cfg, e, step_reports, relaxation)

Cutting ctriterion based on monitoring convergence. The function computes the contraction factor from the distance to convergence (in a user-defined metric) between consecutive iterates. The function also computes the target contraction factor under the assumption that the iterates follow a geometric series, and checks if the iterates are oscillating. Based on this, the iterate is classified as "good", "ok", or "bad", and a counter for number of violations is updated accordingly (+1 for "bad", -1 for "good"). The timestep is aborted if the number of violations exceeds a user-defined limit.

source
Jutul.select_nonlinear_relaxation_model Method
julia
Jutul.select_nonlinear_relaxation_model(model, rel_type::ConvergenceMonitorRelaxation, reports, ω)

Relaxation strategy based on convergence monitoring. The relaxation factor is decreased if the convergence status is "bad", and increased if the status is "good", determined by contraction factors computed from distance to convergence (in a user-defined metric) between consecutive iterates. These are computed during the cutting criterion check and stored in the reports.

source
Jutul.CutCellMeshes.PlaneCut Type
julia
PlaneCut(point, normal)

Define a planar cutting constraint by a point on the plane and a unit normal vector. The normal defines the positive half-space.

source
Jutul.CutCellMeshes.PolygonalSurface Type
julia
PolygonalSurface(polygons, normals)

Define a cutting surface made up of multiple planar polygons. Each polygon is a vector of 3D points (SVector{3}). If normals is omitted, they are computed from the polygon vertices.

source
Jutul.CutCellMeshes._add_face_or_bnd! Method
julia
_add_face_or_bnd!(nodes, left, right, old_face, add_int!, add_bnd!)

Helper: if both left and right are valid (non-zero) cell indices, add an interior face; if only one is valid, add a boundary face on that cell; if neither is valid, skip.

source
Jutul.CutCellMeshes._approx_cell_centroid Method
julia
_approx_cell_centroid(mesh, cell)

Compute an approximate cell centroid by averaging the centroids of all its faces (interior + boundary).

source
Jutul.CutCellMeshes._build_tangent_basis Method
julia
_build_tangent_basis(normal)

Build an orthonormal (u, v) basis in the plane perpendicular to normal.

source
Jutul.CutCellMeshes._cell_centroid_from_nodes Method
julia
_cell_centroid_from_nodes(mesh, cell)

Approximate centroid of a cell from all its unique node coordinates.

source
Jutul.CutCellMeshes._cell_centroid_from_nodes_b Method
julia
_cell_centroid_from_nodes_b(mesh_b, cell_b, combined_nodes, node_map_b)

Approximate centroid of a cell from mesh_b using combined node coordinates.

source
Jutul.CutCellMeshes._chain_boundary_edges Method
julia
_chain_boundary_edges(edges) -> Vector{Int}

Given a set of directed/undirected edges, chain them into a single polygon boundary. Returns an ordered list of node indices.

source
Jutul.CutCellMeshes._compute_residual_polygons Method
julia
_compute_residual_polygons(face_poly, carved_polys, area_tol)

Compute the residual boundary polygon(s) after subtracting intersection regions from a face polygon. For each carved polygon, clips the remaining pieces against the complement of the carved polygon. Returns a list of residual convex polygons, or empty if the face is fully consumed.

source
Jutul.CutCellMeshes._deduplicate_face_nodes Method
julia
_deduplicate_face_nodes(nodes)

Remove consecutive duplicate node indices from a face node list, including wrap-around (last == first). Returns a new vector. Faces with fewer than 3 unique nodes after deduplication are degenerate.

source
Jutul.CutCellMeshes._ensure_ccw_2d Method
julia
_ensure_ccw_2d(poly)

Ensure a 2D polygon has counter-clockwise winding order. Uses the signed area (shoelace formula).

source
Jutul.CutCellMeshes._expand_polygon Method
julia
_expand_polygon(poly, frac=0.02) -> Vector{SVector{3, T}}

Expand a polygon slightly outward from its centroid. Each vertex is pushed away from the centroid by frac times the centroid-to-vertex distance. This ensures that the point-in-polygon test reliably includes cells at shared edges and vertices of adjacent polygons.

source
Jutul.CutCellMeshes._fix_boundary_orientation! Method
julia
_fix_boundary_orientation!(nodes, node_points, cell, mesh)

Ensure boundary face normal points outward (away from the cell).

source
Jutul.CutCellMeshes._fix_interior_orientation! Method
julia
_fix_interior_orientation!(nodes, node_points, left, right, mesh)

Ensure interior face normal (computed from node ordering) points from cell left toward cell right. If not, reverse the node order.

source
Jutul.CutCellMeshes._is_convex_polygon Method
julia
_is_convex_polygon(pts, normal; tol=1e-10)

Check whether a 3D planar polygon (given as ordered vertices) is convex when projected onto its plane. normal is the face normal used to define the winding direction. All cross products of consecutive edge pairs must point in the same direction as normal (or be zero for collinear edges).

source
Jutul.CutCellMeshes._merge_face_group! Method
julia
_merge_face_group!(out_nodes, out_meta, fgroup, done, mesh, node_points, tol, is_boundary)

Given a group of faces that all belong to the same cell pair (interior) or same cell (boundary), find clusters of coplanar faces that share nodes and merge each cluster into a single face.

source
Jutul.CutCellMeshes._point_in_face_polygon Method
julia
_point_in_face_polygon(pt, poly, normal)

Test whether a 3D point (assumed to be on the polygon's plane) lies inside the polygon. Projects to the polygon's local 2D frame and uses ray-casting.

source
Jutul.CutCellMeshes._point_inside_mesh Method
julia
_point_inside_mesh(pt, polys, normals, centroids)

Test whether a 3D point is inside a closed mesh defined by boundary face polygons. Uses ray-casting along the +x direction and counts crossings with boundary face triangles.

source
Jutul.CutCellMeshes._polygon_area_2d Method
julia
_polygon_area_2d(poly)

Compute the area of a 2D polygon using the shoelace formula.

source
Jutul.CutCellMeshes._polygon_intersection_2d Method
julia
_polygon_intersection_2d(subject, clip)

Compute the intersection of two 2D convex polygons using the Sutherland-Hodgman algorithm. Both polygons are reoriented to counter-clockwise winding before clipping. Returns a vector of 2D vertices.

source
Jutul.CutCellMeshes._polygon_normal_from_pts Method
julia
_polygon_normal_from_pts(pts)

Compute unit normal of a planar polygon from 3D points using Newell's method.

source
Jutul.CutCellMeshes._rebuild_mesh Method
julia
_rebuild_mesh(mesh, node_points, face_nodes, face_neighbors, bnd_nodes, bnd_cells)

Build a new UnstructuredMesh from merged face data.

source
Jutul.CutCellMeshes._rebuild_mesh_with_nodes Method
julia
_rebuild_mesh_with_nodes(mesh, new_nodes)

Create a new UnstructuredMesh identical to mesh but with new_nodes as node points.

source
Jutul.CutCellMeshes._remove_cells Method
julia
_remove_cells(mesh, keep) -> (new_mesh, cell_mapping)

Remove cells from a mesh. keep[c] is true for cells to retain. Returns the new mesh and a vector mapping new cell indices to old cell indices.

source
Jutul.CutCellMeshes._split_polygon_by_line_2d Method
julia
_split_polygon_by_line_2d(poly, point_on_line, inward_normal)

Split a 2D polygon by a line defined by a point and an inward normal. Returns (inside, outside) where inside is the part on the inward side and outside is the part on the outward side.

source
Jutul.CutCellMeshes._subtract_convex_2d Method
julia
_subtract_convex_2d(subject, clip)

Subtract convex polygon clip from convex polygon subject. Returns a list of convex polygon pieces that cover subject \ clip. Uses successive clipping against the complement of each edge of clip.

source
Jutul.CutCellMeshes.build_cut_mesh Method
julia
build_cut_mesh(mesh, plane, node_points, is_cut, cut_infos, node_class, get_intersection, extra_out, partial_cut, do_merge_faces)

Build the final mesh after cutting.

When partial_cut is :positive or :negative, only cells on the specified side are kept. Cut cells lose the sub-cell on the discarded side and the cut face becomes a boundary face. Uncut cells entirely on the discarded side are removed.

When do_merge_faces is true, coplanar faces that share the same cell pair (or same cell for boundary faces) and share at least two nodes are merged into a single face.

source
Jutul.CutCellMeshes.cell_any_node_in_bounding_polygon Method
julia
cell_any_node_in_bounding_polygon(mesh, cell, plane, bounding_polygon_2d)

Check whether any of a cell's nodes, when projected onto the cutting plane, falls inside the 2D bounding polygon. Used for the clip_to_polygon option to include partially-inside cells.

source
Jutul.CutCellMeshes.cell_bounding_box Method
julia
cell_bounding_box(mesh, cell)

Compute the axis-aligned bounding box of a cell, returns (min_pt, max_pt).

source
Jutul.CutCellMeshes.cell_centroid_in_bounding_polygon Method
julia
cell_centroid_in_bounding_polygon(mesh, cell, plane, bounding_polygon_2d)

Check whether a cell's centroid, when projected onto the cutting plane, falls inside the 2D bounding polygon.

source
Jutul.CutCellMeshes.cell_nodes Method
julia
cell_nodes(mesh, cell)

Get all unique node indices for a cell.

source
Jutul.CutCellMeshes.classify_cell Method
julia
classify_cell(mesh, cell, plane; tol)

Classify a cell with respect to a cutting plane. Returns:

  • :positive if all nodes are on positive side (or on plane)

  • :negative if all nodes are on negative side (or on plane)

  • :cut if nodes span both sides

source
Jutul.CutCellMeshes.classify_point Method
julia
classify_point(plane, pt; tol)

Return +1, -1, or 0 depending on whether pt is on the positive side, negative side, or on the plane.

source
Jutul.CutCellMeshes.clip_face_by_plane Method
julia
clip_face_by_plane(face_nodes, node_points, plane; tol)

Clip a polygon (given by node indices) by a plane. Returns two sets of polygon vertices: one for the positive side and one for the negative side. Uses the Sutherland-Hodgman algorithm variant.

Returns (pos_poly, neg_poly) where each is a Vector{SVector{3, T}}.

source
Jutul.CutCellMeshes.cut_and_displace_mesh Method
julia
cut_and_displace_mesh(mesh::UnstructuredMesh{3}, plane::PlaneCut;
    constant = 0.0, shift_lr = 0.0, angle = 0.0,
    side = :positive, kwargs...)

Cut a 3D mesh along a plane using cut_mesh, displace one side, and glue the two sides back together. All three displacement operations act in the plane, so the cut interface remains in contact (no gap, no collision).

Two in-plane tangent directions are defined automatically:

julia
t₁ = normalize(cross(n, ref))
t₂ = cross(n, t₁)

where n is the plane normal and ref is a reference vector chosen to avoid degeneracy. t₁ and t₂ are orthogonal tangent directions within the cutting plane.

The displacement applied to each node is the combination of:

  1. A uniform shift along t₁ (up-down): constant · t₁

  2. A uniform shift along t₂ (left-right): shift_lr · t₂

  3. An in-plane rotation by angle (radians) around the plane normal n, pivoting at plane.point.

All three operations preserve the cut-surface contact (they slide points within the plane but never move them out of it) and preserve cell volumes.

Keyword arguments

  • constant::Real = 0.0: Uniform shift along t₁ (up-down direction).

  • shift_lr::Real = 0.0: Uniform shift along t₂ (left-right direction).

  • angle::Real = 0.0: In-plane rotation (radians) around the plane normal n, pivoting at plane.point.

  • side::Symbol = :positive: Which side to shift (:positive or :negative).

  • tol::Real = 1e-6: Node-merge tolerance for gluing.

  • face_tol::Real = 1e-4: Face centroid proximity tolerance.

  • coplanar_tol::Real = 1e-3: Normal-direction coplanarity tolerance for face matching.

  • area_tol::Real = 1e-10: Minimum face area to keep.

  • min_cut_fraction::Real = 0.05: Passed to cut_mesh.

  • extra_out::Bool = false: Return mapping information.

When extra_out=true the returned Dict contains:

  • :cell_index – maps each new cell to its original cell index in the input mesh (composed through cut_mesh and extract_submesh).

  • :cell_side – per cell, :positive or :negative indicating which side of the cut plane it belongs to.

  • :face_index_a, :face_index_b – per interior face, index in the positive-side or negative-side sub-mesh (0 otherwise).

  • :boundary_face_index_a, :boundary_face_index_b – same for boundary faces.

  • :new_faces – indices of newly created interior faces from gluing.

Returns a new UnstructuredMesh, or (UnstructuredMesh, Dict) when extra_out=true.

source
Jutul.CutCellMeshes.cut_mesh Method
julia
cut_mesh(mesh::UnstructuredMesh{3}, plane::PlaneCut; kwargs...)
cut_mesh(mesh::UnstructuredMesh{3}, surface::PolygonalSurface; kwargs...)

Cut an UnstructuredMesh in 3D by a planar constraint. Cells that are intersected by the plane are split into two new cells, one on each side of the plane.

  • mesh: A 3D UnstructuredMesh

  • plane or surface: The cutting constraint

  • min_cut_fraction: Cells where the cut produces a sub-cell with volume less than this fraction of the original are left unsplit (default 0.05).

  • bounding_polygon: Optional vector of 3D points defining a polygon in the cutting plane. Only cells whose centroid projects inside this polygon will be cut. If nothing (default), all intersected cells are cut.

  • clip_to_polygon: If true and bounding_polygon is provided, cells that are partially inside the bounding polygon (any node projects inside) will also be cut. Default is false.

  • extra_out: If true, return a tuple (mesh, info_dict) where info_dict contains:

    • :cell_index: Vector mapping each new cell to its original cell index.

    • :face_index: Vector mapping each new interior face to its original face index (0 for newly created cut faces).

    • :boundary_face_index: Vector mapping each new boundary face to its original boundary face index.

    • :new_faces: Vector of indices of the interior faces added by cutting.

Returns a new UnstructuredMesh, or (UnstructuredMesh, Dict) if extra_out=true.

source
Jutul.CutCellMeshes.cut_mesh Method
julia
cut_mesh(mesh::UnstructuredMesh{3}, cuts::Vector{Any}; kwargs...)

Cut an UnstructuredMesh in 3D by multiple cutting constraints. Performs one cut per element in the vector, sequentially applying each cut to the result of the previous cut.

  • mesh: A 3D UnstructuredMesh

  • cuts: Vector of PlaneCut or PolygonalSurface objects

  • extra_out: If true, return a tuple (mesh, info_dict) where info_dict contains:

    • :cell_index: Vector mapping each new cell to its original cell index.

    • :face_index: Vector mapping each new interior face to its original face index (0 for newly created cut faces).

    • :boundary_face_index: Vector mapping each new boundary face to its original boundary face index.

    • :new_faces: Vector of indices of the interior faces added by cutting.

    • :cut_no: Vector where info_dict[:cut_no][f] = n if face f was generated as a result of cut number n, and 0 if the face is not new (was part of the original mesh).

All other keyword arguments are passed to individual cut operations.

Returns a new UnstructuredMesh, or (UnstructuredMesh, Dict) if extra_out=true.

source
Jutul.CutCellMeshes.cut_mesh Method
julia
cut_mesh(mesh, plane; partial_cut=:none, ...)

When partial_cut is :positive or :negative, only cells on the specified side of the cutting plane are kept after cutting. Cut cells lose their sub-cell on the discarded side and the cut face becomes a new boundary face. Uncut cells that lie entirely on the discarded side are removed. When partial_cut=:none (default), both sub-cells are kept (standard behaviour).

source
Jutul.CutCellMeshes.dominant_side Method
julia
dominant_side(fnodes, node_class)

Determine which side of the plane a face is on.

source
Jutul.CutCellMeshes.edge_plane_intersection Method
julia
edge_plane_intersection(p1, p2, plane)

Find the intersection point of line segment (p1, p2) with a plane. Returns the intersection point. Assumes the segment does cross the plane.

source
Jutul.CutCellMeshes.embed_mesh Method
julia
embed_mesh(mesh_a::UnstructuredMesh{3}, mesh_b::UnstructuredMesh{3}; kwargs...)

Embed mesh B inside mesh A by removing overlapping cells from A, cutting partially overlapping cells, and gluing the two meshes together.

The structure of mesh B is preserved exactly. Cells in A that are entirely inside B are removed. Cells in A that are partially cut by the boundary of B are split so that only the portion outside B remains. The trimmed A and B are then stitched together with glue_mesh.

Keyword arguments

  • extra_out::Bool = false: If true, return (mesh, info) where info is a Dict{Symbol, Any} containing:

    • :cell_origin: Vector{Symbol} — :mesh_a or :mesh_b for each cell.

    • :cell_index_a: Vector{Int} — maps each cell to its index in the original mesh A (0 for cells from B).

    • :cell_index_b: Vector{Int} — maps each cell to its index in the original mesh B (0 for cells from A).

  • min_cut_fraction::Real = 0.01: Passed to cut_mesh for volume filtering.

  • tol::Real = 1e-6: Node merging tolerance for gluing.

  • face_tol::Real = 1e-4: Face centroid proximity tolerance for gluing.

  • coplanar_tol::Real = 1e-3: Coplanarity tolerance for gluing.

  • merge_faces::Bool = true: Whether to merge coplanar faces after cutting.

Returns a new UnstructuredMesh{3}, or (UnstructuredMesh{3}, Dict) when extra_out=true.

source
Jutul.CutCellMeshes.glue_mesh Method
julia
glue_mesh(mesh_a::UnstructuredMesh{3}, mesh_b::UnstructuredMesh{3}; kwargs...)

Glue two 3D UnstructuredMesh instances together by merging boundary faces that are in close proximity. Nodes within distance tol are merged, and overlapping boundary faces become new interior faces with the correct neighborship. Non-overlapping boundary faces remain as boundary faces. Faces may be split when only partially overlapping.

Keyword arguments

  • tol::Real = 1e-6: Distance tolerance for merging nodes.

  • face_tol::Real = 1e-4: Tolerance for determining if two boundary face centroids are close enough to attempt intersection.

  • coplanar_tol::Real = 1e-3: Maximum allowed normal-direction distance between two face planes for them to be considered coplanar and eligible for gluing.

  • area_tol::Real = 1e-10: Minimum area for a face to be kept.

  • interface_point::Union{Nothing, AbstractVector} = nothing: When provided together with interface_normal, only boundary faces whose centroids lie within coplanar_tol of the interface plane are considered for gluing. This prevents spurious matches between boundary faces far from the intended gluing interface.

  • interface_normal::Union{Nothing, AbstractVector} = nothing: Unit normal of the interface plane (see interface_point).

  • extra_out::Bool = false: If true, return (mesh, info) where info is a Dict with:

    • :cell_index_a – maps new cell indices to original cell indices in mesh_a (0 for cells from mesh_b).

    • :cell_index_b – maps new cell indices to original cell indices in mesh_b (0 for cells from mesh_a).

    • :face_index_a – maps new interior face to original face in mesh_a (0 otherwise).

    • :face_index_b – maps new interior face to original face in mesh_b (0 otherwise).

    • :boundary_face_index_a – maps new boundary face to original boundary face in mesh_a (0 otherwise).

    • :boundary_face_index_b – maps new boundary face to original boundary face in mesh_b (0 otherwise).

    • :new_faces – indices of newly created interior faces from gluing.

Returns a new UnstructuredMesh, or (UnstructuredMesh, Dict) when extra_out=true.

source
Jutul.CutCellMeshes.merge_coplanar_faces Method
julia
merge_coplanar_faces(mesh; coplanar_tol=1e-8)

Post-process a mesh by merging coplanar faces that share the same cell pair (for interior faces) or the same cell (for boundary faces) and share at least two nodes. The merged polygon is re-ordered so that its normal points from left to right cell (interior) or outward from the cell (boundary).

Returns a new UnstructuredMesh.

source
Jutul.CutCellMeshes.order_polygon_points Method
julia
order_polygon_points(pts, normal)

Order polygon points counter-clockwise when viewed from the direction of normal.

source
Jutul.CutCellMeshes.point_in_polygon_2d Method
julia
point_in_polygon_2d(pt, polygon)

Check whether a 2D point lies inside a 2D polygon using the ray-casting algorithm.

source
Jutul.CutCellMeshes.polygon_area Method
julia
polygon_area(poly)

Compute the area of a 3D planar polygon.

source
Jutul.CutCellMeshes.polygon_centroid Method
julia
polygon_centroid(poly)

Compute the centroid of a 3D planar polygon.

source
Jutul.CutCellMeshes.polygon_normal Method
julia
polygon_normal(poly)

Compute the unit normal of a planar polygon from its vertices using Newell's method.

source
Jutul.CutCellMeshes.project_polygon_to_2d Method
julia
project_polygon_to_2d(polygon, plane)

Project a 3D bounding polygon onto the cutting plane, returning 2D coordinates.

source
Jutul.CutCellMeshes.project_to_plane Method
julia
project_to_plane(pt, plane)

Project a 3D point onto the cutting plane, returning 2D coordinates (u, v) in a local coordinate system on the plane.

source
Jutul.CutCellMeshes.signed_distance Method
julia
signed_distance(plane, point)

Compute the signed distance from point to the plane defined by plane. Positive values are on the side of the normal.

source
Jutul.EmbeddedMeshes Module
julia
EmbeddedMeshes

A module for handling embedded mesh structures in Jutul, designed for e.g., discrete fracture matrix (DFM) simulations.

The EmbeddedMeshes module provides functionality to work with meshes where lower-dimensional features (like fractures or faults) are embedded within higher-dimensional domains. These embedded features are represented as interconnected faces that can intersect with each other, creating complex network topologies.

source
Jutul.EmbeddedMeshes.EmbeddedMesh Type
julia
EmbeddedMesh <: FiniteVolumeMesh

A mesh type for representing embedded lower-dimensional features (such as fractures or faults) within a computational domain. The mesh consists of interconnected faces.

Fields

  • unstructured_mesh::UnstructuredMesh: The underlying unstructured mesh representation

  • parent_faces::Vector{Int}: Indices of the parent mesh faces that make up the embedded mesh

  • intersection_neighbors::Vector{Vector{Int}}: Embedded mesh cells grouped per intersection

  • intersection_faces::Vector{Vector{Int}}: Face indices per intersection, aligned with intersection_neighbors. For :remove, these are boundary face indices; for :star_delta and :keep, these are internal face indices.

  • intersection_cells::Vector{Int}: Embedded mesh cell indices created for kept intersections

source
Jutul.EmbeddedMeshes.EmbeddedMesh Method
julia
EmbeddedMesh(mesh::UnstructuredMesh, faces)

Construct an embedded mesh from selected faces of an unstructured mesh.

Arguments

  • mesh::UnstructuredMesh: Parent mesh containing the faces

  • faces: Collection of face indices to include in the embedded mesh

Keyword arguments

  • intersection_strategy::Symbol = :keep: Strategy for handling intersections.
    • :star_delta (default): Intersections with three or more faces are split into pairwise internal connections.

    • :remove: Intersections are removed by duplicating the intersecting edge as a boundary edge for each face.

    • :keep: Intersections are kept as-is, with an additional cell created for each intersection and connected to all intersecting faces.

Returns

  • EmbeddedMesh: Embedded mesh made up of the specified faces.
source
Jutul.EmbeddedMeshes.make_mesh_from_faces Method
julia
make_mesh_from_faces(mesh, faces)

Helper for EmbeddedMesh constructor.

source
Jutul.compute_half_face_trans Method
julia
Jutul.compute_half_face_trans(mesh::EmbeddedMesh, cell_centroids, face_centroids, face_areas, perm, faces, facepos)

Compute half-face transmissibilities for finite volume discretization in embedded meshes.

source
Jutul.KAPreconditioners.AMGHierarchy Type

Reusable AMG hierarchy and Krylov-compatible left preconditioner.

source
Jutul.KAPreconditioners.AMGOptions Type
julia
AMGOptions(; coarsening=HMIS(), interpolation=default_interpolation(coarsening), ...)

Configuration for the backend-portable AMG hierarchy. Interpolation is an independent hierarchy option whose default follows the coarsening method: piecewise constant for aggregation, classical for Ruge-Stuben, and Extended+i for HMIS. aggressive_levels applies a second coarsening pass to that many levels, starting at the finest level. Its default of zero disables aggressive coarsening. aggressive_num_paths=1 retains every direct or distance-two path in the second strength graph; larger values require more paths and reduce aggressiveness. This option applies to RS and HMIS, not aggregation. aggressive_interpolation=nothing uses two-stage Extended+i, inheriting ordinary truncation and row limits for the final product while leaving both factors untruncated. Supply TwoStageExtendedIInterpolation(...) for independent factor and product controls.

strength_type is shared by all coarsening methods: :signed uses only off-diagonal entries opposite in sign to the diagonal, :absolute uses all off-diagonal magnitudes, and the default :signed_fallback uses signed strength unless a row has no opposite-sign entries, then uses magnitudes. HMIS with classical interpolation receives the classical second-pass repair.

source
Jutul.KAPreconditioners.Aggregation Type

Unsmoothed, strength-based aggregation.

source
Jutul.KAPreconditioners.BackendBufferPrefix Type

Logical prefix retaining the full backend allocation for later reuse.

source
Jutul.KAPreconditioners.ClassicalInterpolation Type
julia
ClassicalInterpolation(truncation=0.0, max_elements=0, norm_p=1, rescale=true)

Classical interpolation through strong coarse neighbors. A zero max_elements retains every candidate. By default, truncation compares weight magnitudes to truncation times the largest magnitude, and rescaling preserves the untruncated row sum. Explicit norm_p=p compares the p-th powers instead.

source
Jutul.KAPreconditioners.CoarseLUState Type

Cached sparse LU state for a CPU coarse grid.

source
Jutul.KAPreconditioners.ConstantInterpolation Type

Piecewise-constant interpolation for unsmoothed aggregation.

source
Jutul.KAPreconditioners.DILU Type
julia
DILU(steps=1, damping=1.0)

Diagonal ILU(0), implemented with level-scheduled factorization and triangular sweeps following Andersen et al. The level schedule preserves the natural row ordering, so host and accelerator backends construct the same preconditioner.

source
Jutul.KAPreconditioners.DenseLUState Type

Backend-native dense LU factorization for a coarse grid.

source
Jutul.KAPreconditioners.ExtendedIInterpolation Type
julia
ExtendedIInterpolation(truncation=0.0, max_elements=4, norm_p=1, rescale=true)

Configuration for distance-two Extended+i interpolation. When rescale is enabled, truncation preserves the untruncated interpolation-row sum. A zero max_elements retains every candidate. norm_p has the same meaning as for ClassicalInterpolation.

source
Jutul.KAPreconditioners.GalerkinMap Type

Triples grouped by coarse nonzero; enables one kernel item per output.

source
Jutul.KAPreconditioners.GaussSeidel Type
julia
GaussSeidel(steps=1, damping=1.0)

Forward Gauss-Seidel on the down cycle and backward Gauss-Seidel on the up cycle. This CPU smoother mirrors BoomerAMG's default serial relaxation.

source
Jutul.KAPreconditioners.HMIS Type

Hybrid modified independent-set coarsening.

source
Jutul.KAPreconditioners.HostLUState Type

Standard host LU fallback for backends without a native dense LU overload.

source
Jutul.KAPreconditioners.ILU0 Type
julia
ILU0(steps=1, damping=1.0)

Level-scheduled incomplete LU factorization with zero fill. The symbolic level schedules are retained and reused when matrix coefficients are updated.

source
Jutul.KAPreconditioners.KASparseLUFactor Type

The portable sparse LU accepts a fixed CSR pattern. With pivoting enabled it uses a dense factor buffer so row swaps can introduce arbitrary fill. Set pivoting=false to use the sparse symbolic fill pattern without row swaps.

source
Jutul.KAPreconditioners.RugeStuben Type
julia
RugeStuben(theta=0.25; second_pass=true)

Classical Ruge-Stuben C/F splitting. The second pass enforces the shared coarse-neighbor condition for classical interpolation. Disable it to use a cheaper first-pass split, preferably with Extended+i interpolation.

source
Jutul.KAPreconditioners.SPAI0 Type

Sparse approximate-inverse relaxation with the matrix sparsity pattern.

source
Jutul.KAPreconditioners.SetupWorkspace Type

Host scratch and staging storage retained across symbolic rebuilds.

source
Jutul.KAPreconditioners.SparseLU Type

Sparse LU for a fixed CSR pattern.

source
Jutul.KAPreconditioners.TwoStageExtendedIInterpolation Type
julia
TwoStageExtendedIInterpolation(; truncation=0.0, max_elements=0,
    norm_p=1, rescale=true, stage_truncation=0.0, stage_max_elements=0)

Hypre's two-stage Extended+i aggressive interpolation (agg_interp_type=1). Build P1 from fine points to the first coarse set, then partial Extended+i P2 from that set to the final coarse set using the original matrix. Truncate the product P1_P2 with truncation and max_elements. The independent stage__parameters control both factors (hypre's AggP12 controls); zero row limits mean unlimited. This variant is only valid foraggressive_interpolation.

source
Jutul.KAPreconditioners.VendorILU Type
julia
VendorILU(steps=1, damping=1.0)

Backend-native ILU(0). Scalar matrices use the vendor CSR implementation and matrices with static dense blocks use the vendor block CSR implementation. Setup throws when the matrix backend has no native implementation.

source
Jutul.KAPreconditioners.apply! Method

Apply the hierarchy as a linear preconditioner (x is cleared first).

source
Jutul.KAPreconditioners.buffer_prefix Method

Use the first n entries of a backend buffer without reallocating it.

source
Jutul.KAPreconditioners.copy_reusing Method

Copy into an old backend allocation when its type and capacity permit.

source
Jutul.KAPreconditioners.csr_matrix Method

Convert Julia CSC storage to Jutul's CSR representation.

source
Jutul.KAPreconditioners.cycle! Method

Apply one cycle to the current iterate without clearing it.

source
Jutul.KAPreconditioners.grown_backend_capacity Method

Capacity used when an existing backend buffer has to grow.

source
Jutul.KAPreconditioners.hmis_rs_first_pass! Function

HYPRE-compatible RS first pass shared by classical RS and HMIS.

source
Jutul.KAPreconditioners.release_replaced_backend_storage! Method

Backend hook invoked after symbolic hierarchy rebuilds have accumulated enough replaced device storage. Accelerators whose array storage is released by host finalizers can collect those wrappers and release allocator cache here.

source
Jutul.KAPreconditioners.repair_aggressive_split! Method

Promote uncovered F points so aggressive interpolation has no empty rows.

source
Jutul.KAPreconditioners.resetup_amg! Function
julia
resetup_amg!(H, A, reuse=:operators)

Refresh a hierarchy for new coefficients.

  • :operators preserves C/F splits, interpolation values, sparse patterns, and every array; Galerkin operators and all smoother coefficients are recomputed.

  • :sparsity additionally recomputes the retained interpolation weights in place using the configured interpolation method.

  • :memory recomputes all symbolic data while recycling compatible hierarchy buffers. The finest sparsity pattern must be unchanged; coefficients may alter strength, splitting, interpolation, and every coarse pattern.

  • :partial_operators and :partial_sparsity retain the first n_levels_partial_keep levels (default 3), updating them as in :operators and :sparsity, respectively. n_partial_keep (default -1, disabled) can end the retained prefix sooner: the first level with a matrix size below that value is rebuilt. Remaining levels are rebuilt as in :memory.

  • :none is a completely fresh setup and is useful as a reference baseline.

The first two modes perform no hierarchy-array allocation.

source
Jutul.KAPreconditioners.reusable_buffer Method

Return the allocation backing a contiguous prefix used for reuse.

source
Jutul.KAPreconditioners.ruge_stuben_second_pass! Function

Enforce the classical RS common-C-neighbor condition for strong F-F edges.

source
Jutul.KAPreconditioners.second_strength_graph Method

Build HYPRE's second strength graph for aggressive coarsening. Its vertices are the C points from the first split, and its edges are the direct and distance-two strong connections between those points (S + S^2). An edge requires at least num_paths paths; a direct connection counts as two paths, as in HYPRE.

source
Jutul.KAPreconditioners.setup_amg Method
julia
setup_amg(A, options=AMGOptions())

Build an owned, reusable AMG hierarchy. Numerical kernels and all hierarchy arrays use the backend of A (or the backend requested when calling csr_matrix).

source
Jutul.KAPreconditioners.setup_smoother Function
julia
setup_smoother(A, config=SPAI0(); reuse=nothing)

Build a reusable smoother/preconditioner for A. Symbolic data and work buffers are retained by the returned state. Pass a compatible state through reuse to update coefficients without rebuilding sparsity-dependent data.

source
Jutul.KAPreconditioners.smooth! Function

Apply one or more stationary smoothing steps to the current iterate x.

source
Jutul.KAPreconditioners.solve! Method
julia
solve!(x, H, b; rtol=1e-8, atol=0, maxiter=100)

Solve with repeated AMG cycles. Returns (x, iterations) and records the final relative residual in H.last_residual.

source
Jutul.KAPreconditioners.update_smoother! Function

Update a smoother for new coefficients with the same sparsity pattern.

source
Jutul.KernelExecution.KernelAbstractionsContext Type
julia
KernelAbstractionsContext(backend; float_type=Float64, index_type=Int,
                          linear_float_type=float_type,
                          linear_index_type=index_type,
                          matrix_layout=EquationMajorLayout(),
                          workgroupsize=256, minbatch=minbatch(nothing),
                          use_kernels_for_secondary=!is_cpu_backend,
                          secondary_scheme=:flat,
                          reduce_memory=true, use_vendor_linalg=true)

Execution context for a SimulationModel or MultiModel on a KernelAbstractions backend. Build the model and Simulator on the CPU, then use transfer_to_backend to adapt the completed simulator. A multimodel application can select host evaluation, device assembly, or fully host-side execution per submodel through DeviceExecutionMode.

minbatch is the minimum number of entries per CPU batch. CPU loops use Polyester and execute directly when there is only one batch; accelerator backends launch KernelAbstractions kernels.

use_kernels_for_secondary controls whether secondary properties use KernelAbstractions kernels. It defaults to false for the CPU backend, where the regular host-parallel path is generally preferable, and to true for accelerator backends, which require kernel evaluation for device arrays.

secondary_scheme selects host secondary-variable scheduling: :flat (default), :fused (cache tiling using minbatch entities per tile), or :strided (up to four interleaved batches per worker). See secondary_scheme. The non-default schemes require use_kernels_for_secondary=false. For example, transfer_to_backend(sim, CPU(); secondary_scheme=:fused) enables tiling through the regular backend-transfer interface.

float_type and index_type select assembly and state storage. The linear_float_type and linear_index_type keywords select the linearized system and solver storage, and default to the corresponding assembly types.

With reduce_memory=true, TPFA conservation laws without face-variable fluxes use fused equation assembly, computing cell half-face flux values on the fly instead of retaining them in backend storage.

use_vendor_linalg=true uses cuSPARSE on CUDA and rocSPARSE on AMDGPU for supported sparse matrix-vector products. Vendor descriptors, analysis and workspace are retained for repeated products with the same matrix, including in-place updates of its values. Set it to false to use KA kernels instead.

source
Jutul.KernelExecution.PreparedCrossTermStorage Type

Cross-term storage carrying a pre-converted kernel evaluation plan. The ordinary storage interface is forwarded through data, keeping the cached launch details out of the generic multimodel evaluation path.

source
Jutul.transfer_to_backend Method
julia
transfer_to_backend(simulator, backend; kwarg...)
transfer_to_backend(simulator, context::KernelAbstractionsContext)

Adapt a fully initialized CPU simulator to a KernelAbstractions backend. SimulationModel and MultiModel are supported. Sparsity discovery and Jacobian/cross-term alignment finish on the CPU before the CSR arrays are moved. Array aliases used by primary variables, parameters, residual views and Jacobian buffers are rebuilt against the adapted root arrays. Submodels marked AssembleOnDevice retain their CPU model and storage and copy into preallocated backend mirrors after evaluation. Mixed host/device cross terms execute on the host by default; set mixed_cross_terms_on_host=false to use backend evaluation instead.

source