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
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.
Jutul.AbstractGlobalObjective Type
Abstract type for objective as a global objective function on the form:
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.
Jutul.AbstractSumObjective Type
Abstract type for objective as a sum of function values on the form:
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.
Jutul.AbstractTerminationCriterion Type
Abstract type for termination criteria for steady-state time-stepping simulations.
Subtypes should implement the method
timestepping_is_done(C::AbstractTerminationCriterion, simulator, states, substates, reports, solve_recorder)that returns a Bool indicating whether the time-stepping should terminate.
sourceJutul.BlockJacobianPositions Type
Logical alignment matrix storing only the first scalar position of each block.
sourceJutul.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)₂]
sourceJutul.BoundaryFaces Type
Entity for faces on the boundary (faces that are only connected to a single Cells)
Jutul.CartesianMesh Type
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 withnxcells in the x-direction.Δ::Tuple=Tuple(ones(length(dims))): Equal length todims. 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> CartesianMesh((3, 5, 2), (2.0, 3.0, 5.0))
CartesianMesh (3D) with 3x5x2=30 cellsGenerate a non-uniform 2D mesh:
julia> CartesianMesh((2, 3), ([1.0, 2.0], [0.1, 3.0, 2.5]))
CartesianMesh (2D) with 2x3x1=6 cellsJutul.Cells Type
Entity for Cells (closed volumes with averaged properties for a finite-volume solver)
sourceJutul.CoarseMesh Method
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.
Jutul.CompactAutoDiffCache Type
Cache that holds an AD vector/matrix together with their positions.
sourceJutul.DataDomain Method
DataDomain(domain::JutulDomain; property1 = p1, property2 = p2, ...)A wrapper around a domain that allows for storing of entity-associated data.
Example:
# 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 okJutul.DefaultContext Type
Default CPU context. See secondary_scheme for secondary-variable scheduling.
Jutul.DeviceExecutionMode Type
DeviceExecutionModeExecution 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 anotherAssembleOnDevicemodel are evaluated on the host and copied to the device. Cross terms with aSolveFullyOnDevicemodel are evaluated on the device after synchronizing the host model's state.NothingOnDevice: variables, equations, assembly and the linear system remain on the host.
Jutul.DiscretizedDomain Type
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.
sourceJutul.EndTimeTerminationCriterion Type
EndTimeTerminationCriterion(end_time)A termination criterion that stops time-stepping when the global time reaches end_time.
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)₂
sourceJutul.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)₂
sourceJutul.FaceMap Type
Struct that contains mappings for a set of faces that are made up of nodes and are part of cells.
sourceJutul.FastAssemblyData Method
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.
sourceJutul.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.
Jutul.FusedEquationAssemblyStorage Type
Data retained in place of the cell half-face flux cache when TPFA fluxes are evaluated as part of equation assembly.
sourceJutul.GenericKrylov Type
GenericKrylov(solver = :gmres; preconditioner = nothing; <kwarg>)Solver that wraps Krylov.jl with support for preconditioning.
Jutul.HelperSimulator Method
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.
sourceJutul.ImmutableJutulStorage Type
Immutable storage whose named fields and value types are fully specialized.
sourceJutul.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.
Jutul.IndirectionMap Method
imap = IndirectionMap(vec_of_vec::Vector{V}) where VCreate indirection map for a variable length dense vector that is represented as a Vector of Vectors.
sourceJutul.JutulAutoDiffCache Type
An AutoDiffCache is a type that holds both a set of AD values and a map into some global Jacobian.
sourceJutul.JutulCase Type
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.
sourceJutul.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!
Jutul.JutulContext Type
Abstract type for the context Jutul should execute in (matrix formats, memory allocation, etc.)
sourceJutul.JutulDiscretization Type
d = disc(i, Cells())Ask discretization for entry i when discretizing some equation on the chosen entity (e.g. Cells)
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.
sourceJutul.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.
Jutul.KASmootherPreconditioner Type
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.
Jutul.LUPreconditioner Type
Full LU factorization as preconditioner (intended for smaller subsystems)
sourceJutul.LUSolver Type
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.
Jutul.LimitByFailedTimestepSelector Type
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.
Jutul.MRSTWrapMesh Type
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.
Jutul.MultiModel Type
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.
Jutul.NoTerminationCriterion Type
NoTerminationCriterion()A termination criterion that never terminates prematurely, leaving all timesteps to be executed.
sourceJutul.ParallelCSRContext Type
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.
Jutul.SPAI0Preconditioner Type
Sparse Approximate Inverse preconditioner of lowest order – SPAI(0)
sourceJutul.ScalarVariable Type
Abstract type for scalar variables (one entry per entity, e.g. pressure or temperature in each cell of a model)
sourceJutul.SimulationModel Method
SimulationModel(domain, system; <kwarg>)Instantiate a model for a given system discretized on the domain.
Jutul.SimulationModel Method
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.
Jutul.Simulator Method
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.
Jutul.SparsityTracingWrapper Method
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).
sourceJutul.TwoPointFiniteVolumeGeometry Type
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.
sourceJutul.UnstructuredMesh Method
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.
Jutul.VectorVariables Type
Abstract type for vector variables (more than one entry per entity, for example saturations or displacements)
sourceJutul.WrappedGlobalObjective Type
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).
sourceJutul.WrappedSumObjective Type
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).
sourceJutul.absolute_increment_limit Method
Absolute allowable change for variable during a nonlinear update.
sourceJutul.add_option! Function
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.
Jutul.align_to_jacobian! Method
Update an equation so that it knows where to store its derivatives in the Jacobian representation.
sourceJutul.allocate_array_ad Method
allocate_array_ad(v::AbstractMatrix, ...)Convert matrix to AD matrix.
sourceJutul.allocate_array_ad Method
allocate_array_ad(v::AbstractVector, ...)Convert vector to AD vector.
sourceJutul.allocate_array_ad Method
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 ifmis given.m::Integer: number of rows (optional)
Keyword arguments
npartials = 1: Number of partials derivatives to allocate for each elementdiag_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> 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> 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> 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)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.
sourceJutul.apply_forces_to_equation! Method
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.
sourceJutul.as_value Method
Create a mapped array that produces only the values when indexed.
Only useful for AD arrays, otherwise it does nothing.
sourceJutul.associated_entity Method
The entity a variable is associated with, and can hold partial derivatives with respect to.
sourceJutul.backend_copyto! Method
backend_copyto!(destination, source)Copy compatible simulation storage from host evaluation buffers to backend buffers. Unsupported metadata is deliberately left unchanged by default.
sourceJutul.cartesian_partition Function
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)
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)
mesh = CartesianMesh((50, 50, 1))
p_ijk = Jutul.cartesian_partition(domain, (5, 5, 5), :ijk)Jutul.cell_dims Method
cell_dims(g, pos)::TupleGet physical cell dimensions of cell with index pos for grid g.
Jutul.cell_index Method
cell_index(g, pos)Get linear (scalar) index of mesh cell from provided IJK tuple pos.
Jutul.cells_inside_bounding_box Method
cells_inside_bounding_box(G::UnstructuredMesh, low_bb, high_bb; algorithm = :box, atol = 0.01)Jutul.check_amgcl_availability Method
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.
Jutul.check_lbfgsb_availability Method
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.
Jutul.check_plotting_availability Method
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.
Jutul.compress_timesteps Function
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.
Jutul.compress_timesteps Method
compress_timesteps(case::JutulCase; max_step = Inf)Compress time steps for a Jutul case. See compress_timesteps for the general case.
Jutul.compute_boundary_trans Method
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.
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.
Jutul.compute_half_face_trans Method
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.
Jutul.convergence_criterion Method
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 checkedeq_s: storage foreqwhere values are contained.r: the local residual part corresponding to this model, as a matrix with column index equaling entity index
Jutul.convert_from_si Method
convert_from_si(value, unit_name::Union{Symbol, String})Convert value from SI representation to the unit in unit_symbol.
Examples
julia> convert_from_si(3600.0, :hour) # Get 3600 s represented as hours
1.0Jutul.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.
sourceJutul.convert_to_si Function
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> 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-6Jutul.data_domain_to_parameters_gradient Method
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].
Jutul.declare_pattern Method
Give out source, target arrays of equal length for a given equation attached to the given model.
sourceJutul.declare_sparsity Function
Give out I, J arrays of equal length for a given equation attached to the given model.
sourceJutul.degrees_of_freedom_per_entity Method
Number of independent primary variables / degrees of freedom per computational entity.
sourceJutul.descalarize_primary_variable! Function
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.
Jutul.descalarize_primary_variables! Function
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.
Jutul.evaluate_all_secondary_variables Function
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).
sourceJutul.evaluation_state Method
state = evaluation_state(storage)Get the evaluation state (at the end of the current timestep) from the simulator storage.
sourceJutul.evaluation_state Method
state = evaluation_state(s::JutulSimulator)Get the state from a simulator for use during equation assembly.
sourceJutul.evaluation_state0 Method
state = evaluation_state0(storage)Get the evaluation state at the previous timestep from the simulator storage.
sourceJutul.evaluation_state0 Method
state = evaluation_state(s::JutulSimulator)Get the state at the previous step from a simulator for use during equation assembly.
sourceJutul.expand_to_ministeps Method
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.
Jutul.expand_to_ministeps Method
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.
Jutul.export_mesh_vtu Function
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
using WriteVTK
export_mesh_vtu(mesh, "output.vtu")
export_mesh_vtu(mesh, "output.vtu"; cell_data = (pressure = p,))Jutul.extra_debug_output! Method
extra_debug_output!(report, storage, model, config, iteration, dt)Add extra debug output to report during a nonlinear iteration.
sourceJutul.extract_submesh Method
extract_submesh(g::UnstructuredMesh, cells)Extract a subgrid for a given mesh and a iterable of cells to keep.
Jutul.extrude_mesh Method
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.
sourceJutul.face_area_vector Method
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!).
Jutul.face_average Method
face_average(F, tpfa)Compute the arithmetic average of F(left) and F(right) across a face.
Jutul.find_enclosing_cell Method
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.
Jutul.find_enclosing_cells Method
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 thatdirection .* lengthsis 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.
Jutul.get_1d_interpolator Method
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 toxsmethod=LinearInterpolant: constructor for the interpolation. Defaults toLinearInterpolantwhich 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 forx < xs[1])cap_end = cap_endpoints:Fine-grained version of cap_endpoints for the end of the interval only (extrapolation forx > xs[end])
Additional keyword arguments are passed onto the interpolator constructor.
sourceJutul.get_2d_interpolator Method
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.
Jutul.get_ad_entity_scalar Method
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).
Jutul.get_dependencies Method
Get dependencies of variable when viewed as a secondary variable. Normally autogenerated with @jutul_secondary
sourceJutul.get_diagonal_entries Method
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.
sourceJutul.get_entity_tag Method
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.
sourceJutul.get_entries Method
Get entries of autodiff cache. Entries are AD vectors that hold values and derivatives.
sourceJutul.get_entries Method
Get the entries of the main autodiff cache for an equation.
Note: This only gets the .equation field's entries.
sourceJutul.get_mesh_entity_tag Method
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.
Jutul.get_parameters Method
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.
sourceJutul.get_primary_variable_ordered_entities Method
get_primary_variable_ordered_entities(model::SimulationModel)Get only the entities where primary variables are present, sorted by their order in the primary variables.
sourceJutul.get_primary_variables Method
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.
Jutul.get_secondary_variables Method
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.
sourceJutul.get_sparse_arguments Method
get_sparse_arguments(storage, model)Get the [SparsePattern]@ref for the Jacobian matrix of a given simulator storage and corresponding model.
Jutul.get_tstr Function
get_tstr(dT, lim = 3)Get formatted time string of dT given in seconds, limited to lim number of units.
Jutul.get_variable Method
get_variable(model::SimulationModel, name::Symbol)Get implementation of variable or parameter with name name for the model.
Jutul.get_variables Method
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.
Jutul.get_variables_and_parameters Method
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.
Jutul.gradient Method
gradient(X::AbstractMatrix, i, tpfa::TPFA)Compute the gradient of row i of cell-centered matrix X across a face.
Jutul.gradient Method
gradient(X::AbstractVector, tpfa::TPFA)Compute the gradient of cell-centered values X across a face: X[right] - X[left].
Jutul.gradient Method
gradient(F, tpfa::TPFA)Compute the gradient using a function handle F(cell) across a face.
Jutul.initialize_extra_state_fields! Method
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).
sourceJutul.initialize_storage! Method
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.
sourceJutul.initialize_variable_value Method
Initializer for the value of non-scalar primary variables
sourceJutul.interpolation_constant_lookup Function
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.
Jutul.jutul_message Function
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.
Jutul.jutul_output_path Function
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``.
Jutul.jutul_table_format_with_data_hlines Method
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.
Jutul.linear_timestep_selection Function
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.
Jutul.load_balanced_endpoint Method
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.
Jutul.load_balanced_interval Method
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.
<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
sourceJutul.local_residual_view Method
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.
Jutul.matrix_row_view Method
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.
Jutul.maybe_convert_evaluation_state Method
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.
Jutul.merge_step_report_errors Method
merge_step_report_errors(data; fn = max)Merge step reports errors of the same type using a pair wise reduction (default: max)
sourceJutul.mesh_from_gmsh Function
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.
Jutul.model_accumulation! Function
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.
sourceJutul.model_residual! Function
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.
sourceJutul.model_residual Method
model_residual(sim::HelperSimulator, x, y = missing; kwarg...)Out of place version of model_residual!
Jutul.number_of_boundary_faces Function
number_of_boundary_faces(g)Get the number of boundary/exterior faces in a mesh.
sourceJutul.number_of_cells Method
number_of_cells(g)::IntegerGet the number of cells in a mesh.
sourceJutul.number_of_cells Method
number_of_cells(D::Union{DataDomain, DiscretizedDomain})Get the number of cells in a DataDomain or DiscretizedDomain.
Jutul.number_of_degrees_of_freedom Method
Total number of degrees of freedom for a model, over all primary variables and all entities.
sourceJutul.number_of_entities Method
Get the number of entities (e.g. the number of cells) that the equation is defined on.
sourceJutul.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
sourceJutul.number_of_entities Method
Number of entities for vector stored in state (just the number of elements)
sourceJutul.number_of_entities Method
Number of entities for matrix stored in state (convention is number of columns)
sourceJutul.number_of_equations_per_entity Method
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)
sourceJutul.number_of_faces Method
number_of_faces(g)::IntegerGet the number of faces in a mesh.
sourceJutul.number_of_faces Method
number_of_faces(D::Union{DataDomain, DiscretizedDomain})Get the number of faces in a DataDomain or DiscretizedDomain.
Jutul.number_of_half_faces Method
number_of_half_faces(D::Union{DataDomain, DiscretizedDomain})Get the number of half-faces in a DataDomain or DiscretizedDomain.
Jutul.number_of_partials_per_entity Method
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.
Jutul.number_of_values Function
Total number of values for a model, for a given type of variables over all entities
sourceJutul.numerical_eltype Method
numerical_eltype(x::AbstractArray{T}) where TGet the numerical eltype (i.e. the inner type of the element type that could potentially be AD)
sourceJutul.numerical_type Method
numerical_type(::T) where TGet 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.
sourceJutul.optimization_step_info Method
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, usestep_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 multiplestep_infoentries 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)
Jutul.parameters_jacobian_wrt_data_domain Method
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.
Jutul.partition Function
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)
sourceJutul.partition_hypergraph Function
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).
Jutul.physical_representation Method
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.
sourceJutul.physical_representation Method
physical_representation(x::DataDomain)Get the underlying physical representation (domain or mesh) that is wrapped.
sourceJutul.physical_representation Method
physical_representation(x::DiscretizedDomain)Get the underlying physical representation (domain or mesh) that was discretized.
sourceJutul.physical_representation Method
physical_representation(m::SimulationModel)Get the underlying physical representation for the model (domain or mesh)
sourceJutul.pick_next_timestep Method
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.
Jutul.plot_cell_data! Method
plot_cell_data!(ax, mesh, data; kwarg...)Mutating version of plot_cell_data that plots into an existing Makie Axis
Jutul.plot_cell_data Method
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.
Jutul.plot_explorer Method
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).
Jutul.plot_interactive Method
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.
Jutul.plot_mesh! Method
plot_mesh!(ax, mesh)Mutating version of plot_mesh that plots into an existing Makie Axis instance.
Jutul.plot_mesh Method
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.
Jutul.plot_mesh_edges! Method
plot_mesh_edges!(ax, mesh; kwarg...)Plot the edges of all cells on the exterior of a mesh into existing Makie Axis ax.
Jutul.plot_mesh_edges Method
plot_mesh_edges(mesh; kwarg...)Plot the edges of all cells on the exterior of a mesh.
sourceJutul.prepare_backend_transfer! Method
prepare_backend_transfer!(storage, model)Application hook for refreshing host-side numeric buffers immediately before they are copied to a backend mirror.
sourceJutul.prepare_host_transfer! Method
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.
sourceJutul.prepare_step_storage Method
prepare_step_storage(storage, model, ::Missing)Initialize storage for prepare_step_handler.
sourceJutul.process_partition Function
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.
g = CartesianMesh((5,))
p = [1, 1, 2, 1, 1] # Block 1 is disconnected!
process_partition(g, p)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.
Jutul.refactorize_linear_system! Method
Refresh an existing factorization for a linear-system block.
sourceJutul.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.
sourceJutul.replace_variables! Method
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 replacedvarname=vardef::JutulVariables: replace variable withvarnamebyvardefthrow=true: throw an error if the named variable definition is not found in primary or secondary, otherwise silently return themodel.
Jutul.scalarize_primary_variable Method
scalarize_primary_variable(model, source_vec, var::Jutul.ScalarVariable, index)Scalarize a primary variable. For scalars, this means getting the value itself.
sourceJutul.scalarize_primary_variables Function
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.
sourceJutul.scalarize_primary_variables! Method
scalarize_primary_variables!(V::Vector{T}, model, state, pvars::NamedTuple) where TScalarize into array. See scalarize_primary_variables for more details.
Jutul.scalarized_primary_variable_type Function
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)
sourceJutul.secondary_scheme Method
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, usingminbatch(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.
Jutul.segment_face_intersections! Method
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.
Jutul.segment_intersects_box Method
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].
Jutul.set_default_tolerances Method
set_default_tolerances(model)Set default tolerances for the nonlinear convergence check of the governing equations.
sourceJutul.set_parameters! Method
set_parameters!(model, parname = pardef)Set a parameter with name varname to the definition vardef (adding if it does not exist)
Jutul.set_primary_variables! Method
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)
Jutul.set_secondary_variables! Method
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)
Jutul.setup_adjoint_storage Method
setup_adjoint_storage(model; state0 = setup_state(model), parameters = setup_parameters(model))Set up storage for use with solve_adjoint_sensitivities!.
Jutul.setup_cross_term_storage_extra! Method
Application hook for preallocating cross-term-specific storage.
sourceJutul.setup_forces Method
setup_forces(model::JutulModel; force_name = force_value)Set up forces for a given model. Keyword arguments varies depending on what the model supports.
sourceJutul.setup_parameter_optimization Method
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 objectivedF_o(dFdx, x): evaluate gradient of objective, mutatingdFdx(may trigger evaluation ofF_o)F_and_dF(F, dFdx, x): evaluateFand/ordF. Ifnothingis 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.
Jutul.setup_parameters Method
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.
Jutul.setup_partitioner_hypergraph Method
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.
Jutul.setup_state! Function
setup_state!(state, model::JutulModel, init_values::AbstractDict = Dict())Initialize primary variables and other state fields, given initial values as a Dict
sourceJutul.setup_state Method
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
Jutul.setup_state_and_parameters Method
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)
Jutul.setup_storage! Method
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.
sourceJutul.setup_storage Method
setup_storage(model::JutulModel; kwarg...)Allocate storage for the model. You should overload setup_storage! if you have a custom definition.
sourceJutul.si_unit Method
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> si_unit(:day) # Get days represented as seconds
86400.0Jutul.si_units Method
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> meter, hour = si_units(:meter, :hour)
(1.0, 3600.0)Jutul.simulate! Method
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 timestates,reports: Pre-allocated output containers. Defaults are fresh empty vectors. Supply your own to retain partial output whensimulate!throws mid-loop (e.g. from apost_ministep_hook).
See also simulate for additional supported input arguments.
Jutul.simulate Method
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 usingsetup_statefor themodelin use.model::JutulModel: model that describes the discretized system to solve, for exampleSimulationModelorMultiModel.timesteps: Vector of desired report steps. The simulator will perform time integration untilsum(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 aInfvalue 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 passInfand no termination criterion is provided, the simulator will error.parameters=setup_parameters(model): Optional overrides the default parameters for the model.forces=nothing: Eithernothing(for no forces), a single set of forces fromsetup_forces(model)or aVectorof such forces with equal length totimesteps.restart=nothing: If an integer is provided, the simulation will attempt to restart from that step. Requires thatoutput_pathis provided here or in theconfig.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.
Jutul.simulate Method
simulate(state0, sim::JutulSimulator, timesteps; parameters = nothing, kwarg...)Simulate a set of timesteps with simulator for the given initial state0 and optionally specific parameters.
Jutul.simulator_config Method
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.
Jutul.solve_adjoint_forces Method
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.
Jutul.solve_adjoint_sensitivities! Method
solve_adjoint_sensitivities!(∇G, storage, states, state0, timesteps, G; forces)Non-allocating version of solve_adjoint_sensitivities.
Jutul.solve_adjoint_sensitivities Method
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.
Jutul.solve_numerical_sensitivities Method
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.
Jutul.solve_timestep! Method
solve_timestep!(sim, dT, forces, max_its, config; <keyword arguments>)Internal function for solving a single time-step with fixed driving forces.
Arguments
sim:Simulatorinstance.dT: time-step to be solvedforces: Driving forces for the time-stepmax_its: Maximum number of steps/Newton iterations.config: Configuration for solver (typically output fromsimulator_config).
Note: This function is exported for fine-grained simulation workflows. The general simulate interface is both easier to use and performs additional validation.
Jutul.successful_reports Function
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.
Jutul.successful_reports Function
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].
Jutul.synchronize Method
Synchronize backend after allocations.
Some backends may require notification that storage has been allocated.
sourceJutul.synchronize_cross_term_states! Method
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.
Jutul.synchronize_host_equations! Method
synchronize_host_equations!(storage, model)Queue host-evaluated equations for backend assembly after host equation updates, forces, and boundary conditions have completed.
sourceJutul.timestepping_is_done Method
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 byget_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 ifoutput_substatesis 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 withget_current_time(solve_recorder, :global).
Jutul.tpfv_geometry Function
tpfv_geometry(g)Generate two-point finite-volume geometry for a given grid, if supported.
See also TwoPointFiniteVolumeGeometry.
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.
sourceJutul.transfer_cross_term_evaluation! Method
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.
sourceJutul.transfer_csr_to_backend Method
Copy a CPU CSR matrix to the backend used by a reference CSR matrix.
sourceJutul.transfer_entities! Method
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.
Jutul.transfer_to_backend Function
transfer_to_backend(simulator, backend; kwargs...)Transfer an initialized simulator to an execution backend. Backend modules implement this interface for the contexts they support.
sourceJutul.unsafe_reinterpret Method
unsafe_reinterpret(Vt, v, n)Unsafely reinterpret v as a n length vector of value type Vt
sourceJutul.update_before_step_multimodel_backend! Method
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.
Jutul.update_cross_terms! Method
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.
Jutul.update_equations! Function
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.
sourceJutul.update_equations_and_apply_forces! Method
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.
Jutul.update_ka_amg! Function
Update an existing KernelAbstractions algebraic multigrid hierarchy.
sourceJutul.update_linearized_system! Function
update_linearized_system!(storage, model::JutulModel; <keyword arguments>)Update the linearized system with the current set of equations.
sourceJutul.update_linearized_system_equation! Method
Update a linearized system based on the values and derivatives in the equation.
sourceJutul.update_parameter_before_step! Method
update_parameter_before_step!(prm_val, prm, storage, model, dt, forces)Update parameters before time-step. Used for hysteretic parameters.
sourceJutul.update_secondary_variable! Function
Update a secondary variable. Normally autogenerated with @jutul_secondary
sourceJutul.update_state_dependents! Method
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.
sourceJutul.update_values! Method
update_values!(x, dx)Replace values (for non-Real types, direct assignment)
sourceJutul.update_values! Method
update_values!(x, dx)Replace values of x in-place by y, leaving x with the values of y and the partials of x.
Jutul.upwind Method
upwind(upw::SPU, X::AbstractArray, q)Single-point upwinding: index into array X at the upwind cell.
Jutul.upwind Method
upwind(upw::SPU, F, q)Single-point upwinding: evaluate F(cell) at the upwind cell.
Jutul.upwind Method
upwind(upw::SPU, m::AbstractArray{<:SCT.Dual}, q)Adjoint pattern tracking overload: touches both cells so the sparsity tracker sees the full dependency pattern.
sourceJutul.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.
sourceJutul.variable_scale Method
Define a "typical" numerical value for a variable to scale the linear system entries.
sourceJutul.vectorize_variables Function
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
[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.
sourceJutul.write_reports_to_mat_format Function
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.
sourceJutul.@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:
@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
endThe 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):
function get_dependencies(var::MyVarType, model)
return (:a, :b, :c)
endThe second function defines a generic version that takes in state, and automatically expands the set of dependencies into getfield calls.
function update_secondary_variable!(array_target, var::MyVarType, model, state, ix)
some_fn!(array_target, var, model, state.a, state.b, state.c, ix)
endNote that the input names of arguments 4 to end-1 matter, as these will be fetched from state, exactly as written.
sourceJutul.@si_str Macro
si"kg/meter"A string macro to convert unit strings to SI conversion factors. Convenience function for si_unit.
Examples
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.2Jutul.ConvergenceMonitors.ConvergenceMonitorRelaxation Method
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.
Jutul.ConvergenceMonitors.compute_contraction_factor Method
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.
sourceJutul.ConvergenceMonitors.compute_distance Method
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.
sourceJutul.ConvergenceMonitors.flatten_dict Function
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.
Jutul.ConvergenceMonitors.get_model_residuals Method
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
residuals[equation_type][equation][norm] = res/tolJutul.ConvergenceMonitors.get_multimodel_residuals Method
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
residuals[model][equation_type][equation][norm] = res/tolJutul.ConvergenceMonitors.make_report Method
make_report(θ, θ_target, oscillation, status)Utility for generating a report from the convergence monitor.
sourceJutul.ConvergenceMonitors.nonconverged_equations Method
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.
sourceJutul.ConvergenceMonitors.oscillation Function
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.
sourceJutul.ConvergenceMonitors.print_convergence_status Method
print_convergence_status(cc::ConvergenceMonitorCuttingCriterion, it, it0)Utility for printing the status of the convergence monitor.
sourceJutul.ConvergenceMonitors.process_name Method
process_name(name)Process a names to be suibale as dictionary keys.
sourceJutul.ConvergenceMonitors.reset! Method
reset!(cc::ConvergenceMonitorCuttingCriterion, template, max_iter)Utility for resetting convergence monitor cutting criterion.
sourceJutul.ConvergenceMonitors.scaled_residual_norm Method
scaled_residual_norm(report)Compute distance to convergence as the residual norm of the equations scaled by their respective tolerances.
sourceJutul.ConvergenceMonitors.set_convergence_monitor_cutting_criterion! Method
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).
Jutul.ConvergenceMonitors.set_convergence_monitor_relaxation! Method
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!.
Jutul.cutting_criterion Method
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.
sourceJutul.select_nonlinear_relaxation_model Method
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.
sourceJutul.CutCellMeshes.PlaneCut Type
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.
sourceJutul.CutCellMeshes.PolygonalSurface Type
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.
Jutul.CutCellMeshes._add_face_or_bnd! Method
_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.
Jutul.CutCellMeshes._approx_cell_centroid Method
_approx_cell_centroid(mesh, cell)Compute an approximate cell centroid by averaging the centroids of all its faces (interior + boundary).
sourceJutul.CutCellMeshes._build_tangent_basis Method
_build_tangent_basis(normal)Build an orthonormal (u, v) basis in the plane perpendicular to normal.
Jutul.CutCellMeshes._cell_centroid_from_nodes Method
_cell_centroid_from_nodes(mesh, cell)Approximate centroid of a cell from all its unique node coordinates.
sourceJutul.CutCellMeshes._cell_centroid_from_nodes_b Method
_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.
sourceJutul.CutCellMeshes._chain_boundary_edges Method
_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.
sourceJutul.CutCellMeshes._compute_residual_polygons Method
_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.
sourceJutul.CutCellMeshes._deduplicate_face_nodes Method
_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.
sourceJutul.CutCellMeshes._ensure_ccw_2d Method
_ensure_ccw_2d(poly)Ensure a 2D polygon has counter-clockwise winding order. Uses the signed area (shoelace formula).
sourceJutul.CutCellMeshes._expand_polygon Method
_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.
Jutul.CutCellMeshes._fix_boundary_orientation! Method
_fix_boundary_orientation!(nodes, node_points, cell, mesh)Ensure boundary face normal points outward (away from the cell).
sourceJutul.CutCellMeshes._fix_interior_orientation! Method
_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.
Jutul.CutCellMeshes._is_convex_polygon Method
_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).
Jutul.CutCellMeshes._merge_face_group! Method
_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.
sourceJutul.CutCellMeshes._point_in_face_polygon Method
_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.
sourceJutul.CutCellMeshes._point_inside_mesh Method
_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.
sourceJutul.CutCellMeshes._polygon_area_2d Method
_polygon_area_2d(poly)Compute the area of a 2D polygon using the shoelace formula.
sourceJutul.CutCellMeshes._polygon_intersection_2d Method
_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.
sourceJutul.CutCellMeshes._polygon_normal_from_pts Method
_polygon_normal_from_pts(pts)Compute unit normal of a planar polygon from 3D points using Newell's method.
sourceJutul.CutCellMeshes._rebuild_mesh Method
_rebuild_mesh(mesh, node_points, face_nodes, face_neighbors, bnd_nodes, bnd_cells)Build a new UnstructuredMesh from merged face data.
sourceJutul.CutCellMeshes._rebuild_mesh_with_nodes Method
_rebuild_mesh_with_nodes(mesh, new_nodes)Create a new UnstructuredMesh identical to mesh but with new_nodes as node points.
Jutul.CutCellMeshes._remove_cells Method
_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.
Jutul.CutCellMeshes._split_polygon_by_line_2d Method
_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.
sourceJutul.CutCellMeshes._subtract_convex_2d Method
_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.
Jutul.CutCellMeshes.build_cut_mesh Method
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.
Jutul.CutCellMeshes.cell_any_node_in_bounding_polygon Method
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.
Jutul.CutCellMeshes.cell_bounding_box Method
cell_bounding_box(mesh, cell)Compute the axis-aligned bounding box of a cell, returns (min_pt, max_pt).
sourceJutul.CutCellMeshes.cell_centroid_in_bounding_polygon Method
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.
sourceJutul.CutCellMeshes.cell_nodes Method
cell_nodes(mesh, cell)Get all unique node indices for a cell.
sourceJutul.CutCellMeshes.classify_cell Method
classify_cell(mesh, cell, plane; tol)Classify a cell with respect to a cutting plane. Returns:
:positiveif all nodes are on positive side (or on plane):negativeif all nodes are on negative side (or on plane):cutif nodes span both sides
Jutul.CutCellMeshes.classify_point Method
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.
Jutul.CutCellMeshes.clip_face_by_plane Method
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}}.
sourceJutul.CutCellMeshes.cut_and_displace_mesh Method
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:
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:
A uniform shift along
t₁(up-down):constant · t₁A uniform shift along
t₂(left-right):shift_lr · t₂An in-plane rotation by
angle(radians) around the plane normaln, pivoting atplane.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 alongt₁(up-down direction).shift_lr::Real = 0.0: Uniform shift alongt₂(left-right direction).angle::Real = 0.0: In-plane rotation (radians) around the plane normaln, pivoting atplane.point.side::Symbol = :positive: Which side to shift (:positiveor: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 tocut_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 inputmesh(composed throughcut_meshandextract_submesh).:cell_side– per cell,:positiveor:negativeindicating 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.
Jutul.CutCellMeshes.cut_mesh Method
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 3DUnstructuredMeshplaneorsurface: The cutting constraintmin_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. Ifnothing(default), all intersected cells are cut.clip_to_polygon: Iftrueandbounding_polygonis provided, cells that are partially inside the bounding polygon (any node projects inside) will also be cut. Default isfalse.extra_out: Iftrue, return a tuple(mesh, info_dict)whereinfo_dictcontains::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.
Jutul.CutCellMeshes.cut_mesh Method
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 3DUnstructuredMeshcuts: Vector ofPlaneCutorPolygonalSurfaceobjectsextra_out: Iftrue, return a tuple(mesh, info_dict)whereinfo_dictcontains::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 whereinfo_dict[:cut_no][f] = nif facefwas generated as a result of cut numbern, 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.
Jutul.CutCellMeshes.cut_mesh Method
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).
Jutul.CutCellMeshes.dominant_side Method
dominant_side(fnodes, node_class)Determine which side of the plane a face is on.
sourceJutul.CutCellMeshes.edge_plane_intersection Method
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.
sourceJutul.CutCellMeshes.embed_mesh Method
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: Iftrue, return(mesh, info)whereinfois aDict{Symbol, Any}containing::cell_origin:Vector{Symbol}—:mesh_aor:mesh_bfor 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 tocut_meshfor 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.
Jutul.CutCellMeshes.glue_mesh Method
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 withinterface_normal, only boundary faces whose centroids lie withincoplanar_tolof 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 (seeinterface_point).extra_out::Bool = false: Iftrue, return(mesh, info)whereinfois aDictwith::cell_index_a– maps new cell indices to original cell indices inmesh_a(0 for cells frommesh_b).:cell_index_b– maps new cell indices to original cell indices inmesh_b(0 for cells frommesh_a).:face_index_a– maps new interior face to original face inmesh_a(0 otherwise).:face_index_b– maps new interior face to original face inmesh_b(0 otherwise).:boundary_face_index_a– maps new boundary face to original boundary face inmesh_a(0 otherwise).:boundary_face_index_b– maps new boundary face to original boundary face inmesh_b(0 otherwise).:new_faces– indices of newly created interior faces from gluing.
Returns a new UnstructuredMesh, or (UnstructuredMesh, Dict) when extra_out=true.
Jutul.CutCellMeshes.merge_coplanar_faces Method
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.
Jutul.CutCellMeshes.order_polygon_points Method
order_polygon_points(pts, normal)Order polygon points counter-clockwise when viewed from the direction of normal.
Jutul.CutCellMeshes.point_in_polygon_2d Method
point_in_polygon_2d(pt, polygon)Check whether a 2D point lies inside a 2D polygon using the ray-casting algorithm.
sourceJutul.CutCellMeshes.polygon_area Method
polygon_area(poly)Compute the area of a 3D planar polygon.
sourceJutul.CutCellMeshes.polygon_centroid Method
polygon_centroid(poly)Compute the centroid of a 3D planar polygon.
sourceJutul.CutCellMeshes.polygon_normal Method
polygon_normal(poly)Compute the unit normal of a planar polygon from its vertices using Newell's method.
sourceJutul.CutCellMeshes.project_polygon_to_2d Method
project_polygon_to_2d(polygon, plane)Project a 3D bounding polygon onto the cutting plane, returning 2D coordinates.
sourceJutul.CutCellMeshes.project_to_plane Method
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.
sourceJutul.CutCellMeshes.signed_distance Method
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.
Jutul.EmbeddedMeshes Module
EmbeddedMeshesA 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.
sourceJutul.EmbeddedMeshes.EmbeddedMesh Type
EmbeddedMesh <: FiniteVolumeMeshA 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 representationparent_faces::Vector{Int}: Indices of the parent mesh faces that make up the embedded meshintersection_neighbors::Vector{Vector{Int}}: Embedded mesh cells grouped per intersectionintersection_faces::Vector{Vector{Int}}: Face indices per intersection, aligned withintersection_neighbors. For:remove, these are boundary face indices; for:star_deltaand:keep, these are internal face indices.intersection_cells::Vector{Int}: Embedded mesh cell indices created for kept intersections
Jutul.EmbeddedMeshes.EmbeddedMesh Method
EmbeddedMesh(mesh::UnstructuredMesh, faces)Construct an embedded mesh from selected faces of an unstructured mesh.
Arguments
mesh::UnstructuredMesh: Parent mesh containing the facesfaces: 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.
Jutul.EmbeddedMeshes.make_mesh_from_faces Method
make_mesh_from_faces(mesh, faces)Helper for EmbeddedMesh constructor.
sourceJutul.compute_half_face_trans Method
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.
sourceJutul.KAPreconditioners.AMGHierarchy Type
Reusable AMG hierarchy and Krylov-compatible left preconditioner.
sourceJutul.KAPreconditioners.AMGOptions Type
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.
Jutul.KAPreconditioners.BackendBufferPrefix Type
Logical prefix retaining the full backend allocation for later reuse.
sourceJutul.KAPreconditioners.ClassicalInterpolation Type
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.
Jutul.KAPreconditioners.ConstantInterpolation Type
Piecewise-constant interpolation for unsmoothed aggregation.
sourceJutul.KAPreconditioners.DILU Type
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.
sourceJutul.KAPreconditioners.DenseLUState Type
Backend-native dense LU factorization for a coarse grid.
sourceJutul.KAPreconditioners.ExtendedIInterpolation Type
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.
Jutul.KAPreconditioners.GalerkinMap Type
Triples grouped by coarse nonzero; enables one kernel item per output.
sourceJutul.KAPreconditioners.GaussSeidel Type
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.
sourceJutul.KAPreconditioners.HostLUState Type
Standard host LU fallback for backends without a native dense LU overload.
sourceJutul.KAPreconditioners.ILU0 Type
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.
sourceJutul.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.
Jutul.KAPreconditioners.RugeStuben Type
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.
sourceJutul.KAPreconditioners.SPAI0 Type
Sparse approximate-inverse relaxation with the matrix sparsity pattern.
sourceJutul.KAPreconditioners.SetupWorkspace Type
Host scratch and staging storage retained across symbolic rebuilds.
sourceJutul.KAPreconditioners.TwoStageExtendedIInterpolation Type
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.
Jutul.KAPreconditioners.VendorILU Type
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.
sourceJutul.KAPreconditioners.apply! Method
Apply the hierarchy as a linear preconditioner (x is cleared first).
Jutul.KAPreconditioners.buffer_prefix Method
Use the first n entries of a backend buffer without reallocating it.
Jutul.KAPreconditioners.copy_reusing Method
Copy into an old backend allocation when its type and capacity permit.
sourceJutul.KAPreconditioners.csr_matrix Method
Convert Julia CSC storage to Jutul's CSR representation.
sourceJutul.KAPreconditioners.cycle! Method
Apply one cycle to the current iterate without clearing it.
sourceJutul.KAPreconditioners.grown_backend_capacity Method
Capacity used when an existing backend buffer has to grow.
sourceJutul.KAPreconditioners.hmis_rs_first_pass! Function
HYPRE-compatible RS first pass shared by classical RS and HMIS.
sourceJutul.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.
sourceJutul.KAPreconditioners.repair_aggressive_split! Method
Promote uncovered F points so aggressive interpolation has no empty rows.
sourceJutul.KAPreconditioners.resetup_amg! Function
resetup_amg!(H, A, reuse=:operators)Refresh a hierarchy for new coefficients.
:operatorspreserves C/F splits, interpolation values, sparse patterns, and every array; Galerkin operators and all smoother coefficients are recomputed.:sparsityadditionally recomputes the retained interpolation weights in place using the configured interpolation method.:memoryrecomputes 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_operatorsand:partial_sparsityretain the firstn_levels_partial_keeplevels (default 3), updating them as in:operatorsand: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.:noneis a completely fresh setup and is useful as a reference baseline.
The first two modes perform no hierarchy-array allocation.
sourceJutul.KAPreconditioners.reusable_buffer Method
Return the allocation backing a contiguous prefix used for reuse.
sourceJutul.KAPreconditioners.ruge_stuben_second_pass! Function
Enforce the classical RS common-C-neighbor condition for strong F-F edges.
sourceJutul.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.
Jutul.KAPreconditioners.setup_amg Method
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).
Jutul.KAPreconditioners.setup_smoother Function
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.
Jutul.KAPreconditioners.smooth! Function
Apply one or more stationary smoothing steps to the current iterate x.
Jutul.KAPreconditioners.solve! Method
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.
Jutul.KAPreconditioners.update_smoother! Function
Update a smoother for new coefficients with the same sparsity pattern.
sourceJutul.KernelExecution.KernelAbstractionsContext Type
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.
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.
Jutul.transfer_to_backend Method
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.