licenses
sequencelengths 1
3
| version
stringclasses 677
values | tree_hash
stringlengths 40
40
| path
stringclasses 1
value | type
stringclasses 2
values | size
stringlengths 2
8
| text
stringlengths 25
67.1M
| package_name
stringlengths 2
41
| repo
stringlengths 33
86
|
---|---|---|---|---|---|---|---|---|
[
"MIT"
] | 0.6.30 | d1abcd4b0b02e036f6a7630f6b563b576e9a8561 | code | 867 | using Revise
using Dates
using ElectroPhysiology
using PhysiologyAnalysis
using Pkg; Pkg.activate("test")
#%% When we get to the dataframe creation we can fill in details here
using XLSX, DataFrames, Query
#%% Open all dates for the imaging files
img_dir = raw"G:\Data\Calcium Imaging"
patch_dir = raw"G:\Data\Patching"
filename = raw"G:\Data\Analysis\data_analysis.xlsx"
#Don't often need to do this (eventually we need to add an update button)
dataset = create2PDataSheet(img_dir, patch_dir; verbose = true)
dataset = IV_analysis!(dataset)
dataset = pair_experiments!(dataset)
save2PDataSheet(filename, dataset)
#You can use this to open the datasheet after it has been saved
dataset = open2PDataSheet(filename)
dataset["ABF Files"].filename
all_datasheet = dataset["All Files"]
img_datasheet = dataset["TIF Files"]
patch_datasheet = dataset["ABF Files"] | PhysiologyAnalysis | https://github.com/mattar13/PhysiologyAnalysis.jl.git |
|
[
"MIT"
] | 0.6.30 | d1abcd4b0b02e036f6a7630f6b563b576e9a8561 | code | 1611 | #%% Load Packages _________________________________________________________________________#
using Pkg; Pkg.activate(".")
using ElectroPhysiology, PhysiologyAnalysis
Pkg.activate("test")
using PhysiologyPlotting, GLMakie
import GLMakie.Axis
using FileIO, ImageView, Images
using Statistics
#=[Point to filenames]=========================================================#
data_fn = "D:/Data/Calcium Imaging/2024_02_12_WT/Cell1/cell1001.tif"
save_fn = "D:/Data/Analysis/2024_02_12_WTCell1_2P.mp4"
#[Open and prepare the data]______________________________________________________________#
fps = 1.45
data = readImage(data_fn);
px_x, px_y = data.HeaderDict["framesize"]
xlims = data.HeaderDict["xrng"]; #Extract the x domain
ylims = data.HeaderDict["yrng"]; #Extract the y domain
t = data.t #Extract the t domain
#Every other frame is a different channel
t = t[1:2:end]
mov = get_all_frames(data)[:,:,1:2:end]; #get all frames as a 3D array
fluo = mean(mov, dims = (1,2))[1,1,:]
zproj = maximum(mov, dims = 3)[:,:,1] #Can we save this directly?
# Plot the data _________________________________________________________________________#
fig = Figure(size = (500, 600))
ax1 = Axis(fig[1,1])
ax2 = Axis(fig[2,1])
rowsize!(fig.layout, 2, Relative(1/4))
hm1 = heatmap!(ax1, xlims, ylims, zproj, colormap = Reverse(:speed), colorrange = (0.0, 0.01))
lines!(ax2, t, fluo)
ticker = vlines!(ax2, [0.0])
# Animate the Imaging video ___________________________________________________________#
record(fig, save_fn, 2:length(t), framerate = fps*10) do i
println(i)
hm1[3] = mov[:,:,i]
ticker[1] = [t[i]]
end | PhysiologyAnalysis | https://github.com/mattar13/PhysiologyAnalysis.jl.git |
|
[
"MIT"
] | 0.6.30 | d1abcd4b0b02e036f6a7630f6b563b576e9a8561 | code | 2610 | #%% Load Packages _________________________________________________________________________#
using Pkg; Pkg.activate(".")
using ElectroPhysiology, PhysiologyAnalysis
Pkg.activate("test")
using GLMakie
import GLMakie.Axis
using FileIO, ImageView, Images
using Statistics
save_fn = "D:/Data/Analysis/2024_02_12_WTCell1_IC2P.mp4"
#%%=[Point to this for data from cell 1]=========================================================#
data2P_fn = "D:/Data/Calcium Imaging/2024_02_12_WT/Cell1/cell1001.tif"
dataIC_fn = "D:/Data/Patching/2024_02_12_WT/Cell1/24212004.abf"
#%%=[Point to this for data from cell 3]=========================================================#
#data2P_fn = "D:/Data/Calcium Imaging/2024_03_11_VglutGC6/Cell3/freeRec001.tif"
#dataIC_fn = "D:/Data/Patching/2024_03_11_VglutGC6/Cell3/24311015.abf"
#%%=[Open and prepare 2P data]=========================================================#
fps = 1.45
data2P = readImage(data2P_fn; sampling_rate = fps, chName = "525 nm");
px_x, px_y = data2P.HeaderDict["framesize"]
xlims = data2P.HeaderDict["xrng"]; #Extract the x domain
ylims = data2P.HeaderDict["yrng"]; #Extract the y domain
t = data2P.t #Extract the t domain
t = t[1:2:end] #Cell 1 only needs uncommented (I recorded with both green and red. Silly me)
mov = get_all_frames(data2P)[:,:,1:2:end] #get all frames as a 3D array
fluo = mean(mov, dims = (1,2))[1,1,:]
zproj = maximum(mov, dims = 3)[:,:,1] #Can we save this directly?
# Open and prepare the data______________________________________________________________#
dataIC = readABF(dataIC_fn);
downsample!(dataIC, 1000.0); #Go through these functions much more extensively
# Create the plot_______________________________________________________________________#
fig = Figure(size = (1000, 500))
ax1 = Axis(fig[1:2,1])
ax2 = Axis(fig[1,2], title = "Sample rate = $fps hz", ylabel = "Fluorescence ($(data2P.chUnits[1]))")
ax3 = Axis(fig[2,2], title = "Sample rate = $(1/dataIC.dt) hz", ylabel = "Membrane Voltage ($(dataIC.chUnits[1]))")
hm1 = heatmap!(ax1, xlims, ylims, zproj, colormap = Reverse(:speed), colorrange = (0.001, 0.01))
lines!(ax2, t, fluo, color = :green)
experimentplot!(ax3, dataIC, channel = 1)
ticker1 = vlines!(ax2, [0.0], color = :black)
ticker2 = vlines!(ax3, [0.0], color = :black)
Colorbar(fig[3, 1], hm1, vertical = false, label = "Fluorescence (px)")
# Animate the data ___________________________________________________________________#
record(fig, save_fn, enumerate(t), framerate = fps*10) do (i, t)
println(t)
hm1[3] = mov[:,:,i]
ticker1[1] = [t]
ticker2[1] = [t]
end
display(fig) | PhysiologyAnalysis | https://github.com/mattar13/PhysiologyAnalysis.jl.git |
|
[
"MIT"
] | 0.6.30 | d1abcd4b0b02e036f6a7630f6b563b576e9a8561 | code | 1154 | #=[Import packages]============================================================#
using Pkg; Pkg.activate(".")
using ElectroPhysiology, PhysiologyAnalysis
using Statistics
Pkg.activate("test")
using PhysiologyPlotting
using GLMakie
import PhysiologyPlotting.experimentplot
#=[Point to filenames]=========================================================#
data_fn = "D:/Data/Patching/2024_02_12_WT/Cell1/24212004.abf"
save_fn = "D:/Data/Analysis/2024_02_12_WT_Cell1_IC.png"
#=[Open the data]==============================================================#
data = readABF(data_fn);
downsample!(data, 1000.0); #Go through these functions much more extensively
data.HeaderDict
#=[Plot data]==================================================================#
fig, axs = experimentplot(data)
save(save_fn, fig)
#=[Do some analysis]===========================================================#
threshold = calculate_threshold(data, Z = 2)
timestamps = get_timestamps(data, Z = 2)
#durations, intervals = extract_interval(timestamps[1,1])
# Eventually need to figure this out, but not today
# max_interval_algorithim(timestamps[1,1], SPBmin = 1, verbose = true)
| PhysiologyAnalysis | https://github.com/mattar13/PhysiologyAnalysis.jl.git |
|
[
"MIT"
] | 0.6.30 | d1abcd4b0b02e036f6a7630f6b563b576e9a8561 | docs | 684 | # PhysiologyAnalysis.jl
[![License][license-img]](LICENSE)
[![][docs-stable-img]][docs-stable-url]
[![][GHA-img]][GHA-url]
[license-img]: http://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square
[docs-stable-img]: https://img.shields.io/badge/docs-stable-blue.svg
[docs-stable-url]: https://mattar13.github.io/ElectroPhysiology.jl/dev
[GHA-img]: https://github.com/mattar13/PhysiologyAnalysis.jl/workflows/CI/badge.svg
[GHA-url]: https://github.com/mattar13/PhysiologyAnalysis.jl/actions?query=workflows/CI
This is the analysis toolkit for the larger package ElectroPhysiology.jl
see documentation [here](https://github.com/mattar13/ElectroPhysiology.jl)
| PhysiologyAnalysis | https://github.com/mattar13/PhysiologyAnalysis.jl.git |
|
[
"MIT"
] | 0.1.0 | e203f036dfa6aabe0dee0f760dc752245f2d9887 | code | 295 | #!/usr/bin/env bash
#=
exec julia --project="$(realpath $(dirname $0))" --color=yes --startup-file=no -e "include(popfirst!(ARGS))" \
"${BASH_SOURCE[0]}" "$@"
=#
module EyeTrackingUtils
export make_clean_data
include(joinpath(dirname(@__FILE__), "prep.jl"))
end # end module
| EyeTrackingUtils | https://github.com/jakewilliami/EyeTrackingUtils.jl.git |
|
[
"MIT"
] | 0.1.0 | e203f036dfa6aabe0dee0f760dc752245f2d9887 | code | 5832 | #!/usr/bin/env bash
#=
exec julia --project="$(realpath $(dirname $0))" --color=yes --startup-file=no -e "include(popfirst!(ARGS))" \
"${BASH_SOURCE[0]}" "$@"
=#
using DataFrames
using Query
using Lazy: @> # or using DataConvenience: @>, but Lazy exports groupby
using DataFramesMeta: @where
using Statistics: mean
_isbool(x)::Bool = isequal(x, true) || isequal(x, false) ? true : false
_iscategorical(df::DataFrame, x)::Bool = isa(df.x, CategoricalArray)
function _islogical(x)::Bool
if _isbool(x)
return true
elseif isnumeric(x)
else
throw(error("""
One of your columns ($(col)) could not be converted
to the correct format (Bool). Please do so manually.
"""))
end
end
_asnumeric(x) = parse(Float64, x)
_aslogical(x) = parse(Bool, x)
function _check_then_convert(
df::DataFrame,
x,
check_function::Function,
convert_function::Function,
colname::Union{String, Symbol}
)
if ! check_function(df, x)
println("Converting $(colname) to proper type...")
x = convert_function(df, Symbol(x))
println("...done")
end
if colname == "Trackloss" && any(isnothing(x))
@warn "Found NAs in trackloss column. These will be treated as TRACKLOSS = false."
x = isnothing(x) ? false : x
end
return x
end
function _check_then_convert(
x,
check_function::Function,
convert_function::Function,
colname::Union{String, Symbol}
)
if ! check_function(x)
println("Converting $(colname) to proper type...")
x = convert_function(x)
println("...done")
end
if colname == "Trackloss" && any(isnothing(x))
@warn "Found NAs in trackloss column. These will be treated as TRACKLOSS = false."
x = isnothing(x) ? false : x
end
return x
end
function make_clean_data(
data,
participant_column,
trackloss_column,
time_column,
trial_column,
aoi_columns,
treat_non_aoi_looks_as_missing;
item_columns = nothing
)
## Data options:
data_options = Dict{Symbol, Any}(
:participant_column => participant_column,
:trackloss_column => trackloss_column,
:time_column => time_column,
:trial_column => trial_column,
:item_columns => item_columns,
:aoi_columns => aoi_columns,
:treat_non_looks_as_missing => treat_non_looks_as_missing
)
## Check for reserved column name:
if data_options[:time_column] == "Time"
throw(error("""
We apologise for the invonvenience, but your `time_column` cannot be called 'Time'.
This name is a reserved name that EyeTrackingUtils uses. Please rename.
"""))
end
if "Time" ∈ names(data)
@warn """Your dataset has a column called 'time', but this column
is reserved for EyeTrackingUtils. Will rename to 'TimeOriginal'...
"""
rename!(data, Dict(:Time => "TimeOriginal"))
end
## Verify columns:
out = copy(data)
col_type_converter = Dict{Symbol, Function}(
:participant_column => x -> _check_then_convert(data, x, _iscategorical, categorical!, "Participants"),
:time_column => x -> _check_then_convert(data, x, isnumeric, _asnumeric, "Time"),
:trial_column => x -> _check_then_convert(data, x, _iscategorical, categorical!, "Trial"),
:trackloss_column => x -> _check_then_convert(x, _isbool, _aslogical, "Trackloss"),
:item_columns => x -> _check_then_convert(data, x, _iscategorical, categorical!, "Item"),
:aoi_columns => x -> _check_then_convert(x, _isbool, _aslogical, "AOI")
)
for col in keys(col_type_converter)
for i in 1:length(data_options[col])
if isnothing(out.data_options[Symbol(col)][i])
throw(error("Data are missing: $(col)"))
end
out.data_options = col_type_converter[Symbol(col)](out.data_options[Symbol(col)][i])
end
end
## Deal with non-AOI looks:
if treat_non_aoi_looks_as_missing
# any_aoi = sum(, dims=2) > 0 ? # second dimension is the sum of the rows
any_aoi = sum.(skipmissing.(eachrow(out.data_options[Symbol(aoi_columns)]))) > 0
out.data_options[Symbol(trackloss_column)][!any_aoi] = true
end
## Set All AOI rows with trackloss to NA:
# this ensures that any calculations of proportion-looking will not include trackloss in the denominator
for aoi in data_options[Symbol(aoi_columns)]
out.aoi[out.data_options[Symbol(trackloss_column)]] = missing # or nothing?
end
# Check for duplicate values of Trial column within Participants
duplicates = @> out begin
groupby([:participant_column, :trial_column, :time_column])
combine(nrow => :n)
@where :n .> 1
end
if nrow(duplicates) > 0
println(duplicates)
throw(error("""
It appears that `trial_column` is not unique within participants. See above for a summary
of which participant*trials have duplicate timestamps. EyeTrackingUtils requires that each participant
only have a single trial with the same `trial_column` value. If you repeated items in your experiment,
use `item_column` to specify the name of the item, and set `trial_column` to a unique value
(e.g., the trial index).
"""))
end
out = @> out begin
groupby([:participant_column, :trial_column, :time_column])
end
end
struct eR_data_eR_df
out::DataFrame
eR
end
## Assign attribute:
# class(out) <- c("eyetrackingR_data", "eyetrackingR_df", class(out))
# attr(out, "eyetrackingR") <- list(data_options = data_options)
# return(out)
| EyeTrackingUtils | https://github.com/jakewilliami/EyeTrackingUtils.jl.git |
|
[
"MIT"
] | 0.1.0 | e203f036dfa6aabe0dee0f760dc752245f2d9887 | code | 179 | #!/usr/bin/env bash
#=
exec julia --project="$(realpath $(dirname $0))" --color=yes --startup-file=no -e "include(popfirst!(ARGS))" \
"${BASH_SOURCE[0]}" "$@"
=#
| EyeTrackingUtils | https://github.com/jakewilliami/EyeTrackingUtils.jl.git |
|
[
"MIT"
] | 0.1.0 | e203f036dfa6aabe0dee0f760dc752245f2d9887 | code | 352 | #!/usr/bin/env bash
#=
exec julia --project="$(realpath $(dirname $0))" --color=yes --startup-file=no -e "include(popfirst!(ARGS))" \
"${BASH_SOURCE[0]}" "$@"
=#
include(joinpath(dirname(dirname(@__FILE__)), "src", "EyeTracking.jl"))
using .EyeTracking
using Test
@testset "EyeTracking.jl" begin
# Write your tests here.
end
| EyeTrackingUtils | https://github.com/jakewilliami/EyeTrackingUtils.jl.git |
|
[
"MIT"
] | 0.1.0 | e203f036dfa6aabe0dee0f760dc752245f2d9887 | docs | 3022 | <h1 align="center">
Eye Tracking Utils
</h1>
[![Code Style: Blue][code-style-img]][code-style-url] [](https://travis-ci.com/jakewilliami/EyeTracking.jl) 
## Note
**THIS PACKAGE IS UNDER DEVELOPMENT AND IS NOT READY FOR USE**
Though we have hopes for this repository to be a registered package in the future, it is only for testing purposes, to be used in parallel to other tools, at this point in time. This project is currently worked on by [Alexandros Tantos](https://github.com/atantos), [Jake Ireland](https://github.com/jakewilliami), and others.
It is preferrable that you have `coreutils` (or something similar, giving you access to `realpath`) installed for the project path to be interpretted by the shebang correctly.
## Introduction
This is a Julia implementation of a robust data-preparation and -analysis package using data from eye tracking experiments. This package is designed modelling an R package called [`eyetrackingR`](https://github.com/jwdink/eyetrackingR). This package is not to be confused with the "EyeTracking.jl" package (at time of writing; October, 2020), which [seems to be a GUI-style experimental interface](https://github.com/dandandai/EyeTracking.jl/) (at first glance, perhaps similar to [PyGaze](https://github.com/esdalmaijer/PyGaze)).
## Installation and Set Up
Ensure you `cd` into the `EyeTrackingUtils.jl` directory after `clone`ing it, and run
```bash
julia -E 'import Pkg; etu_home = dirname(@__FILE__); Pkg.activate(etu_home), Pkg.instantiate()'
```
To obtain any dependencies. This step will not be necessary once this package is registered.
## How it works
This package has two main steps in the workflow, whose second step has three paths. This workflow is drawn from [`eyetrackingR`](http://www.eyetracking-r.com/workflow).
1. **Data cleaning** — obtain data and information about data from various eye-tracking sources (this step should be extremely robust), and puts data into a standardised format for analyses.
2. **Analyses** —:
		 a) *Overall Looking*;
		 b) *Onset-Contingent*;
		 c) *Time-Course of Looking*.
## Timeline of Progression
- [cdf151e](https://github.com/jakewilliami/EyeTracking.jl/commit/cdf151e) — Began working on the package.
## To Do
- Summarise ([Query.jl?](https://github.com/queryverse/Query.jl))
- Read from [EDF](https://github.com/beacon-biosignals/EDF.jl) file.
## A Note on running on BSD:
The default JuliaPlots backend `GR` does not provide binaries for FreeBSD. [Here's how you can build it from source.](https://github.com/jheinen/GR.jl/issues/268#issuecomment-584389111). That said, `StatsPlots` is only a dependency for an example, and not for the main package.
[code-style-img]: https://img.shields.io/badge/code%20style-blue-4495d1.svg
[code-style-url]: https://github.com/invenia/BlueStyle
| EyeTrackingUtils | https://github.com/jakewilliami/EyeTrackingUtils.jl.git |
|
[
"MIT"
] | 0.3.5 | 71e40b5d9aaa5749942cb2183fb5add45f146ff2 | code | 12988 | module CMPFit
using Printf
using Pkg, Pkg.Artifacts
function binary_lib_path()
for file in readdir(artifact"libmpfit")
if !isnothing(match(r"^libmpfit", file))
return joinpath(artifact"libmpfit", file)
end
end
end
const libmpfit = binary_lib_path()
# Exported symbols
export cmpfit
######################################################################
# Private definitions
######################################################################
#---------------------------------------------------------------------
"Parameter info strutcture"
mutable struct Parinfo
fixed::Cint # 1 = fixed; 0 = free
limited::NTuple{2, Cint} # 1 = low/upper limit; 0 = no limit
limits::NTuple{2, Cdouble} # lower/upper limit boundary value
char::Ptr{Cchar} # Name of parameter, or 0 for none
step::Cdouble # Step size for finite difference
relstep::Cdouble # Relative step size for finite difference
side::Cint #= Sidedness of finite difference derivative
0 - one-sided derivative computed automatically
1 - one-sided derivative (f(x+h) - f(x) )/h
-1 - one-sided derivative (f(x) - f(x-h))/h
2 - two-sided derivative (f(x+h) - f(x-h))/(2*h)
3 - user-computed analytical derivatives
=#
deriv_debug::Cint #= Derivative debug mode: 1 = Yes; 0 = No;
If yes, compute both analytical and numerical
derivatives and print them to the console for
comparison.
NOTE: when debugging, do *not* set side = 3,
but rather to the kind of numerical derivative
you want to compare the user-analytical one to
(0, 1, -1, or 2).
=#
deriv_reltol::Cdouble # Relative tolerance for derivative debug printout
deriv_abstol::Cdouble # Absolute tolerance for derivative debug printout
"Create an empty `Parinfo` structure."
Parinfo() = new(0, (0, 0), (0, 0), 0, 0, 0, 0, 0, 0, 0)
end
#---------------------------------------------------------------------
"Create a `Vector{Parinfo}` of empty `Parinfo` structures, whose length is given by `npar`."
function Parinfo(npar::Int)
return [Parinfo() for i in 1:npar]
end
#---------------------------------------------------------------------
#Define sibling structure with toggled mutability
struct imm_Parinfo
fixed::Cint
limited::NTuple{2, Cint}
limits::NTuple{2, Cdouble}
char::Ptr{Cchar}
step::Cdouble
relstep::Cdouble
side::Cint
deriv_debug::Cint
deriv_reltol::Cdouble
deriv_abstol::Cdouble
end
function imm_Parinfo(p::Parinfo)
imm_Parinfo(ntuple((i->begin
getfield(p, i)
end), nfields(p))...)
end
#---------------------------------------------------------------------
"CMPFit config structure"
mutable struct Config
ftol::Cdouble # Relative chi-square convergence criterium Default: 1e-10
xtol::Cdouble # Relative parameter convergence criterium Default: 1e-10
gtol::Cdouble # Orthogonality convergence criterium Default: 1e-10
epsfcn::Cdouble # Finite derivative step size Default: eps()
stepfactor::Cdouble # Initial step bound Default: 100.0
covtol::Cdouble # Range tolerance for covariance calculation Default: 1e-14
maxiter::Cint # Maximum number of iterations. If maxiter == MP_NO_ITER,
# then basic error checking is done, and parameter
# errors/covariances are estimated based on input
# parameter values, but no fitting iterations are done.
# Default: 200
maxfev::Cint; # Maximum number of function evaluations, or 0 for no limit
# Default: 0 (no limit)
nprint::Cint; # Default: 1
douserscale::Cint # Scale variables by user values?
# 1 = yes, user scale values in diag;
# 0 = no, variables scaled internally (Default)
nofinitecheck::Cint # Disable check for infinite quantities from user?
# 0 = do not perform check (Default)
# 1 = perform check
iterproc::Cint # Placeholder pointer - must set to 0
Config() = new(1e-10, 1e-10, 1e-10, eps(), 100, 1e-14, 200, 0, 1, 0, 0, 0)
end
#---------------------------------------------------------------------
"CMPFit return structure (C side)."
mutable struct Result_C
bestnorm::Cdouble # Final chi^2
orignorm::Cdouble # Starting value of chi^2
niter::Cint # Number of iterations
nfev::Cint # Number of function evaluations
status::Cint # Fitting status code
npar::Cint # Total number of parameters
nfree::Cint # Number of free parameters
npegged::Cint # Number of pegged parameters
nfunc::Cint # Number of residuals (= num. of data points)
resid::Ptr{Cdouble} # Final residuals nfunc-vector, or 0 if not desired
perror::Ptr{Cdouble} # Final parameter uncertainties (1-sigma) npar-vector, or 0 if not desired
covar::Ptr{Cdouble} # Final parameter covariance matrix npar x npar array, or 0 if not desired
version::NTuple{20, Cchar} # `mpfit` version string
"Create an empty `Result_C` structure."
Result_C() = new(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NTuple{20, Cchar}("\0"^20))
end
#---------------------------------------------------------------------
"CMPFit return structure (Julia side)."
mutable struct Result
bestnorm::Float64 # Final chi^2
orignorm::Float64 # Starting value of chi^2
niter::Int64 # Number of iterations
nfev::Int64 # Number of function evaluations
status::Int64 # Fitting status code
npar::Int64 # Total number of parameters
nfree::Int64 # Number of free parameters
npegged::Int64 # Number of pegged parameters
nfunc::Int64 # Number of residuals (= num. of data points)
perror::Vector{Float64} # Final parameter uncertainties (1-sigma)
covar::Matrix{Float64} # Final parameter covariance matrix
version::String # CMPFit version string
param::Vector{Float64} # Array of best fit parameters
dof::Int # Degrees of freedom
elapsed::Float64 # Elapsed time [s]
end
#---------------------------------------------------------------------
# Add Base.show method to show CMPFit results
function Base.show(io::IO, res::Result)
@printf io " CMPFit ver. = %s\n" res.version
@printf io " STATUS = %d\n" res.status
@printf io " CHI-SQUARE = %f (%d DOF)\n" res.bestnorm res.dof
@printf io " NPAR = %d\n" res.npar
@printf io " NFREE = %d\n" res.nfree
@printf io " NPEGGED = %d\n" res.npegged
@printf io " NITER = %d\n" res.niter
@printf io " NFEV = %d\n" res.nfev
@printf io "Elapsed time = %f s\n" res.elapsed
@printf io "\n"
for i in 1:res.npar
@printf io " P[%d] = %f +/- %f\n" i res.param[i] res.perror[i]
end
end
#---------------------------------------------------------------------
mutable struct Wrap_A_Function
funct::Function
end
#---------------------------------------------------------------------
# This function can not be nested into mpfit since this would lead to the error:
# ERROR: closures are not yet c-callable
#
"Function called from C to calculate the residuals"
function julia_eval_resid(ndata::Cint, npar::Cint, _param::Ptr{Cdouble}, _resid::Ptr{Cdouble}, _derivs::Ptr{Ptr{Cdouble}}, _funct::Ptr{Wrap_A_Function})
wrap = unsafe_load(_funct)
param = unsafe_wrap(Vector{Float64}, _param, npar)
resid = unsafe_wrap(Vector{Float64}, _resid, ndata)
pderiv = Vector{Int}()
vderiv = Vector{Vector{Float64}}()
if _derivs != C_NULL
derivs = unsafe_wrap(Vector{Ptr{Cdouble}}, _derivs, npar)
for ipar in 1:npar
if derivs[ipar] != C_NULL
push!(pderiv, ipar)
push!(vderiv, unsafe_wrap(Vector{Float64}, derivs[ipar], ndata))
end
end
end
# Compute residuals
if length(pderiv) > 0
jresid = wrap.funct(param, pderiv, vderiv)
else
jresid = wrap.funct(param)
end
resid .= reshape(jresid, length(jresid))
return Cint(0)::Cint
end
######################################################################
# Public functions
######################################################################
#---------------------------------------------------------------------
"Main CMPFit function"
function cmpfit(funct::Function,
_param::Vector{Float64};
parinfo=nothing, config=nothing)
# Compute elapsed time
elapsedtime = Base.time_ns()
# Use a local copy
param = deepcopy(_param)
# Check user function by evaluating it
model = funct(param)
res_C = Result_C()
res_C.perror = Libc.malloc(length(param) * sizeof(Cdouble) )
res_C.covar = Libc.malloc(length(param)^2 * sizeof(Cdouble) )
if parinfo == nothing
parinfo = Parinfo(length(param))
end
if length(parinfo) != length(param)
error("Lengths of `param` and `parinfo` arrays are different")
end
imm_parinfo = map(imm_Parinfo, parinfo)
if config == nothing
config = Config()
end
wrap = Wrap_A_Function(funct)
status = -999
try
#C-compatible address of the Julia `julia_eval_resid` function.
c_eval_resid = @cfunction(julia_eval_resid, Cint, (Cint, Cint, Ptr{Cdouble}, Ptr{Cdouble}, Ptr{Ptr{Cdouble}}, Ptr{Wrap_A_Function}))
status = ccall((:mpfit, libmpfit), Cint,
(Ptr{Nothing}, Cint , Cint, Ptr{Cdouble}, Ptr{imm_Parinfo}, Ptr{Config}, Ptr{Wrap_A_Function}, Ref{Result_C}),
c_eval_resid , length(model), length(param), param , imm_parinfo , Ref(config), Ref(wrap) , res_C)
catch err
error("An error occurred during `mpfit` call.")
end
@assert status >= 0 "mpfit returned status = $status < 0."
perror = Vector{Float64}();
covar = Array{Float64, 2}(undef, 0, 0)
covar = Vector{Float64}()
for i in 1:length(param) ; push!(perror, unsafe_load(res_C.perror, i)); end
for i in 1:length(param)^2; push!(covar , unsafe_load(res_C.covar , i)); end
covar = reshape(covar, length(param), length(param))
version = findall(x -> x != 0, collect(res_C.version))
if length(version) == 0
version = ""
else
version = join(Char.(res_C.version[version]))
end
result = Result(res_C.bestnorm,
res_C.orignorm,
res_C.niter,
res_C.nfev,
res_C.status,
res_C.npar,
res_C.nfree,
res_C.npegged,
res_C.nfunc,
perror,
covar,
version,
param,
res_C.nfunc - res_C.nfree,
0.)
Libc.free(res_C.perror)
Libc.free(res_C.covar )
elapsedtime = Base.time_ns() - elapsedtime
result.elapsed = convert(Float64, elapsedtime / 1e9)
return result
end
#---------------------------------------------------------------------
function cmpfit(independentData::AbstractArray,
observedData::AbstractArray,
uncertainties::AbstractArray,
funct::Function,
guessParam::Vector{Float64};
parinfo=nothing, config=nothing)
function cmpfit_callback(param::Vector{Float64})
model = funct(independentData, param)
ret = (observedData - model) ./ uncertainties
return ret
end
function cmpfit_callback(param::Vector{Float64}, pderiv::Vector{Int}, vderiv::Vector{Vector{Float64}})
model = funct(independentData, param, pderiv, vderiv)
ret = (observedData - model) ./ uncertainties
for i in 1:length(vderiv)
vderiv[i] ./= -uncertainties
end
return ret
end
cmpfit(cmpfit_callback, guessParam, parinfo=parinfo, config=config)
end
end # module
| CMPFit | https://github.com/gcalderone/CMPFit.jl.git |
|
[
"MIT"
] | 0.3.5 | 71e40b5d9aaa5749942cb2183fb5add45f146ff2 | code | 4910 | using Test
using CMPFit
@info CMPFit.binary_lib_path()
## testlinfit
x = [-1.7237128E+00,1.8712276E+00,-9.6608055E-01,
-2.8394297E-01,1.3416969E+00,1.3757038E+00,
-1.3703436E+00,4.2581975E-02,-1.4970151E-01,
8.2065094E-01]
y = [1.9000429E-01,6.5807428E+00,1.4582725E+00,
2.7270851E+00,5.5969253E+00,5.6249280E+00,
0.787615,3.2599759E+00,2.9771762E+00,
4.5936475E+00]
e = fill(0., size(y)) .+ 0.07
param = [1., 1.]
function linfunc(x::Vector{Float64}, p::Vector{Float64})
return @. p[1] + p[2]*x
end
res = cmpfit(x, y, e, linfunc, param)
@test res.bestnorm ≈ 2.756285 rtol=1.e-5
@test res.status == 1
@test res.npar == 2
@test res.nfree == 2
@test res.npegged == 0
@test res.dof == 8
zero = res.perror .- [0.0222102, 0.018938];
@test minimum(zero) ≈ 0 atol=1.e-5
@test maximum(zero) ≈ 0 atol=1.e-5
zero = res.param .- [3.209966, 1.770954];
@test minimum(zero) ≈ 0 atol=1.e-5
@test maximum(zero) ≈ 0 atol=1.e-5
## testquadfit
x = [-1.7237128E+00,1.8712276E+00,-9.6608055E-01,
-2.8394297E-01,1.3416969E+00,1.3757038E+00,
-1.3703436E+00,4.2581975E-02,-1.4970151E-01,
8.2065094E-01]
y = [2.3095947E+01,2.6449392E+01,1.0204468E+01,
5.40507,1.5787588E+01,1.6520903E+01,
1.5971818E+01,4.7668524E+00,4.9337711E+00,
8.7348375E+00]
e = fill(0., size(y)) .+ 0.2
param = [1., 1., 1.]
function quadfunc(x::Vector{Float64}, p::Vector{Float64})
return @. p[1] + p[2]*x + p[3]*(x*x)
end
res = cmpfit(x, y, e, quadfunc, param)
@test res.bestnorm ≈ 5.679323 rtol=1.e-5
@test res.status == 1
@test res.npar == 3
@test res.nfree == 3
@test res.npegged == 0
@test res.dof == 7
zero = res.perror .- [0.097512, 0.054802, 0.054433];
@test minimum(zero) ≈ 0 atol=1.e-5
@test maximum(zero) ≈ 0 atol=1.e-5
zero = res.param .- [4.703829, 0.062586, 6.163087];
@test minimum(zero) ≈ 0 atol=1.e-5
@test maximum(zero) ≈ 0 atol=1.e-5
## testquadfix
param = [1., 0., 1.]
pinfo = CMPFit.Parinfo(length(param))
pinfo[2].fixed = 1
res = cmpfit(x, y, e, quadfunc, param, parinfo=pinfo)
@test res.bestnorm ≈ 6.983588 rtol=1.e-5
@test res.status == 1
@test res.npar == 3
@test res.nfree == 2
@test res.npegged == 0
@test res.dof == 8
zero = res.perror .- [0.097286, 0., 0.053743];
@test minimum(zero) ≈ 0 atol=1.e-5
@test maximum(zero) ≈ 0 atol=1.e-5
zero = res.param .- [4.696254, 0., 6.172954];
@test minimum(zero) ≈ 0 atol=1.e-5
@test maximum(zero) ≈ 0 atol=1.e-5
## testgaussfit
x = [-1.7237128E+00,1.8712276E+00,-9.6608055E-01,
-2.8394297E-01,1.3416969E+00,1.3757038E+00,
-1.3703436E+00,4.2581975E-02,-1.4970151E-01,
8.2065094E-01]
y = [-4.4494256E-02,8.7324673E-01,7.4443483E-01,
4.7631559E+00,1.7187297E-01,1.1639182E-01,
1.5646480E+00,5.2322268E+00,4.2543168E+00,
6.2792623E-01]
e = fill(0., size(y)) .+ 0.5
param = [0.0, 1.0, 1.0, 1.0]
function gaussfunc(x::Vector{Float64}, p::Vector{Float64})
sig2 = p[4] * p[4];
xc = @. x - p[3];
return @. p[2] * exp(-0.5 * xc *xc / sig2) + p[1]
end
res = cmpfit(x, y, e, gaussfunc, param)
@test res.bestnorm ≈ 10.350032 rtol=1.e-5
@test res.status == 1
@test res.npar == 4
@test res.nfree == 4
@test res.npegged == 0
@test res.dof == 6
zero = res.perror .- [0.232234, 0.395434, 0.074715, 0.089997];
@test minimum(zero) ≈ 0 atol=1.e-5
@test maximum(zero) ≈ 0 atol=1.e-5
zero = res.param .- [0.480441, 4.550754, -0.062562, 0.397473];
@test minimum(zero) ≈ 0 atol=1.e-5
@test maximum(zero) ≈ 0 atol=1.e-5
## testgaussfit (with explicit derivatives)
gaussfunc_deriv(x::Vector{Float64}, p::Vector{Float64}) = gaussfunc(x, p)
function gaussfunc_deriv(x::Vector{Float64}, p::Vector{Float64}, pderiv::Vector{Int}, vderiv::Vector{Vector{Float64}})
sig2 = p[4] * p[4];
xc = x .- p[3];
ee = exp.(-0.5 .* xc.^2 ./ sig2)
for i in 1:length(pderiv)
ipar = pderiv[i]
if ipar == 1
vderiv[i] .= 1.
elseif ipar == 2
vderiv[i] .= ee
elseif ipar == 3
vderiv[i] .= p[2] .* ee .* (x .- p[3]) ./ sig2
elseif ipar == 4
vderiv[i] .= p[2] .* ee .* (x .- p[3]).^2 ./ sig2 ./ p[4]
end
end
return p[2] .* ee .+ p[1]
end
pinfo = CMPFit.Parinfo(length(param))
setfield!.(pinfo, :side, Int32(3))
res = cmpfit(x, y, e, gaussfunc_deriv, param, parinfo=pinfo)
## testgaussfix
param = [0.0, 1.0, 0.0, 0.1]
pinfo = CMPFit.Parinfo(length(param))
pinfo[1].fixed = 1
pinfo[3].fixed = 1
res = cmpfit(x, y, e, gaussfunc, param, parinfo=pinfo)
@test res.bestnorm ≈ 15.516134 rtol=1.e-5
@test res.status == 1
@test res.npar == 4
@test res.nfree == 2
@test res.npegged == 0
@test res.dof == 8
zero = res.perror .- [0., 0.329307, 0., 0.053804];
@test minimum(zero) ≈ 0 atol=1.e-5
@test maximum(zero) ≈ 0 atol=1.e-5
zero = res.param .- [0., 5.059244, 0., 0.479746];
@test minimum(zero) ≈ 0 atol=1.e-5
@test maximum(zero) ≈ 0 atol=1.e-5
| CMPFit | https://github.com/gcalderone/CMPFit.jl.git |
|
[
"MIT"
] | 0.3.5 | 71e40b5d9aaa5749942cb2183fb5add45f146ff2 | docs | 3481 | # CMPFit
## A Julia wrapper for the `mpfit` library (MINPACK minimization).
[](https://travis-ci.org/gcalderone/CMPFit.jl)
The `CMPFit.jl` package is a wrapper for the [`mpfit` C-library](https://www.physics.wisc.edu/~craigm/idl/cmpfit.html) by Craig Markwardt, providing access to the the [MINPACK](http://www.netlib.org/minpack/) implementation of the
[Levenberg-Marquardt algorithm](https://en.wikipedia.org/wiki/Levenberg%E2%80%93Marquardt_algorithm), and allowing simple and quick solutions to Least Squares minimization problems in Julia.
**This is a wrapper for a C library, hence it uses a binary library compiled from C.**
Check the [LsqFit](https://github.com/JuliaNLSolvers/LsqFit.jl) package for a pure Julia solution.
-------
## Installation
In the Julia REPL type:
``` julia
] add CMPFit
```
This will automaticaly download the binary `cmpfit` library (v1.4) as an artifact matching your platform.
-------
## Usage
Usage is very simple: given a set of observed data and uncertainties, define a (whatever complex) Julia function to evaluate a model to be compared with the data, and ask `cmpfit` to find the model parameter values which best fit the data.
Example:
``` julia
using CMPFit
# Independent variable
x = [-1.7237128E+00,1.8712276E+00,-9.6608055E-01,
-2.8394297E-01,1.3416969E+00,1.3757038E+00,
-1.3703436E+00,4.2581975E-02,-1.4970151E-01,
8.2065094E-01]
# Observed data
y = [-4.4494256E-02,8.7324673E-01,7.4443483E-01,
4.7631559E+00,1.7187297E-01,1.1639182E-01,
1.5646480E+00,5.2322268E+00,4.2543168E+00,
6.2792623E-01]
# Data uncertainties
e = fill(0., size(y)) .+ 0.5
# Define a model (actually a Gaussian curve)
function GaussModel(x::Vector{Float64}, p::Vector{Float64})
sig2 = p[4] * p[4]
xc = @. x - p[3]
model = @. p[2] * exp(-0.5 * xc * xc / sig2) + p[1]
return model
end
# Guess model parameters
param = [0.0, 1.0, 1.0, 1.0]
# Call `cmpfit` and print the results:
res = cmpfit(x, y, e, GaussModel, param);
println(res)
```
The value returned by `cmpfit` is a Julia structure. You may look at its content with:
``` julia
dump(res)
```
Specifically, the best fit parameter values and their 1-sigma uncertainties are:
``` Julia
println(res.param)
println(res.perror)
```
`CMPFit` mirrors all the facilities provided by the underlying C-library, e.g. a parameter can be fixed during the fit, or its value limited to a specific range. Moreover, the whole fitting process may be customized for, e.g., limiting the maximum number of model evaluation, or change the relative chi-squared convergence criterium. E.g.:
``` Julia
# Set guess parameters
param = [0.5, 4.5, 1.0, 1.0]
# Create the `parinfo` structures for the 4 parameters used in the
# example above:
pinfo = CMPFit.Parinfo(4)
# Fix the value of the 1st parameter:
pinfo[1].fixed = 1
# Set a lower (4) and upper limit (5) for the 2nd parameter
pinfo[2].limited = (1,1)
pinfo[2].limits = (4, 5)
# Create a `config` structure
config = CMPFit.Config()
# Limit the maximum function evaluation to 200
config.maxfev = 200
# Change the chi-squared convergence criterium:
config.ftol = 1.e-5
# Re-run the minimization process
res = cmpfit(x, y, e, GaussModel, param, parinfo=pinfo, config=config);
println(res)
```
See [Craig's webpage](https://www.physics.wisc.edu/~craigm/idl/cmpfit.html) for further documentation on the `config` and `parinfo` structures.
| CMPFit | https://github.com/gcalderone/CMPFit.jl.git |
|
[
"MIT"
] | 0.2.0 | 9eb8d474c659d6cdf4c83d34d6673917fff8b1af | code | 7883 | module Qutilities
using LinearAlgebra: Diagonal, eigvals, Hermitian, svdvals, tr
export
binent,
concurrence,
concurrence_lb,
formation,
mutinf,
negativity,
ptrace,
ptranspose,
purity,
sigma_x,
sigma_y,
sigma_z,
spinflip,
S_renyi,
S_vn
# All logarithms are base 2.
const LOG = log2
"""
hermitize(rho::AbstractMatrix)
Make `rho` Hermitian, but carefully.
"""
function hermitize(rho::AbstractMatrix)
size(rho, 1) == size(rho, 2) || throw(DomainError(size(rho), "Only square matrices are supported."))
err = maximum(abs.(rho - rho'))
if err > 1e-12
@warn "Matrix is not Hermitian: $(err)"
end
# Make the diagonal strictly real.
rho_H = copy(rho)
for i in 1:size(rho_H, 1)
rho_H[i, i] = real(rho_H[i, i])
end
Hermitian(rho_H)
end
hermitize(rho::Diagonal) = rho
"""
nonneg(x::Real)
`x` if `x` is non-negative; zero if `x` is negative.
"""
nonneg(x::Real) = x < 0 ? zero(x) : x
"""
shannon(xs::AbstractVector)
Shannon entropy of `xs`.
"""
shannon(xs::AbstractVector) = -sum([x * LOG(x) for x in xs if x > 0])
# Single-qubit Pauli matrices.
const sigma_x = [[0.0, 1.0] [1.0, 0.0]]
const sigma_y = [[0.0, im] [-im, 0.0]]
const sigma_z = [[1.0, 0.0] [0.0, -1.0]]
"""
ptrace(rho::AbstractMatrix{T}, dims, which::Int)
Partial trace of `rho` along dimension `which` from `dims`.
"""
function ptrace(rho::AbstractMatrix{T}, dims, which::Int) where {T}
size(rho) == (prod(dims), prod(dims)) || throw(DomainError(size(rho), "Only square matrices are supported."))
size_before = prod(dims[1:(which-1)])
size_at = dims[which]
size_after = prod(dims[(which+1):end])
result = zeros(T, size_before*size_after, size_before*size_after)
for i1 in 1:size_before
for j1 in 1:size_before
for k in 1:size_at
for i2 in 1:size_after
for j2 in 1:size_after
row1 = size_after*(i1-1) + i2
col1 = size_after*(j1-1) + j2
row2 = size_at*size_after*(i1-1) + size_after*(k-1) + i2
col2 = size_at*size_after*(j1-1) + size_after*(k-1) + j2
result[row1, col1] += rho[row2, col2]
end
end
end
end
end
result
end
"""
ptrace(rho::AbstractMatrix, which::Int=2)
Partial trace of `rho` along dimension `which`.
`rho` is split into halves and the trace is over the second half by default.
"""
function ptrace(rho::AbstractMatrix, which::Int=2)
size(rho, 1) % 2 == 0 || throw(DomainError(size(rho, 1), "Matrix size must be even."))
s = div(size(rho, 1), 2)
ptrace(rho, (s, s), which)
end
"""
ptranspose(rho::AbstractMatrix, dims, which::Int)
Partial transpose of `rho` along dimension `which` from `dims`.
"""
function ptranspose(rho::AbstractMatrix, dims, which::Int)
size(rho) == (prod(dims), prod(dims)) || throw(DomainError(size(rho), "Only square matrices are supported."))
size_before = prod(dims[1:(which-1)])
size_at = dims[which]
size_after = prod(dims[(which+1):end])
result = similar(rho)
for i1 in 1:size_before
for j1 in 1:size_before
for i2 in 1:size_at
for j2 in 1:size_at
for i3 in 1:size_after
for j3 in 1:size_after
row1 = size_at*size_after*(i1-1) + size_after*(i2-1) + i3
col1 = size_at*size_after*(j1-1) + size_after*(j2-1) + j3
row2 = size_at*size_after*(i1-1) + size_after*(j2-1) + i3
col2 = size_at*size_after*(j1-1) + size_after*(i2-1) + j3
result[row1, col1] = rho[row2, col2]
end
end
end
end
end
end
result
end
"""
ptranspose(rho::AbstractMatrix, which::Int=2)
Partial transpose of `rho` along dimension `which`.
`rho` is split into halves and the transpose is over the second half by
default.
"""
function ptranspose(rho::AbstractMatrix, which::Int=2)
size(rho, 1) % 2 == 0 || throw(DomainError(size(rho, 1), "Matrix size must be even."))
s = div(size(rho, 1), 2)
ptranspose(rho, (s, s), which)
end
"""
binent(x::Real)
Binary entropy of `x`.
"""
binent(x::Real) = shannon([x, one(x) - x])
"""
purity(rho::AbstractMatrix)
Purity of `rho`.
"""
purity(rho::AbstractMatrix) = rho^2 |> tr |> real
"""
S_vn(rho::AbstractMatrix)
Von Neumann entropy of `rho`.
"""
S_vn(rho::AbstractMatrix) = rho |> hermitize |> eigvals |> shannon
"""
S_renyi(rho::AbstractMatrix, alpha::Real=2)
Order `alpha` Rényi entropy of `rho`.
The `alpha` parameter may have any value on the interval `[0, Inf]` except 1.
It defaults to 2.
"""
function S_renyi(rho::AbstractMatrix, alpha::Real=2)
E = rho |> hermitize |> eigvals
alpha == Inf && return E |> maximum |> LOG |> -
LOG(sum(E.^alpha)) / (1 - alpha)
end
"""
mutinf(rho::AbstractMatrix, S::Function=S_vn)
Mutual information of `rho` using the entropy function `S`.
"""
function mutinf(rho::AbstractMatrix, S::Function=S_vn)
S(ptrace(rho, 1)) + S(ptrace(rho, 2)) - S(rho)
end
"""
spinflip(rho::AbstractMatrix)
Wootters spin-flip operation for two qubits in the mixed state `rho` in the
standard basis.
Ref: Wootters, W. K. (1998). Entanglement of formation of an arbitrary state of
two qubits. Physical Review Letters, 80(10), 2245.
"""
function spinflip(rho::AbstractMatrix)
size(rho) == (4, 4) || throw(DomainError(size(rho), "Matrix must be 4 by 4."))
Y = kron(sigma_y, sigma_y)
Y * conj(rho) * Y
end
"""
concurrence(rho::AbstractMatrix)
Concurrence of a mixed state `rho` for two qubits in the standard basis.
Ref: Wootters, W. K. (1998). Entanglement of formation of an arbitrary state of
two qubits. Physical Review Letters, 80(10), 2245.
"""
function concurrence(rho::AbstractMatrix)
size(rho) == (4, 4) || throw(DomainError(size(rho), "Matrix must be 4 by 4."))
E = rho * spinflip(rho) |> eigvals
if any(imag(E) .> 1e-15)
@warn "Complex eigenvalues: $(maximum(imag(E)))"
end
if any(real(E) .< -1e-12)
@warn "Negative eigenvalues: $(minimum(real(E)))"
end
F = sort(sqrt.(nonneg.(real(E))))
nonneg(F[end] - sum(F[1:(end-1)]))
end
"""
concurrence_lb(rho::AbstractMatrix)
Lower bound on the concurrence for two qubits in the mixed state `rho` in the
standard basis.
Ref: Mintert, F., & Buchleitner, A. (2007). Observable entanglement measure for
mixed quantum states. Physical Review Letters, 98(14), 140505.
"""
function concurrence_lb(rho::AbstractMatrix)
size(rho) == (4, 4) || throw(DomainError(size(rho), "Matrix must be 4 by 4."))
2.0*(purity(rho) - purity(ptrace(rho))) |> nonneg |> sqrt
end
"""
formation(C::Real)
Entanglement of formation for two qubits with concurrence `C`.
Ref: Wootters, W. K. (1998). Entanglement of formation of an arbitrary state of
two qubits. Physical Review Letters, 80(10), 2245.
"""
formation(C::Real) = binent(0.5 * (1.0 + sqrt(1.0 - C^2)))
"""
formation(rho::AbstractMatrix)
Entanglement of formation for two qubits in the mixed state `rho` in the
standard basis.
Ref: Wootters, W. K. (1998). Entanglement of formation of an arbitrary state of
two qubits. Physical Review Letters, 80(10), 2245.
"""
formation(rho::AbstractMatrix) = rho |> concurrence |> formation
"""
negativity(rho::AbstractMatrix)
Logarithmic negativity for a symmetric bipartition of `rho`.
Ref: Plenio, M. B. (2005). Logarithmic negativity: A full entanglement monotone
that is not convex. Physical Review Letters, 95(9), 090503.
"""
negativity(rho::AbstractMatrix) = rho |> ptranspose |> svdvals |> sum |> LOG
end
| Qutilities | https://github.com/0/Qutilities.jl.git |
|
[
"MIT"
] | 0.2.0 | 9eb8d474c659d6cdf4c83d34d6673917fff8b1af | code | 5413 | using Qutilities
using Test
using LinearAlgebra: diagm, I, tr
@testset "Qutilities" begin
@testset "sigma_x, sigma_y, sigma_z" begin
@test sigma_x^2 == I
@test sigma_y^2 == I
@test sigma_z^2 == I
@test -im*sigma_x*sigma_y*sigma_z == I
end
@testset "ptrace, ptranspose" begin
let A = I(2),
B = reshape(1:16, 4, 4),
C = [[0, 0, 1] [0, 1, 0] [1, 0, 0]],
ABC = kron(A, B, C),
dims = (2, 4, 3)
@test ptrace(ABC, dims, 1) == tr(A) * kron(B, C)
@test ptranspose(ABC, dims, 1) == kron(A', B, C)
@test ptrace(ABC, dims, 2) == tr(B) * kron(A, C)
@test ptranspose(ABC, dims, 2) == kron(A, B', C)
@test ptrace(ABC, dims, 3) == tr(C) * kron(A, B)
@test ptranspose(ABC, dims, 3) == kron(A, B, C')
end
let M = reshape(1.0:16.0, 4, 4),
MT1 = [[1.0, 2.0, 9.0, 10.0] [5.0, 6.0, 13.0, 14.0] [3.0, 4.0, 11.0, 12.0] [7.0, 8.0, 15.0, 16.0]],
MT2 = [[1.0, 5.0, 3.0, 7.0] [2.0, 6.0, 4.0, 8.0] [9.0, 13.0, 11.0, 15.0] [10.0, 14.0, 12.0, 16.0]]
@test ptrace(M, (1, 4), 1) == M
@test ptranspose(M, (1, 4), 1) == M
@test ptrace(M, (1, 4), 2) == fill(tr(M), 1, 1)
@test ptranspose(M, (1, 4), 2) == transpose(M)
@test ptrace(M, (2, 2), 1) == [[12.0, 14.0] [20.0, 22.0]]
@test ptranspose(M, (2, 2), 1) == MT1
@test ptrace(M, (2, 2), 2) == [[7.0, 11.0] [23.0, 27.0]]
@test ptranspose(M, (2, 2), 2) == MT2
@test ptrace(M, (4, 1), 1) == fill(tr(M), 1, 1)
@test ptranspose(M, (4, 1), 1) == transpose(M)
@test ptrace(M, (4, 1), 2) == M
@test ptranspose(M, (4, 1), 2) == M
@test ptrace(M, 1) == ptrace(M, (2, 2), 1)
@test ptrace(M, 2) == ptrace(M, (2, 2), 2)
@test ptranspose(M, 1) == ptranspose(M, (2, 2), 1)
@test ptranspose(M, 2) == ptranspose(M, (2, 2), 2)
@test ptrace(M) == ptrace(M, (2, 2), 2)
@test ptranspose(M) == ptranspose(M, (2, 2), 2)
end
let M = [[1.0, im] [im, 1.0]]
@test ptrace(M, (1, 2), 1) == M
@test ptranspose(M, (1, 2), 1) == M
@test ptrace(M, (1, 2), 2) == fill(tr(M), 1, 1)
@test ptranspose(M, (1, 2), 2) == transpose(M)
end
end
@testset "binent" begin
@test binent(0.0) == 0.0
@test binent(0.5) == 1.0
@test binent(1.0) == 0.0
end
@testset "purity, S_vn, S_renyi" begin
let rho1 = I(4) / 4.0,
rho2 = [[2.0, im] [-im, 2.0]] / 2.0,
eigs2 = [1.0, 3.0] / 2.0
@test purity(rho1) == 0.25
@test purity(rho2) == sum(eigs2.^2)
@test S_renyi(rho1, 0) == 2.0
@test S_renyi(rho2, 0) == 1.0
@test S_vn(rho1) == 2.0
@test S_vn(rho2) == -sum(eigs2 .* log2.(eigs2))
@test S_renyi(rho1) == 2.0
@test S_renyi(rho2) == -log2(sum(eigs2.^2))
@test S_renyi(rho1, Inf) == 2.0
@test S_renyi(rho2, Inf) == -log2(maximum(eigs2))
end
end
@testset "mutinf" begin
let rho = diagm([3, 2, 1, 2]) / 8.0
@test isapprox(mutinf(rho), (1.5 - 5.0 * log2(5.0) / 8.0))
@test isapprox(mutinf(rho, S_renyi), (1.0 + 2.0 * log2(3.0) - log2(17.0)))
end
end
@testset "spinflip, concurrence, concurrence_lb, formation, negativity" begin
let rho = reshape(1.0:16.0, 4, 4),
rho_f = [[16.0, -15.0, -14.0, 13.0] [-12.0, 11.0, 10.0, -9.0] [-8.0, 7.0, 6.0, -5.0] [4.0, -3.0, -2.0, 1.0]]
@test spinflip(rho) == rho_f
end
let rho = zeros(4, 4)
rho[1, 1] = 0.5
rho[4, 4] = 0.5
let C = concurrence(rho)
@test spinflip(rho) == rho
@test C == 0.0
@test concurrence_lb(rho) == 0.0
@test formation(C) == 0.0
@test negativity(rho) == 0.0
end
end
let rho = zeros(4, 4)
rho[1, 1] = 0.125
for i in 2:3, j in 2:3
rho[i, j] = 0.375
end
rho[4, 4] = 0.125
let C = concurrence(rho),
a = (2 + sqrt(3.0)) / 4.0,
b = (2 - sqrt(3.0)) / 4.0
@test spinflip(rho) == rho
@test C == 0.5
@test concurrence_lb(rho) == sqrt(3.0)/4.0
@test formation(C) == -a * log2(a) - b * log2(b)
@test negativity(rho) == log2(1.5)
end
end
let rho = zeros(4, 4)
for i in 2:3, j in 2:3
rho[i, j] = 0.5
end
let C = concurrence(rho)
@test spinflip(rho) == rho
@test C == 1.0
@test concurrence_lb(rho) == 1.0
@test formation(C) == 1.0
@test negativity(rho) == 1.0
end
end
let rho = Matrix{ComplexF64}(undef, 4, 4)
for i in 1:4
for j in 1:4
if i < j
rho[i, j] = 0.0625im
elseif i == j
rho[i, j] = 0.25
else
rho[i, j] = -0.0625im
end
end
end
let C = concurrence(rho),
rho_f = copy(transpose(rho))
rho_f[1, 4] *= -1
rho_f[2, 3] *= -1
rho_f[3, 2] *= -1
rho_f[4, 1] *= -1
@test spinflip(rho) == rho_f
@test C == 0.0
@test concurrence_lb(rho) == 0.0
@test formation(C) == 0.0
@test isapprox(negativity(rho), 0.0, atol=1e-15)
end
end
end
end
| Qutilities | https://github.com/0/Qutilities.jl.git |
|
[
"MIT"
] | 0.2.0 | 9eb8d474c659d6cdf4c83d34d6673917fff8b1af | docs | 1143 | # Qutilities
Assorted utilities for quantum information.
Tested with Julia 1.3.
## Installation
```
pkg> add Qutilities
```
## Examples
```julia
julia> using Qutilities
julia> rho = [[1, 0, 0, 0] [0, 3, 3, 0] [0, 3, 3, 0] [0, 0, 0, 1]]/8.0
4×4 Array{Float64,2}:
0.125 0.0 0.0 0.0
0.0 0.375 0.375 0.0
0.0 0.375 0.375 0.0
0.0 0.0 0.0 0.125
julia> ptrace(rho)
2×2 Array{Float64,2}:
0.5 0.0
0.0 0.5
julia> ptranspose(rho)
4×4 Array{Float64,2}:
0.125 0.0 0.0 0.375
0.0 0.375 0.0 0.0
0.0 0.0 0.375 0.0
0.375 0.0 0.0 0.125
julia> purity(rho)
0.59375
julia> S_renyi(rho, 0)
2.0
julia> S_vn(rho)
1.061278124459133
julia> S_renyi(rho)
0.7520724865564145
julia> S_renyi(rho, Inf)
0.4150374992788438
julia> mutinf(rho)
0.9387218755408671
julia> concurrence(rho)
0.5
julia> formation(rho)
0.35457890266527003
julia> negativity(rho)
0.5849625007211562
```
## Testing
To run all the tests, activate the package before calling `test`:
```
pkg> activate .
(Qutilities) pkg> test
```
## License
Provided under the terms of the MIT license.
See `LICENSE` for more information.
| Qutilities | https://github.com/0/Qutilities.jl.git |
|
[
"MIT"
] | 0.0.2 | 5b2502075691622572035a53ca1f852acad50e5d | code | 677 | using SortMark
using Documenter
DocMeta.setdocmeta!(SortMark, :DocTestSetup, :(using SortMark); recursive=true)
makedocs(;
modules=[SortMark],
authors="Lilith Orion Hafner <60898866+LilithHafner@users.noreply.github.com> and contributors",
repo="https://github.com/LilithHafner/SortMark.jl/blob/{commit}{path}#{line}",
sitename="SortMark.jl",
format=Documenter.HTML(;
prettyurls=get(ENV, "CI", "false") == "true",
canonical="https://LilithHafner.github.io/SortMark.jl",
assets=String[],
),
pages=[
"Home" => "index.md",
],
)
deploydocs(;
repo="github.com/LilithHafner/SortMark.jl",
devbranch="main",
)
| SortMark | https://github.com/LilithHafner/SortMark.jl.git |
|
[
"MIT"
] | 0.0.2 | 5b2502075691622572035a53ca1f852acad50e5d | code | 10278 | module SortMark
export make_df, compute!, reproduce, stat!
using DataFrames: DataFrame, DataFrameRow
using Random: shuffle, shuffle!
using Base.Order
using Base.Sort: Algorithm
using Statistics
using HypothesisTests
using ProgressMeter
include("print.jl")
## Types
const Ints = [Int64, Int8, Int32, Int16, Int128]
const UInts = unsigned.(Ints)
const Floats = [Float64, Float32, Float16]
const BitTypes = vcat(Ints, Floats, UInts, Char, Bool)
matched_UInt(::Type{Float64}) = UInt64
matched_UInt(::Type{Float32}) = UInt32
matched_UInt(::Type{Float16}) = UInt16
matched_UInt(T::Type{<:Signed}) = unsigned(T)
matched_UInt(T::Type{<:Unsigned}) = T
matched_UInt(::Type{Char}) = UInt32
## Special Values
special_values(T) = T
function special_values(T::Type{<:AbstractFloat})
U = matched_UInt(T)
T[-π, -1.0, -1/π, 1/π, 1.0, π, -0.0, 0.0, Inf, -Inf, NaN, -NaN,
prevfloat(T(0)), nextfloat(T(0)), prevfloat(T(Inf)), nextfloat(T(-Inf)),
reinterpret(T, reinterpret(U, T(NaN)) | 0x73), reinterpret(T, reinterpret(U, -T(NaN)) | 0x37)]
end
function special_values(T::Type{<:Union{Signed, Unsigned}})
T[17, -T(17), 0, -one(T), 1, typemax(T), typemin(T), typemax(T)-1, typemin(T)+1]
end
special_values(T::Type{Bool}) = [true, false]
bit_random(T::Type{Bool}, len::Integer) = rand(T, len)
bit_random(T::Type, len::Integer) = reinterpret.(T, rand(matched_UInt(T), len))
## Sources (perhaps chagne this to a module-level function with dispatch by symbol)
const sources = Dict(
:simple => (T, len) -> rand(T, len),
:special => (T, len) -> rand(special_values(T), len),
:tricky => (T, len) -> vcat(
rand(special_values(T), len-2*(len÷3)),
rand(T, len÷3),
bit_random(T, len÷3)),
:small_positive => (T::Type{<:Real}, len) -> rand(T.(1:min(1_000, typemax(T))), len)
)
## Lengths
function lengths(min=1, max=100_000, spacing=3)
length = 1+round(Integer, (log(max)-log(min))/log(spacing))
source = exp.(range(log(min), log(max), length=length))
sort!(collect(Set(round.(Integer, source))))
end
## Orders
const orders = [Forward, Reverse]
##Data frame (this could be much faster if it constructed by column instead of row)
"""
make_df(algs = [MergeSort, QuickSort]; ...)
Make a dataframe where each row is a sorting task specified by the cartesian product of
keyword arguments.
# Arguments
- `algs::AbstractVector{<:Base.Sort.Algorithm} = [MergeSort, QuickSort]`:
sorting algorithms to test
- `unstable::AbstractVector{<:Base.Sort.Algorithm} = [QuickSort]`:
which of the algorithms are allowed to be unstable
Axes of the cartesian product
- `Types::AbstractVector{<:Type} = SortMark.BitTypes`:
element type
- `lens::AbstractVector{<:Integer} = SortMark.lengths()`:
number of elements to be sorted
- `orders::AbstractVector{<:Ordering} = SortMark.orders`:
orders to sort by
- `sources::AbstractDict{<:Any, <:Function} = SortMark.sources`:
generation procedures to create input data
Benchmarking time
- `seconds::Union{Real, Nothing} = .005`:
maximum benchmarking time for each row. Compute sum(df.seconds) for an estimated
benchmarking runtime
- `samples::Union{Nothing, Integer} = nothing`:
maximum number of samples for each row. Compute sum(df.seconds) for an estimated
benchmarking runtime
Setting `seconds` or `samples` to `nothing` removes that limit.
"""
function make_df(algs::AbstractVector{<:Algorithm} = [MergeSort, QuickSort];
Types::AbstractVector{<:Type} = BitTypes,
lens::AbstractVector{<:Integer} = lengths(),
orders::AbstractVector{<:Ordering} = orders,
sources::AbstractDict{<:Any, <:Function} = sources, unstable = [QuickSort],
seconds::Union{Real, Nothing} = .005,
samples::Union{Integer, Nothing} = seconds==nothing ? 1 : nothing)
df = DataFrame(ContainerType=Type{<:AbstractVector}[], Type=Type[], len=Int[],
order=Ordering[], source_key=Symbol[], source=Function[], algs=Vector{<:Algorithm}[], unstable=Vector{<:Algorithm}[],
evals=Int[], samples=Union{Nothing, Int}[], seconds=Union{Nothing, Float64}[], data=DataFrame[],
errors=Dict[])
for Type in Types, len in lens, order in orders, (source_key, source) in pairs(sources)
if source_key == :small_positive && !(Type <: Real); continue; end
push!(df, (Vector, Type, len, order, source_key, source, algs, unstable,
max(1, 1_000 ÷ max(len, 1)), samples, seconds, DataFrame([Float64[] for _ in algs], Symbol.(algs)),
Dict()))
end
df
end
##Compute data
function target!(vec, alg, order)
sort!(vec, alg=alg, order=order)
end
const PASSED_TESTS = Ref(0)
"""
compute!(df::DataFrame; verbose=true, fail_fast=true)
Test and run benchmarks for every row in `df`.
Benchmark results are saved in df.data.
"""
function compute!(df::DataFrame; verbose=true, fail_fast=true)
start_time = time()
benchmark_start_time = sum(sum(sum.(eachcol(d))) for d in df.data)
start_passed_tests = PASSED_TESTS[]
empty!.(df.errors)
rows = shuffle(eachrow(df))#TODO make this appear immediately
nominal_runtime = sum([s==nothing ? .001 : s for s in df.seconds])
dt = max(.1, min(1, nominal_runtime/100))
message = "$(round(Integer, nominal_runtime))s, Progress: "
try
@showprogress dt message for row in rows
compute!(row, fail_fast)
end
catch
printstyled("\nFailed test set stored as SortMark.fail. Reproduce it's error with reproduce().\n", color=Base.debug_color())
rethrow()
end
np, nf, ne = PASSED_TESTS[]-start_passed_tests, 0, 0
for dict in df.errors, vect in values(dict), err in vect
if err isa AssertionError
nf += 1
else
ne += 1
end
end
end_time = time()
benchmark_end_time = sum(sum(sum.(eachcol(d))) for d in df.data)
if !all(isempty.(df.errors))
global fail = deepcopy(df[findfirst((!).(isempty.(df.errors))), :])
color = Base.error_color()
printstyled("ERROR: Some tests did not pass: $np passed, $nf failed, $ne errored.\n", color=color)
verbose && Print._print(df, np, end_time-start_time, benchmark_end_time-benchmark_start_time, color)
printstyled("SortMark.fail is an example of a failed set of tests. Reproduce it's error with reproduce().\n", color=Base.debug_color())
elseif verbose
Print._print(df, np, end_time-start_time, benchmark_end_time-benchmark_start_time, :normal)
end
df
end
function compute!(row::DataFrameRow, fail_fast=true)
Base.require_one_based_indexing(row.algs)
gen() = row.ContainerType(row.source(row.Type, row.len))
if row.samples == nothing && row.seconds == nothing
println("WARNING: row=$row has unbounded samples=$samples and seconds=$seconds.
Because of this absence of an end condition it will hang.")
end
sample = 1
start_time = time()
while (row.samples == nothing || sample <= row.samples) &&
(row.seconds == nothing || time() < start_time+row.seconds)
perm = shuffle!(collect(axes(row.algs, 1)))
times = trial(row, row.algs[perm], [gen() for _ in 1:row.evals], fail_fast)
push!(row.data, times[invperm(perm)])
sample += 1
end
row
end
function trial(row, algs, inputs, fail_fast)
Base.require_one_based_indexing(algs)
stable_output = nothing
test_index = rand(eachindex(inputs))
times = []
order = row.order
for alg in algs
cinputs = copy.(inputs)
outputs = similar(inputs)
t = @elapsed for i in eachindex(inputs, cinputs, outputs)
try
outputs[i] = target!(cinputs[i], alg, order)
catch x
log_error!(row, x, alg, copy(inputs[i]), fail_fast)
end
end
push!(times, t/length(inputs))
try
test_sorted(outputs[test_index], cinputs[test_index], inputs[test_index], row.order)
if alg ∉ row.unstable
if stable_output == nothing
stable_output = outputs[test_index]
else
test_matched(stable_output, outputs[test_index])
end
end
catch x
log_error!(row, x, alg, copy(inputs[test_index]), fail_fast)
end
end
times
end
function test_sorted(output, cinput, input, order)
@assert cinput === output
PASSED_TESTS[] += 1
@assert issorted(output, order=order)
PASSED_TESTS[] += 1
@assert typeof(input) == typeof(output)
PASSED_TESTS[] += 1
@assert axes(input) == axes(output)
PASSED_TESTS[] += 1
nothing
end
function test_matched(a, b)
@assert all(a .=== b)
PASSED_TESTS[] += 1
nothing
end
function log_error!(row, exception, alg, input, fail_fast)
entry = (exception, input)
if alg ∉ keys(row.errors)
row.errors[alg] = []
end
push!(row.errors[alg], entry)
if fail_fast || exception isa InterruptException
global fail = row
throw(exception)
end
end
fail = nothing
function reproduce(row=fail, alg=nothing)
if fail == nothing || isempty(row.errors)
return "no errors"
end
if alg == nothing
alg = first(keys(row.errors))
end
x, input = first(row.errors[alg])
cinput = copy(input)
println("sort!($cinput, "* (row.order != Forward ? "order=$(row.order), " : "")*"alg=$alg)")
output = target!(cinput, alg, row.order)
test_sorted(output, cinput, input, row.order)
test_matched(output, sort(input, alg=MergeSort))
"no errors"
end
##Statistics
"""
function stat!(df, a=1, b=2)
Compute comparative stats for the `a`th and `b`th algorithm tested in `df`.
Returns the 95% confidence interval for the ratio of runtimes a/b for each row.
"""
function stat!(df, a=1, b=2)
df.log_test = [length(eachrow(d)) <= 1 ? missing : OneSampleTTest(d[!,a]-d[!,b]) for d in [log.(frame) for frame in df.data]]
df.pvalue = [ismissing(t) ? missing : pvalue(t) for t in df.log_test]
df.point_estimate = [ismissing(t) ? missing : exp(mean(confint(t))) for t in df.log_test]
df.confint = [ismissing(t) ? missing : exp.(confint(t)) for t in df.log_test]
end
end #module
| SortMark | https://github.com/LilithHafner/SortMark.jl.git |
|
[
"MIT"
] | 0.0.2 | 5b2502075691622572035a53ca1f852acad50e5d | code | 1693 | module Print
pluralize(n::Real, name, plural="s", singular="") = "$n $(name)$(n != 1 ? plural : singular)"
function and_join(strs::AbstractVector)
if length(strs) == 0
"nothing"
elseif length(strs) == 1
strs[1]
elseif length(strs) == 2
join(strs, " and ")
else
join(strs[1:end-1], ", ") * ", and " * last(strs)
end
end
function algs(df)
algs = union(df.algs...)
unstable = union(df.unstable...)
and_join([alg ∈ unstable ? "$alg (unstable)" : "$alg" for alg in algs])
end
function domain(df)
and_join(collect(pluralize(length(unique(a)), n) * z for (a,n,z) in [
(df.ContainerType, "container type", ""),
(df.Type, "element type", ""),
(df.len, "length", " up to $(maximum(df.len))"),
(df.order, "order", ""),
(df.source, "distribution", ""),
]))
end
function silly_split(str::AbstractString, width=last(displaysize(stdout)))
last_break=0
v = collect(str)
while true
i = last_break+width
if i > length(v)
return typeof(str)(v)
end
while true
if i <= last_break
return typeof(str)(v)
end
if v[i] == ' '
break
end
i -= 1
end
v[i] = '\n'
last_break = i
end
end
function _print(df, passed_tests, time, benchmark_time, color)
printstyled(silly_split("$(algs(df)) passed $(pluralize(passed_tests, "test")) spanning"*
" $(domain(df)) in $(round(Integer, time))s. $(round(Integer, benchmark_time))s"*
" ($(round(Integer, benchmark_time/time*100))%) spent in benchmarks.\n"), color=color)
end
end
| SortMark | https://github.com/LilithHafner/SortMark.jl.git |
|
[
"MIT"
] | 0.0.2 | 5b2502075691622572035a53ca1f852acad50e5d | code | 165 | using SortMark
df = make_df()
skip = (df.Type .<: Union{UInt64,UInt128}) .&
(df.source_key .== :small_positive)
compute!(df[(!).(skip), :])
stat!(df)
SortMark
| SortMark | https://github.com/LilithHafner/SortMark.jl.git |
|
[
"MIT"
] | 0.0.2 | 5b2502075691622572035a53ca1f852acad50e5d | docs | 8510 | # SortMark
<!-- [](https://LilithHafner.github.io/SortMark.jl/stable) -->
<!-- [](https://LilithHafner.github.io/SortMark.jl/dev) -->
[](https://github.com/LilithHafner/SortMark.jl/actions)
[](https://codecov.io/gh/LilithHafner/SortMark.jl)
A package for efficiently benchmarking and testing sorting algorithms under a wide variety of conditions.
Example usage:
```jl
]add https://github.com/LilithHafner/SortMark.jl
using SortMark
df = make_df(); #wow, what's goin on here? I whish this package were better documented.
compute!(df); #this errors... what gives?
#=
6s, Progress: 7%|███▉ | ETA: 0:00:11
Failed test set stored as SortMark.fail. Reproduce it's error with reproduce().
ERROR: AssertionError: issorted(output, order = order)
Stacktrace:
[1] log_error!(row::DataFrames.DataFrameRow{DataFrames.DataFrame, DataFrames.Index}, exception::AssertionError, alg::Base.Sort.QuickSortAlg, input::Vector{UInt128}, fail_fast::Bool)
@ SortMark ~/.julia/dev/SortMark/src/SortMark.jl:238
[2] trial(row::DataFrames.DataFrameRow{DataFrames.DataFrame, DataFrames.Index}, algs::Vector{Base.Sort.Algorithm}, inputs::Vector{Vector{UInt128}}, fail_fast::Bool)
@ SortMark ~/.julia/dev/SortMark/src/SortMark.jl:205
[3] compute!(row::DataFrames.DataFrameRow{DataFrames.DataFrame, DataFrames.Index}, fail_fast::Bool)
@ SortMark ~/.julia/dev/SortMark/src/SortMark.jl:166
[4] macro expansion
@ ~/.julia/dev/SortMark/src/SortMark.jl:109 [inlined]
[5] macro expansion
@ ~/.julia/packages/ProgressMeter/Vf8un/src/ProgressMeter.jl:940 [inlined]
[6] compute!(df::DataFrames.DataFrame; verbose::Bool, fail_fast::Bool)
@ SortMark ~/.julia/dev/SortMark/src/SortMark.jl:108
[7] compute!(df::DataFrames.DataFrame)
@ SortMark ~/.julia/dev/SortMark/src/SortMark.jl:94
[8] top-level scope
@ none:1
=#
# And what's that fancily colored text above the error message?
# hmm... "Failed test set stored as SortMark.fail"
SortMark.fail
#=
DataFrameRow
Row │ ContainerType Type len order source_key ⋯
│ Type… Type Int64 Ordering… Symbol ⋯
─────┼──────────────────────────────────────────────────────────────────────────────────────
765 │ Vector{T} where T UInt64 3162 ReverseOrdering{ForwardOrdering}… small_positive ⋯
8 columns omitted
=#
#So... I see we've got a problem for sorting arrays of 3162 small_positive unsigned 64-bit
#integers into reverse order, whatever that means... Seems highly unlikely. Here, look:
sort(rand(UInt64(0):UInt64(10), 3162), rev=true)
#=
3162-element Vector{UInt64}:
0x0000000000000004
0x0000000000000002
0x0000000000000005
0x0000000000000007
0x0000000000000005
0x0000000000000003
0x0000000000000003
0x0000000000000007
⋮
0x0000000000000006
0x000000000000000a
0x0000000000000001
0x0000000000000000
0x0000000000000006
0x0000000000000007
0x0000000000000005
=#
#wait a second, what the *** is happening??
#turns out this specific corner case for sorting is broken in julia. See https://github.com/JuliaLang/julia/pull/42718.
#coolbeans, wow. It runs tests. But I don't care about this edge case, let me start benchmarking!
compute!(df, fail_fast=false);
julia> compute!(df, fail_fast=false);
#=
6s, Progress: 100%|█████████████████████████████████████████████████| Time: 0:00:08
ERROR: Some tests did not pass: 237880 passed, 0 failed, 64 errored.
Base.Sort.MergeSortAlg() and Base.Sort.QuickSortAlg() (unstable) passed 237880 tests
spanning 1 container type, 15 element types, 11 lengths up to 100000, 2 orders, and 4
distributions in 9s. 3s (37%) spent in benchmarks.
SortMark.fail is an example of a failed set of tests. Reproduce it's error with reproduce().
=#
# Great! Errors. I love errors. Let's ignore them. Moving on...
stat!(df); #what a generic name, what is going on here?
df.pvalue
#=
1298-element Vector{Union{Missing, Float64}}:
0.07382948536988579
0.08300533865888364
0.17255705413564795
0.043603017750311335
⋮
0.1296444186512252
0.2606328408111021
0.13892181597945655
0.21527141177932066
=#
#we are comparing the runtime of two different soring algorithms:
df.algs[1]
#=
2-element Vector{Base.Sort.Algorithm}:
Base.Sort.MergeSortAlg()
Base.Sort.QuickSortAlg()
=#
#and those are the p-values indicating wheather we have a statistically significant difference.
#those pvalues are too high for my analysis. Let's get more data.
df.seconds .*= 10; #This will also make it take longer, oh well; more time to oggle at the beautiful loading bar courtesy of ProgressMeter.jl
compute!(df, fail_fast=false); # fun fact, the old data is still here. We just add more! If you want to clear the data, make a new df! (later there might be a better way)
#=
65s, Progress: 100%|██████████████████████████████████████████████████████████████████████████████████████████████████████████████| Time: 0:01:08
ERROR: Some tests did not pass: 2874132 passed, 0 failed, 780 errored.
Base.Sort.MergeSortAlg() and Base.Sort.QuickSortAlg() (unstable) passed 2874132 tests spanning 1 container type, 15 element types, 11 lengths up to
100000, 2 orders, and 4 distributions in 69s. 23s (33%) spent in benchmarks.
SortMark.fail is an example of a failed set of tests. Reproduce it's error with reproduce().
=#
#Can we take a moment to look at the numbers that just printed, that's alot of tests running! and over quite a range of inputs. Only 33% of time spent benchmarking, that doesn't sound good. When I tried this with BenchmarkTools, though, t = @timed @benchmark sort(x) setup=(x=rand(10_000)); sum(t.value.times*1e-9)/t.time gives me a similar 37%.
#Back to the data. We have to recompute stats
stat!(df);
df.pvalue
#=
1298-element Vector{Float64}:
1.038512836886463e-6
1.4407708601335978e-12
0.00031705574988325153
2.1261920179458133e-25
⋮
0.16674400469382414
0.2926325656250292
0.2092427712164047
0.25919129227369314
=#
# Okay some of those p-values are quite low.
mean(df.pvalue .< .05)
# 0.8828967642526965
# and most of them are significant. What is the speed ratio?
df.point_estimate
#=
1298-element Vector{Float64}:
1.520647201551295
1.4571719750761662
1.3179061226433113
1.436741386153265
⋮
1.012936243595496
1.0125157172530284
0.9624269936973555
1.0199318692241786
=#
#looks like that ratio is either 1.5 or 1? who knows? and what's the certianty?
df.confint
#=
1298-element Vector{Tuple{Float64, Float64}}:
(1.4132192824122347, 1.636241410206905)
(1.4028173986436836, 1.513632613197085)
(1.1469008134953327, 1.5144086809105701)
(1.400298646448291, 1.4741325473114575)
⋮
(0.994382971723014, 1.0318356838024756)
(0.9889886111508599, 1.036602511015198)
(0.9052958042424497, 1.0231636044888415)
(0.9849999662469475, 1.0561025923916885)
=#
#Better. Is MergeSort ever faster?
minimum(last.(df.confint))
# 0.975616697789511 Apparently, but probably not by a huge amount. Let's investigate.
df[minimum(last.(df.confint)) .== last.(df.confint), :]
#=
1×17 DataFrame
Row │ ContainerType Type len order source_key source algs ⋯
│ Type… Type Int64 Ordering… Symbol Function Array… ⋯
─────┼───────────────────────────────────────────────────────────────────────────────────────────────────────────
1 │ Vector{T} where T Bool 10 ForwardOrdering() simple #1 Base.Sort.Algorithm[MergeSortAl ⋯
11 columns omitted
=#
#Sorting 10 Bools... this is incredibly bizzare. Why would anyone do this? Why would we use comparison sorting?
#What even is the p-value?
findfirst(minimum(last.(df.confint)) .== last.(df.confint))
#1229
df.pvalues
#0.009056184456237987
#See, that's only .01, and we were p-hacking. We'll just repeat a more fucused study with fresh data:
empty!(df.data[1229]);
df.seconds[1229] = 1
compute!(df[1229, :]);
df.confint[1229]
#(0.97468593850494, 0.9843292697105394)
df.pvalue[1229]
#1.971128265512963e-16
#Hmm... something is afoot...
#etc. etc.
```
| SortMark | https://github.com/LilithHafner/SortMark.jl.git |
|
[
"MIT"
] | 0.0.2 | 5b2502075691622572035a53ca1f852acad50e5d | docs | 180 | ```@meta
CurrentModule = SortMark
```
# SortMark
Documentation for [SortMark](https://github.com/LilithHafner/SortMark.jl).
```@index
```
```@autodocs
Modules = [SortMark]
```
| SortMark | https://github.com/LilithHafner/SortMark.jl.git |
|
[
"BSD-3-Clause"
] | 0.4.1 | ccc61241a1b3b3e60145580de043ecb2d3a4d5bc | code | 687 | using SpectralInference
using Documenter
DocMeta.setdocmeta!(SpectralInference, :DocTestSetup, :(using SpectralInference); recursive=true)
makedocs(;
modules=[SpectralInference],
authors="Benjamin Doran and collaborators",
repo="https://github.com/aramanlab/SpectralInference.jl/blob/{commit}{path}#{line}",
sitename="SpectralInference.jl",
format=Documenter.HTML(;
prettyurls=get(ENV, "CI", "false") == "true",
canonical="https://aramanlab.github.io/SpectralInference.jl",
assets=String[],
),
pages=[
"Home" => "index.md",
],
)
deploydocs(;
repo="github.com/aramanlab/SpectralInference.jl",
devbranch="main",
)
| SpectralInference | https://github.com/aramanlab/SpectralInference.jl.git |
|
[
"BSD-3-Clause"
] | 0.4.1 | ccc61241a1b3b3e60145580de043ecb2d3a4d5bc | code | 13707 | module NewickTreeExt
using SpectralInference, NewickTree
using StatsBase: sample, mean
using NewickTree: Node
using NewickTree: prewalk, height, getpath
using NewickTree: setdistance!, setsupport!, support, getpath
"""
getleafnames(t::NewickTree.Node)
Get names of all the leafs with `t` as ancester
"""
SpectralInference.getleafnames(t::Node) = name.(getleaves(t))
"""
getleafids(t::NewickTree.Node)
Get IDs of all the leafs with `t` as ancester
"""
SpectralInference.getleafids(t::Node) = id.(getleaves(t))
# how to delete a newick tree node
function Base.delete!(n::Node)
p = parent(n)
cs = children(n)
for c in cs
push!(p, c)
end
delete!(p, n)
end
"""
network_distance(n::Node, m::Node)
shortest traversal distance between two nodes
sibling nodes would have network distance = 2
"""
function SpectralInference.network_distance(n::Node, m::Node)
p1, p2 = getpath(n, m)
(length(p1) - 1) + (length(p2) - 1)
end
"""
network_distances(t::Node)
shortest traversal distance between all leafs with `t` as ancester
sibling nodes would have network distance = 2
"""
function SpectralInference.network_distances(tree::Node)
leaves = getleaves(tree)
dists = zeros(length(leaves), length(leaves))
for j in axes(dists, 2), i in (j+1):lastindex(dists, 1)
dists[i, j] = network_distance(leaves[i], leaves[j])
dists[j, i] = dists[i, j]
end
return dists
end
"""
patristic_distance(n::Node, m::Node)
shortest branch length path between two nodes.
sibling nodes `i`, and `j` of parent `p` would have patristic `distance(i, p) + distance(j, p)`
"""
function SpectralInference.patristic_distance(n::Node, m::Node)
NewickTree.getdistance(n, m)
end
"""
patristic_distances(t::Node)
shortest branch length path between all leafs with `t` as ancester
sibling nodes `i`, and `j` of parent `p` would have patristic `distance(i, p) + distance(j, p)`
"""
function SpectralInference.patristic_distances(tree::Node)
leaves = getleaves(tree)
dists = zeros(length(leaves), length(leaves))
for j in axes(dists, 2), i in (j+1):lastindex(dists, 1)
dists[i, j] = patristic_distance(leaves[i], leaves[j])
dists[j, i] = dists[i, j]
end
return dists
end
"""
fscore_precision_recall(reftree, predictedtree)
fscore, precision, and recall of branches between the two trees
"""
function SpectralInference.fscore_precision_recall(reftree::Node, predtree::Node; β=1.0)
truesplits = keys(_tally_tree_bifurcations(reftree))
predsplits = keys(_tally_tree_bifurcations(predtree))
compsplits = [k for k in truesplits] .== permutedims([k for k in predsplits])
precision = mean(sum(compsplits; dims=1))
recall = mean(sum(compsplits; dims=2))
fscore = (1 + β) * (precision * recall) / (β * precision + recall)
return fscore, precision, recall
end
"""
tally_tree_bifurcations(rootnode::AbstractTree, [cntr::Accumulator])
returns tally of leaf groups based on splitting tree at each internal node
assumes nodenames are strings parsible to integers, and returns Accumulator with key
as a string: `1110000` where 1 = belonging to smaller group & 0 = belonging to the larger.
values are the number of times this split is observed. cntr is modified in place so using
the same counter in multiple calls will keep a tally across multiple trees
"""
function _tally_tree_bifurcations(tree::Node, cntr=Dict{BitVector,Int}(); countroot=true)
leafnames = sort(getleafnames(tree))
nleaves = length(leafnames)
for node in prewalk(tree)
# only internal nodes
isleaf(node) && continue
!countroot && isroot(node) && continue
# get leaves
key = zeros(Bool, nleaves)
subsetleaves = indexin(getleafnames(node), leafnames)
key[subsetleaves] .= true
# convert to bitstring true := smaller cluster
keystr = sum(key) <= nleaves / 2 ? key : .!key
cntr[keystr] = 1 + get(cntr, keystr, 0)
end
cntr
end
"""
cuttree(distfun::Function, tree::NewickTree.Node, θ)
returns all vector of Nodes where distance to root is
greater than theta `d > θ`.
distance function must take to NewickTree.Node objects and
compute a scaler distance between them.
"""
function SpectralInference.cuttree(distfun::Function, tree::Node, θ)
θ ≤ distfun(tree, tree) && return [tree]
ns = typeof(tree)[]
# define tree traversal
function walk!(n, t)
distn = distfun(n, t)
distp = distfun(parent(n), t)
# if edge crosses θ then add current node
if distp ≤ θ < distn
push!(ns, n)
return
# if node is leaf an within θ add as singlet cluster
elseif isleaf(n) && distn ≤ θ
push!(ns, n)
return
# otherwise continue taversing tree
else
!isleaf(n) && for c in n.children
walk!(c, t)
end
return
end
end
# actually taverse the tree
for c in tree.children
walk!(c, tree)
end
return ns
end
"""
mapnodes(fun::Function, tree::NewickTree.Node, args...; filterfun::Function=x->true, kwargs...)
maps function `fun()` across internal nodes of tree.
args and kwargs are passed to `fun()`
"""
function SpectralInference.mapnodes(fun::Function, tree::Node, args...; filterfun::Function=x -> true, kwargs...)
results = Vector()
for (i, node) in enumerate(prewalk(tree))
# only internal nodes
filterfun(node) || continue
# run function
push!(results, fun(node, args...; kwargs...))
end
return results
end
"""
mapinternalnodes(fun::Function, tree::NewickTree.Node, args...; kwargs...)
maps function `fun()` across internal nodes of tree.
args and kwargs are passed to `fun()`
"""
function SpectralInference.mapinternalnodes(fun::Function, tree::Node, args...; kwargs...)
results = Vector()
for (i, node) in enumerate(prewalk(tree))
# only internal nodes
isleaf(node) && continue
# run function
push!(results, fun(node, args...; kwargs...))
end
return results
end
"""
maplocalnodes(fun::Function, tree::NewickTree.Node, args...; kwargs...)
maps function `fun()` across internal nodes of tree conditioned on having
one direct child that is a leaf.
args and kwargs are passed to `fun()`
"""
function SpectralInference.maplocalnodes(fun::Function, tree::Node, args...; kwargs...)
results = Vector()
for (i, node) in enumerate(prewalk(tree))
# only internal nodes
isleaf(node) && continue
# only nodes that have a leaf as child
all(.!isleaf.(children(node))) && continue
# run function
push!(results, fun(node, args...; kwargs...))
end
return results
end
"""
collectiveLCA(nodes)
finds last common ancester of a collection of Nodes
"""
function SpectralInference.collectiveLCA(nodes::AbstractArray{<:NewickTree.Node})
lca = map(b -> NewickTree.getlca(nodes[1], b), nodes[2:end])
idx = argmin(NewickTree.height.(lca))
lca[idx]
end
"""
as_polytomy(fun::Function, tree::NewickTree.Node)
as_polytomy!(fun::Function, tree::NewickTree.Node)
removes internal nodes from tree based on `fun()`
which must return true if node is to be removed
by default removes zero length branches
(i.e. nodes where distance between child and parent == 0)
"""
function SpectralInference.as_polytomy(fun::Function, tree::Node)
tree_new = deepcopy(tree)
as_polytomy!(fun, tree_new)
tree_new
end
function SpectralInference.as_polytomy!(fun::Function, tree::Node)
for n in filter(fun, prewalk(tree))
!isroot(n) && !isleaf(n) && delete!(n)
end
end
"""
ladderize!(tree, rev=false)
sorts children of each node by number of leaves descending from the child in ascending order.
"""
function SpectralInference.ladderize!(t; rev=false)
function walk!(n)
if isleaf(n)
return 1
else
numleaves = [walk!(c) for c in children(n)]
n.children .= n.children[sortperm(numleaves, rev=rev)]
return sum(numleaves)
end
end
walk!(t)
end
"""
spectral_lineage_encoding(tree::Node, orderedleafnames=getleafnames(tree); filterfun=x->true)
returns vector of named tuples with the id `nodeid` of the node and `sle` a vector of booleans
ordered by `orderedleafnames` where true indicates the leaf descends from the node and false indicates that it does not.
"""
function SpectralInference.spectral_lineage_encoding(tree::Node, orderedleafids=getleafids(tree); filterfun=x -> true)
map(filter(filterfun, prewalk(tree))) do node
tmp = falses(length(orderedleafids))
tmp[indexin(getleafids(node), orderedleafids)] .= true
nodeid = id(node)
(; nodeid, sle=tmp)
end
end
"""
pairedMI_across_treedepth(metacolumns, metacolumns_ids, tree)
pairedMI_across_treedepth(metacolumns, metacolumns_ids, compare::Function=(==), tree::Node; ncuts=100, bootstrap=false, mask=nothing)
iterates over each metacolumn and calculates MI between the paired elements of the metacolumn and the paired elements of tree clusters.
Args:
* metacolumns: column iterator, can be fed to `map(metacolumns)`
* metacolumn_ids: ids for each element in the metacolumn. should match the leafnames of the tree, but not necessarily the order.
* tree: NewickTree tree
* compare: function used to calculate similarity of two elements in metacolumn.
Should be written for each element as it will be broadcast across all pairs.
Returns:
* (; MI, treedepths)
* MI: Vector{Vector{Float64}} MI for each metacolumn and each tree depth
* treedepths Vector{<:Number} tree depth (away from root) for each cut of the tree
"""
function SpectralInference.pairedMI_across_treedepth(metacolumns, metacolumn_ids, tree::Node;
comparefun::Function=(==), treecut_distancefun::Function=network_distance, ncuts=100, bootstrap=false, mask=nothing)
clusts, treedepths = clusters_per_cutlevel(treecut_distancefun, tree, ncuts)
clust_names = getleafnames(tree)
MI = map(metacolumns) do mcol
pmcol = comparefun.(mcol, permutedims(mcol))
_collectMI_across_treedepth(clusts, clust_names, metacolumn_ids, pmcol; bootstrap, mask)
end
(; MI, treedepths)
end
"""
clusters_per_cutlevel(distfun::Function, tree::Node, ncuts::Number)
Returns:
* clusts: vector of cluster-memberships. each value indicates the cluster membership of the leaf at that cut.
leaves are ordered in prewalk order within each membership vector
* treedepths: distance from root for each of the `ncuts`
"""
function SpectralInference.clusters_per_cutlevel(distfun::Function, tree::Node, ncuts::Number)
minmax = extrema(maplocalnodes(distfun, tree, tree))
treedepths = range(zero(first(minmax)), minmax[2], length=ncuts)
clusts_nodes = [cuttree(distfun, tree, cut) for cut in treedepths]
clustmappings = map(c -> getleafnames.(c), clusts_nodes)
clusts = [Int.(vcat([zeros(length(c)) .+ j for (j, c) in enumerate(clustmapping)]...)) for clustmapping in clustmappings]
(; clusts, treedepths)
end
function _collectMI_across_treedepth(clusts, clust_names, IDS, ptax; bootstrap=false, mask=nothing)
uppertriangle = triu(trues(size(ptax)), 1)
uppertriangle = isnothing(mask) ? uppertriangle : uppertriangle[mask, mask]
clustorder = indexin(IDS, clust_names)
# ptax = if isnothing(mask) ptax[uppertriangle] else ptax[mask, mask][uppertriangle] end
map(clusts) do cids
ptax, mask, clustorder, uppertriangle
pcids = cids[clustorder] .== permutedims(cids[clustorder])
pcids = if isnothing(mask)
pcids
else
pcids[mask, mask]
end
wptax = if isnothing(mask)
ptax
else
ptax[mask, mask]
end
pcids = pcids[uppertriangle]
wptax = wptax[uppertriangle]
if bootstrap
vals_idx = sample(axes(pcids, 1), length(pcids), replace=true)
pcids = pcids[vals_idx]
wptax = wptax[vals_idx]
end
empiricalMI(wptax, pcids)
end
end
using PrecompileTools
@setup_workload begin
@compile_workload begin
N = 10
for T in [Float64, Float32, Int64, Int32]
m = rand(T, N, N)
usv = svd(m)
dij = spectraldistances(usv.U, usv.S, getintervals(usv.S))
hc = UPGMA_tree(dij)
tree = readnw(newickstring(hc, string.(1:N)))
leafnames = getleafnames(tree)
network_distances(tree)
patristic_distances(tree)
fscore_precision_recall(tree, tree) == (1.0, 1.0, 1.0)
cuttree(network_distance, tree, 0.0)
collectiveLCA(getleaves(tree))
as_polytomy(n -> NewickTree.support(n) < 0.5, tree)
mi, treedepths = pairedMI_across_treedepth((; a=rand(Bool, N), b=rand([1, 0], N)), leafnames, tree; ncuts=5)
mi, treedepths = pairedMI_across_treedepth((; a=rand(UInt16, N), b=rand(Float64, N)), leafnames, tree; ncuts=5, comparefun=(x, y) -> abs(x - y))
mi, treedepths = pairedMI_across_treedepth((; a=rand(UInt16, N), b=rand(Float64, N)), leafnames, tree; treecut_distancefun=patristic_distance, ncuts=5, comparefun=(x, y) -> abs(x - y))
leafids = getleafids(tree)
spectral_lineage_encoding(tree)
spectral_lineage_encoding(tree, leafids)
spectral_lineage_encoding(tree; filterfun=!isleaf)
spectral_lineage_encoding(tree, leafids; filterfun=!isleaf)
end
end
end
end # module | SpectralInference | https://github.com/aramanlab/SpectralInference.jl.git |
|
[
"BSD-3-Clause"
] | 0.4.1 | ccc61241a1b3b3e60145580de043ecb2d3a4d5bc | code | 1433 | module SpectralInference
using Reexport
using StatsBase: indicatormat, quantile, cor, fit, Histogram, entropy
using Distances: Distances, WeightedEuclidean
using Clustering: Clustering, hclust, Hclust
using SparseArrays: sparse
using LinearAlgebra: svd, SVD
using Printf: @sprintf
using FreqTables: freqtable
using CategoricalArrays: cut
@reexport using LinearAlgebra
@reexport using Clustering: hclust
const ALPHA = 1.0
const QUANT = 0.5
export spectraldistances,
spectraldistances_trace,
spectralcorrelations,
getintervalsIQR,
getintervals,
projectinLSV, projectinRSV, projectout,
UPGMA_tree,
newickstring
include("core.jl")
export explainedvariance, scaledcumsum,
distancetrace_spaceneeded, distancematrix_spaceneeded,
squareform
include("helpers.jl")
export empiricalMI, adjustedrandindex, vmeasure_homogeneity_completeness
include("empiricalMI.jl")
export readphylip, onehotencode
include("parsephylip.jl")
# extension functions
export getleafnames,
getleafids,
network_distance,
network_distances,
patristic_distance,
patristic_distances,
fscore_precision_recall,
cuttree,
mapnodes,
mapinternalnodes,
maplocalnodes,
collectiveLCA,
as_polytomy,
as_polytomy!,
pairedMI_across_treedepth,
clusters_per_cutlevel,
ladderize!,
spectral_lineage_encoding
include("treefunctions.jl")
include("precompile_workload.jl")
end
| SpectralInference | https://github.com/aramanlab/SpectralInference.jl.git |
|
[
"BSD-3-Clause"
] | 0.4.1 | ccc61241a1b3b3e60145580de043ecb2d3a4d5bc | code | 9868 |
"""
getintervals(S::AbstractVector{<:Number}; alpha=1.0, q=0.5)
finds spectral partitions. Computes log difference between each subsequent singular
value and by default selects the differences that are larger than `1.0 * Q2(differences)`
i.e. finds breaks in the spectrum that explain smaller scales of variance
Args:
* S: singular values of a SVD factorization
* alpha: scalar multiple of `q`
* q: which quantile of log differences to use; by default Q2
Returns:
* AbstractVector{UnitRange} indices into S corresponding to the spectral partitions
"""
function getintervals(S::AbstractVector{<:Number}; alpha=1.0, q=0.5)
potentialbreaks = abs.(diff(log.(S .+ 1)))
θ = alpha * quantile(potentialbreaks, q)
breaks = findall(potentialbreaks .> θ) .+ 1
starts, ends = vcat(1, breaks), vcat(breaks .- 1, length(S))
intervals = map((s, e) -> s:e, starts, ends)
return intervals
end
"""
getintervals_IQR(S::AbstractVector{<:Number}; alpha=1.5, ql=.25, qh=.75)
finds spectral partitions. Computes log difference between each subsequent singular
value and by default selects the differences that are larger than `1.5 * IQR(differences)`
i.e. finds breaks in the spectrum that explain smaller scales of variance
Args:
* S: singular values of a SVD factorization
* alpha: scalar multiple of `q`
* q: which quantile of log differences to use; by default Q3
Returns:
* AbstractVector{UnitRange} indices into S corresponding to the spectral partitions
"""
function getintervalsIQR(S::AbstractVector{<:Number}; alpha=1.5, ql=0.25, qh=0.75)
potentialbreaks = abs.(diff(log.(S .+ 1)))
Q1, Q3 = quantile(potentialbreaks, [ql, qh])
θ = Q3 + alpha * (Q3 - Q1)
breaks = findall(potentialbreaks .> θ) .+ 1
starts, ends = vcat(1, breaks), vcat(breaks .- 1, length(S))
intervals = map((s, e) -> s:e, starts, ends)
return intervals
end
"""
spectraldistances(A::AbstractMatrix; [onrows=true, alpha=1.0, q=0.5])
spectraldistances(usv::SVD; [onrows=true, alpha=1.0, q=0.5])
spectraldistances(vecs::AbstactMatrix, vals::AbstractMatrix, intervals::AbstractVector{<:UnitRange})
computes the cumulative spectral residual distance for spectral phylogenetic inference
```(∑_{p ∈ P} ||UₚΣₚ||₂)²```
where ``P`` are the spectral partitions found with `getintervals`.
Args:
* A, usv: AbstractMatrix or SVD factorization (AbstractMatrix is passed to `svd()` before calculation)
* onrows: if true will compute spectral distances on the left singular vectors (U matrix), if false will calculate on the right singular vectors or (V matrix)
* alpha, q: are passed to `getintervals()` see its documentation
Returns:
* distance matrix
"""
function spectraldistances(A::AbstractMatrix{<:Number}; onrows=true::Bool, alpha=ALPHA, q=QUANT)
spectraldistances(svd(A); onrows, alpha, q)
end
function spectraldistances(usv::SVD; onrows=true::Bool, alpha=ALPHA, q=QUANT)
if onrows
spectraldistances(usv.U, usv.S; alpha, q)
else
spectraldistances(usv.V, usv.S; alpha, q)
end
end
function spectraldistances(vecs::AbstractMatrix{<:T}, vals::AbstractVector{<:T}; alpha=ALPHA, q=QUANT) where {T<:Number}
intervals = getintervals(vals; alpha, q)
spectraldistances(vecs, vals, intervals)
end
function spectraldistances(vecs::AbstractMatrix{<:T}, vals::AbstractVector{<:T}, intervals::AbstractVector) where {T<:Number}
spimtx = zeros(size(vecs, 1), size(vecs, 1))
for grp in intervals
spimtx += Distances.pairwise(WeightedEuclidean(vals[grp]), vecs'[grp, :]; dims=2)
end
return spimtx .^ 2
end
"""
spectraldistances_trace(usv::SVD; onrows=true, groups=nothing, alpha=1.0, q=0.5)
spectraldistances_trace(vecs, vals, groups)
calculates spectral residual within each partition of spectrum and each pair of taxa
returns matrix where rows are spectral partitions and columns are taxa:taxa pairs
ordered as the upper triangle in rowwise order, or lower triangle in colwise order.
Args:
* method: `spectraldistances_trace(vecs, vals, groups)`
* vecs: either usv.U or usv.V matrix
* vals: usv.S singular values vector
* groups: usually calculated with `getintervals(usv.S; alpha=alpha, q=q)`
* method: `spectraldistances_trace(usv::SVD; onrows=true, groups=nothing, alpha=1.0, q=0.5)`
* usv: SVD object
* onrows: true/false switch to calculate spectral distance on rows (U matrix) or columns (V matrix).
* groups: if nothing groups are calculated with `getintervals(usv.S; alpha=alpha, q=q)`,
otherwise they assume a vector of index ranges `[1:1, 2:3, ...]` to group `usv.S` with.
* alpha: passed to `getintervals`
* q: passed to `getintervals`
"""
function spectraldistances_trace(usv::SVD; onrows=true, groups=nothing, alpha=ALPHA, q=QUANT)
groups = isnothing(groups) ? getintervals(usv.S; alpha=alpha, q=q) : groups
vecs = onrows ? usv.U : usv.V
r = zeros(length(groups), binomial(size(vecs, 1), 2))
spectraldistances_trace!(r, vecs, usv.S, groups)
return r
end
function spectraldistances_trace(vecs, vals, groups)
Nsmps = size(vecs, 1)
r = zeros(length(groups), binomial(Nsmps, 2))
spectraldistances_trace!(r, vecs, vals, groups)
return r
end
function spectraldistances_trace!(r, vecs, vals, groups)
Nsmps = size(vecs, 1)
for (k, (i, j)) in enumerate(((i, j) for j in 1:Nsmps for i in (j+1):Nsmps))
for (g, grp) in enumerate(groups)
r[g, k] = WeightedEuclidean(vals[grp])(vecs'[grp, i], vecs'[grp, j])
end
end
end
"""
projectinLSV(data::AbstractArray{T}, usv::SVD{T}, [window])
returns estimated left singular vectors (aka: LSV or Û) for new data based on already calculated SVD factorization
"""
projectinLSV(data::AbstractArray, usv::SVD) = data * usv.V * inv(diagm(usv.S))
projectinLSV(data::AbstractArray, usv::SVD, window) = data * usv.V[:, window] * inv(diagm(usv.S[window]))
"""
projectinRSV(data::AbstractArray, usv::SVD, [window])
returns estimated transposed right singular vectors (RSV or V̂ᵗ) for new data based on already calculated SVD factorization
"""
projectinRSV(data::AbstractArray, usv::SVD) = inv(diagm(usv.S)) * usv.U' * data
projectinRSV(data::AbstractArray, usv::SVD, window) = inv(diagm(usv.S[window])) * usv.U'[window, :] * data
"""
projectout(usv::SVD, [window])
recreates original matrix i.e. calculates ``UΣV'`` or if window is included
creates a spectrally filtered version of the original matrix off of the provided components in `window`.
i.e., `usv.U[:, window] * diagm(usv.S[window]) * usv.Vt[window, :]`
"""
projectout(usv::SVD) = usv.U * diagm(usv.S) * usv.Vt
projectout(usv::SVD, window) = usv.U[:, window] * diagm(usv.S[window]) * usv.Vt[window, :]
"""
UPGMA_tree(Dij::AbstractMatrix{<:Number})
shorthand for `Clustering.hclust(Dij, linkage=:average, branchorder=:optimal)`
"""
function UPGMA_tree(Dij::AbstractMatrix{<:Number})
Clustering.hclust(Dij, linkage=:average, branchorder=:optimal)
end
"""
calc_spcorr_mtx(vecs::AbstractMatrix{<:Number}, window)
calc_spcorr_mtx(vecs::AbstractMatrix{<:Number}, vals::AbstractVector{<:Number}, window)
Calculates pairwise spectral (pearson) correlations for a set of observations.
Args:
* vecs: set of left or right singular vectors with observations/features on rows and spectral components on columns
* vals: vector of singular values
* window: set of indices of `vecs` columns to compute correlations across
Returns:
* correlation matrix where each pixel is the correlation between a pair of observations
"""
function spectralcorrelations(vecs::AbstractMatrix{<:Number}, window)
cor(vecs[:, window]')
end
function spectralcorrelations(vecs::AbstractMatrix{<:Number}, vals::AbstractVector{<:Number}, window)
contributions = vecs[:, window] * diagm(vals[window])
cor(contributions')
end
"""
newickstring(hc::Hclust[, tiplabels::AbstractVector[<:String]])
convert Hclust to newick tree string
Args:
* hc: `Hclust` object from Clustering package
* tiplabels: `AbstractVector{<:String}` names in same order as distance matrix
Returns:
* [newick tree](https://en.wikipedia.org/wiki/Newick_format) formated string
"""
newickstring(hc::Hclust; labelinternalnodes=false) = newickstring(hc, string.(1:length(hc.order)); labelinternalnodes)
newickstring(hc::Hclust, tiplabels::AbstractVector{<:Symbol}; labelinternalnodes=false) = newickstring(hc, string.(tiplabels); labelinternalnodes)
function newickstring(hc::Hclust, tiplabels::AbstractVector{<:AbstractString}; labelinternalnodes=false)
r = length(hc.heights)
_newickstring(view(hc.merges, :, :), view(hc.heights, :), r, r, view(tiplabels, :); labelinternalnodes) * ";"
end
function _newickstring(merges::A, heights::B, i::C, p::C, tiplabels::D; labelinternalnodes=false)::String where {
A<:AbstractArray{<:Integer},B<:AbstractVector{<:AbstractFloat},
C<:Integer,D<:AbstractVector{<:AbstractString}
}
j::Int64 = merges[i, 1] # left subtree pointer
k::Int64 = merges[i, 2] # right subtree pointer
a::String = if j < 0 # if tip format tip
tiplabels[abs(j)] * ':' * @sprintf("%e", heights[i])
else # recurse and format internal node
_newickstring(view(merges, :, :), view(heights, :), j, i, view(tiplabels, :); labelinternalnodes)
end
b::String = if k < 0 # if tip format tip
tiplabels[abs(k)] * ':' * @sprintf("%e", heights[i])
else # recurse and format internal node
_newickstring(view(merges, :, :), view(heights, :), k, i, view(tiplabels, :); labelinternalnodes)
end
nid = labelinternalnodes ? "node" * string(length(heights) + i + 1) : ""
dist = @sprintf("%e", heights[p] - heights[i])
_newick_merge_strings(a, b, nid, dist)
end
function _newick_merge_strings(a::S, b::S, n::S, d::S) where {S<:String}
'(' * a * ',' * b * ')' * n * ':' * d
end | SpectralInference | https://github.com/aramanlab/SpectralInference.jl.git |
|
[
"BSD-3-Clause"
] | 0.4.1 | ccc61241a1b3b3e60145580de043ecb2d3a4d5bc | code | 7017 | ### MI functions ###
"""
empiricalMI(a::AbstractVector{<:Float}, b::AbstractVector{<:Float}[, nbins=50, normalize=false])
computes empirical MI from identity of ``H(a) + H(b) - H(a,b)``. where
``H := -sum(p(x)*log(p(x))) + log(Δ)``
the ``+ log(Δ)`` corresponds to the log binwidth and unbiases the entropy estimate from binwidth choice.
estimates are roughly stable from ``32`` (``32^2 ≈ 1000`` total bins) to size of sample. going from a small undersestimate to a small overestimate across that range.
We recommend choosing the `sqrt(mean(1000, samplesize))` for `nbins` argument, or taking a few estimates across that range and averaging.
Args:
* a, vecter of length N
* b, AbstractVector of length N
* nbins, number of bins per side, use 1000 < nbins^2 < length(a) for best results
* base, base unit of MI (defaults to nats with base=ℯ)
* normalize, bool, whether to normalize with mi / mean(ha, hb)
Returns:
* MI
"""
function empiricalMI(a::AbstractVector{T}, b::AbstractVector{T}; nbins=50, base=ℯ, normalize=false) where {T<:AbstractFloat}
# num samples marginal then total
N = length(a)
breaks_a = range(minimum(a), maximum(a), length=nbins)
breaks_b = range(minimum(b), maximum(b), length=nbins)
ab_counts = fit(Histogram, (a, b), (breaks_a, breaks_b)).weights
a_counts = sum(ab_counts; dims=1)
b_counts = sum(ab_counts; dims=2)
# frequency
afreq = vec((a_counts) ./ (N))
bfreq = vec((b_counts) ./ (N))
abfreq = vec((ab_counts) ./ (N))
Δ_a = breaks_a[2] - breaks_a[1]
Δ_b = breaks_b[2] - breaks_b[1]
# approx entropy
ha = entropy(afreq, base) + log(base, Δ_a)
hb = entropy(bfreq, base) + log(base, Δ_b)
hab = entropy(abfreq, base) + log(base, Δ_a * Δ_b)
# mi
mi = ha + hb - hab
mi = normalize ? 2mi / (ha + hb) : mi
# return (mi = mi, ha = ha, hb = hb, hab = hab)
return mi
end
# value grouped by binary catagory
function empiricalMI(ab::AbstractVector{F}, mask::M; nbins=100, base=ℯ, normalize=false) where {F<:Number,M<:Union{BitVector,AbstractVector{<:Bool}}}
length(ab) == length(mask) ||
throw(ArgumentError("length of vals and meta must match; got vals=$(length(vals)), meta=$(length(meta))"))
# num samples marginal then total
N = length(ab)
Na, Nb = sum(mask), (length(mask) - sum(mask))
mask = Bool.(mask)
# if mask is not grouping than there is no added information
Na > 0 && Nb > 0 || return mi = 0.0
## otherwise ##
# form edges
edges = range(minimum(ab), maximum(ab), length=nbins)
# fit hist and get counts
a_counts = fit(Histogram, ab[mask], edges).weights
b_counts = fit(Histogram, ab[.!mask], edges).weights
ab_counts = a_counts .+ b_counts
# get binwidth
Δ = edges[2] - edges[1]
# frequency
afreq = vec((a_counts) ./ (Na)) #Δ/Δ
bfreq = vec((b_counts) ./ (Nb)) #Δ/Δ
abfreq = vec((ab_counts) ./ (N)) #Δ/Δ
# approx entropy
ha = entropy(afreq, base) + log(base, Δ)
hb = entropy(bfreq, base) + log(base, Δ)
hab = entropy(abfreq, base) + log(base, Δ)
# mi
mi = hab - (Na / N * ha + Nb / N * hb) # original had flipped signs
# return (mi = mi, ha = ha, hb = hb, hab = hab)
mi = normalize ? 2mi / (ha + hb) : mi
return mi
end
# value grouped by multiple categories
function empiricalMI(a::AbstractVector{V}, b::AbstractVector{M}; nbins=100, kwargs...) where
{V<:AbstractFloat,M<:AbstractString}
binned_a, a_bw = _bin_numbers(a, nbins)
empiricalMI(binned_a, b; bw_a=a_bw, kwargs...)
end
# discrete catagories
empiricalMI(a::BitVector, b::BitVector; kwargs...) = empiricalMI(Int.(a), Int.(b); kwargs...)
function empiricalMI(a::AbstractVector{T}, b::AbstractVector{T}; bw_a=1.0, bw_b=1.0, base=ℯ, normalize=false) where
{T<:Union{Integer,AbstractString}}
counts = freqtable(a, b)
N = sum(counts)
Ha = entropy(sum(counts, dims=2) ./ N, base) + log(base, bw_a)
Hb = entropy(sum(counts, dims=1) ./ N, base) + log(base, bw_b)
Hab = entropy(counts ./ N, base) + log(base, bw_a * bw_b)
mi = Ha + Hb - Hab
mi = normalize ? 2mi / (Ha + Hb) : mi
end
_bin_numbers(v::AbstractVector{<:AbstractString}, nbins) = v, 1.0
_bin_numbers(v::AbstractVector{<:Integer}, nbins) = string.(v), 1.0
function _bin_numbers(v::AbstractVector{<:Number}, nbins)
breaks = range(minimum(v), maximum(v), length=nbins)
delta = breaks[2] - breaks[1]
binned_v = cut(v, breaks; extend=true)
return string.(binned_v), delta
end
"""
vmeasure_homogeneity_completeness(labels_true, labels_pred; β=1.)
calculates and returns v-measure, homogeneity, completeness;
similar to f-score, precision, and recall respectively
Args:
* β, weighting term for v-measure, if β is greater than 1 completeness
is weighted more strongly in the calculation, if β is less than 1,
homogeneity is weighted more strongly
Citation:
* A. Rosenberg, J. Hirschberg, in Proceedings of the 2007 Joint Conference
on Empirical Methods in Natural Language Processing and Computational Natural
Language Learning (EMNLP-CoNLL) (Association for Computational Linguistics,
Prague, Czech Republic, 2007; https://aclanthology.org/D07-1043), pp. 410–420.
"""
function vmeasure_homogeneity_completeness(labels_true, labels_pred; β=1.0)
if length(labels_true) == 0
return 1.0, 1.0, 1.0
end
N = length(labels_true)
entropy_C = entropy(freqtable(labels_true) ./ N)
entropy_K = entropy(freqtable(labels_pred) ./ N)
entropy_CK = entropy(freqtable(labels_true, labels_pred) ./ N)
MI = entropy_C + entropy_K - entropy_CK
homogeneity = entropy_C != 0.0 ? (MI / entropy_C) : 1.0
completeness = entropy_K != 0.0 ? (MI / entropy_K) : 1.0
if homogeneity + completeness == 0.0
v_measure_score = 0.0
else
v_measure_score = (
(1 + β) * homogeneity * completeness / (β * homogeneity + completeness)
)
end
return v_measure_score, homogeneity, completeness
end
"""
adjustedrandindex(a::AbstractVector{<:Number}, b::AbstractVector{<:Number}; nbins=50)
Args:
* a, vector of numbers
* b, vector of numbers
* nbins, for continuous approximates discrete, for discrete choose nbins>max_number_of_classes
"""
function adjustedrandindex(a::AbstractVector{<:Number}, b::AbstractVector{<:Number}; nbins=50)
# num samples marginal then total
N = length(a)
ab = vcat(a, b)
breaks = range(minimum(ab), maximum(ab), length=nbins)
# contingency and marginal counts
ab_counts = fit(Histogram, (a, b), (breaks, breaks)).weights
a_counts = sum(ab_counts; dims=1)
b_counts = sum(ab_counts; dims=2)
# count possible pairs
contingentpairs = sum(binomial.(abcounts, 2))
a_pairs = sum(binomial.(a_counts, 2))
b_pairs = sum(binomial.(b_counts, 2))
possiblepairs = binomial(N, 2)
expectedpairs = a_pairs * b_pairs / possiblepairs
# calculate ARI
return (contingentpairs - expectedpairs) / ((a_pairs + b_pairs) / 2 - expectedpairs) # ARI
end
| SpectralInference | https://github.com/aramanlab/SpectralInference.jl.git |
|
[
"BSD-3-Clause"
] | 0.4.1 | ccc61241a1b3b3e60145580de043ecb2d3a4d5bc | code | 3519 | """
scaledcumsum(c; dims=1)
cumsum divided by maximum cumulative value
"""
function scaledcumsum(c; dims=1)
cc = cumsum(c, dims=dims)
cc ./ maximum(cc, dims=dims)
end
"""
explainedvariance(s::AbstractVector{<:Number})
"""
function explainedvariance(s::AbstractVector{<:Number})
s .^ 2 / sum(s .^ 2)
end
"""
distancetrace_spaceneeded(n, p; bits=64) = Base.format_bytes(binomial(n,2) * p * bits)
how much memory is needed to store spectral residual trace
Args:
* n: number of samples
* p: number of partitions/components
"""
distancetrace_spaceneeded(n, p; bits=64) = Base.format_bytes(binomial(n, 2) * p * bits)
"""
distancematrix_spaceneeded(n, p; bits=64) = Base.format_bytes(binomial(n,2) * p * bits)
how much memory is needed to store distance matrix
Args:
* n: number of samples
"""
distancematrix_spaceneeded(n; bits=64) = Base.format_bytes(n^2 * bits)
"""
pairwise(func::Function, m::AbstractMatrix)
returns the lower columnwise offdiagonal of `result[k] = func(i, j)`
where k is the kth pair and i and j are the ith and kth columns of m
calculated from `enumerate(((i, j) for j in axes(m, 2) for i in (j+1):lastindex(m, 2)))`
"""
function pairwise(func::Function, m::AbstractMatrix)
result = zeros(binomial(size(m, 2), 2))
for (k, (i, j)) in enumerate(((i, j) for j in axes(m, 2) for i in (j+1):lastindex(m, 2)))
result[k] = func(m[:, i], m[:, j])
end
return result
end
numpairs2N(x) = (1 + sqrt(1 + 8x)) / 2
checkoffdiagonal(d) = numpairs2N(length(d)) % 1 == 0
"""
squareform(d::AbstractVector, fillvalue=zero(eltype(d)))
squareform(d::AbstractVector, fillvalue=zero(eltype(d)))
If `d` is a vector, `squareform` checks if it of `n` choose 2 length for integer `n`, then fills the values of a symetric square matrix with the values of `d`.
If `d` is a matrix, `squareform` checks if it is square then fills the values of vector with the lower offdiagonal of matrix `d` in column order form.
`fillvalue` is the initial value of the produced vector or matrix. Only really apparant in a produced matrix where it will be the values on the diagonal.
"""
function squareform(d::AbstractVector, fillvalue=zero(eltype(d)))
checkoffdiagonal(d) || throw(ArgumentError("Vector wrong length, to be square matrix offdiagonals"))
n = numpairs2N(length(d))
Dij = fill(fillvalue, Int(n), Int(n))
for (k, (i, j)) in enumerate(((i, j) for j in axes(Dij, 2) for i in (j+1):lastindex(Dij, 1)))
Dij[i, j] = d[k]
Dij[j, i] = d[k]
end
Dij
end
function squareform(d::AbstractMatrix, fillvalue=zero(eltype(d)))
(size(d, 1) == size(d, 2)) || throw(ArgumentError("size of d: $(size(d)), is not square"))
n = binomial(size(d, 1), 2)
Dk = fill(fillvalue, n)
for (k, (i, j)) in enumerate(((i, j) for j in axes(d, 2) for i in (j+1):lastindex(d, 1)))
Dk[k] = d[i, j]
end
Dk
end
"""
k2ij(k, n)
which pair `(i,j)` produces the `k`th element of combinations(vec), where vec is length `n`
"""
function k2ij(k, n) # column major ordering of lower triangle
rvLinear = (n * (n - 1)) ÷ 2 - k
i = floor(Int, (sqrt(1 + 8 * rvLinear) - 1) ÷ 2)
j = rvLinear - i * (i + 1) ÷ 2
(n - j, n - (i + 1))
end
"""
ij2k(i,j,n)
with pair `(i,j)` give index `k` to the pairs produced by combinations(vec), where vec is length `n`
"""
function ij2k(i, j, n) # for symetric matrix
i, j = i < j ? (i, j) : (j, i)
k = ((n * (n - 1)) ÷ 2) - ((n - i) * ((n - i) - 1)) ÷ 2 + j - n
end
| SpectralInference | https://github.com/aramanlab/SpectralInference.jl.git |
|
[
"BSD-3-Clause"
] | 0.4.1 | ccc61241a1b3b3e60145580de043ecb2d3a4d5bc | code | 1011 | """
readphylip(fn::String)
Read phylip alignment file, return dataframe of IDs and Sequences
"""
function readphylip(fn::AbstractString)
smps, seqs = open(fn, "r") do reader
nsmp, nfeat = parse.(Int, split(readline(reader)))
smps = String[]
seqs = String[]
for l in 1:nsmp
smp, seq = split(readline(reader))
push!(smps, smp)
push!(seqs, seq)
end
all(s -> length(s) == nfeat, seqs) || throw(DimensionMismatch("Length of all sequences must be the equal"))
return smps, seqs
end
return (; smps, seqs)
end # read phylip
onehotencode(seqs::AbstractVector{<:AbstractString}) = onehotencode(_stringcolumntocharmtx(seqs))
function onehotencode(chardf::AbstractMatrix{<:Char})
ohemtx = Vector()
for col in eachcol(chardf)
push!(ohemtx, indicatormat(col)')
end
return sparse(hcat(ohemtx...))
end
function _stringcolumntocharmtx(seqs)
reduce(vcat, permutedims.(collect.(seqs)))
end | SpectralInference | https://github.com/aramanlab/SpectralInference.jl.git |
|
[
"BSD-3-Clause"
] | 0.4.1 | ccc61241a1b3b3e60145580de043ecb2d3a4d5bc | code | 665 | using PrecompileTools
@setup_workload begin
@compile_workload begin
for T in [Float64, Float32, Int64, Int32]
m = rand(T, 10, 10)
usv = svd(m)
dij = spectraldistances(usv.U, usv.S, getintervals(usv.S))
dij = spectraldistances(usv, alpha=1.0, q=0.5)
dij_trace = spectraldistances_trace(usv, alpha=1.0, q=0.5)
dij_trace = spectraldistances_trace(usv.U, usv.S, getintervalsIQR(usv.S))
spcorr = spectralcorrelations(usv.U, 1:4)
spcorr = spectralcorrelations(usv.U, usv.S, 1:4)
t = UPGMA_tree(dij)
newickstring(t)
end
end
end | SpectralInference | https://github.com/aramanlab/SpectralInference.jl.git |
|
[
"BSD-3-Clause"
] | 0.4.1 | ccc61241a1b3b3e60145580de043ecb2d3a4d5bc | code | 4139 | # function definitions are in extensions for various backends of tree implementations
""" returns names of all leaves desended from a node in prewalk order """
function getleafnames end
""" returns ids of all leaves desended from a node in prewalk order """
function getleafids end
"""
network_distance(leaf_i, leaf_j)
returns network distance between two leaves
"""
function network_distance end
"""
network_distances(tree::Node)
returns network distances between all pairs of leaves (leaves are in same order as `getleafnames`)
"""
function network_distances end
"""
patristic_distance(leaf_i, leaf_j)
returns patristic distance between two leaves
"""
function patristic_distance end
"""
patristic_distances(tree::Node)
returns patristic distances between all pairs of leaves (leaves are in same order as `getleafnames`)
"""
function patristic_distances end
"""
fscore_precision_recall(reftree, predictedtree)
fscore, precision, and recall of branches between the two trees
"""
function fscore_precision_recall end
"""
cuttree(tree, θ)
return vector of nodes whose distance from the root are < θ and whose children's distance to the root are > θ
"""
function cuttree end
"""
mapnodes(f::Function, tree)
maps across all nodes that have children in prewalk order and applies function `f(node)`
"""
function mapnodes end
"""
mapinternalnodes(f::Function, tree)
maps across all nodes that have children in prewalk order and applies function `f(node)`
"""
function mapinternalnodes end
"""
maplocalnodes(f::Function, tree)
maps across all nodes that have a leaf as a child in prewalk order and applies function `f(node)`
"""
function maplocalnodes end
"""
collectiveLCA(treenodes::AbstractVector)
returns last common ancestor of the vector of treenodes
"""
function collectiveLCA end
"""
as_polytomy!(f::Function, tree)
in-place removal of nodes. function `f` should return `true` if the node is to be removed.
Children of node are attached to the parent of the removed node
"""
function as_polytomy! end
"""
as_polytomy(f::Function, tree)
Makes a copy of the tree, then removes nodes. function `f` should return `true` if the node is to be removed.
Children of node are attached to the parent of the removed node
"""
function as_polytomy end
"""
pairedMI_across_treedepth(metacolumns, metacolumns_ids, tree)
pairedMI_across_treedepth(metacolumns, metacolumns_ids, compare::Function=(==), tree::Node; ncuts=100, bootstrap=false, mask=nothing)
iterates over each metacolumn and calculates MI between the paired elements of the metacolumn and the paired elements of tree clusters.
Args:
* metacolumns: column iterator, can be fed to `map(metacolumns)`
* metacolumn_ids: ids for each element in the metacolumn. should match the leafnames of the tree, but not necessarily the order.
* tree: NewickTree tree
* compare: function used to calculate similarity of two elements in metacolumn. Should be written for each element as it will be broadcast across all pairs.
Returns:
* (; MI, treedepths)
* MI: Vector{Vector{Float64}} MI for each metacolumn and each tree depth
* treedepths Vector{<:Number} tree depth (away from root) for each cut of the tree
"""
function pairedMI_across_treedepth end
"""
clusters_per_cutlevel(distfun::Function, tree::Node, ncuts::Number)
Returns:
* clusts: vector of cluster-memberships. each value indicates the cluster membership of the leaf at that cut.
leaves are ordered in prewalk order within each membership vector
* treedepths: distance from root for each of the `ncuts`
"""
function clusters_per_cutlevel end
"""
ladderize!(tree, rev=false)
sorts children of each node by number of leaves descending from the child in ascending order.
"""
function ladderize! end
"""
spectral_lineage_encoding(tree::Node, orderedleafnames=getleafnames(tree); filterfun=x->true)
returns vector of named tuples with the id `nodeid` of the node and `sle` a vector of booleans
ordered by `orderedleafnames` where true indicates the leaf descends from the node and false indicates that it does not.
"""
function spectral_lineage_encoding end | SpectralInference | https://github.com/aramanlab/SpectralInference.jl.git |
|
[
"BSD-3-Clause"
] | 0.4.1 | ccc61241a1b3b3e60145580de043ecb2d3a4d5bc | code | 6933 | using SpectralInference
using Test
using Distributions
@testset "SpectralInference" begin
@testset "core" begin
Dij_true = [
0.0 2.0 5.3642 5.3642
2.0 0.0 5.3642 5.3642
5.3642 5.3642 0.0 2.0
5.3642 5.3642 2.0 0.0
]
M = Float64.([
0 1 0 1 1 1
0 1 1 0 1 1
1 0 1 1 0 1
1 0 1 1 1 0
])
Mr2 = [
-3.93055e-16 1.0 0.5 0.5 1.0 1.0
9.01494e-16 1.0 0.5 0.5 1.0 1.0
1.0 -1.5782e-16 1.0 1.0 0.5 0.5
1.0 -1.5782e-16 1.0 1.0 0.5 0.5
]
expS = [
10.0, 3.0, 3.0, 1.0, 1.0, 1.0, 0.0,
]
usv = svd(M)
Dij_pred = spectraldistances(usv.U, usv.S, [1:1, 2:2, 3:4])
@inferred spectraldistances(usv.U, usv.S, [1:1, 2:2, 3:4])
# tests for getting partitions
@test getintervals(expS) == [1:1, 2:3, 4:6, 7:7]
@inferred getintervals(expS) == [1:1, 2:3, 4:6, 7:7]
@test getintervalsIQR(expS) == [1:7]
# test if SpectralInference distance works
@test isapprox(Dij_pred, Dij_true, atol=1e-5)
# test if we get the same SpectralInference tree
hc = SpectralInference.UPGMA_tree(Dij_pred)
nw = newickstring(hc, ["A", "B", "C", "D"], labelinternalnodes=false)
@test replace(nw, r"(:)[^,)]*(?=[,);])" => "") ∈ [
"((A,B),(C,D));", "((A,B),(D,C));", "((B,A),(C,D));", "((B,A),(D,C));",
"((C,D),(A,B));", "((D,C),(A,B));", "((C,D),(B,A));", "((D,C),(B,A));"
]
# @test nw == "((B:2.000000e+00,A:2.000000e+00):3.364199e+00,(D:2.000000e+00,C:2.000000e+00):3.364199e+00):0.000000e+00;"
# test projecting in and out of SVD space
@test projectout(usv) ≈ M
@test projectout(usv, 1:2) ≈ Mr2
@test projectinLSV(M, usv) ≈ usv.U
@test projectinLSV(M, usv, 1:3) ≈ usv.U[:, 1:3]
@test projectinRSV(M, usv) ≈ usv.Vt
@test projectinRSV(M, usv, 1:3) ≈ usv.Vt[1:3, :]
# test partial spi_trace calculations result in summed SpectralInference distance matrix
@test isapprox(vec(sum(spectraldistances_trace(usv, q=0.25), dims=1) .^ 2), Dij_true[triu(trues(4, 4), 1)], atol=1e-5)
# test spectral correlations
@inferred spectralcorrelations(usv.U, usv.S, 1:4)
end
@testset "helpers.jl" begin
expS = [
10.0, 3.0, 3.0, 1.0, 1.0, 1.0, 0.0,
]
v = explainedvariance(expS)
@test v ≈ (expS .^ 2) ./ sum((expS .^ 2))
@test scaledcumsum(v) ≈ cumsum(v) ./ maximum(cumsum(v))
@test SpectralInference.distancetrace_spaceneeded(100, 100; bits=64) == "30.212 MiB"
@test SpectralInference.distancetrace_spaceneeded(1000, 1000; bits=64) == "29.773 GiB"
@test SpectralInference.distancematrix_spaceneeded(100; bits=64) == "625.000 KiB"
@test SpectralInference.distancematrix_spaceneeded(1000; bits=64) == "61.035 MiB"
@test SpectralInference.distancematrix_spaceneeded(1000; bits=32) == "30.518 MiB"
M = Float64.([
0 1 0 1 1 1
0 1 1 0 1 1
1 0 1 1 0 1
1 0 1 1 1 0
])
ps = SpectralInference.pairwise((i, j) -> i' * j, M')
@test ps ≈ [3.0, 2.0, 2.0, 2.0, 2.0, 3.0]
@test SpectralInference.numpairs2N(6) == 4.0
@test SpectralInference.numpairs2N(5) ≈ 3.7015621187164243
@test squareform(ps) ≈ [
0.0 3.0 2.0 2.0
3.0 0.0 2.0 2.0
2.0 2.0 0.0 3.0
2.0 2.0 3.0 0.0
]
@test squareform(ps, 4.0) ≈ [
4.0 3.0 2.0 2.0
3.0 4.0 2.0 2.0
2.0 2.0 4.0 3.0
2.0 2.0 3.0 4.0
]
@test SpectralInference.k2ij(4, 4) == (3, 2)
@test SpectralInference.k2ij(6, 4) == (4, 3)
@test SpectralInference.ij2k(3, 2, 4) == 4
@test SpectralInference.ij2k(4, 3, 4) == 6
end
@testset "empiricalMI" begin
x = [0, 0, 0, 1, 1, 1]
for T in [Int64, Int32, Int16]
t = T.(x)
@test empiricalMI(t, t, base=2) == 1.0
@test empiricalMI(t, t) ≈ 0.6931471805599453 atol = 1e-10
end
# test masked MI
x = randn(1000)
for T in [Float64, Float32, Float16]
t = T.(x)
@test empiricalMI([t; t .+ 10.0], [trues(1000); falses(1000)], base=2) ≈ 1.0 atol = 1e-3
end
ρ = 0.8
mvN = MultivariateNormal([1 ρ; ρ 1])
trueMI_e = (2 * entropy(Normal(0, 1))) - entropy(mvN) # entropy as marginals - joint
trueMI_2 = (2 * entropy(Normal(0, 1), 2)) - entropy(mvN, 2) # entropy as marginals - joint
x = rand(mvN, 10_000)'
@test empiricalMI(x[:, 1], x[:, 2], nbins=32) ≈ trueMI_e atol = 1e-1
@test empiricalMI(x[:, 1], x[:, 2], nbins=32, base=2) ≈ trueMI_2 atol = 1e-1
end
if VERSION >= v"1.9"
@test isnothing(Base.get_extension(SpectralInference, :NewickTreeExt))
using NewickTree
@test !isnothing(Base.get_extension(SpectralInference, :NewickTreeExt))
@testset "NewickTreeExt" begin
m = rand(100, 40)
usv = svd(m)
dij = spectraldistances(usv.U, usv.S, getintervals(usv.S))
hc = UPGMA_tree(dij)
tree = readnw(newickstring(hc, string.(1:100)))
leafnames = getleafnames(tree)
@inferred network_distances(tree)
@inferred patristic_distances(tree)
@test fscore_precision_recall(tree, tree) == (1.0, 1.0, 1.0)
@inferred cuttree(network_distance, tree, 0.0)
@inferred Node collectiveLCA(getleaves(tree))
@inferred Node as_polytomy(n -> NewickTree.support(n) < 0.5, tree)
mi, treedepths = pairedMI_across_treedepth((; a=rand(Bool, 100), b=rand([1, 0], 100)), leafnames, tree; ncuts=50)
@test length(treedepths) == length(mi.a) == length(mi.b)
mi, treedepths = pairedMI_across_treedepth((; a=rand(UInt16, 100), b=rand(Float64, 100)), leafnames, tree; ncuts=50, comparefun=(x, y) -> abs(x - y))
@test length(treedepths) == length(mi.a) == length(mi.b)
mi, treedepths = pairedMI_across_treedepth((; a=rand(UInt16, 100), b=rand(Float64, 100)), leafnames, tree; ncuts=50, treecut_distancefun=patristic_distance, comparefun=(x, y) -> abs(x - y))
@test length(treedepths) == length(mi.a) == length(mi.b)
leafids = getleafids(tree)
@inferred spectral_lineage_encoding(tree)
@inferred spectral_lineage_encoding(tree, leafids)
@inferred spectral_lineage_encoding(tree; filterfun=!isleaf)
@inferred spectral_lineage_encoding(tree, sample(leafids, length(leafids), replace=false); filterfun=!isleaf)
end
end # VERSION >= v"1.9"
end # SpectralInference testset | SpectralInference | https://github.com/aramanlab/SpectralInference.jl.git |
|
[
"BSD-3-Clause"
] | 0.4.1 | ccc61241a1b3b3e60145580de043ecb2d3a4d5bc | docs | 5255 | # Spectral Inference
[](https://aramanlab.github.io/SpectralInference.jl/stable)
[](https://aramanlab.github.io/SpectralInference.jl/dev)
[](https://github.com/aramanlab/SpectralInference.jl/actions/workflows/CI.yml?query=branch%3Amain)
[](https://codecov.io/gh/aramanlab/SpectralInference.jl)
## Install
type:
```julia-repl
] dev git@github.com:aramanlab/SpectralInference.jl.git
```
into the julia command line
## Examples
calculate Spectral distances
```julia
using SpectralInference
M = rand(100, 100)
usv = svd(M) # from linear algebra
spectralpartitions = getintervals(usv.S, alpha=1.0, q=0.5)
Dij = spectraldistances(usv.U, usv.S, spectralpartitions)
```
make a tree from the distances using basic hierarchical clusting
```julia
# shortcut of `hclust(spimtx; linkage=:average, branchorder=:optimal)` from Clustering package
spitree = UPGMA_tree(Dij)
```
or with neighbor joining
```julia
using NeighborJoining # https://github.com/BenjaminDoran/NeighborJoining.jl
njclusts = regNJ(Dij) # or fastNJ(Dij)
ids = string.(1:100);
nwstring = NeighborJoining.newickstring(njclusts, ids)
```
example script for running SpectralInference on a gene expression matrix in a `.csv` file to generate spectral tree.
```julia
# Example SpectralInference code for gene expression matrix in .csv format (genes = rows, cells = columns)
# Ben Doran / Noah Gamble
# 2023/08/07
# Load packages
using SpectralInference
using NeighborJoining
using CSV, DataFrames
using LinearAlgebra
using Clustering
using Muon
using JLD2
# Load matrix as data frame from .csv
df = CSV.read("/path/to/geneexpressionmatrix.csv", DataFrame)
# Copy to matrix
m = Matrix(df[:,2:end]) #
# filter out low abundance genes
filt_thresh = 10
genecounts = mapslices(r -> sum(r.>0), m, dims=2) |> vec
idx_keep = genecounts .> filt_thresh
m = m[idx_keep,:]
# Organize into annotated data object
# m' is transpose of m (make samples rows)
adata = AnnData(X = m')
adata.obs_names .= names(df)[2:end]
adata.var_names .= string.(df.Column1[idx_keep])
@info size(adata.X)
# Perform SVD
@info "Peforming SVD..."
@time usv = svd(adata.X)
# Perform SpectralInference
@info "Calculating SpectralInference matrix..."
@time dij = spectraldistances(usv.U, usv.S, getintervals(usv.S))
# Cluster to tree
@info "Clustering SpectralInference matrix..."
# @time spitree = UPGMA_tree(dij)
# @time nwtreestring = SpectralInference.newickstring(spitree, adata.obs_names.vals)
@time spitree = regNJ(dij)
@time nwtreestring = NeighborJoining.newickstring(spitree, adata.obs_names.vals)
# Add SpectralInference matrix to adata object
@info "Adding SpectralInference matrix to ADATA..."
adata.obsp["spectraldistances"] = dij
adata.obs[:,"order"] = spitree.order
adata.uns["cellmerges"] = spitree.merges
adata.uns["heights"] = spitree.heights
adata.uns["treelinkage"] = string(spitree.linkage)
adata.uns["newicktreestring"] = nwtreestring
# Write annotated data to and Newick tree to disk
@info "Writing results to disk..."
@time begin
writeh5ad("spi_test.h5ad", adata)
open("test_tree.nw.txt", "w") do io
println(io, nwtreestring)
end
jldsave("test_tree.jld2"; spitree)
end
```
example script for creating bootstrap spectral tree and calculating support values
```julia
using SpectralInference
using NeighborJoining
using Muon
spitst = readh5ad("spi_test.h5ad")
mtx = spitst.X[:, :]
NBOOT = 100
boottrees = map(1:NBOOT) do i
ncols = size(mtx, 2)
tmpmtx = mtx[:, rand(1:ncols, ncols)]
usv = svd(tmpmtx)
dij = spectraldistances(usv.U, usv.S, getintervals(usv.S))
nwtreestring = NeighborJoining.newickstring(regNJ(dij))
end
open("test_tree_bootstraps.nw.txt", "w") do io
for t in boottrees
println(io, t)
end
end
# calculate support values
using GoTree_jll
reftreefile = joinpath(pwd(), "test_tree.nw.txt")
boottreefile = joinpath(pwd(), "test_tree_bootstraps.nw.txt")
supporttreefile = joinpath(pwd(), "test_tree_bootstraps.nw.txt")
run(`$(gotree()) -i $reftreefile -b $boottreefile -o $supporttreefile`)
```
script for calculating MI between metavariables and tree depths
```julia
using SpectralInference
using NewickTree
using Muon, DataFrames
spitst = readh5ad("spi_test.h5ad")
spitree = readnw(readline(joinpath(pwd(), "test_tree_bootstraps.nw.txt")))
spitree_50pct = as_polytomy(n->NewickTree.support(n)<.5, spitree)
leafnames = getleafnames(spitree_50pct)
mi, treedepths = pairedMI_across_treedepth(eachcolumn(spitst.obs), leafnames, spitree_50pct; ncuts=100)
NBOOTS = 50
results = map(1:NBOOTS) do i
pairedMI_across_treedepth(eachcolumn(spitst.obs), leafnames, spitree_50pct; bootstrap=true, ncuts=100)
end
rowmask = spitst.obs.count .> 15
results = map(1:NBOOTS) do i
pairedMI_across_treedepth(eachcolumn(spitst.obs), leafnames, spitree_50pct; mask=rowmask, bootstrap=true, ncuts=100)
end
all_mi_results = first.(results)
all_treedepths_results = last.(results)
```
## Citing
See [`CITATION.bib`](CITATION.bib) for the relevant reference(s).
| SpectralInference | https://github.com/aramanlab/SpectralInference.jl.git |
|
[
"BSD-3-Clause"
] | 0.4.1 | ccc61241a1b3b3e60145580de043ecb2d3a4d5bc | docs | 222 | ```@meta
CurrentModule = SpectralInference
```
# SpectralInference
Documentation for [SpectralInference](https://github.com/aramanlab/SpectralInference.jl).
```@index
```
```@autodocs
Modules = [SpectralInference]
```
| SpectralInference | https://github.com/aramanlab/SpectralInference.jl.git |
|
[
"MIT"
] | 0.3.0 | 2fca7ee903e9c45871c1948e6b5fffdf359e2da3 | code | 588 | using Documenter, Literate, PDELib
function make_all()
makedocs(
sitename="PDELib.jl",
modules = [PDELib],
clean = false,
doctest = false,
authors = "J. Fuhrmann, Ch.Merdon. T. Streckenbach",
repo="https://github.com/WIAS-BERLIN/PDELib.jl",
pages=[
"Home"=>"index.md",
"Introductory Material"=>"intro.md",
],
)
if !isinteractive()
deploydocs(repo = "github.com/WIAS-BERLIN/PDELib.jl.git",
devbranch = "main"
)
end
end
make_all()
| PDELib | https://github.com/WIAS-BERLIN/PDELib.jl.git |
|
[
"MIT"
] | 0.3.0 | 2fca7ee903e9c45871c1948e6b5fffdf359e2da3 | code | 40503 | ### A Pluto.jl notebook ###
# v0.19.19
using Markdown
using InteractiveUtils
# This Pluto notebook uses @bind for interactivity. When running this notebook outside of Pluto, the following 'mock version' of @bind gives bound variables a default value (instead of an error).
macro bind(def, element)
quote
local iv = try Base.loaded_modules[Base.PkgId(Base.UUID("6e696c72-6542-2067-7265-42206c756150"), "AbstractPlutoDingetjes")].Bonds.initial_value catch; b -> missing; end
local el = $(esc(element))
global $(esc(def)) = Core.applicable(Base.get, el) ? Base.get(el) : iv(el)
el
end
end
# ╔═╡ d432ad64-f91f-11ea-2e48-4bc7472ac64c
begin
using SimplexGridFactory
using ExtendableGrids
using Triangulate
using TetGen
using GridVisualize
using PlutoVista
using PlutoUI
isdefined(Main,:PlutoRunner) ? default_plotter!(PlutoVista) : default_plotter!(nothing)
end
# ╔═╡ 940b1996-fe9d-11ea-2fa4-8b72bee62b76
md"""
# Grid creation and visualization in PDELib.jl
This notebook shows how to perform grid creation and visualization with the assistance of the packages [ExtendableGrids.jl](https://github.com/j-fu/ExtendableGrids.jl) and [SimplexGridFactory.jl](https://github.com/j-fu/SimplexGridFactory.jl) which are part of the [PDELib.jl](https://github.com/WIAS-BERLIN/PDElib.jl) meta package.
Visualization in this notebook is done using the [GridVisualize.jl](https://github.com/j-fu/GridVisualize.jl) package.
"""
# ╔═╡ 47103e8f-a4ff-46ed-a632-572a2e194a50
md"""
## 1D grids
1D grids are created just from arrays of montonically increasing coordinates
using the [simplexgrid](https://j-fu.github.io/ExtendableGrids.jl/stable/simplexgrid/#ExtendableGrids.simplexgrid-Tuple{AbstractVector{T}%20where%20T}) method.
"""
# ╔═╡ 93a0c45e-d6a3-415a-a82c-e4f7e2a09d22
X1=range(0,1;length=11)
# ╔═╡ 4622a1fc-fda7-4211-9cc0-4eb1a1584aa6
g1=simplexgrid(X1)
# ╔═╡ 3212b930-194d-422e-9d06-65885b25cc6d
md"""
We can plot a grid with a method from `GridVisualize.jl`
"""
# ╔═╡ 5520b8c0-0874-4790-a956-224e6c43d9cf
gridplot(g1; resolution=(500,150),legend=:rt)
# ╔═╡ 13aef2a1-5745-4fe5-9659-6b7c0e7267fc
md"""
We see some additional information:
- `cellregion`: each grid cell (interval, triangle, tetrahedron) as an integer region marker attached
- `bfaceregion`: boundary faces (points, lines, triangles) have an interger boundary region marker attached
We can also have a look into the grid structure:
"""
# ╔═╡ f19d20c8-4d69-442d-99c8-10874fa0a6d3
g1.components
# ╔═╡ 28e2e3b0-c168-481b-b467-29e6a5407431
md"""
Components can be accessed via `[ ]`. In fact the keys in the dictionary of components are [types](https://j-fu.github.io/ExtendableGrids.jl/stable/tdict/).
"""
# ╔═╡ f04017d7-1c55-4118-8467-1e134259e35d
g1[Coordinates]
# ╔═╡ 98016b49-8786-46b9-aca6-01d15c253b3f
g1[CellNodes]
# ╔═╡ 2d392a98-bf32-4145-ae93-a8e218367277
md"""
### Modifying region markers
The `simplexgrid` method provides a default distribution of markers, but we would like to be able to change them. This can be done by putting masks on cells or faces (points in 1D):
"""
# ╔═╡ 88247350-aa6c-4876-82c3-3534036d5702
g2=deepcopy(g1)
# ╔═╡ 42f8d91d-14c7-488f-bdb9-b3d22705186f
cellmask!(g2, [0.0], [0.5], 2);
# ╔═╡ db7e0233-4e08-41b8-9ebe-5570e6d32264
bfacemask!(g2, [0.5],[0.5], 3);
# ╔═╡ 74641f73-2efe-4df8-bebb-ed97e77d869e
gridplot(g2; resolution=(500, 150),legend=:rt)
# ╔═╡ 14fb7977-93cf-4f74-a8ec-b6ee25dbdf86
md"""
### Creating locally refined grids
For this purpose, we just need to create arrays with the corresponding coordinate values. This can be done programmatically.
Two support metods are provided for this purpose.
"""
# ╔═╡ 2d5cb9e1-2d14-415e-b792-c3124901011d
hmin=0.01 ; hmax=0.1
# ╔═╡ b1f903b3-29d7-4909-b7e2-8ef3528c9965
md"""
The `geomspace` method creates an array such that the smallest interval size is `hmin` and the largest interval size is not larger but close to `hmax`, and the interval sizes constitute a geometric sequence.
"""
# ╔═╡ 19125aed-5c46-4968-bcfc-0b469628b68e
X2L=geomspace(0,0.5,hmax,hmin)
# ╔═╡ f9debaf8-efe8-44d1-9671-4aa5bffa9bb8
DX2=X2L[2:end].-X2L[1:end-1]
# ╔═╡ 4f7f9eaf-61c5-4543-ae39-e58ca14fb89a
DX2[1:end-1]./DX2[2:end]
# ╔═╡ f873cb89-da6e-4e11-b3f6-2bf0b766ce5f
X2R=geomspace(0.5,1,hmin,hmax)
# ╔═╡ a2e6c397-4a7e-47eb-ad84-df6e9d3fdd43
md"""
We can glue these arrays together and create a grid from them:
"""
# ╔═╡ 805c2a1e-a6c6-47fc-b719-31c2a671a8d0
X2=glue(X2L,X2R)
# ╔═╡ dd7d8e17-f825-4047-9386-d9e2bfd0a48d
gridplot(simplexgrid(X2); resolution=(500,150),legend=:rt)
# ╔═╡ 3d7db57f-2864-4984-a979-609e1d838a9f
md"""
### Plotting functions
We assume that functions can be represented by their node values an plotted via their piecewise linear interpolants. E.g. they could come from some simulation.
"""
# ╔═╡ 4cf840e6-86c5-4af1-a780-6fc78b60716b
g1d2=simplexgrid(range(-10,10,length=201))
# ╔═╡ 151cc4b8-c5ed-4f5e-8d5f-2f708c9c7fae
fsin=map(sin,g1d2)
# ╔═╡ 605581c4-3c6f-4c31-bd90-7645d3f70315
fcos=map(cos,g1d2)
# ╔═╡ bd40e614-00ef-426d-aa98-eca2ef48320e
fsinh=map(x->sinh(0.2*x), g1d2)
# ╔═╡ 71af99ab-612a-4821-8e9c-efc8766e2e3e
let
vis=GridVisualizer(;resolution=(600,300),legend=:lt)
scalarplot!(vis, g1d2, fsinh, label="sinh", markershape=:dtriangle, color=:red,markevery=5,clear=false)
scalarplot!(vis, g1d2, fcos, label="cos", markershape=:xcross, color=:green, linestyle=:dash, clear=false,markevery=20)
scalarplot!(vis, g1d2, fsin, label="sin", markershape=:none, color=:blue, linestyle=:dot, clear=false, markevery=20)
reveal(vis)
end
# ╔═╡ 6dfa1d73-8baa-4589-b2e6-547834c9e444
md"""
## 2D grids
### Tensor product grids
For 2D tensor product grids, we can again use the `simplexgrid` method
and apply the mask methods for modifying cell and boundary region markers.
"""
# ╔═╡ f9599246-8238-432c-a315-300d74abfa2c
begin
g2d1=simplexgrid(X1,X2)
cellmask!(g2d1, [0.0,0.0], [0.5, 0.5], 2)
cellmask!(g2d1, [0.5,0.5], [1.0, 1.0], 3)
bfacemask!(g2d1, [0.0, 0.0], [0.0, 0.5],5)
end
# ╔═╡ ba5af291-fb16-4f21-8b74-664284bf7bd9
gridplot(g2d1,resolution=(600,400),linewidth=0.5,legend=:lt)
# ╔═╡ dfbaacea-4cb4-4147-9f1b-4424d7a7e89b
md"""
To interact with the plot, you can use the mouse wheel or double toch to zoom,
"shift-mouse-left" to pan, and "alt-mouse-left" or "ctrl-mouse-left" to reset.
"""
# ╔═╡ 7d1698dd-3bb7-4b38-9c6d-a88652749eee
md"""
We can also have a look into the components of a 2D grid:
"""
# ╔═╡ 81249f7c-abdf-43cc-b57f-2915b09da009
g2d1.components
# ╔═╡ 0765641a-8ed9-4579-bd9b-90bb02a55792
md"""
### Unstructured grids
For the triangulation of unstructured grids, we use the mesh generator Triangle via the [Triangulate.jl](https://github.com/JuliaGeometry/Triangulate.jl) and [SimplexGridFactory.jl](https://github.com/j-fu/SimplexGridFactory.jl) packages.
The later package exports the `SimplexGridBuilder` which shall help to simplify the creation of the input for `Triangulate`.
"""
# ╔═╡ 884a11a2-15cf-40fc-a1ca-66ea23c6094e
builder2=let
b=SimplexGridBuilder(Generator=Triangulate)
p1=point!(b,0,0)
p2=point!(b,1,0)
p3=point!(b,1,1)
# Specify outer boundary
facetregion!(b,1)
facet!(b,p1,p2)
facetregion!(b,2)
facet!(b,p2,p3)
facetregion!(b,3)
facet!(b,p3,p1)
cellregion!(b,1)
regionpoint!(b,0.75,0.25)
options!(b,maxvolume=0.01)
b
end
# ╔═╡ 8fbd238c-723e-4bce-af69-9cabfc03f8d9
md"""
We can plot the current state of the builder:
"""
# ╔═╡ 342788d4-e5d0-4239-be87-7658bb67c999
grid2d2=simplexgrid(builder2;maxvolume=0.001)
# ╔═╡ 8f7d958e-5dc5-4324-af21-ad829d7d77eb
gridplot(grid2d2, resolution=(400,300),linewidth=0.5)
# ╔═╡ fd27b44a-f923-11ea-2afb-d79f7e62e214
md"""
### More complicated grids
More complicated grids include:
- local refinement
- interior boundaries
- different region markers
- holes
The particular way to describe these things is due to Jonathan Shewchuk and his mesh generator [Triangle](https://www.cs.cmu.edu/~quake/triangle.html) via its Julia wrapper package [Triangulate.jl](https://github.com/JuliaGeometry/Triangulate.jl).
"""
# ╔═╡ 4a289b23-46b9-495d-b19c-42b3da71b242
md"""
#### Local refinement
"""
# ╔═╡ b12838f0-fe9c-11ea-2939-155ed907322d
refinement_center=[0.8,0.2]
# ╔═╡ d5d8a1d6-fe9d-11ea-0fd8-df6e81492cb5
md"""
For local refimenent, we define a function, which is able to
tell if a triangle is to be refined ("unsuitable") or can be kept as it is.
The function measures the distance between the refinement center and the triangle barycenter. We require that the area increases with the distance from the refinement center.
"""
# ╔═╡ aae2e82a-fe9c-11ea-0427-593f8d2c7746
function unsuitable(x1,y1,x2,y2,x3,y3,area)
bary_x=(x1+x2+x3)/3.0
bary_y=(y1+y2+y3)/3.0
dx=bary_x-refinement_center[1]
dy=bary_y-refinement_center[2]
qdist=dx^2+dy^2
area>0.1*max(1.0e-2,qdist)
end;
# ╔═╡ 1ae86964-fe9e-11ea-303b-65bb128384a5
md"""
#### Interior boundaries
Interior boundaries are described in a similar as exterior ones - just by facets connecting points.
"""
# ╔═╡ 3b8cd906-bc4e-44af-bcf4-8836d597ed4c
md"""
#### Subregions
Subregions are defined as regions surrounded by interior boundaries.
By placing a "region point" into such a region and specifying a "region number",
we can set the cell region marker for all triangles created in the subregion.
"""
# ╔═╡ 9d240ef9-6639-4bde-a463-ea78480a970d
md"""
#### Holes
Holes are defined in a similar way as subregions, but a "hole point" is places into the place which shall become the hole.
"""
# ╔═╡ 511b26c6-f920-11ea-1228-51c3750f495c
builder3=let
b=SimplexGridBuilder(Generator=Triangulate;tol=1.0e-10)
# Specify points
p1=point!(b,0,0)
p2=point!(b,1,0)
p3=point!(b,1,1)
p4=point!(b,0,0.7)
# Specify outer boundary
facetregion!(b,1)
facet!(b,p1,p2)
facetregion!(b,2)
facet!(b,p2,p3)
facetregion!(b,3)
facet!(b,p3,p4)
facetregion!(b,4)
facet!(b,p1,p4)
# Activate unsuitable callback
options!(b,unsuitable=unsuitable)
# Specify interior boundary
facetregion!(b,5)
facet!(b,p1,p3)
# Coarse elements in upper left region #1
cellregion!(b,1)
maxvolume!(b,0.1)
regionpoint!(b,0.1,0.5)
# Fine elements in lower right region #2
cellregion!(b,2)
maxvolume!(b,0.01)
regionpoint!(b,0.9,0.5)
# Hole
hp1=point!(b,0.4,0.1)
hp2=point!(b,0.6,0.1)
hp3=point!(b,0.5,0.3)
holepoint!(b,0.5,0.2)
facetregion!(b,6)
facet!(b,hp1,hp2)
facet!(b,hp2,hp3)
facet!(b,hp3,hp1)
b
end;
# ╔═╡ d2129483-285b-49a2-a11d-886956146b85
md"""
__Create a simplex grid from the builder__
"""
# ╔═╡ ac93589b-6315-4677-9542-c0a2333f1755
grid2d3=simplexgrid(builder3)
# ╔═╡ 59a6c8b5-25aa-47aa-9489-a803672013df
gridplot(grid2d3,legend=:lt, resolution=(400,400))
# ╔═╡ 4c99c40f-cf93-4cba-bef1-0c4ffcbf6833
md"""
### Plotting of functions
Functions defined on the nodes of a triangular grid can be seen as piecewise linear functions from the P1 finite element space defined by the triangulation.
"""
# ╔═╡ bad736d7-875c-4bc0-9ec4-494a90a508f7
fsin2=map((x,y)-> sin(x)*y, grid2d2)
# ╔═╡ a375c23f-6b8c-4b2c-a8b5-d38e6b5a8f6d
fsin3=map((x,y)-> sin(y)*x, grid2d3)
# ╔═╡ c3ef9067-3cdb-4bfd-9406-6ded64539978
scalarplot(grid2d2, fsin2, label="grid2d2")
# ╔═╡ 4dfb2e0f-3e3a-4053-8a76-765546e96992
scalarplot(grid2d3, fsin3, label="grid2d3",colormap=:spring,isolines=10)
# ╔═╡ 2682df92-5955-4b17-ae4f-8e99c5b17980
md"""
## 3D Grids
### Tensor product grids
Please note that "masking" is not yet implemented.
Furthermore, PyPlot visualization is slow, with GLMakie it is way faster.
"""
# ╔═╡ 265fe6c7-d1cc-48a6-8295-f8f55acf677c
X3=range(0.,10.1,length=11)
# ╔═╡ b357395f-2a6e-476f-b008-02802c85a541
grid3d1=simplexgrid(X3,X3,X3)
# ╔═╡ af449be7-aab6-4de5-a059-3f8508502676
func3=map((x,y,z)-> sin(x/2)*cos(y/2)*z/10,grid3d1)
# ╔═╡ 38e2b4a8-2480-40e7-bde3-6d1775201aae
p3dg=GridVisualizer(dim=3,resolution=(200,200))
# ╔═╡ ef1fde48-fe90-4714-ac86-614ae3451aa7
p3ds=GridVisualizer(dim=3,resolution=(400,400))
# ╔═╡ 04041481-0f03-41e1-a7de-1b3fd033c952
mean(x)=sum(x)/length(x)
# ╔═╡ a3844fda-5725-4d95-894b-051a5f6c2faa
md"""
f=$(@bind flevel Slider(range(extrema(func3)...,length=20),default=mean(func3),show_value=true))
x=$(@bind xplane Slider(X3[1]:0.1:X3[end],default=X3[end],show_value=true))
y=$(@bind yplane Slider(X3[1]:0.1:X3[end],default=X3[end],show_value=true))
z=$(@bind zplane Slider(X3[1]:0.1:X3[end],default=X3[end],show_value=true))
"""
# ╔═╡ f97d085c-e7bf-4561-8183-673912bdeab6
gridplot!(p3dg,grid3d1,zplanes=[zplane],yplanes=[yplane], xplanes=[xplane], resolution=(200,200),show=true)
# ╔═╡ d73d18e7-bcf9-4cc1-9154-b70dc1ff5524
scalarplot!(p3ds,grid3d1, func3, zplanes=[zplane], yplanes=[yplane],xplanes=[xplane],levels=[flevel],colormap=:spring,resolution=(200,200),show=true,levelalpha=0.5,outlinealpha=0.1)
# ╔═╡ 6cad87eb-1c59-4000-b688-a6f6d41f9413
md"""
### Unstructured grids
The SimplexGridBuilder API supports creation of three-dimensional grids in way very similar to the 2D case. Just define points with three coordinates and planar (!) facets with at least three points to describe the geometry.
The backend for mesh generation in this case is the [TetGen](http://tetgen.org) mesh generator by Hang Si from WIAS Berlin and its Julia wrapper [TetGen.jl](https://github.com/JuliaGeometry/TetGen.jl).
"""
# ╔═╡ fefc7587-8e25-4080-b934-90c0e1afc56a
builder3d=let
b=SimplexGridBuilder(Generator=TetGen)
p1=point!(b,0,0,0)
p2=point!(b,1,0,0)
p3=point!(b,1,1,0)
p4=point!(b,0,1,0)
p5=point!(b,0,0,1)
p6=point!(b,1,0,1)
p7=point!(b,1,1,1)
p8=point!(b,0,1,1)
facetregion!(b,1)
facet!(b,p1 ,p2 ,p3 ,p4)
facetregion!(b,2)
facet!(b,p5 ,p6 ,p7 ,p8)
facetregion!(b,3)
facet!(b,p1 ,p2 ,p6 ,p5)
facetregion!(b,4)
facet!(b,p2 ,p3 ,p7 ,p6)
facetregion!(b,5)
facet!(b,p3 ,p4 ,p8 ,p7)
facetregion!(b,6)
facet!(b,p4 ,p1 ,p5 ,p8)
hp1=point!(b,0.4,0.4,0.4)
hp2=point!(b,0.6,0.4,0.4)
hp3=point!(b,0.6,0.6,0.4)
hp4=point!(b,0.4,0.6,0.4)
hp5=point!(b,0.4,0.4,0.6)
hp6=point!(b,0.6,0.4,0.6)
hp7=point!(b,0.6,0.6,0.6)
hp8=point!(b,0.4,0.6,0.6)
facetregion!(b,7)
facet!(b,hp1 ,hp2 ,hp3 ,hp4)
facet!(b,hp5 ,hp6 ,hp7 ,hp8)
facet!(b,hp1 ,hp2 ,hp6 ,hp5)
facet!(b,hp2 ,hp3 ,hp7 ,hp6)
facet!(b,hp3 ,hp4 ,hp8 ,hp7)
facet!(b,hp4 ,hp1 ,hp5 ,hp8)
holepoint!(b, 0.5,0.5,0.5)
b
end;
# ╔═╡ 065735f7-c799-4284-bd59-fe6383bb987c
grid3d2=simplexgrid(builder3d,maxvolume=0.0001)
# ╔═╡ 329992a0-e352-468b-af8b-0b190315fc61
gridplot(grid3d2,zplane=0.1,azim=20,elev=20,linewidth=0.5,outlinealpha=0.3)
# ╔═╡ a7965a6e-2e83-47eb-aee2-d366246a8637
html"""<hr>"""
# ╔═╡ 7ad541b1-f40f-4cdd-b7b5-b792a8e63d71
TableOfContents(depth=4)
# ╔═╡ 071b8834-d3d1-4d08-979f-56b05bc1e0d3
md"""
begin
using Pkg
Pkg.activate(mktempdir())
Pkg.add(["PlutoUI","Revise","Triangulate","TetGen"])
using Revise
Pkg.develop(["ExtendableGrids","SimplexGridFactory",
"GridVisualize","PlutoVista"])
end
"""
# ╔═╡ 00000000-0000-0000-0000-000000000001
PLUTO_PROJECT_TOML_CONTENTS = """
[deps]
ExtendableGrids = "cfc395e8-590f-11e8-1f13-43a2532b2fa8"
GridVisualize = "5eed8a63-0fb0-45eb-886d-8d5a387d12b8"
PlutoUI = "7f904dfe-b85e-4ff6-b463-dae2292396a8"
PlutoVista = "646e1f28-b900-46d7-9d87-d554eb38a413"
SimplexGridFactory = "57bfcd06-606e-45d6-baf4-4ba06da0efd5"
TetGen = "c5d3f3f7-f850-59f6-8a2e-ffc6dc1317ea"
Triangulate = "f7e6ffb2-c36d-4f8f-a77e-16e897189344"
[compat]
ExtendableGrids = "~0.9.16"
GridVisualize = "~0.6.1"
PlutoUI = "~0.7.16"
PlutoVista = "~0.8.6"
SimplexGridFactory = "~0.5.18"
TetGen = "~1.4.0"
Triangulate = "~2.2.0"
"""
# ╔═╡ 00000000-0000-0000-0000-000000000002
PLUTO_MANIFEST_TOML_CONTENTS = """
# This file is machine-generated - editing it directly is not advised
manifest_format = "2.0"
project_hash = "923e356fbb96a3a983b9ae7f68ee55a6e7a31a62"
[[deps.AbstractPlutoDingetjes]]
deps = ["Pkg"]
git-tree-sha1 = "8eaf9f1b4921132a4cff3f36a1d9ba923b14a481"
uuid = "6e696c72-6542-2067-7265-42206c756150"
version = "1.1.4"
[[deps.AbstractTrees]]
git-tree-sha1 = "faa260e4cb5aba097a73fab382dd4b5819d8ec8c"
uuid = "1520ce14-60c1-5f80-bbc7-55ef81b5835c"
version = "0.4.4"
[[deps.Adapt]]
deps = ["LinearAlgebra"]
git-tree-sha1 = "195c5505521008abea5aee4f96930717958eac6f"
uuid = "79e6a3ab-5dfb-504d-930d-738a2a938a0e"
version = "3.4.0"
[[deps.ArgTools]]
uuid = "0dad84c5-d112-42e6-8d28-ef12dabb789f"
version = "1.1.1"
[[deps.Artifacts]]
uuid = "56f22d72-fd6d-98f1-02f0-08ddc0907c33"
[[deps.Base64]]
uuid = "2a0f44e3-6c83-55bd-87e4-b1978d98bd5f"
[[deps.BitFlags]]
git-tree-sha1 = "43b1a4a8f797c1cddadf60499a8a077d4af2cd2d"
uuid = "d1d4a3ce-64b1-5f1a-9ba4-7e7e69966f35"
version = "0.1.7"
[[deps.ChainRulesCore]]
deps = ["Compat", "LinearAlgebra", "SparseArrays"]
git-tree-sha1 = "c6d890a52d2c4d55d326439580c3b8d0875a77d9"
uuid = "d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4"
version = "1.15.7"
[[deps.ChangesOfVariables]]
deps = ["ChainRulesCore", "LinearAlgebra", "Test"]
git-tree-sha1 = "38f7a08f19d8810338d4f5085211c7dfa5d5bdd8"
uuid = "9e997f8a-9a97-42d5-a9f1-ce6bfc15e2c0"
version = "0.1.4"
[[deps.CodecZlib]]
deps = ["TranscodingStreams", "Zlib_jll"]
git-tree-sha1 = "ded953804d019afa9a3f98981d99b33e3db7b6da"
uuid = "944b1d66-785c-5afd-91f1-9de20f533193"
version = "0.7.0"
[[deps.ColorSchemes]]
deps = ["ColorTypes", "ColorVectorSpace", "Colors", "FixedPointNumbers", "Random", "SnoopPrecompile"]
git-tree-sha1 = "aa3edc8f8dea6cbfa176ee12f7c2fc82f0608ed3"
uuid = "35d6a980-a343-548e-a6ea-1d62b119f2f4"
version = "3.20.0"
[[deps.ColorTypes]]
deps = ["FixedPointNumbers", "Random"]
git-tree-sha1 = "eb7f0f8307f71fac7c606984ea5fb2817275d6e4"
uuid = "3da002f7-5984-5a60-b8a6-cbb66c0b333f"
version = "0.11.4"
[[deps.ColorVectorSpace]]
deps = ["ColorTypes", "FixedPointNumbers", "LinearAlgebra", "SpecialFunctions", "Statistics", "TensorCore"]
git-tree-sha1 = "600cc5508d66b78aae350f7accdb58763ac18589"
uuid = "c3611d14-8923-5661-9e6a-0046d554d3a4"
version = "0.9.10"
[[deps.Colors]]
deps = ["ColorTypes", "FixedPointNumbers", "Reexport"]
git-tree-sha1 = "fc08e5930ee9a4e03f84bfb5211cb54e7769758a"
uuid = "5ae59095-9a9b-59fe-a467-6f913c188581"
version = "0.12.10"
[[deps.Compat]]
deps = ["Dates", "LinearAlgebra", "UUIDs"]
git-tree-sha1 = "00a2cccc7f098ff3b66806862d275ca3db9e6e5a"
uuid = "34da2185-b29b-5c13-b0c7-acf172513d20"
version = "4.5.0"
[[deps.CompilerSupportLibraries_jll]]
deps = ["Artifacts", "Libdl"]
uuid = "e66e0078-7015-5450-92f7-15fbd957f2ae"
version = "1.0.1+0"
[[deps.Configurations]]
deps = ["ExproniconLite", "OrderedCollections", "TOML"]
git-tree-sha1 = "62a7c76dbad02fdfdaa53608104edf760938c4ca"
uuid = "5218b696-f38b-4ac9-8b61-a12ec717816d"
version = "0.17.4"
[[deps.DataAPI]]
git-tree-sha1 = "e8119c1a33d267e16108be441a287a6981ba1630"
uuid = "9a962f9c-6df0-11e9-0e5d-c546b8b5ee8a"
version = "1.14.0"
[[deps.DataValueInterfaces]]
git-tree-sha1 = "bfc1187b79289637fa0ef6d4436ebdfe6905cbd6"
uuid = "e2d170a0-9d28-54be-80f0-106bbe20a464"
version = "1.0.0"
[[deps.Dates]]
deps = ["Printf"]
uuid = "ade2ca70-3891-5945-98fb-dc099432e06a"
[[deps.Distributed]]
deps = ["Random", "Serialization", "Sockets"]
uuid = "8ba89e20-285c-5b6f-9357-94700520ee1b"
[[deps.DocStringExtensions]]
deps = ["LibGit2"]
git-tree-sha1 = "2fb1e02f2b635d0845df5d7c167fec4dd739b00d"
uuid = "ffbed154-4ef7-542d-bbb7-c09d3a79fcae"
version = "0.9.3"
[[deps.Downloads]]
deps = ["ArgTools", "FileWatching", "LibCURL", "NetworkOptions"]
uuid = "f43a241f-c20a-4ad4-852c-f6b1247861c6"
version = "1.6.0"
[[deps.EarCut_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "e3290f2d49e661fbd94046d7e3726ffcb2d41053"
uuid = "5ae413db-bbd1-5e63-b57d-d24a61df00f5"
version = "2.2.4+0"
[[deps.ElasticArrays]]
deps = ["Adapt"]
git-tree-sha1 = "e1c40d78de68e9a2be565f0202693a158ec9ad85"
uuid = "fdbdab4c-e67f-52f5-8c3f-e7b388dad3d4"
version = "1.2.11"
[[deps.ExproniconLite]]
deps = ["Pkg", "TOML"]
git-tree-sha1 = "c2eb763acf6e13e75595e0737a07a0bec0ce2147"
uuid = "55351af7-c7e9-48d6-89ff-24e801d99491"
version = "0.7.11"
[[deps.ExtendableGrids]]
deps = ["AbstractTrees", "Dates", "DocStringExtensions", "ElasticArrays", "InteractiveUtils", "LinearAlgebra", "Printf", "Random", "SparseArrays", "StaticArrays", "Test", "WriteVTK"]
git-tree-sha1 = "310b903a560b7b18f63486ff93da1ded9cae1f15"
uuid = "cfc395e8-590f-11e8-1f13-43a2532b2fa8"
version = "0.9.16"
[[deps.Extents]]
git-tree-sha1 = "5e1e4c53fa39afe63a7d356e30452249365fba99"
uuid = "411431e0-e8b7-467b-b5e0-f676ba4f2910"
version = "0.1.1"
[[deps.FileIO]]
deps = ["Pkg", "Requires", "UUIDs"]
git-tree-sha1 = "7be5f99f7d15578798f338f5433b6c432ea8037b"
uuid = "5789e2e9-d7fb-5bc7-8068-2c6fae9b9549"
version = "1.16.0"
[[deps.FileWatching]]
uuid = "7b1f6079-737a-58dc-b8bc-7a2ca5c1b5ee"
[[deps.FillArrays]]
deps = ["LinearAlgebra", "Random", "SparseArrays", "Statistics"]
git-tree-sha1 = "9a0472ec2f5409db243160a8b030f94c380167a3"
uuid = "1a297f60-69ca-5386-bcde-b61e274b549b"
version = "0.13.6"
[[deps.FixedPointNumbers]]
deps = ["Statistics"]
git-tree-sha1 = "335bfdceacc84c5cdf16aadc768aa5ddfc5383cc"
uuid = "53c48c17-4a7d-5ca2-90c5-79b7896eea93"
version = "0.8.4"
[[deps.FuzzyCompletions]]
deps = ["REPL"]
git-tree-sha1 = "e16dd964b4dfaebcded16b2af32f05e235b354be"
uuid = "fb4132e2-a121-4a70-b8a1-d5b831dcdcc2"
version = "0.5.1"
[[deps.GPUArraysCore]]
deps = ["Adapt"]
git-tree-sha1 = "57f7cde02d7a53c9d1d28443b9f11ac5fbe7ebc9"
uuid = "46192b85-c4d5-4398-a991-12ede77f4527"
version = "0.1.3"
[[deps.GeoInterface]]
deps = ["Extents"]
git-tree-sha1 = "e315c4f9d43575cf6b4e511259433803c15ebaa2"
uuid = "cf35fbd7-0cd7-5166-be24-54bfbe79505f"
version = "1.1.0"
[[deps.GeometryBasics]]
deps = ["EarCut_jll", "GeoInterface", "IterTools", "LinearAlgebra", "StaticArrays", "StructArrays", "Tables"]
git-tree-sha1 = "fe9aea4ed3ec6afdfbeb5a4f39a2208909b162a6"
uuid = "5c1252a2-5f33-56bf-86c9-59e7332b4326"
version = "0.4.5"
[[deps.GridVisualize]]
deps = ["ColorSchemes", "Colors", "DocStringExtensions", "ElasticArrays", "ExtendableGrids", "GeometryBasics", "GridVisualizeTools", "HypertextLiteral", "LinearAlgebra", "Observables", "OrderedCollections", "PkgVersion", "Printf", "StaticArrays"]
git-tree-sha1 = "b19a5815f9ba376dff963fccdf0c98dbddc6f61d"
uuid = "5eed8a63-0fb0-45eb-886d-8d5a387d12b8"
version = "0.6.1"
[[deps.GridVisualizeTools]]
deps = ["ColorSchemes", "Colors", "DocStringExtensions", "StaticArraysCore"]
git-tree-sha1 = "5964fd3e4080af45bfdbdaff75567759fd0367bd"
uuid = "5573ae12-3b76-41d9-b48c-81d0b6e61cc5"
version = "0.2.1"
[[deps.HTTP]]
deps = ["Base64", "CodecZlib", "Dates", "IniFile", "Logging", "LoggingExtras", "MbedTLS", "NetworkOptions", "OpenSSL", "Random", "SimpleBufferStream", "Sockets", "URIs", "UUIDs"]
git-tree-sha1 = "eb5aa5e3b500e191763d35198f859e4b40fff4a6"
uuid = "cd3eb016-35fb-5094-929b-558a96fad6f3"
version = "1.7.3"
[[deps.Hyperscript]]
deps = ["Test"]
git-tree-sha1 = "8d511d5b81240fc8e6802386302675bdf47737b9"
uuid = "47d2ed2b-36de-50cf-bf87-49c2cf4b8b91"
version = "0.0.4"
[[deps.HypertextLiteral]]
deps = ["Tricks"]
git-tree-sha1 = "c47c5fa4c5308f27ccaac35504858d8914e102f9"
uuid = "ac1192a8-f4b3-4bfe-ba22-af5b92cd3ab2"
version = "0.9.4"
[[deps.IOCapture]]
deps = ["Logging", "Random"]
git-tree-sha1 = "f7be53659ab06ddc986428d3a9dcc95f6fa6705a"
uuid = "b5f81e59-6552-4d32-b1f0-c071b021bf89"
version = "0.2.2"
[[deps.IniFile]]
git-tree-sha1 = "f550e6e32074c939295eb5ea6de31849ac2c9625"
uuid = "83e8ac13-25f8-5344-8a64-a9f2b223428f"
version = "0.5.1"
[[deps.InteractiveUtils]]
deps = ["Markdown"]
uuid = "b77e0a4c-d291-57a0-90e8-8db25a27a240"
[[deps.InverseFunctions]]
deps = ["Test"]
git-tree-sha1 = "49510dfcb407e572524ba94aeae2fced1f3feb0f"
uuid = "3587e190-3f89-42d0-90ee-14403ec27112"
version = "0.1.8"
[[deps.IrrationalConstants]]
git-tree-sha1 = "7fd44fd4ff43fc60815f8e764c0f352b83c49151"
uuid = "92d709cd-6900-40b7-9082-c6be49f344b6"
version = "0.1.1"
[[deps.IterTools]]
git-tree-sha1 = "fa6287a4469f5e048d763df38279ee729fbd44e5"
uuid = "c8e1da08-722c-5040-9ed9-7db0dc04731e"
version = "1.4.0"
[[deps.IteratorInterfaceExtensions]]
git-tree-sha1 = "a3f24677c21f5bbe9d2a714f95dcd58337fb2856"
uuid = "82899510-4779-5014-852e-03e436cf321d"
version = "1.0.0"
[[deps.JLLWrappers]]
deps = ["Preferences"]
git-tree-sha1 = "abc9885a7ca2052a736a600f7fa66209f96506e1"
uuid = "692b3bcd-3c85-4b1f-b108-f13ce0eb3210"
version = "1.4.1"
[[deps.JSON]]
deps = ["Dates", "Mmap", "Parsers", "Unicode"]
git-tree-sha1 = "3c837543ddb02250ef42f4738347454f95079d4e"
uuid = "682c06a0-de6a-54ab-a142-c8b1cf79cde6"
version = "0.21.3"
[[deps.LazilyInitializedFields]]
git-tree-sha1 = "410fe4739a4b092f2ffe36fcb0dcc3ab12648ce1"
uuid = "0e77f7df-68c5-4e49-93ce-4cd80f5598bf"
version = "1.2.1"
[[deps.LibCURL]]
deps = ["LibCURL_jll", "MozillaCACerts_jll"]
uuid = "b27032c2-a3e7-50c8-80cd-2d36dbcbfd21"
version = "0.6.3"
[[deps.LibCURL_jll]]
deps = ["Artifacts", "LibSSH2_jll", "Libdl", "MbedTLS_jll", "Zlib_jll", "nghttp2_jll"]
uuid = "deac9b47-8bc7-5906-a0fe-35ac56dc84c0"
version = "7.84.0+0"
[[deps.LibGit2]]
deps = ["Base64", "NetworkOptions", "Printf", "SHA"]
uuid = "76f85450-5226-5b5a-8eaa-529ad045b433"
[[deps.LibSSH2_jll]]
deps = ["Artifacts", "Libdl", "MbedTLS_jll"]
uuid = "29816b5a-b9ab-546f-933c-edad1886dfa8"
version = "1.10.2+0"
[[deps.Libdl]]
uuid = "8f399da3-3557-5675-b5ff-fb832c97cbdb"
[[deps.Libiconv_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "c7cb1f5d892775ba13767a87c7ada0b980ea0a71"
uuid = "94ce4f54-9a6c-5748-9c1c-f9c7231a4531"
version = "1.16.1+2"
[[deps.LightXML]]
deps = ["Libdl", "XML2_jll"]
git-tree-sha1 = "e129d9391168c677cd4800f5c0abb1ed8cb3794f"
uuid = "9c8b4983-aa76-5018-a973-4c85ecc9e179"
version = "0.9.0"
[[deps.LinearAlgebra]]
deps = ["Libdl", "libblastrampoline_jll"]
uuid = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e"
[[deps.LogExpFunctions]]
deps = ["ChainRulesCore", "ChangesOfVariables", "DocStringExtensions", "InverseFunctions", "IrrationalConstants", "LinearAlgebra"]
git-tree-sha1 = "946607f84feb96220f480e0422d3484c49c00239"
uuid = "2ab3a3ac-af41-5b50-aa03-7779005ae688"
version = "0.3.19"
[[deps.Logging]]
uuid = "56ddb016-857b-54e1-b83d-db4d58db5568"
[[deps.LoggingExtras]]
deps = ["Dates", "Logging"]
git-tree-sha1 = "cedb76b37bc5a6c702ade66be44f831fa23c681e"
uuid = "e6f89c97-d47a-5376-807f-9c37f3926c36"
version = "1.0.0"
[[deps.MIMEs]]
git-tree-sha1 = "65f28ad4b594aebe22157d6fac869786a255b7eb"
uuid = "6c6e2e6c-3030-632d-7369-2d6c69616d65"
version = "0.1.4"
[[deps.Markdown]]
deps = ["Base64"]
uuid = "d6f4376e-aef5-505a-96c1-9c027394607a"
[[deps.MbedTLS]]
deps = ["Dates", "MbedTLS_jll", "MozillaCACerts_jll", "Random", "Sockets"]
git-tree-sha1 = "03a9b9718f5682ecb107ac9f7308991db4ce395b"
uuid = "739be429-bea8-5141-9913-cc70e7f3736d"
version = "1.1.7"
[[deps.MbedTLS_jll]]
deps = ["Artifacts", "Libdl"]
uuid = "c8ffd9c3-330d-5841-b78e-0817d7145fa1"
version = "2.28.0+0"
[[deps.MeshIO]]
deps = ["ColorTypes", "FileIO", "GeometryBasics", "Printf"]
git-tree-sha1 = "8be09d84a2d597c7c0c34d7d604c039c9763e48c"
uuid = "7269a6da-0436-5bbc-96c2-40638cbb6118"
version = "0.4.10"
[[deps.Mmap]]
uuid = "a63ad114-7e13-5084-954f-fe012c677804"
[[deps.MozillaCACerts_jll]]
uuid = "14a3606d-f60d-562e-9121-12d972cd8159"
version = "2022.2.1"
[[deps.MsgPack]]
deps = ["Serialization"]
git-tree-sha1 = "a8cbf066b54d793b9a48c5daa5d586cf2b5bd43d"
uuid = "99f44e22-a591-53d1-9472-aa23ef4bd671"
version = "1.1.0"
[[deps.NetworkOptions]]
uuid = "ca575930-c2e3-43a9-ace4-1e988b2c1908"
version = "1.2.0"
[[deps.Observables]]
git-tree-sha1 = "6862738f9796b3edc1c09d0890afce4eca9e7e93"
uuid = "510215fc-4207-5dde-b226-833fc4488ee2"
version = "0.5.4"
[[deps.OpenBLAS_jll]]
deps = ["Artifacts", "CompilerSupportLibraries_jll", "Libdl"]
uuid = "4536629a-c528-5b80-bd46-f80d51c5b363"
version = "0.3.20+0"
[[deps.OpenLibm_jll]]
deps = ["Artifacts", "Libdl"]
uuid = "05823500-19ac-5b8b-9628-191a04bc5112"
version = "0.8.1+0"
[[deps.OpenSSL]]
deps = ["BitFlags", "Dates", "MozillaCACerts_jll", "OpenSSL_jll", "Sockets"]
git-tree-sha1 = "6503b77492fd7fcb9379bf73cd31035670e3c509"
uuid = "4d8831e6-92b7-49fb-bdf8-b643e874388c"
version = "1.3.3"
[[deps.OpenSSL_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "f6e9dba33f9f2c44e08a020b0caf6903be540004"
uuid = "458c3c95-2e84-50aa-8efc-19380b2a3a95"
version = "1.1.19+0"
[[deps.OpenSpecFun_jll]]
deps = ["Artifacts", "CompilerSupportLibraries_jll", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "13652491f6856acfd2db29360e1bbcd4565d04f1"
uuid = "efe28fd5-8261-553b-a9e1-b2916fc3738e"
version = "0.5.5+0"
[[deps.OrderedCollections]]
git-tree-sha1 = "85f8e6578bf1f9ee0d11e7bb1b1456435479d47c"
uuid = "bac558e1-5e72-5ebc-8fee-abe8a469f55d"
version = "1.4.1"
[[deps.Parsers]]
deps = ["Dates", "SnoopPrecompile"]
git-tree-sha1 = "8175fc2b118a3755113c8e68084dc1a9e63c61ee"
uuid = "69de0a69-1ddd-5017-9359-2bf0b02dc9f0"
version = "2.5.3"
[[deps.Pkg]]
deps = ["Artifacts", "Dates", "Downloads", "LibGit2", "Libdl", "Logging", "Markdown", "Printf", "REPL", "Random", "SHA", "Serialization", "TOML", "Tar", "UUIDs", "p7zip_jll"]
uuid = "44cfe95a-1eb2-52ea-b672-e2afdf69b78f"
version = "1.8.0"
[[deps.PkgVersion]]
deps = ["Pkg"]
git-tree-sha1 = "f6cf8e7944e50901594838951729a1861e668cb8"
uuid = "eebad327-c553-4316-9ea0-9fa01ccd7688"
version = "0.3.2"
[[deps.Pluto]]
deps = ["Base64", "Configurations", "Dates", "Distributed", "FileWatching", "FuzzyCompletions", "HTTP", "HypertextLiteral", "InteractiveUtils", "Logging", "MIMEs", "Markdown", "MsgPack", "Pkg", "PrecompileSignatures", "REPL", "RegistryInstances", "RelocatableFolders", "Sockets", "TOML", "Tables", "URIs", "UUIDs"]
git-tree-sha1 = "f4c99fcadf03dcdd2dd8ae7a56ca963ef1450d4f"
uuid = "c3e4b0f8-55cb-11ea-2926-15256bba5781"
version = "0.19.19"
[[deps.PlutoUI]]
deps = ["AbstractPlutoDingetjes", "Base64", "ColorTypes", "Dates", "FixedPointNumbers", "Hyperscript", "HypertextLiteral", "IOCapture", "InteractiveUtils", "JSON", "Logging", "MIMEs", "Markdown", "Random", "Reexport", "URIs", "UUIDs"]
git-tree-sha1 = "eadad7b14cf046de6eb41f13c9275e5aa2711ab6"
uuid = "7f904dfe-b85e-4ff6-b463-dae2292396a8"
version = "0.7.49"
[[deps.PlutoVista]]
deps = ["ColorSchemes", "Colors", "DocStringExtensions", "GridVisualizeTools", "HypertextLiteral", "Pluto", "UUIDs"]
git-tree-sha1 = "5af654ba1660641b3b80614a7be7eacae4c49875"
uuid = "646e1f28-b900-46d7-9d87-d554eb38a413"
version = "0.8.16"
[[deps.PrecompileSignatures]]
git-tree-sha1 = "18ef344185f25ee9d51d80e179f8dad33dc48eb1"
uuid = "91cefc8d-f054-46dc-8f8c-26e11d7c5411"
version = "3.0.3"
[[deps.Preferences]]
deps = ["TOML"]
git-tree-sha1 = "47e5f437cc0e7ef2ce8406ce1e7e24d44915f88d"
uuid = "21216c6a-2e73-6563-6e65-726566657250"
version = "1.3.0"
[[deps.Printf]]
deps = ["Unicode"]
uuid = "de0858da-6303-5e67-8744-51eddeeeb8d7"
[[deps.REPL]]
deps = ["InteractiveUtils", "Markdown", "Sockets", "Unicode"]
uuid = "3fa0cd96-eef1-5676-8a61-b3b8758bbffb"
[[deps.Random]]
deps = ["SHA", "Serialization"]
uuid = "9a3f8284-a2c9-5f02-9a11-845980a1fd5c"
[[deps.Reexport]]
git-tree-sha1 = "45e428421666073eab6f2da5c9d310d99bb12f9b"
uuid = "189a3867-3050-52da-a836-e630ba90ab69"
version = "1.2.2"
[[deps.RegistryInstances]]
deps = ["LazilyInitializedFields", "Pkg", "TOML", "Tar"]
git-tree-sha1 = "ffd19052caf598b8653b99404058fce14828be51"
uuid = "2792f1a3-b283-48e8-9a74-f99dce5104f3"
version = "0.1.0"
[[deps.RelocatableFolders]]
deps = ["SHA", "Scratch"]
git-tree-sha1 = "90bc7a7c96410424509e4263e277e43250c05691"
uuid = "05181044-ff0b-4ac5-8273-598c1e38db00"
version = "1.0.0"
[[deps.Requires]]
deps = ["UUIDs"]
git-tree-sha1 = "838a3a4188e2ded87a4f9f184b4b0d78a1e91cb7"
uuid = "ae029012-a4dd-5104-9daa-d747884805df"
version = "1.3.0"
[[deps.SHA]]
uuid = "ea8e919c-243c-51af-8825-aaa63cd721ce"
version = "0.7.0"
[[deps.Scratch]]
deps = ["Dates"]
git-tree-sha1 = "f94f779c94e58bf9ea243e77a37e16d9de9126bd"
uuid = "6c6a2e73-6563-6170-7368-637461726353"
version = "1.1.1"
[[deps.Serialization]]
uuid = "9e88b42a-f829-5b0c-bbe9-9e923198166b"
[[deps.SimpleBufferStream]]
git-tree-sha1 = "874e8867b33a00e784c8a7e4b60afe9e037b74e1"
uuid = "777ac1f9-54b0-4bf8-805c-2214025038e7"
version = "1.1.0"
[[deps.SimplexGridFactory]]
deps = ["DocStringExtensions", "ElasticArrays", "ExtendableGrids", "FileIO", "GridVisualize", "LinearAlgebra", "MeshIO", "Printf", "Test"]
git-tree-sha1 = "4566d826852b7815d34c7a8829679c6f15f4b2e7"
uuid = "57bfcd06-606e-45d6-baf4-4ba06da0efd5"
version = "0.5.18"
[[deps.SnoopPrecompile]]
deps = ["Preferences"]
git-tree-sha1 = "e760a70afdcd461cf01a575947738d359234665c"
uuid = "66db9d55-30c0-4569-8b51-7e840670fc0c"
version = "1.0.3"
[[deps.Sockets]]
uuid = "6462fe0b-24de-5631-8697-dd941f90decc"
[[deps.SparseArrays]]
deps = ["LinearAlgebra", "Random"]
uuid = "2f01184e-e22b-5df5-ae63-d93ebab69eaf"
[[deps.SpecialFunctions]]
deps = ["ChainRulesCore", "IrrationalConstants", "LogExpFunctions", "OpenLibm_jll", "OpenSpecFun_jll"]
git-tree-sha1 = "d75bda01f8c31ebb72df80a46c88b25d1c79c56d"
uuid = "276daf66-3868-5448-9aa4-cd146d93841b"
version = "2.1.7"
[[deps.StaticArrays]]
deps = ["LinearAlgebra", "Random", "StaticArraysCore", "Statistics"]
git-tree-sha1 = "6954a456979f23d05085727adb17c4551c19ecd1"
uuid = "90137ffa-7385-5640-81b9-e52037218182"
version = "1.5.12"
[[deps.StaticArraysCore]]
git-tree-sha1 = "6b7ba252635a5eff6a0b0664a41ee140a1c9e72a"
uuid = "1e83bf80-4336-4d27-bf5d-d5a4f845583c"
version = "1.4.0"
[[deps.Statistics]]
deps = ["LinearAlgebra", "SparseArrays"]
uuid = "10745b16-79ce-11e8-11f9-7d13ad32a3b2"
[[deps.StructArrays]]
deps = ["Adapt", "DataAPI", "GPUArraysCore", "StaticArraysCore", "Tables"]
git-tree-sha1 = "b03a3b745aa49b566f128977a7dd1be8711c5e71"
uuid = "09ab397b-f2b6-538f-b94a-2f83cf4a842a"
version = "0.6.14"
[[deps.TOML]]
deps = ["Dates"]
uuid = "fa267f1f-6049-4f14-aa54-33bafae1ed76"
version = "1.0.0"
[[deps.TableTraits]]
deps = ["IteratorInterfaceExtensions"]
git-tree-sha1 = "c06b2f539df1c6efa794486abfb6ed2022561a39"
uuid = "3783bdb8-4a98-5b6b-af9a-565f29a5fe9c"
version = "1.0.1"
[[deps.Tables]]
deps = ["DataAPI", "DataValueInterfaces", "IteratorInterfaceExtensions", "LinearAlgebra", "OrderedCollections", "TableTraits", "Test"]
git-tree-sha1 = "c79322d36826aa2f4fd8ecfa96ddb47b174ac78d"
uuid = "bd369af6-aec1-5ad0-b16a-f7cc5008161c"
version = "1.10.0"
[[deps.Tar]]
deps = ["ArgTools", "SHA"]
uuid = "a4e569a6-e804-4fa4-b0f3-eef7a1d5b13e"
version = "1.10.1"
[[deps.TensorCore]]
deps = ["LinearAlgebra"]
git-tree-sha1 = "1feb45f88d133a655e001435632f019a9a1bcdb6"
uuid = "62fd8b95-f654-4bbd-a8a5-9c27f68ccd50"
version = "0.1.1"
[[deps.Test]]
deps = ["InteractiveUtils", "Logging", "Random", "Serialization"]
uuid = "8dfed614-e22c-5e08-85e1-65c5234f0b40"
[[deps.TetGen]]
deps = ["DocStringExtensions", "GeometryBasics", "LinearAlgebra", "Printf", "StaticArrays", "TetGen_jll"]
git-tree-sha1 = "d99fe468112a24feb36bcdac8c168f423de7e93c"
uuid = "c5d3f3f7-f850-59f6-8a2e-ffc6dc1317ea"
version = "1.4.0"
[[deps.TetGen_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "9ceedd691bce040e24126a56354f20d71554a495"
uuid = "b47fdcd6-d2c1-58e9-bbba-c1cee8d8c179"
version = "1.5.3+0"
[[deps.TranscodingStreams]]
deps = ["Random", "Test"]
git-tree-sha1 = "94f38103c984f89cf77c402f2a68dbd870f8165f"
uuid = "3bb67fe8-82b1-5028-8e26-92a6c54297fa"
version = "0.9.11"
[[deps.Triangle_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "fe28e9a4684f6f54e868b9136afb8fd11f1734a7"
uuid = "5639c1d2-226c-5e70-8d55-b3095415a16a"
version = "1.6.2+0"
[[deps.Triangulate]]
deps = ["DocStringExtensions", "Libdl", "Printf", "Test", "Triangle_jll"]
git-tree-sha1 = "bbca6ec35426334d615f58859ad40c96d3a4a1f9"
uuid = "f7e6ffb2-c36d-4f8f-a77e-16e897189344"
version = "2.2.0"
[[deps.Tricks]]
git-tree-sha1 = "6bac775f2d42a611cdfcd1fb217ee719630c4175"
uuid = "410a4b4d-49e4-4fbc-ab6d-cb71b17b3775"
version = "0.1.6"
[[deps.URIs]]
git-tree-sha1 = "ac00576f90d8a259f2c9d823e91d1de3fd44d348"
uuid = "5c2747f8-b7ea-4ff2-ba2e-563bfd36b1d4"
version = "1.4.1"
[[deps.UUIDs]]
deps = ["Random", "SHA"]
uuid = "cf7118a7-6976-5b1a-9a39-7adc72f591a4"
[[deps.Unicode]]
uuid = "4ec0a83e-493e-50e2-b9ac-8f72acf5a8f5"
[[deps.WriteVTK]]
deps = ["Base64", "CodecZlib", "FillArrays", "LightXML", "TranscodingStreams"]
git-tree-sha1 = "f50c47d715199601a54afdd5267f24c8174842ae"
uuid = "64499a7a-5c06-52f2-abe2-ccb03c286192"
version = "1.16.0"
[[deps.XML2_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Libiconv_jll", "Pkg", "Zlib_jll"]
git-tree-sha1 = "93c41695bc1c08c46c5899f4fe06d6ead504bb73"
uuid = "02c8fc9c-b97f-50b9-bbe4-9be30ff0a78a"
version = "2.10.3+0"
[[deps.Zlib_jll]]
deps = ["Libdl"]
uuid = "83775a58-1f1d-513f-b197-d71354ab007a"
version = "1.2.12+3"
[[deps.libblastrampoline_jll]]
deps = ["Artifacts", "Libdl", "OpenBLAS_jll"]
uuid = "8e850b90-86db-534c-a0d3-1478176c7d93"
version = "5.1.1+0"
[[deps.nghttp2_jll]]
deps = ["Artifacts", "Libdl"]
uuid = "8e850ede-7688-5339-a07c-302acd2aaf8d"
version = "1.48.0+0"
[[deps.p7zip_jll]]
deps = ["Artifacts", "Libdl"]
uuid = "3f19e933-33d8-53b3-aaab-bd5110c3b7a0"
version = "17.4.0+0"
"""
# ╔═╡ Cell order:
# ╟─940b1996-fe9d-11ea-2fa4-8b72bee62b76
# ╠═d432ad64-f91f-11ea-2e48-4bc7472ac64c
# ╟─47103e8f-a4ff-46ed-a632-572a2e194a50
# ╠═93a0c45e-d6a3-415a-a82c-e4f7e2a09d22
# ╠═4622a1fc-fda7-4211-9cc0-4eb1a1584aa6
# ╟─3212b930-194d-422e-9d06-65885b25cc6d
# ╠═5520b8c0-0874-4790-a956-224e6c43d9cf
# ╟─13aef2a1-5745-4fe5-9659-6b7c0e7267fc
# ╠═f19d20c8-4d69-442d-99c8-10874fa0a6d3
# ╟─28e2e3b0-c168-481b-b467-29e6a5407431
# ╠═f04017d7-1c55-4118-8467-1e134259e35d
# ╠═98016b49-8786-46b9-aca6-01d15c253b3f
# ╟─2d392a98-bf32-4145-ae93-a8e218367277
# ╠═88247350-aa6c-4876-82c3-3534036d5702
# ╠═42f8d91d-14c7-488f-bdb9-b3d22705186f
# ╠═db7e0233-4e08-41b8-9ebe-5570e6d32264
# ╠═74641f73-2efe-4df8-bebb-ed97e77d869e
# ╟─14fb7977-93cf-4f74-a8ec-b6ee25dbdf86
# ╠═2d5cb9e1-2d14-415e-b792-c3124901011d
# ╟─b1f903b3-29d7-4909-b7e2-8ef3528c9965
# ╠═19125aed-5c46-4968-bcfc-0b469628b68e
# ╠═f9debaf8-efe8-44d1-9671-4aa5bffa9bb8
# ╠═4f7f9eaf-61c5-4543-ae39-e58ca14fb89a
# ╠═f873cb89-da6e-4e11-b3f6-2bf0b766ce5f
# ╟─a2e6c397-4a7e-47eb-ad84-df6e9d3fdd43
# ╠═805c2a1e-a6c6-47fc-b719-31c2a671a8d0
# ╠═dd7d8e17-f825-4047-9386-d9e2bfd0a48d
# ╟─3d7db57f-2864-4984-a979-609e1d838a9f
# ╠═4cf840e6-86c5-4af1-a780-6fc78b60716b
# ╠═151cc4b8-c5ed-4f5e-8d5f-2f708c9c7fae
# ╠═605581c4-3c6f-4c31-bd90-7645d3f70315
# ╠═bd40e614-00ef-426d-aa98-eca2ef48320e
# ╠═71af99ab-612a-4821-8e9c-efc8766e2e3e
# ╟─6dfa1d73-8baa-4589-b2e6-547834c9e444
# ╠═f9599246-8238-432c-a315-300d74abfa2c
# ╠═ba5af291-fb16-4f21-8b74-664284bf7bd9
# ╟─dfbaacea-4cb4-4147-9f1b-4424d7a7e89b
# ╟─7d1698dd-3bb7-4b38-9c6d-a88652749eee
# ╠═81249f7c-abdf-43cc-b57f-2915b09da009
# ╟─0765641a-8ed9-4579-bd9b-90bb02a55792
# ╠═884a11a2-15cf-40fc-a1ca-66ea23c6094e
# ╟─8fbd238c-723e-4bce-af69-9cabfc03f8d9
# ╠═342788d4-e5d0-4239-be87-7658bb67c999
# ╠═8f7d958e-5dc5-4324-af21-ad829d7d77eb
# ╟─fd27b44a-f923-11ea-2afb-d79f7e62e214
# ╟─4a289b23-46b9-495d-b19c-42b3da71b242
# ╠═b12838f0-fe9c-11ea-2939-155ed907322d
# ╟─d5d8a1d6-fe9d-11ea-0fd8-df6e81492cb5
# ╠═aae2e82a-fe9c-11ea-0427-593f8d2c7746
# ╟─1ae86964-fe9e-11ea-303b-65bb128384a5
# ╟─3b8cd906-bc4e-44af-bcf4-8836d597ed4c
# ╟─9d240ef9-6639-4bde-a463-ea78480a970d
# ╠═511b26c6-f920-11ea-1228-51c3750f495c
# ╟─d2129483-285b-49a2-a11d-886956146b85
# ╠═ac93589b-6315-4677-9542-c0a2333f1755
# ╠═59a6c8b5-25aa-47aa-9489-a803672013df
# ╟─4c99c40f-cf93-4cba-bef1-0c4ffcbf6833
# ╠═bad736d7-875c-4bc0-9ec4-494a90a508f7
# ╠═a375c23f-6b8c-4b2c-a8b5-d38e6b5a8f6d
# ╠═c3ef9067-3cdb-4bfd-9406-6ded64539978
# ╠═4dfb2e0f-3e3a-4053-8a76-765546e96992
# ╟─2682df92-5955-4b17-ae4f-8e99c5b17980
# ╠═265fe6c7-d1cc-48a6-8295-f8f55acf677c
# ╠═b357395f-2a6e-476f-b008-02802c85a541
# ╠═af449be7-aab6-4de5-a059-3f8508502676
# ╠═38e2b4a8-2480-40e7-bde3-6d1775201aae
# ╠═f97d085c-e7bf-4561-8183-673912bdeab6
# ╠═ef1fde48-fe90-4714-ac86-614ae3451aa7
# ╠═d73d18e7-bcf9-4cc1-9154-b70dc1ff5524
# ╠═a3844fda-5725-4d95-894b-051a5f6c2faa
# ╠═04041481-0f03-41e1-a7de-1b3fd033c952
# ╟─6cad87eb-1c59-4000-b688-a6f6d41f9413
# ╠═fefc7587-8e25-4080-b934-90c0e1afc56a
# ╠═065735f7-c799-4284-bd59-fe6383bb987c
# ╠═329992a0-e352-468b-af8b-0b190315fc61
# ╟─a7965a6e-2e83-47eb-aee2-d366246a8637
# ╠═7ad541b1-f40f-4cdd-b7b5-b792a8e63d71
# ╠═071b8834-d3d1-4d08-979f-56b05bc1e0d3
# ╟─00000000-0000-0000-0000-000000000001
# ╟─00000000-0000-0000-0000-000000000002
| PDELib | https://github.com/WIAS-BERLIN/PDELib.jl.git |
|
[
"MIT"
] | 0.3.0 | 2fca7ee903e9c45871c1948e6b5fffdf359e2da3 | code | 28887 | ### A Pluto.jl notebook ###
# v0.19.19
using Markdown
using InteractiveUtils
# This Pluto notebook uses @bind for interactivity. When running this notebook outside of Pluto, the following 'mock version' of @bind gives bound variables a default value (instead of an error).
macro bind(def, element)
quote
local iv = try Base.loaded_modules[Base.PkgId(Base.UUID("6e696c72-6542-2067-7265-42206c756150"), "AbstractPlutoDingetjes")].Bonds.initial_value catch; b -> missing; end
local el = $(esc(element))
global $(esc(def)) = Core.applicable(Base.get, el) ? Base.get(el) : iv(el)
el
end
end
# ╔═╡ 60941eaa-1aea-11eb-1277-97b991548781
begin
using PlutoUI
using ExtendableGrids
using SimplexGridFactory
using PlutoVista
using GridVisualize
using Triangulate
isdefined(Main,:PlutoRunner) ? default_plotter!(PlutoVista) : default_plotter!(nothing)
end
# ╔═╡ 07194f25-5735-452f-9bed-cf791958d44d
md"""
## Grid with quadratic boundary subregions at electrode
"""
# ╔═╡ d0f3483a-2bf4-4e2d-80b0-6c869b45cda8
function qxygrid(;nref=0,xymax=1.0,hxymin=0.1,hxymax=0.1)
Xp=geomspace(0,xymax,hxymin,hxymax)
Xm=-reverse(Xp)
X=glue(Xm,Xp)
gridxy=simplexgrid(X,X)
fill!(gridxy[BFaceRegions],5)
gridxy
end
# ╔═╡ fd8f6c48-0030-4f6f-9fbf-9f2340decbf2
g=qxygrid(hxymin=0.05, hxymax=0.2)
# ╔═╡ bbeeebc0-ae16-4022-975d-35588e62166a
gridplot(g)
# ╔═╡ e6c7e47d-6159-4bb6-a71d-7c633e2fefbd
function qxyzgrid(gridxy ;zmax=1.0,hzmin=0.05,hzmax=0.2)
Z=geomspace(0,zmax,hzmin,hzmax)
gridxyz=simplexgrid(gridxy,Z,top_offset=1)
xymax=gridxy[Coordinates][1,end]
bfacemask!(gridxyz,[-xymax,-xymax,0],[0,0,0],1)
bfacemask!(gridxyz,[0,0,0],[xymax,xymax,0],2)
bfacemask!(gridxyz,[0,-xymax,0],[xymax,0,0],3)
bfacemask!(gridxyz,[-xymax,0,0],[0,xymax,0],4)
gridxyz
end
# ╔═╡ 9800c97e-c25b-4d08-a014-cccd746f7d71
gxyz=qxyzgrid(g)
# ╔═╡ 9a219111-0275-4cd9-b97e-648d3fcfcbb9
vis=GridVisualizer(dim=3,resolution=(400,300));vis
# ╔═╡ 85be1677-87ff-49dc-af9a-557e575bc55f
@bind z Slider(0:0.01:1,show_value=true,default=0.5)
# ╔═╡ 33ecc78c-16ac-46ac-8d83-cbb26288a6fb
gridplot!(vis,gxyz,show=true,zplanes=[z],xplanes=[1],yplanes=[1],outlinealpha=0.3)
# ╔═╡ 9e640256-61a4-4fb9-a449-d5f948fb2d26
md"""
## Grid with inner circle at electrode
"""
# ╔═╡ bf0004f4-b3c8-4385-b87d-df2ef1420408
md"""
### Plain triangulation
"""
# ╔═╡ 1b70e44b-cbe8-4812-b267-ef9bce20a5b7
function cxygrid(;maxvol=0.01,nref=0,xyzmax=1,rad=0.5)
builder=SimplexGridBuilder(Generator=Triangulate)
regionpoint!(builder,(xyzmax-0.1,xyzmax-0.1))
cellregion!(builder,1)
rect2d!(builder,[-xyzmax,-xyzmax],[xyzmax,xyzmax],facetregions=1)
facetregion!(builder,3)
cellregion!(builder,2)
regionpoint!(builder, (0,0))
circle!(builder,(0,0), rad,n=20)
simplexgrid(builder,maxvolume=maxvol)
end
# ╔═╡ 10ebaeab-3ece-480f-9c4d-a676814e2f7f
gcxy=cxygrid()
# ╔═╡ b711885e-cc61-4e08-9367-437731323863
gridplot(gcxy)
# ╔═╡ e4029d2c-18b7-4592-b47d-294e4af93497
gcxy.components
# ╔═╡ 0c3f5b1c-7bcf-491e-8318-73f2c880e0b5
function cxyzgrid(gcxy,zmax=1.0,hzmin=0.05,hzmax=0.2)
Z=geomspace(0,zmax,hzmin,hzmax)
gridxyz=simplexgrid(gcxy,Z,bot_offset=0)
xymax=maximum(gcxy[Coordinates][1,:])
bfacemask!(gridxyz,[-xymax,-xymax,zmax],[xymax,xymax,zmax],5,allow_new=false)
gridxyz
end
# ╔═╡ f9130b5d-b4ea-4ebd-b73f-82a3c1bc1307
gcxyz=cxyzgrid(gcxy)
# ╔═╡ 73847699-40c0-4043-a16f-37883def6858
gcxyz.components
# ╔═╡ bff0a3f1-c545-4fcc-8be8-ef460f8479bd
visc=GridVisualizer(dim=3,resolution=(400,300))
# ╔═╡ 66ce2939-2957-43e0-b7ea-cdd10d9fc17e
@bind zc Slider(0:0.01:1,show_value=true,default=0.5)
# ╔═╡ a310027d-3f9e-4de5-bc9e-5457cb19eef5
gridplot!(visc,gcxyz,show=true,zplanes=[zc],xplanes=[1],yplanes=[1],outlinealpha=0.3)
# ╔═╡ 752bdb8f-de5a-4863-b2d1-53d69aff7dcb
md"""
### Grid with anisotropic local refinement at electrode
"""
# ╔═╡ 5aef30a0-8712-4c6c-9465-25da0624b408
function grxy(;nang=40,nxy=15, r=0.5, dr=0.1,hrmin=0.01,hrmax=0.05,xymax=1.0)
rad1=geomspace(r-dr,r,hrmax,hrmin)
rad2=geomspace(r,r+dr,hrmin,hrmax)
ang=range(0,2π,length=nang)
δr=2π*r/nang
maxvol=0.5*δr^2
ring1=ringsector(rad1,ang)
ring1[CellRegions].=1
ring2=ringsector(rad2,ang)
ring1[CellRegions].=2
ring=glue(ring1,ring2,breg=3)
binner=SimplexGridBuilder(Generator=Triangulate)
regionpoint!(binner,(0,0))
cellregion!(binner,2)
facetregion!(binner,2)
bregions!(binner,ring,[1])
ginner=simplexgrid(binner,maxvolume=maxvol,nosteiner=true)
ginner[CellRegions].=2
bouter=SimplexGridBuilder(Generator=Triangulate)
holepoint!(bouter,(0,0))
facetregion!(bouter,3)
bregions!(bouter,ring,[2])
regionpoint!(bouter,(xymax-0.1,xymax-0.1))
cellregion!(bouter,3)
rect2d!(bouter,[-xymax,-xymax],[xymax,xymax],facetregions=1,nx=nxy,ny=nxy)
gouter=simplexgrid(bouter;maxvolume=maxvol*2,nosteiner=true)
glue(glue(gouter,ring),ginner)
end
# ╔═╡ 4debce38-96c5-4661-a965-1ca723fa8a36
rxygrid=grxy()
# ╔═╡ 52f4c693-0218-4f56-ac95-abd6d99a0b67
gridplot(rxygrid)
# ╔═╡ f43bd8ff-a2ed-4740-a61e-4f5d2c615c10
grxyz=cxyzgrid(rxygrid)
# ╔═╡ b9ced73f-e7a0-4573-9413-c2a231d21c78
visr=GridVisualizer(dim=3,resolution=(400,300))
# ╔═╡ 2c285e4f-9f10-474b-9482-83a5c4cbfe09
@bind zr Slider(0:0.01:1,show_value=true,default=0.5)
# ╔═╡ 97d8db91-16e6-4070-81a0-7bcaff6cc9f6
gridplot!(visr,grxyz,show=true,zplanes=[zr],xplanes=[1],yplanes=[1],outlinealpha=0.3)
# ╔═╡ 78dba5b2-52c9-40cd-bc1d-d5c343271f97
html"""<hr> """
# ╔═╡ b9cc0359-7286-4c02-ba10-35303da26a50
TableOfContents()
# ╔═╡ 605c914d-607b-4d2e-80c5-d14cb6918e32
md"""
begin
using Pkg
Pkg.activate(mktempdir())
Pkg.add(["PlutoUI","Revise","Triangulate"])
using Revise
Pkg.develop(["ExtendableGrids","SimplexGridFactory",
"GridVisualize","PlutoVista"])
end
"""
# ╔═╡ 00000000-0000-0000-0000-000000000001
PLUTO_PROJECT_TOML_CONTENTS = """
[deps]
ExtendableGrids = "cfc395e8-590f-11e8-1f13-43a2532b2fa8"
GridVisualize = "5eed8a63-0fb0-45eb-886d-8d5a387d12b8"
PlutoUI = "7f904dfe-b85e-4ff6-b463-dae2292396a8"
PlutoVista = "646e1f28-b900-46d7-9d87-d554eb38a413"
SimplexGridFactory = "57bfcd06-606e-45d6-baf4-4ba06da0efd5"
Triangulate = "f7e6ffb2-c36d-4f8f-a77e-16e897189344"
[compat]
ExtendableGrids = "~0.9.16"
GridVisualize = "~0.6.1"
PlutoUI = "~0.7.16"
PlutoVista = "~0.8.6"
SimplexGridFactory = "~0.5.18"
Triangulate = "~2.2.0"
"""
# ╔═╡ 00000000-0000-0000-0000-000000000002
PLUTO_MANIFEST_TOML_CONTENTS = """
# This file is machine-generated - editing it directly is not advised
manifest_format = "2.0"
project_hash = "ed5d0e039c16ed3dff8cdeb7be686be0cd3c7d3e"
[[deps.AbstractPlutoDingetjes]]
deps = ["Pkg"]
git-tree-sha1 = "8eaf9f1b4921132a4cff3f36a1d9ba923b14a481"
uuid = "6e696c72-6542-2067-7265-42206c756150"
version = "1.1.4"
[[deps.AbstractTrees]]
git-tree-sha1 = "faa260e4cb5aba097a73fab382dd4b5819d8ec8c"
uuid = "1520ce14-60c1-5f80-bbc7-55ef81b5835c"
version = "0.4.4"
[[deps.Adapt]]
deps = ["LinearAlgebra"]
git-tree-sha1 = "195c5505521008abea5aee4f96930717958eac6f"
uuid = "79e6a3ab-5dfb-504d-930d-738a2a938a0e"
version = "3.4.0"
[[deps.ArgTools]]
uuid = "0dad84c5-d112-42e6-8d28-ef12dabb789f"
version = "1.1.1"
[[deps.Artifacts]]
uuid = "56f22d72-fd6d-98f1-02f0-08ddc0907c33"
[[deps.Base64]]
uuid = "2a0f44e3-6c83-55bd-87e4-b1978d98bd5f"
[[deps.BitFlags]]
git-tree-sha1 = "43b1a4a8f797c1cddadf60499a8a077d4af2cd2d"
uuid = "d1d4a3ce-64b1-5f1a-9ba4-7e7e69966f35"
version = "0.1.7"
[[deps.ChainRulesCore]]
deps = ["Compat", "LinearAlgebra", "SparseArrays"]
git-tree-sha1 = "c6d890a52d2c4d55d326439580c3b8d0875a77d9"
uuid = "d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4"
version = "1.15.7"
[[deps.ChangesOfVariables]]
deps = ["ChainRulesCore", "LinearAlgebra", "Test"]
git-tree-sha1 = "38f7a08f19d8810338d4f5085211c7dfa5d5bdd8"
uuid = "9e997f8a-9a97-42d5-a9f1-ce6bfc15e2c0"
version = "0.1.4"
[[deps.CodecZlib]]
deps = ["TranscodingStreams", "Zlib_jll"]
git-tree-sha1 = "ded953804d019afa9a3f98981d99b33e3db7b6da"
uuid = "944b1d66-785c-5afd-91f1-9de20f533193"
version = "0.7.0"
[[deps.ColorSchemes]]
deps = ["ColorTypes", "ColorVectorSpace", "Colors", "FixedPointNumbers", "Random", "SnoopPrecompile"]
git-tree-sha1 = "aa3edc8f8dea6cbfa176ee12f7c2fc82f0608ed3"
uuid = "35d6a980-a343-548e-a6ea-1d62b119f2f4"
version = "3.20.0"
[[deps.ColorTypes]]
deps = ["FixedPointNumbers", "Random"]
git-tree-sha1 = "eb7f0f8307f71fac7c606984ea5fb2817275d6e4"
uuid = "3da002f7-5984-5a60-b8a6-cbb66c0b333f"
version = "0.11.4"
[[deps.ColorVectorSpace]]
deps = ["ColorTypes", "FixedPointNumbers", "LinearAlgebra", "SpecialFunctions", "Statistics", "TensorCore"]
git-tree-sha1 = "600cc5508d66b78aae350f7accdb58763ac18589"
uuid = "c3611d14-8923-5661-9e6a-0046d554d3a4"
version = "0.9.10"
[[deps.Colors]]
deps = ["ColorTypes", "FixedPointNumbers", "Reexport"]
git-tree-sha1 = "fc08e5930ee9a4e03f84bfb5211cb54e7769758a"
uuid = "5ae59095-9a9b-59fe-a467-6f913c188581"
version = "0.12.10"
[[deps.Compat]]
deps = ["Dates", "LinearAlgebra", "UUIDs"]
git-tree-sha1 = "00a2cccc7f098ff3b66806862d275ca3db9e6e5a"
uuid = "34da2185-b29b-5c13-b0c7-acf172513d20"
version = "4.5.0"
[[deps.CompilerSupportLibraries_jll]]
deps = ["Artifacts", "Libdl"]
uuid = "e66e0078-7015-5450-92f7-15fbd957f2ae"
version = "1.0.1+0"
[[deps.Configurations]]
deps = ["ExproniconLite", "OrderedCollections", "TOML"]
git-tree-sha1 = "62a7c76dbad02fdfdaa53608104edf760938c4ca"
uuid = "5218b696-f38b-4ac9-8b61-a12ec717816d"
version = "0.17.4"
[[deps.DataAPI]]
git-tree-sha1 = "e8119c1a33d267e16108be441a287a6981ba1630"
uuid = "9a962f9c-6df0-11e9-0e5d-c546b8b5ee8a"
version = "1.14.0"
[[deps.DataValueInterfaces]]
git-tree-sha1 = "bfc1187b79289637fa0ef6d4436ebdfe6905cbd6"
uuid = "e2d170a0-9d28-54be-80f0-106bbe20a464"
version = "1.0.0"
[[deps.Dates]]
deps = ["Printf"]
uuid = "ade2ca70-3891-5945-98fb-dc099432e06a"
[[deps.Distributed]]
deps = ["Random", "Serialization", "Sockets"]
uuid = "8ba89e20-285c-5b6f-9357-94700520ee1b"
[[deps.DocStringExtensions]]
deps = ["LibGit2"]
git-tree-sha1 = "2fb1e02f2b635d0845df5d7c167fec4dd739b00d"
uuid = "ffbed154-4ef7-542d-bbb7-c09d3a79fcae"
version = "0.9.3"
[[deps.Downloads]]
deps = ["ArgTools", "FileWatching", "LibCURL", "NetworkOptions"]
uuid = "f43a241f-c20a-4ad4-852c-f6b1247861c6"
version = "1.6.0"
[[deps.EarCut_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "e3290f2d49e661fbd94046d7e3726ffcb2d41053"
uuid = "5ae413db-bbd1-5e63-b57d-d24a61df00f5"
version = "2.2.4+0"
[[deps.ElasticArrays]]
deps = ["Adapt"]
git-tree-sha1 = "e1c40d78de68e9a2be565f0202693a158ec9ad85"
uuid = "fdbdab4c-e67f-52f5-8c3f-e7b388dad3d4"
version = "1.2.11"
[[deps.ExproniconLite]]
deps = ["Pkg", "TOML"]
git-tree-sha1 = "c2eb763acf6e13e75595e0737a07a0bec0ce2147"
uuid = "55351af7-c7e9-48d6-89ff-24e801d99491"
version = "0.7.11"
[[deps.ExtendableGrids]]
deps = ["AbstractTrees", "Dates", "DocStringExtensions", "ElasticArrays", "InteractiveUtils", "LinearAlgebra", "Printf", "Random", "SparseArrays", "StaticArrays", "Test", "WriteVTK"]
git-tree-sha1 = "310b903a560b7b18f63486ff93da1ded9cae1f15"
uuid = "cfc395e8-590f-11e8-1f13-43a2532b2fa8"
version = "0.9.16"
[[deps.Extents]]
git-tree-sha1 = "5e1e4c53fa39afe63a7d356e30452249365fba99"
uuid = "411431e0-e8b7-467b-b5e0-f676ba4f2910"
version = "0.1.1"
[[deps.FileIO]]
deps = ["Pkg", "Requires", "UUIDs"]
git-tree-sha1 = "7be5f99f7d15578798f338f5433b6c432ea8037b"
uuid = "5789e2e9-d7fb-5bc7-8068-2c6fae9b9549"
version = "1.16.0"
[[deps.FileWatching]]
uuid = "7b1f6079-737a-58dc-b8bc-7a2ca5c1b5ee"
[[deps.FillArrays]]
deps = ["LinearAlgebra", "Random", "SparseArrays", "Statistics"]
git-tree-sha1 = "9a0472ec2f5409db243160a8b030f94c380167a3"
uuid = "1a297f60-69ca-5386-bcde-b61e274b549b"
version = "0.13.6"
[[deps.FixedPointNumbers]]
deps = ["Statistics"]
git-tree-sha1 = "335bfdceacc84c5cdf16aadc768aa5ddfc5383cc"
uuid = "53c48c17-4a7d-5ca2-90c5-79b7896eea93"
version = "0.8.4"
[[deps.FuzzyCompletions]]
deps = ["REPL"]
git-tree-sha1 = "e16dd964b4dfaebcded16b2af32f05e235b354be"
uuid = "fb4132e2-a121-4a70-b8a1-d5b831dcdcc2"
version = "0.5.1"
[[deps.GPUArraysCore]]
deps = ["Adapt"]
git-tree-sha1 = "57f7cde02d7a53c9d1d28443b9f11ac5fbe7ebc9"
uuid = "46192b85-c4d5-4398-a991-12ede77f4527"
version = "0.1.3"
[[deps.GeoInterface]]
deps = ["Extents"]
git-tree-sha1 = "e315c4f9d43575cf6b4e511259433803c15ebaa2"
uuid = "cf35fbd7-0cd7-5166-be24-54bfbe79505f"
version = "1.1.0"
[[deps.GeometryBasics]]
deps = ["EarCut_jll", "GeoInterface", "IterTools", "LinearAlgebra", "StaticArrays", "StructArrays", "Tables"]
git-tree-sha1 = "fe9aea4ed3ec6afdfbeb5a4f39a2208909b162a6"
uuid = "5c1252a2-5f33-56bf-86c9-59e7332b4326"
version = "0.4.5"
[[deps.GridVisualize]]
deps = ["ColorSchemes", "Colors", "DocStringExtensions", "ElasticArrays", "ExtendableGrids", "GeometryBasics", "GridVisualizeTools", "HypertextLiteral", "LinearAlgebra", "Observables", "OrderedCollections", "PkgVersion", "Printf", "StaticArrays"]
git-tree-sha1 = "b19a5815f9ba376dff963fccdf0c98dbddc6f61d"
uuid = "5eed8a63-0fb0-45eb-886d-8d5a387d12b8"
version = "0.6.1"
[[deps.GridVisualizeTools]]
deps = ["ColorSchemes", "Colors", "DocStringExtensions", "StaticArraysCore"]
git-tree-sha1 = "5964fd3e4080af45bfdbdaff75567759fd0367bd"
uuid = "5573ae12-3b76-41d9-b48c-81d0b6e61cc5"
version = "0.2.1"
[[deps.HTTP]]
deps = ["Base64", "CodecZlib", "Dates", "IniFile", "Logging", "LoggingExtras", "MbedTLS", "NetworkOptions", "OpenSSL", "Random", "SimpleBufferStream", "Sockets", "URIs", "UUIDs"]
git-tree-sha1 = "eb5aa5e3b500e191763d35198f859e4b40fff4a6"
uuid = "cd3eb016-35fb-5094-929b-558a96fad6f3"
version = "1.7.3"
[[deps.Hyperscript]]
deps = ["Test"]
git-tree-sha1 = "8d511d5b81240fc8e6802386302675bdf47737b9"
uuid = "47d2ed2b-36de-50cf-bf87-49c2cf4b8b91"
version = "0.0.4"
[[deps.HypertextLiteral]]
deps = ["Tricks"]
git-tree-sha1 = "c47c5fa4c5308f27ccaac35504858d8914e102f9"
uuid = "ac1192a8-f4b3-4bfe-ba22-af5b92cd3ab2"
version = "0.9.4"
[[deps.IOCapture]]
deps = ["Logging", "Random"]
git-tree-sha1 = "f7be53659ab06ddc986428d3a9dcc95f6fa6705a"
uuid = "b5f81e59-6552-4d32-b1f0-c071b021bf89"
version = "0.2.2"
[[deps.IniFile]]
git-tree-sha1 = "f550e6e32074c939295eb5ea6de31849ac2c9625"
uuid = "83e8ac13-25f8-5344-8a64-a9f2b223428f"
version = "0.5.1"
[[deps.InteractiveUtils]]
deps = ["Markdown"]
uuid = "b77e0a4c-d291-57a0-90e8-8db25a27a240"
[[deps.InverseFunctions]]
deps = ["Test"]
git-tree-sha1 = "49510dfcb407e572524ba94aeae2fced1f3feb0f"
uuid = "3587e190-3f89-42d0-90ee-14403ec27112"
version = "0.1.8"
[[deps.IrrationalConstants]]
git-tree-sha1 = "7fd44fd4ff43fc60815f8e764c0f352b83c49151"
uuid = "92d709cd-6900-40b7-9082-c6be49f344b6"
version = "0.1.1"
[[deps.IterTools]]
git-tree-sha1 = "fa6287a4469f5e048d763df38279ee729fbd44e5"
uuid = "c8e1da08-722c-5040-9ed9-7db0dc04731e"
version = "1.4.0"
[[deps.IteratorInterfaceExtensions]]
git-tree-sha1 = "a3f24677c21f5bbe9d2a714f95dcd58337fb2856"
uuid = "82899510-4779-5014-852e-03e436cf321d"
version = "1.0.0"
[[deps.JLLWrappers]]
deps = ["Preferences"]
git-tree-sha1 = "abc9885a7ca2052a736a600f7fa66209f96506e1"
uuid = "692b3bcd-3c85-4b1f-b108-f13ce0eb3210"
version = "1.4.1"
[[deps.JSON]]
deps = ["Dates", "Mmap", "Parsers", "Unicode"]
git-tree-sha1 = "3c837543ddb02250ef42f4738347454f95079d4e"
uuid = "682c06a0-de6a-54ab-a142-c8b1cf79cde6"
version = "0.21.3"
[[deps.LazilyInitializedFields]]
git-tree-sha1 = "410fe4739a4b092f2ffe36fcb0dcc3ab12648ce1"
uuid = "0e77f7df-68c5-4e49-93ce-4cd80f5598bf"
version = "1.2.1"
[[deps.LibCURL]]
deps = ["LibCURL_jll", "MozillaCACerts_jll"]
uuid = "b27032c2-a3e7-50c8-80cd-2d36dbcbfd21"
version = "0.6.3"
[[deps.LibCURL_jll]]
deps = ["Artifacts", "LibSSH2_jll", "Libdl", "MbedTLS_jll", "Zlib_jll", "nghttp2_jll"]
uuid = "deac9b47-8bc7-5906-a0fe-35ac56dc84c0"
version = "7.84.0+0"
[[deps.LibGit2]]
deps = ["Base64", "NetworkOptions", "Printf", "SHA"]
uuid = "76f85450-5226-5b5a-8eaa-529ad045b433"
[[deps.LibSSH2_jll]]
deps = ["Artifacts", "Libdl", "MbedTLS_jll"]
uuid = "29816b5a-b9ab-546f-933c-edad1886dfa8"
version = "1.10.2+0"
[[deps.Libdl]]
uuid = "8f399da3-3557-5675-b5ff-fb832c97cbdb"
[[deps.Libiconv_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "c7cb1f5d892775ba13767a87c7ada0b980ea0a71"
uuid = "94ce4f54-9a6c-5748-9c1c-f9c7231a4531"
version = "1.16.1+2"
[[deps.LightXML]]
deps = ["Libdl", "XML2_jll"]
git-tree-sha1 = "e129d9391168c677cd4800f5c0abb1ed8cb3794f"
uuid = "9c8b4983-aa76-5018-a973-4c85ecc9e179"
version = "0.9.0"
[[deps.LinearAlgebra]]
deps = ["Libdl", "libblastrampoline_jll"]
uuid = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e"
[[deps.LogExpFunctions]]
deps = ["ChainRulesCore", "ChangesOfVariables", "DocStringExtensions", "InverseFunctions", "IrrationalConstants", "LinearAlgebra"]
git-tree-sha1 = "946607f84feb96220f480e0422d3484c49c00239"
uuid = "2ab3a3ac-af41-5b50-aa03-7779005ae688"
version = "0.3.19"
[[deps.Logging]]
uuid = "56ddb016-857b-54e1-b83d-db4d58db5568"
[[deps.LoggingExtras]]
deps = ["Dates", "Logging"]
git-tree-sha1 = "cedb76b37bc5a6c702ade66be44f831fa23c681e"
uuid = "e6f89c97-d47a-5376-807f-9c37f3926c36"
version = "1.0.0"
[[deps.MIMEs]]
git-tree-sha1 = "65f28ad4b594aebe22157d6fac869786a255b7eb"
uuid = "6c6e2e6c-3030-632d-7369-2d6c69616d65"
version = "0.1.4"
[[deps.Markdown]]
deps = ["Base64"]
uuid = "d6f4376e-aef5-505a-96c1-9c027394607a"
[[deps.MbedTLS]]
deps = ["Dates", "MbedTLS_jll", "MozillaCACerts_jll", "Random", "Sockets"]
git-tree-sha1 = "03a9b9718f5682ecb107ac9f7308991db4ce395b"
uuid = "739be429-bea8-5141-9913-cc70e7f3736d"
version = "1.1.7"
[[deps.MbedTLS_jll]]
deps = ["Artifacts", "Libdl"]
uuid = "c8ffd9c3-330d-5841-b78e-0817d7145fa1"
version = "2.28.0+0"
[[deps.MeshIO]]
deps = ["ColorTypes", "FileIO", "GeometryBasics", "Printf"]
git-tree-sha1 = "8be09d84a2d597c7c0c34d7d604c039c9763e48c"
uuid = "7269a6da-0436-5bbc-96c2-40638cbb6118"
version = "0.4.10"
[[deps.Mmap]]
uuid = "a63ad114-7e13-5084-954f-fe012c677804"
[[deps.MozillaCACerts_jll]]
uuid = "14a3606d-f60d-562e-9121-12d972cd8159"
version = "2022.2.1"
[[deps.MsgPack]]
deps = ["Serialization"]
git-tree-sha1 = "a8cbf066b54d793b9a48c5daa5d586cf2b5bd43d"
uuid = "99f44e22-a591-53d1-9472-aa23ef4bd671"
version = "1.1.0"
[[deps.NetworkOptions]]
uuid = "ca575930-c2e3-43a9-ace4-1e988b2c1908"
version = "1.2.0"
[[deps.Observables]]
git-tree-sha1 = "6862738f9796b3edc1c09d0890afce4eca9e7e93"
uuid = "510215fc-4207-5dde-b226-833fc4488ee2"
version = "0.5.4"
[[deps.OpenBLAS_jll]]
deps = ["Artifacts", "CompilerSupportLibraries_jll", "Libdl"]
uuid = "4536629a-c528-5b80-bd46-f80d51c5b363"
version = "0.3.20+0"
[[deps.OpenLibm_jll]]
deps = ["Artifacts", "Libdl"]
uuid = "05823500-19ac-5b8b-9628-191a04bc5112"
version = "0.8.1+0"
[[deps.OpenSSL]]
deps = ["BitFlags", "Dates", "MozillaCACerts_jll", "OpenSSL_jll", "Sockets"]
git-tree-sha1 = "6503b77492fd7fcb9379bf73cd31035670e3c509"
uuid = "4d8831e6-92b7-49fb-bdf8-b643e874388c"
version = "1.3.3"
[[deps.OpenSSL_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "f6e9dba33f9f2c44e08a020b0caf6903be540004"
uuid = "458c3c95-2e84-50aa-8efc-19380b2a3a95"
version = "1.1.19+0"
[[deps.OpenSpecFun_jll]]
deps = ["Artifacts", "CompilerSupportLibraries_jll", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "13652491f6856acfd2db29360e1bbcd4565d04f1"
uuid = "efe28fd5-8261-553b-a9e1-b2916fc3738e"
version = "0.5.5+0"
[[deps.OrderedCollections]]
git-tree-sha1 = "85f8e6578bf1f9ee0d11e7bb1b1456435479d47c"
uuid = "bac558e1-5e72-5ebc-8fee-abe8a469f55d"
version = "1.4.1"
[[deps.Parsers]]
deps = ["Dates", "SnoopPrecompile"]
git-tree-sha1 = "8175fc2b118a3755113c8e68084dc1a9e63c61ee"
uuid = "69de0a69-1ddd-5017-9359-2bf0b02dc9f0"
version = "2.5.3"
[[deps.Pkg]]
deps = ["Artifacts", "Dates", "Downloads", "LibGit2", "Libdl", "Logging", "Markdown", "Printf", "REPL", "Random", "SHA", "Serialization", "TOML", "Tar", "UUIDs", "p7zip_jll"]
uuid = "44cfe95a-1eb2-52ea-b672-e2afdf69b78f"
version = "1.8.0"
[[deps.PkgVersion]]
deps = ["Pkg"]
git-tree-sha1 = "f6cf8e7944e50901594838951729a1861e668cb8"
uuid = "eebad327-c553-4316-9ea0-9fa01ccd7688"
version = "0.3.2"
[[deps.Pluto]]
deps = ["Base64", "Configurations", "Dates", "Distributed", "FileWatching", "FuzzyCompletions", "HTTP", "HypertextLiteral", "InteractiveUtils", "Logging", "MIMEs", "Markdown", "MsgPack", "Pkg", "PrecompileSignatures", "REPL", "RegistryInstances", "RelocatableFolders", "Sockets", "TOML", "Tables", "URIs", "UUIDs"]
git-tree-sha1 = "f4c99fcadf03dcdd2dd8ae7a56ca963ef1450d4f"
uuid = "c3e4b0f8-55cb-11ea-2926-15256bba5781"
version = "0.19.19"
[[deps.PlutoUI]]
deps = ["AbstractPlutoDingetjes", "Base64", "ColorTypes", "Dates", "FixedPointNumbers", "Hyperscript", "HypertextLiteral", "IOCapture", "InteractiveUtils", "JSON", "Logging", "MIMEs", "Markdown", "Random", "Reexport", "URIs", "UUIDs"]
git-tree-sha1 = "eadad7b14cf046de6eb41f13c9275e5aa2711ab6"
uuid = "7f904dfe-b85e-4ff6-b463-dae2292396a8"
version = "0.7.49"
[[deps.PlutoVista]]
deps = ["ColorSchemes", "Colors", "DocStringExtensions", "GridVisualizeTools", "HypertextLiteral", "Pluto", "UUIDs"]
git-tree-sha1 = "5af654ba1660641b3b80614a7be7eacae4c49875"
uuid = "646e1f28-b900-46d7-9d87-d554eb38a413"
version = "0.8.16"
[[deps.PrecompileSignatures]]
git-tree-sha1 = "18ef344185f25ee9d51d80e179f8dad33dc48eb1"
uuid = "91cefc8d-f054-46dc-8f8c-26e11d7c5411"
version = "3.0.3"
[[deps.Preferences]]
deps = ["TOML"]
git-tree-sha1 = "47e5f437cc0e7ef2ce8406ce1e7e24d44915f88d"
uuid = "21216c6a-2e73-6563-6e65-726566657250"
version = "1.3.0"
[[deps.Printf]]
deps = ["Unicode"]
uuid = "de0858da-6303-5e67-8744-51eddeeeb8d7"
[[deps.REPL]]
deps = ["InteractiveUtils", "Markdown", "Sockets", "Unicode"]
uuid = "3fa0cd96-eef1-5676-8a61-b3b8758bbffb"
[[deps.Random]]
deps = ["SHA", "Serialization"]
uuid = "9a3f8284-a2c9-5f02-9a11-845980a1fd5c"
[[deps.Reexport]]
git-tree-sha1 = "45e428421666073eab6f2da5c9d310d99bb12f9b"
uuid = "189a3867-3050-52da-a836-e630ba90ab69"
version = "1.2.2"
[[deps.RegistryInstances]]
deps = ["LazilyInitializedFields", "Pkg", "TOML", "Tar"]
git-tree-sha1 = "ffd19052caf598b8653b99404058fce14828be51"
uuid = "2792f1a3-b283-48e8-9a74-f99dce5104f3"
version = "0.1.0"
[[deps.RelocatableFolders]]
deps = ["SHA", "Scratch"]
git-tree-sha1 = "90bc7a7c96410424509e4263e277e43250c05691"
uuid = "05181044-ff0b-4ac5-8273-598c1e38db00"
version = "1.0.0"
[[deps.Requires]]
deps = ["UUIDs"]
git-tree-sha1 = "838a3a4188e2ded87a4f9f184b4b0d78a1e91cb7"
uuid = "ae029012-a4dd-5104-9daa-d747884805df"
version = "1.3.0"
[[deps.SHA]]
uuid = "ea8e919c-243c-51af-8825-aaa63cd721ce"
version = "0.7.0"
[[deps.Scratch]]
deps = ["Dates"]
git-tree-sha1 = "f94f779c94e58bf9ea243e77a37e16d9de9126bd"
uuid = "6c6a2e73-6563-6170-7368-637461726353"
version = "1.1.1"
[[deps.Serialization]]
uuid = "9e88b42a-f829-5b0c-bbe9-9e923198166b"
[[deps.SimpleBufferStream]]
git-tree-sha1 = "874e8867b33a00e784c8a7e4b60afe9e037b74e1"
uuid = "777ac1f9-54b0-4bf8-805c-2214025038e7"
version = "1.1.0"
[[deps.SimplexGridFactory]]
deps = ["DocStringExtensions", "ElasticArrays", "ExtendableGrids", "FileIO", "GridVisualize", "LinearAlgebra", "MeshIO", "Printf", "Test"]
git-tree-sha1 = "4566d826852b7815d34c7a8829679c6f15f4b2e7"
uuid = "57bfcd06-606e-45d6-baf4-4ba06da0efd5"
version = "0.5.18"
[[deps.SnoopPrecompile]]
deps = ["Preferences"]
git-tree-sha1 = "e760a70afdcd461cf01a575947738d359234665c"
uuid = "66db9d55-30c0-4569-8b51-7e840670fc0c"
version = "1.0.3"
[[deps.Sockets]]
uuid = "6462fe0b-24de-5631-8697-dd941f90decc"
[[deps.SparseArrays]]
deps = ["LinearAlgebra", "Random"]
uuid = "2f01184e-e22b-5df5-ae63-d93ebab69eaf"
[[deps.SpecialFunctions]]
deps = ["ChainRulesCore", "IrrationalConstants", "LogExpFunctions", "OpenLibm_jll", "OpenSpecFun_jll"]
git-tree-sha1 = "d75bda01f8c31ebb72df80a46c88b25d1c79c56d"
uuid = "276daf66-3868-5448-9aa4-cd146d93841b"
version = "2.1.7"
[[deps.StaticArrays]]
deps = ["LinearAlgebra", "Random", "StaticArraysCore", "Statistics"]
git-tree-sha1 = "6954a456979f23d05085727adb17c4551c19ecd1"
uuid = "90137ffa-7385-5640-81b9-e52037218182"
version = "1.5.12"
[[deps.StaticArraysCore]]
git-tree-sha1 = "6b7ba252635a5eff6a0b0664a41ee140a1c9e72a"
uuid = "1e83bf80-4336-4d27-bf5d-d5a4f845583c"
version = "1.4.0"
[[deps.Statistics]]
deps = ["LinearAlgebra", "SparseArrays"]
uuid = "10745b16-79ce-11e8-11f9-7d13ad32a3b2"
[[deps.StructArrays]]
deps = ["Adapt", "DataAPI", "GPUArraysCore", "StaticArraysCore", "Tables"]
git-tree-sha1 = "b03a3b745aa49b566f128977a7dd1be8711c5e71"
uuid = "09ab397b-f2b6-538f-b94a-2f83cf4a842a"
version = "0.6.14"
[[deps.TOML]]
deps = ["Dates"]
uuid = "fa267f1f-6049-4f14-aa54-33bafae1ed76"
version = "1.0.0"
[[deps.TableTraits]]
deps = ["IteratorInterfaceExtensions"]
git-tree-sha1 = "c06b2f539df1c6efa794486abfb6ed2022561a39"
uuid = "3783bdb8-4a98-5b6b-af9a-565f29a5fe9c"
version = "1.0.1"
[[deps.Tables]]
deps = ["DataAPI", "DataValueInterfaces", "IteratorInterfaceExtensions", "LinearAlgebra", "OrderedCollections", "TableTraits", "Test"]
git-tree-sha1 = "c79322d36826aa2f4fd8ecfa96ddb47b174ac78d"
uuid = "bd369af6-aec1-5ad0-b16a-f7cc5008161c"
version = "1.10.0"
[[deps.Tar]]
deps = ["ArgTools", "SHA"]
uuid = "a4e569a6-e804-4fa4-b0f3-eef7a1d5b13e"
version = "1.10.1"
[[deps.TensorCore]]
deps = ["LinearAlgebra"]
git-tree-sha1 = "1feb45f88d133a655e001435632f019a9a1bcdb6"
uuid = "62fd8b95-f654-4bbd-a8a5-9c27f68ccd50"
version = "0.1.1"
[[deps.Test]]
deps = ["InteractiveUtils", "Logging", "Random", "Serialization"]
uuid = "8dfed614-e22c-5e08-85e1-65c5234f0b40"
[[deps.TranscodingStreams]]
deps = ["Random", "Test"]
git-tree-sha1 = "94f38103c984f89cf77c402f2a68dbd870f8165f"
uuid = "3bb67fe8-82b1-5028-8e26-92a6c54297fa"
version = "0.9.11"
[[deps.Triangle_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "fe28e9a4684f6f54e868b9136afb8fd11f1734a7"
uuid = "5639c1d2-226c-5e70-8d55-b3095415a16a"
version = "1.6.2+0"
[[deps.Triangulate]]
deps = ["DocStringExtensions", "Libdl", "Printf", "Test", "Triangle_jll"]
git-tree-sha1 = "bbca6ec35426334d615f58859ad40c96d3a4a1f9"
uuid = "f7e6ffb2-c36d-4f8f-a77e-16e897189344"
version = "2.2.0"
[[deps.Tricks]]
git-tree-sha1 = "6bac775f2d42a611cdfcd1fb217ee719630c4175"
uuid = "410a4b4d-49e4-4fbc-ab6d-cb71b17b3775"
version = "0.1.6"
[[deps.URIs]]
git-tree-sha1 = "ac00576f90d8a259f2c9d823e91d1de3fd44d348"
uuid = "5c2747f8-b7ea-4ff2-ba2e-563bfd36b1d4"
version = "1.4.1"
[[deps.UUIDs]]
deps = ["Random", "SHA"]
uuid = "cf7118a7-6976-5b1a-9a39-7adc72f591a4"
[[deps.Unicode]]
uuid = "4ec0a83e-493e-50e2-b9ac-8f72acf5a8f5"
[[deps.WriteVTK]]
deps = ["Base64", "CodecZlib", "FillArrays", "LightXML", "TranscodingStreams"]
git-tree-sha1 = "f50c47d715199601a54afdd5267f24c8174842ae"
uuid = "64499a7a-5c06-52f2-abe2-ccb03c286192"
version = "1.16.0"
[[deps.XML2_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Libiconv_jll", "Pkg", "Zlib_jll"]
git-tree-sha1 = "93c41695bc1c08c46c5899f4fe06d6ead504bb73"
uuid = "02c8fc9c-b97f-50b9-bbe4-9be30ff0a78a"
version = "2.10.3+0"
[[deps.Zlib_jll]]
deps = ["Libdl"]
uuid = "83775a58-1f1d-513f-b197-d71354ab007a"
version = "1.2.12+3"
[[deps.libblastrampoline_jll]]
deps = ["Artifacts", "Libdl", "OpenBLAS_jll"]
uuid = "8e850b90-86db-534c-a0d3-1478176c7d93"
version = "5.1.1+0"
[[deps.nghttp2_jll]]
deps = ["Artifacts", "Libdl"]
uuid = "8e850ede-7688-5339-a07c-302acd2aaf8d"
version = "1.48.0+0"
[[deps.p7zip_jll]]
deps = ["Artifacts", "Libdl"]
uuid = "3f19e933-33d8-53b3-aaab-bd5110c3b7a0"
version = "17.4.0+0"
"""
# ╔═╡ Cell order:
# ╠═60941eaa-1aea-11eb-1277-97b991548781
# ╟─07194f25-5735-452f-9bed-cf791958d44d
# ╠═d0f3483a-2bf4-4e2d-80b0-6c869b45cda8
# ╠═fd8f6c48-0030-4f6f-9fbf-9f2340decbf2
# ╠═bbeeebc0-ae16-4022-975d-35588e62166a
# ╠═e6c7e47d-6159-4bb6-a71d-7c633e2fefbd
# ╠═9800c97e-c25b-4d08-a014-cccd746f7d71
# ╠═9a219111-0275-4cd9-b97e-648d3fcfcbb9
# ╠═85be1677-87ff-49dc-af9a-557e575bc55f
# ╠═33ecc78c-16ac-46ac-8d83-cbb26288a6fb
# ╟─9e640256-61a4-4fb9-a449-d5f948fb2d26
# ╟─bf0004f4-b3c8-4385-b87d-df2ef1420408
# ╠═1b70e44b-cbe8-4812-b267-ef9bce20a5b7
# ╠═10ebaeab-3ece-480f-9c4d-a676814e2f7f
# ╠═b711885e-cc61-4e08-9367-437731323863
# ╠═e4029d2c-18b7-4592-b47d-294e4af93497
# ╠═0c3f5b1c-7bcf-491e-8318-73f2c880e0b5
# ╠═f9130b5d-b4ea-4ebd-b73f-82a3c1bc1307
# ╠═73847699-40c0-4043-a16f-37883def6858
# ╠═bff0a3f1-c545-4fcc-8be8-ef460f8479bd
# ╠═66ce2939-2957-43e0-b7ea-cdd10d9fc17e
# ╠═a310027d-3f9e-4de5-bc9e-5457cb19eef5
# ╟─752bdb8f-de5a-4863-b2d1-53d69aff7dcb
# ╠═5aef30a0-8712-4c6c-9465-25da0624b408
# ╠═4debce38-96c5-4661-a965-1ca723fa8a36
# ╠═52f4c693-0218-4f56-ac95-abd6d99a0b67
# ╠═f43bd8ff-a2ed-4740-a61e-4f5d2c615c10
# ╠═b9ced73f-e7a0-4573-9413-c2a231d21c78
# ╠═2c285e4f-9f10-474b-9482-83a5c4cbfe09
# ╠═97d8db91-16e6-4070-81a0-7bcaff6cc9f6
# ╟─78dba5b2-52c9-40cd-bc1d-d5c343271f97
# ╠═b9cc0359-7286-4c02-ba10-35303da26a50
# ╠═605c914d-607b-4d2e-80c5-d14cb6918e32
# ╟─00000000-0000-0000-0000-000000000001
# ╟─00000000-0000-0000-0000-000000000002
| PDELib | https://github.com/WIAS-BERLIN/PDELib.jl.git |
|
[
"MIT"
] | 0.3.0 | 2fca7ee903e9c45871c1948e6b5fffdf359e2da3 | code | 85347 | ### A Pluto.jl notebook ###
# v0.17.1
using Markdown
using InteractiveUtils
# This Pluto notebook uses @bind for interactivity. When running this notebook outside of Pluto, the following 'mock version' of @bind gives bound variables a default value (instead of an error).
macro bind(def, element)
quote
local iv = try Base.loaded_modules[Base.PkgId(Base.UUID("6e696c72-6542-2067-7265-42206c756150"), "AbstractPlutoDingetjes")].Bonds.initial_value catch; b -> missing; end
local el = $(esc(element))
global $(esc(def)) = Core.applicable(Base.get, el) ? Base.get(el) : iv(el)
el
end
end
# ╔═╡ d05f97e2-85ba-11eb-06ea-c933332c0630
using ForwardDiff
# ╔═╡ 092e6940-8598-11eb-335d-9fd32dadd468
begin
using VoronoiFVM # the finite volume solver
using ExtendableGrids # grid management
using GridVisualize # visualization on grids
end
# ╔═╡ cf503e46-85bb-11eb-2ae7-e959707a01a9
using DifferentialEquations
# ╔═╡ 134530ae-85c2-11eb-1556-a3aa72624a7a
begin
using SimplexGridFactory
using Triangulate
using GradientRobustMultiPhysics
end
# ╔═╡ e44bb844-85cc-11eb-05c9-cdaaa914d6c1
begin
using LinearAlgebra
using Printf
ENV["LC_NUMERIC"]="C" # This is needed for triangle
ENV["MPLBACKEND"]="agg" # Ensure pyplot has the right backend for pluto on mac
using PlutoUI
using AbstractTrees
using PyPlot
using AbstractTrees, PyPlot,PlutoUI
AbstractTrees.children(x::Type) = subtypes(x) # Enable AbstractTrees to show typet trees
PyPlot.svg(true) # Choose svg driver for pyplot
end;
# ╔═╡ b7d13a60-8370-11eb-3a14-1df66337bc34
md"""
# PDELib.jl
### Towards software components for the numerical solution of partial differential equations in Julia
### J. Fuhrmann, Ch. Merdon, T. Streckenbach
$(Resource("https://www.wias-berlin.de/layout3/img/logo-tablet.png"))
#### WIAS Berlin, 2021-03-16
Update 2021-11-18: switch to Pluto's built-in package manager
"""
# ╔═╡ 6c221d04-863c-11eb-0bf8-41f7a6288b66
md"""
## pdelib
"""
# ╔═╡ 68847d40-863c-11eb-18d3-e1060d831230
html"""<iframe src="https://www.wias-berlin.de/software/index.jsp?lang=1&id=pdelib" width=600 height=200) </iframe>"""
# ╔═╡ b0581c08-863c-11eb-0d81-d59ac5f24479
md"""
- Thanks to: Timo Streckenbach, Hartmut Langmach, Manfred Uhle, Hang Si, Klaus Gärtner, Thomas Koprucki, Matthias Liero, Hong Zhao, Jaques Bloch, Ulrich Wilbrandt and many others who contributed code and/or ideas to the core code
- Attempt to have a flexible toolbox for working with PDEs in research and applications
- Some applications based on pdelib: Semiconductors (ddfermi), Electrochemistry, Steel manufacturing (with RG4), Pressure robust FEM
- Patrico Farrell, Markus Kantner, Duy Hai Doan, Thomas Petzold, Alexander Linke, Christian Merdon ...
- Main languages: C++, Python, Lua
"""
# ╔═╡ 0d1ef53a-85c8-11eb-13ef-952df60b51b0
md"""
# Why Julia?
"""
# ╔═╡ 174e53bc-863f-11eb-169d-2fe8a9b2adfb
md"""
... BTW thanks to Alexander Linke for keeping his (and my) eye on Julia
"""
# ╔═╡ d2f59d32-863a-11eb-2ffe-37e8d2a06d27
md"""
## The two-language problem
- Efficient computational cores in compiled languages (Fortran,C, C++)
- Embedded into scripting languages (Python, Lua)
- Support of pre- and postprocessing
- "Glueing" together different algoritms
- Hard to explain and to maintain ⇒ preference for commercial tools (Matlab, Comsol, ... ) outside of core scientifc computing research
- __Julia__ attempts to bridge this gap: write code like in python or matlab which nevertheless performs like code from compiled languages
"""
# ╔═╡ 7cb4be3c-8372-11eb-17cc-ad4f68a34e72
md"""
## Julia homepage [http://www.julialang.org](http://www.julialang.org)
"""
# ╔═╡ 3a462e56-8371-11eb-0503-bf8ebd33276b
html"""<iframe src="https://www.julialang.org" width=650 height=300></iframe>"""
# ╔═╡ 00bcd2be-8373-11eb-368e-61b2cdc2ab74
md"""
## Some general points
- Multidimensional arrays as first class objects
- Extensive library of standard functions, linear algebra operations
- Easy Interfacing to C, Python, R $\dots$
- Build and distribution system for binary code for Linux, Windows, MacOS
- Interactive Read-Eval-Print-Loop (REPL)
- Integration with Visual Studio Code editor
- Notebook functionality: Jupyter, Pluto
- This talk's slides are a Pluto notebook
"""
# ╔═╡ d0c8331e-840b-11eb-249b-5bba159d0d60
md"""
## Julia packages
"""
# ╔═╡ 3b05b78a-83e9-11eb-3d9e-8dda5fb67594
md"""
- Packages provide functionality which is not part of the core Julia installation
- Each package is a git repository containing
- Prescribed subdirectory structure (`src`,`doc`,`test`)
- Metadata on package and dependencies (`Project.toml`)
- ⇒ No julia package without version management
- Packages can be registered in package registries which are themselves git repositories containing metadata of registered packages.
- By default, a [General Registry](https://github.com/JuliaRegistries/General) is used
- Additonal project specific registries can be added to a Julia installation
"""
# ╔═╡ 151c3696-840e-11eb-0cd6-d91971fcf502
md"""
## $(Resource("https://julialang.github.io/Pkg.jl/v1/assets/logo.png", :width=>150, :style => "vertical-align:middle")) Package manager
- For installing (adding) or removing packages, Julia has a package manager `Pkg` which is integrated into the core language
- Fine grained package version management supports reproducible research
- UPDATE 2021-11-18: Pluto notebooks like this one have their own package managenment aimed at reproducibility.
"""
# ╔═╡ 5062ea76-83e9-11eb-26ad-cb5cb7746014
md"""
## CI (Continuous integration)
- Julia provides integrated unit testing facilities
- It is seen as good style to have package unit tests covering as much of the code as possible
- Github Actions or Gitlab Runner can be used to trigger unit tests for all major operating systems on every commit
"""
# ╔═╡ 0d9b6474-85e8-11eb-24a1-e7c037afb546
html"""<p style="text-align:center"> <img src="https://avatars.githubusercontent.com/u/44036562?s=200&v=4" height=150>
<img src="https://geontech.com/wp-content/uploads/2017/08/runner_logo.png" height=150 ></p>
"""
# ╔═╡ 47127b3a-83e9-11eb-22cf-9904b800edeb
md"""
## $(Resource("https://juliadocs.github.io/Documenter.jl/stable/assets/logo.svg",:height=> 100, :style=>"vertical-align: middle;"))Documentation
- Docstrings document Julia code
- They can be inquired by interactive help facilities (`@doc` macro, `?` mode in REPL)
- During CI runs, automatic documentation generation via `Documenter.jl` puts them together into documentation pages served from `github.io`
"""
# ╔═╡ 2f1894e0-842c-11eb-2489-ab7cbaa2fe68
html"""<iframe src="https://juliadocs.github.io/Documenter.jl/stable/" width=650 height=250></iframe>"""
# ╔═╡ 86f5e288-85b4-11eb-133e-25e1fbe363da
md"""
## Just-In-Time compilation
- Julia has high level syntax comparable to Python or Matlab, but has been developed from scratch in order to integrate Just-In-Time compilation (JIT) into every of its aspects.
- JIT compilation turns source code into machine code when executing a function the first time
- JIT compilation can be sometimes time consuming, so in many cases one encounters a "JIT-lag" during the first run of an instance of code
"""
# ╔═╡ 5dd7b7b6-8634-11eb-37d0-f13485dca6a0
md"""$(Resource("https://wias-berlin.de/people/fuhrmann/blobs/julia_introspect.png",:height=>300)) (c) D. Robinson
"""
# ╔═╡ 568527e0-8374-11eb-17b8-7d100bbd8e37
md"""
## Multiple Dispatch
- Aka "Generic Lambdas" in C++-Speak
- Define a function and its derivative:
"""
# ╔═╡ 045e2078-8641-11eb-188f-a98971dc8155
md"""
- In Julia, methods are attached to functions instead of classes
- in C++ speak, a Julia method is a specialization of template code for a particular template parameter
- The type of the return value is determined by the type of the input:
"""
# ╔═╡ 8773d184-8375-11eb-0e52-53c2df5dff93
md"""
## Machine code generated by JIT
"""
# ╔═╡ caf52886-8375-11eb-3cf8-a949cf8a3a25
md"""
## Multiple Dispatch: Discussion
- Multiple dispatch allows the JIT compiler to generate optimized machine code tailored to the particular combination of parameter types
- This comes with a price tag: dispatching at compile time influences the performance of the compilation process
- Akin to compiling template heavy C++ code
$(Resource("https://imgs.xkcd.com/xk3d/303/compiling.png",:width=>300))
(from xkcd)
Are there other advantages than performance after the first function call?
"""
# ╔═╡ f7f2cb36-8375-11eb-0c40-c5063c068bef
md"""
## Dual numbers
- Complex numbers $\mathbb C$: extend the real numbers $\mathbb R$ based on the introduction of $i$ with $i^2=-1$.
- Dual numbers: extend the real numbers by formally adding a number $\varepsilon$ with $\varepsilon^2=0$:
$D= \{ a + b\varepsilon \; |\; a,b \in \mathbb R\} =
\left\{ \begin{pmatrix}
a & b \\
0 & a
\end{pmatrix} \; |\; a,b\in\mathbb R \right\}\subset \mathbb R^{2\times 2}$
- Evaluating polynomials on dual numbers: Let $p(x)=\sum_{i=0}^n p_i x^i$. Then
$\begin{align*}
p(a+b\varepsilon) &= \sum_{i=0}^n p_i a^i + \sum_{i=1}^n i p_i a^{i-1} b\varepsilon
= p(a)+bp'(a)\varepsilon
\end{align*}$
- ``\Rightarrow`` forward mode automatic differentiation
So let us have this in Julia! But before, have some glance on Julia's type system...
"""
# ╔═╡ 9507b252-837a-11eb-332e-117ceb07cf2b
md"""
## The Julia type system
- Julia is a strongly typed language, information about the layout of a value in memory is encoded in its type
- Concrete types:
- Every value in Julia has a concrete type
- Concrete types correspond to computer representations of objects
- Abstract types
- Abstract types label concepts which work for several concrete types without regard to their memory layout etc.
- The functionality of an abstract type is implicitely characterized by the methods working on it
- Types can have subtypes, e.g. `Int64<:Real` says that the concrete type `Float64` (possibly through several hierarchy steps) is a subtype of `Real`.
- Julia types form a tree, with concrete types as leaves
"""
# ╔═╡ 5d5cef6a-85ba-11eb-263e-0dcbcb148ac0
md"""
## Type tree emanating from `Number`
"""
# ╔═╡ 6fb193dc-837b-11eb-0380-3136d173692b
Tree(Number)
# ╔═╡ 69e51df4-8379-11eb-12c6-93e6d605be60
md"""
## A custom dual number type
[Nathan Krislock](https://julialang.zulipchat.com/#narrow/stream/225542-helpdesk/topic/Comparing.20julia.20and.20numpy/near/209143302) provided a simple dual number arithmetic example in Julia.
- Define a struct parametrized with type T. This is akin a template class in C++
- The type shall work with all methods working with `Number`
- In order to construct a Dual number from arguments of different types, allow promotion aka "parameter type homogenization"
"""
# ╔═╡ b7872370-8376-11eb-0abb-5ba2ba60697f
begin
struct DualNumber{T} <: Number where {T <: Real}
value::T
deriv::T
end
DualNumber(v,d) = DualNumber(promote(v,d)...)
end;
# ╔═╡ ccbd1974-8642-11eb-39db-212dcf3821fc
md"""
In c++ we would write something along
````
template <typename T> class DualNumber {
T value;
T deriv;};
````
"""
# ╔═╡ bd938738-8379-11eb-2e7b-3521b0c4d225
DualNumber(3,2.0)
# ╔═╡ 192ee390-8379-11eb-1666-9bd411478d4d
md"""
## Promotion and Conversion
- Promote a pair of `DualNumber{T}` and `Real` number to `DualNumber{T}` if needed
- This is a function on types !
- Julia functions can have multiple methods. Here, we add another method to the function `promote_rule`:
"""
# ╔═╡ 04d59916-8379-11eb-0c09-d91190563a84
Base.promote_rule(::Type{DualNumber{T}}, ::Type{<:Real}) where T<:Real = DualNumber{T}
# ╔═╡ 3e02d072-837a-11eb-2838-259e4228d577
md"""
- Define a way to convert a `Real` to `DualNumber`
"""
# ╔═╡ e134f5a6-8378-11eb-0766-657ab2915de3
Base.convert(::Type{DualNumber{T}}, x::Real) where T<:Real = DualNumber(x,zero(T))
# ╔═╡ 9eae6a52-837b-11eb-1f08-ff6a44398858
md"""
## Simple arithmetic for `DualNumber`
"""
# ╔═╡ 518b68fe-8643-11eb-3243-719110f74026
md"""
All these definitions add methods to the functions `+, /, *, -, inv` which allow them to work for `DualNumber`
"""
# ╔═╡ 544c6a08-81dd-11eb-301f-df0c8194d88f
begin
import Base: +, /, *, -, inv
+(x::DualNumber, y::DualNumber) = DualNumber(x.value + y.value, x.deriv + y.deriv)
-(y::DualNumber) = DualNumber(-y.value, -y.deriv)
-(x::DualNumber, y::DualNumber) = x + -y
*(x::DualNumber, y::DualNumber) = DualNumber(x.value*y.value, x.value*y.deriv + x.deriv*y.value)
inv(y::DualNumber{T}) where T<:Union{Integer, Rational} = DualNumber(1//y.value, (-y.deriv)//y.value^2)
inv(y::DualNumber{T}) where T<:Union{AbstractFloat,AbstractIrrational} = DualNumber(1/y.value, (-y.deriv)/y.value^2)
/(x::DualNumber, y::DualNumber) = x*inv(y)
end;
# ╔═╡ c42de0a2-8374-11eb-2bf2-e11a848bf099
p(x) = x^3 + 2x^2 + 2x + 1
# ╔═╡ 8aa0565e-85cd-11eb-32de-739cf53f6419
p(3//1)
# ╔═╡ ebf09b36-8374-11eb-06a5-f3baec9932c2
with_terminal() do
@code_native p(3)
end
# ╔═╡ 296637fc-8376-11eb-0fef-050bf60bb7ff
dp(x) = 3x^2 + 4x + 2
# ╔═╡ 92e1351e-837c-11eb-3b02-33ccb80a48d8
md"""
## Test the implementation
Compare the evaluation of the polynomial `p` and its derivative `dp` on a value `x` with the evaluation of `p` with `DuallNumber(x,1)`.
"""
# ╔═╡ 63e18f7a-837c-11eb-0285-b76ef6d38a1f
x=14//3
# ╔═╡ 549161a6-81df-11eb-2de0-f5629bcd3005
p(x), dp(x), p(DualNumber(x,1))
# ╔═╡ 563e9540-840d-11eb-2a8b-5fca30564841
md"""
## ForwardDiff.jl
"""
# ╔═╡ bfe00216-81e7-11eb-16a1-3f1436253097
md"""
This was of course a toy example. For more serious work, we can use the `Dual` type from the [ForwardDiff.jl](https://github.com/JuliaDiff/ForwardDiff.jl) package. This also works for standard functions and for partial derivatives.
"""
# ╔═╡ 244e9f36-837e-11eb-1a02-a1989909f58f
p(x),dp(x), p(ForwardDiff.Dual(x,1))
# ╔═╡ 255b62e0-8380-11eb-1c58-7fb1c067f0e5
md"""
## A simple Newton solver
"""
# ╔═╡ ff99425c-837f-11eb-2217-e54e40a5a314
function newton(A,b,u0; tol=1.0e-12, maxit=100)
# Define storage place for the result of function + Jacobian
result=DiffResults.JacobianResult(u0)
history=Float64[]
u=copy(u0)
it=1
while it<maxit
# This call evaluates both function and jacobian at once
ForwardDiff.jacobian!(result,(v)->A(v)-b ,u)
res=DiffResults.value(result)
jac=DiffResults.jacobian(result)
# Solve the Jacobian linear system
h=jac\res
u-=h
nm=norm(h)
push!(history,nm)
if nm<tol
return u,history
end
it=it+1
end
throw("convergence failed")
end
# ╔═╡ 1fc5d0ee-85bb-11eb-25d8-69151e6dafc2
md"""
## Test the Newton solver
"""
# ╔═╡ 5ab844b2-8380-11eb-3eff-f562f445b06f
A(x)= [ x[1]+exp(x[1])+3*x[2]*x[3],
0.1*x[2]+x[2]^5-3*x[1]-x[3],
x[3]^5+x[1]*x[2]*x[3]
]
# ╔═╡ 8214acb2-8380-11eb-2d24-1bef38c4e1da
b=[0.3,0.1,0.2];
# ╔═╡ 919677d6-8380-11eb-3e1c-152fea8b92ec
result, history=newton(A,b,ones(3))
# ╔═╡ c41db0b8-8380-11eb-14cc-71af2cd90a9f
A(result)-b
# ╔═╡ 71e783ea-8381-11eb-3eaa-5142de7bbd68
md"""
# I WANT THIS FOR THE SOLUTION OF NONLINEAR PDES!!!
"""
# ╔═╡ d39e6472-8594-11eb-07d6-8961306a6a44
md""
# ╔═╡ d6076ec0-8594-11eb-154d-1dc03499315f
md""
# ╔═╡ dc76902a-85c8-11eb-24a5-5b456ad625d9
md"""
# VoronoiFVM.jl
"""
# ╔═╡ eedfd550-85cd-11eb-1bbf-4daf6fc4d019
html"""<iframe src="https://j-fu.github.io/VoronoiFVM.jl/stable/" width=650 height=400> </iframe>"""
# ╔═╡ 5e0307a2-85be-11eb-2295-3d1f2b01256b
md"""
## The Voronoi Finite Volume Method
$(Resource("https://j-fu.github.io/VoronoiFVM.jl/stable/trivoro.png",:width=>300))
$(Resource("https://j-fu.github.io/VoronoiFVM.jl/stable/vor.png",:width=>300))
"""
# ╔═╡ d0e82116-85bf-11eb-1580-c5cb1efc1ba1
md"""
- __Continuous:__ $n$ coupled PDEs in $\Omega\subset \mathbb R^d$ for unknown $\mathbf u(\vec x,t)=(u^1(\vec x,t)\dots u^n(\vec x,t))$
$$\partial_t \mathbf s(\mathbf u) - \nabla \cdot \mathbf j(\mathbf u, \nabla \mathbf u) + \mathbf r(\mathbf u) =0$$
"Storage" $\mathbf s(\mathbf u)$, "Reaction" $\mathbf r(\mathbf u)$, "Flux" $\mathbf j(\mathbf u, \nabla \mathbf u)$
- __Discretized:__
$$|\omega_k|\frac{s(\mathbf u_k)-\mathbf s(\mathbf u^{\text{old}}_k)}{\Delta t}\\ + \sum_{\omega_l \text{neigbour of} \omega_k} |\omega_k\cap\omega_l| \mathbf g(\mathbf u_k , \mathbf u_l) + |\omega_k|\mathbf r(\mathbf u_k)=0$$
"Storage" $\mathbf s(\mathbf u_k)$, "Reaction" $\mathbf r(\mathbf u_k)$, inter-REV flux $\mathbf g(\mathbf u_k, \mathbf u_L)$ ⇒ Software API
"""
# ╔═╡ b1d732c0-8381-11eb-0d91-eb04784ec1cb
md"""
## Some features of VoronoiFVM.jl
- Use automatic differentiation (AD) to calculate Jacobi matrices for Newton's method from the describing functions $\mathbf r(), \mathbf g(), \mathbf s()$
- AD is applied at the local level -- on grid nodes and grid edges
- `ExtendableSparse.jl` package allows for efficient value insertion into sparse matrices during assembly into the global matrix
Let us add the package to the environment of this notebook:
"""
# ╔═╡ 62cc9dea-8382-11eb-0552-f3858008c864
md"""
## Example: porous medium equation
```math
\partial_t u -\Delta u^m = 0
```
in $\Omega=(-1,1)$ with homogeneous Neumann boundary conditons. I has an exact solution, the so-called Barenblatt solution.
The Barenblatt solution is an exact solution of this problem for m>1. It has a finite support.
"""
# ╔═╡ be46f34a-8383-11eb-2972-87f7ef807ebe
function barenblatt(x,t,m)
t1=t^(-1.0/(m+1.0))
x1=1- (x*t1)^2*(m-1)/(2.0*m*(m+1))
x1<0.0 ? 0.0 : t1*x1^(1.0/(m-1.0))
end;
# ╔═╡ 488377d4-8593-11eb-2f16-1b031f62537b
md"""
We use the exact solution for $t=t_0=0.001$ as initial value.
"""
# ╔═╡ ad3a5aac-8382-11eb-140b-c10660fd8c61
md"""
## Define problem in VoronoiFVM.jl
"""
# ╔═╡ 99ce60fa-85e2-11eb-29af-a5f0feb65191
md"""
The problem has one species, set its number:
"""
# ╔═╡ ae80e57c-85e2-11eb-1297-3b0219a7af3b
iu=1;
# ╔═╡ 89607c62-85e2-11eb-25b7-8b5cb4771d02
md"""
Flux between two neigboring control volumes. Just use the finite differences in $u^m$.
"""
# ╔═╡ dca25088-8382-11eb-0584-399677021678
md"""
"Storage" is the function under the time derivative.
"""
# ╔═╡ d2bfa708-8382-11eb-3bab-07447ecb4adb
pmstorage(f,u,node)=f[1]=u[1];
# ╔═╡ 7b954d3c-8593-11eb-0cfc-2b1a0e51d6e6
md"""
## Implicit Euler in VoronoiFVM
"""
# ╔═╡ 01415fe2-8644-11eb-1fad-51fc9957aea8
md"""
## DifferentialEquations.jl
"""
# ╔═╡ 1a6fbeb4-8644-11eb-00d9-832a003ccd4b
html"""<iframe src="https://diffeq.sciml.ai/stable/" width=650 height=300></iframe>"""
# ╔═╡ 61666f48-8644-11eb-36a6-35129059c0fd
md"""
Can we use this package for the transient solution based on the method of lines ? This could open pathways e.g. to access Machine Learning with PDEs...
"""
# ╔═╡ 79a8c4a4-8593-11eb-0e16-99a6cff3040e
md"""
## Solver using DifferentialEquations.jl
"""
# ╔═╡ ffd27a44-8385-11eb-150e-2f9a8bc48ec7
function plotsol(sol,X)
f=sol[1,:,:]'
fmax=maximum(sol[1,:,1])
rnge=range(0,fmax,length=11)
contourf(X,sol.t,f,rnge,cmap=:summer)
contour(X,sol.t,f,rnge,colors=:black)
xlabel("x")
ylabel("t")
end;
# ╔═╡ c7cf0430-85bc-11eb-1527-b152703c025c
md"""
## Compare solutions
"""
# ╔═╡ 099134de-85be-11eb-2aed-812180c08921
diffeq_solver=DifferentialEquations.Rosenbrock23();
# ╔═╡ 528624f4-85c3-11eb-1579-cb4852b9904b
m=2; n=20;
# ╔═╡ 07923cf2-85c9-11eb-0563-3b29940f50bb
let
fig=PyPlot.figure(1)
clf()
X=collect(range(-1,1,length=500))
for t in [0.001,0.002, 0.004, 0.008, 0.01]
PyPlot.plot(X,map( (x) -> barenblatt(x,t,m),X),label="t=$(t)")
end
PyPlot.legend()
PyPlot.grid()
fig.set_size_inches(6,1.5)
fig
end
# ╔═╡ 9c94a022-8382-11eb-38ad-adc4d894e517
function pmflux(f,u0,edge)
u=unknowns(edge,u0)
f[iu]=u[iu,1]^m-u[iu,2]^m
end;
# ╔═╡ 845f6460-8382-11eb-21b0-b7082bdd66e3
function create_porous_medium_problem(n,m)
X=collect(range(-1,1,length=n))
grid=simplexgrid(X)
physics=VoronoiFVM.Physics(flux=pmflux,storage=pmstorage,num_species=1)
sys=VoronoiFVM.System(grid,physics)
enable_species!(sys,iu,[1])
sys,X
end;
# ╔═╡ 5c82b6bc-8383-11eb-192e-71e5336e0425
function solve_vfvm(;n=20,m=2,t0=0.001, tend=0.01,tstep=1.0e-7)
sys,X=create_porous_medium_problem(n,m)
inival=unknowns(sys)
inival[1,:].=map(x->barenblatt(x,t0,m),sys.grid)
control=VoronoiFVM.NewtonControl()
control.Δt=tstep
control.Δu_opt=0.05
control.Δt_min=tstep
control.tol_relative=1.0e-5
t_elapsed=@elapsed sol=VoronoiFVM.solve(inival,sys,[t0,tend],control=control)
err=norm(sol[1,:,end]-map(x->barenblatt(x,tend,m),sys.grid),Inf)
sol,X,err,t_elapsed
end
# ╔═╡ d84c89de-8384-11eb-28aa-132d56751734
function solve_diffeq(;n=20,m=2, t0=0.001,tend=0.01,solver=nothing)
sys,X=create_porous_medium_problem(n,m)
inival=unknowns(sys)
inival[1,:].=map(x->barenblatt(x,t0,m),sys.grid)
tspan = (t0,tend)
t_elapsed=@elapsed begin
f = DifferentialEquations.ODEFunction( VoronoiFVM.eval_rhs!,
jac= VoronoiFVM.eval_jacobian!,
jac_prototype = VoronoiFVM.jac_prototype(sys),
mass_matrix= VoronoiFVM.mass_matrix(sys))
prob = DifferentialEquations.ODEProblem(f,vec(inival),tspan,sys)
sol = DifferentialEquations.solve(prob,solver)
sol = TransientSolution([reshape(sol.u[i],sys) for i=1:length(sol.u)] ,sol.t)
end
err=norm(sol[1,:,end]-map(x->barenblatt(x,tend,m),sys.grid),Inf)
sol,X,err,t_elapsed
end
# ╔═╡ 52fc31d1-d41b-410d-bb07-17b991d34f05
md"""
UPDATE: timing from the first click on solve will include JIT compilation. Try to run the code a second time to see computation time.
"""
# ╔═╡ c06c99c8-85bc-11eb-29b5-694d7fab6673
md"""
Solve: $(@bind solve_pm CheckBox())
"""
# ╔═╡ 3aed6f3c-85be-11eb-30ae-6170b11fc0a1
if solve_pm
sol_vfvm,X_vfvm,err_vfvm,t_vfvm=solve_vfvm(m=m,n=n)
end;
# ╔═╡ 20fc42e6-8385-11eb-1b8d-c70dcb798cff
if solve_pm
sol_diffeq,X_diffeq,err_diffeq,t_diffeq=solve_diffeq(m=m,n=n,solver=diffeq_solver)
end;
# ╔═╡ 0c0a4210-8386-11eb-08a2-ff3625833da3
if solve_pm
clf()
subplot(121)
title(@sprintf("VoronoiFVM\n %.0f ms\n err=%.2e",t_vfvm*1000,err_vfvm))
plotsol(sol_vfvm,X_vfvm)
subplot(122)
plotsol(sol_diffeq,X_diffeq)
title(@sprintf("DifferentialEquations\n %.0f ms\n err=%.2e",t_diffeq*1000,err_diffeq))
tight_layout()
gcf().set_size_inches(7,3.5)
gcf()
end
# ╔═╡ 51a150ee-8388-11eb-33e2-fb03cf4c0c76
md"""
## More VoronoiFVM.jl features
- 1/2/3D grids
- Multispecies handling for subdomains, interfaces
- Testfunction based current calculation for implicit Euler metod
- Small signal analysis in frequency domain (impedance spectroscopy); automatic linearization comes here in handy as well
Currently used for:
- Solid oxide cell simulation (EDLSOC project with P. Vágner, V. Miloš)
- Semiconductor and Perovskite modeling in LG5 (Successor of C++- ddfermi, with P. Farell, D. Abdel)
- Investigation of finite volume discretizations with B. Gaudeul
- Rotating disk electrode calculations (With R. Kehl, LuCaMag project)
- Nanopores with P. Berg
"""
# ╔═╡ be8470e0-8594-11eb-2d55-657b74d82ccb
md""
# ╔═╡ 50602f28-85da-11eb-1f03-5d33ec4ee42e
md"""
# GradientRobustMultiphysics.jl
"""
# ╔═╡ 913c1c76-8645-11eb-24b6-47bc88ad6f5d
md"""
- Started by Ch. Merdon based on the same package infrastructure for grid management, sparse matrix assembly and visualization
"""
# ╔═╡ da9158d6-85ce-11eb-3494-6bbd1b790284
html"""<iframe src="https://chmerdon.github.io/GradientRobustMultiPhysics.jl/stable/pdedescription/" width=650 height=300> </iframe>"""
# ╔═╡ 4563f38a-8389-11eb-0596-81019d2948c8
md"""
## GradientRobustMultiPhysics.jl features
- Low order H1,Hdiv,Hcurl FEM in 1D/2D/3D on simplices and parallelograms
- Standard interpolations that satisfy commutating diagram ``\mathrm{Curl} (I_{Hcurl}\; v) = I_{Hdiv} \mathrm{Curl}\; v``
- AD for shape function derivatives up to 2nd order on reference geometry
- user provides weak formulation by combining assembly patterns (bilinearform, linearform, trilinearform etc.) and function operators for their arguments and a kernel function for further manipulation (like application of parameters) + boundary data
- AD for kernels (like (u grad)u for NSE or (1+grad(u))*C*eps(u) for nonlinear elasticity)
- divergence-preserving reconstruction operators as a function operator
- adaptive mesh refinement in 2D available
"""
# ╔═╡ b6dacce0-838c-11eb-18ca-fd4e85901bde
md"""
## Define grid for Karman vortex street
"""
# ╔═╡ f9479696-838a-11eb-22cd-13f069f2dc9a
function make_grid(L,H; n=20,maxvol=0.1)
builder=SimplexGridBuilder(Generator=Triangulate)
function circlehole!(builder, center, radius; n=20)
points=[point!(builder, center[1]+radius*sin(t),center[2]+radius*cos(t))
for t in range(0,2π,length=n)]
for i=1:n-1
facet!(builder,points[i],points[i+1])
end
facet!(builder,points[end],points[1])
holepoint!(builder,center)
end
p1=point!(builder,0,0)
p2=point!(builder,L,0)
p3=point!(builder,L,H)
p4=point!(builder,0,H)
facetregion!(builder,1); facet!(builder,p1,p2)
facetregion!(builder,2); facet!(builder,p2,p3)
facetregion!(builder,3); facet!(builder,p3,p4)
facetregion!(builder,4); facet!(builder,p4,p1)
facetregion!(builder,5); circlehole!(builder, (0.25,H/2),0.05,n=20)
simplexgrid(builder,maxvolume=maxvol)
end;
# ╔═╡ f95fed4c-85c2-11eb-2b76-a94551adbec1
md"""
## The grid
"""
# ╔═╡ 87dca836-85b3-11eb-1d28-73c08f594823
L=2.2; H=0.41;
# ╔═╡ b272ebcc-85c3-11eb-1fad-bf71ffde1a6c
md"""
## Constitutive functions
"""
# ╔═╡ f6a6c162-b795-46e3-9229-ecad67836fb3
md"""
UPDATE: The API of GradientRobustMultiPhysics changed since the time of the talk.
"""
# ╔═╡ 05910082-85c4-11eb-2bd2-556c9e2c1975
md"""
Inlet data for Karman vortex street example:
"""
# ╔═╡ f572f800-8388-11eb-2774-95a3ff9a3ad6
function bnd_inlet!(result,x)
result[1] = 6*x[2]*(H-x[2])/H^2;
result[2] = 0.0;
end;
# ╔═╡ 4fdf3a96-85c4-11eb-2f44-bd15bdf02dec
md"""
Nonlinear convection term to be handeled by AD
"""
# ╔═╡ 4cf131ae-85c4-11eb-28c6-a9d9a73d681e
function ugradu_kernel_AD(result, input)
# input = [VeloIdentity(u), grad(u)]
# result = (u * grad) u = grad(u)*u
fill!(result,0)
for j = 1 : 2, k = 1 : 2
result[j] += input[k]*input[2 + (j-1)*2+k]
end
return nothing
end;
# ╔═╡ c0f97390-85c4-11eb-2398-8d96e73caae2
md"""
## Create Navier-Stokes problem
"""
# ╔═╡ e9ce479c-85c3-11eb-0a14-e10dfe1dceb9
function create_problem(;viscosity=1.0e-3)
Problem = PDEDescription("NSE problem")
add_unknown!(Problem; equation_name = "momentum equation",
unknown_name = "velocity")
add_unknown!(Problem; equation_name = "incompressibility constraint",
unknown_name = "pressure")
# add Laplacian to [velo,velo] block
add_operator!(Problem, [1,1], LaplaceOperator(viscosity,2,2; store = true))
# add Lagrange multiplier for divergence of velocity to [velo,pressure] block
add_operator!(Problem, [1,2], LagrangeMultiplier(Divergence))
# add boundary data (bregion 2 is outflow)
user_function_inflow = DataFunction(bnd_inlet!, [2,2];
name = "u_inflow", dependencies = "X", quadorder = 2)
add_boundarydata!(Problem, 1, [1,3,5], HomogeneousDirichletBoundary)
add_boundarydata!(Problem, 1, [4], BestapproxDirichletBoundary;
data = user_function_inflow)
action_kernel = ActionKernel(ugradu_kernel_AD, [2,6];
dependencies = "", quadorder = 1)
# div-free reconstruction operator for Identity
VeloIdentity = ReconstructionIdentity{HDIVRT0{2}}
NLConvectionOperator = GenerateNonlinearForm("(u * grad) u * v",
[VeloIdentity, Gradient], [1,1],
VeloIdentity, action_kernel; ADnewton = true)
add_operator!(Problem, [1,1], NLConvectionOperator)
Problem
end
# ╔═╡ a0161bd8-85c4-11eb-2366-45621bbe59b4
md"""
## Solve Navier-Stokes problem
"""
# ╔═╡ ebcd0b92-8388-11eb-02f3-99334d45c9be
function solve_problem(grid,Problem)
# generate FESpaces
FESpaceVelocity = FESpace{H1BR{2}}(grid)
FESpacePressure = FESpace{H1P0{1}}(grid,broken=true)
Solution = FEVector{Float64}("velocity",FESpaceVelocity)
append!(Solution,"pressure",FESpacePressure)
GradientRobustMultiPhysics.solve!(Solution, Problem;
maxIterations = 12, maxResidual = 1e-10)
Solution
end
# ╔═╡ 3199edda-85c5-11eb-2da5-0dafc6cd7b84
md"""
## Run problem creation and solver
"""
# ╔═╡ 95c2ce84-85c3-11eb-37a7-bf13754d062c
maxvol=2.0e-3 # 1.0e-4 still runs in finite time
# ╔═╡ f50ae9c4-838b-11eb-1822-499d9f4afbe4
grid=make_grid(L,H;n=40,maxvol=maxvol)
# ╔═╡ 0bfe0312-838c-11eb-06d2-dbefd908b8ae
gridplot(grid,Plotter=PyPlot, resolution=(800,200))
# ╔═╡ d3d7a9e4-838a-11eb-3e70-9525fb60e1c1
md"""
Solve: $(@bind solve_karman CheckBox())
"""
# ╔═╡ 0eb76256-8389-11eb-2e40-0d4e94c1d18d
if solve_karman
problem=create_problem()
Solution=solve_problem(grid,problem)
GradientRobustMultiPhysics.plot(Solution, [1], [Identity]; Plotter = PyPlot)
end
# ╔═╡ fb4690e2-838e-11eb-38e9-29168d5f6360
md"""
# PDELib.jl
- Combine the tools described so far into a meta-package with liberal licenses (MIT, BSD)
- Translation table between C++ pdelib modules and corresponding Julia packages:
| pdelib (C++) | PDELib.jl | |
|:------------ |:---------------------------- |:---------------- |
| fvsys2 | VoronoiFVM.jl |
| femlib | GradientRobustMultiPhysics.jl|
| Grid | ExtendableGrids.jl |
| GridFactory | SimplexGridFactory.jl |
| gltools | GridVisualize.jl | (PyPlot,Plots,(Makie))
| VMatrix | ExtendableSparse.jl |
- Maintained by WIAS but not part of PDElib.jl (for licensing reasons):
| pdelib (C++) | Julia | |
|:------------ |:---------------------------- |:---------------- |
| triwrap.cxx | Triangulate.jl | (Triangle interface) |
| tetwrap.cxx | TetGen.jl | (TetGen interface, with S. Danisch)|
"""
# ╔═╡ 4d14735c-8647-11eb-2891-91d1bc0fe717
md"""
## Profiting from the community
"""
# ╔═╡ 4446bc76-8647-11eb-3d4b-af4000b83024
md"""
- (to be) (partially) replaced by other Julia packages
| pdelib (C++) | Julia | |
|:------------ |:---------------------------- |:---------------- |
| Iteration | IterativeSolvers.jl | |
| Bifurcation | BifurcationKit.jl | |
| VPrecon | IncompleteLU.jl||
| | AlgebraicMultigrid.jl||
| | ...||
"""
# ╔═╡ 07658648-8596-11eb-12f2-7564ab864a2e
md"""
## Outlook
- Continue transition of knowledge to Julia packages
- Integrate C++ pdelib via python interface (e.g. gltools graphics)
- Support for projects in semiconductor simulation, electrochemistry $\dots$
- Charge transport in semiconductors and electrochemical devices
- Coupling to additional physics: Nanowires, light...
- Further development of gradient robust FEM:
- compressible flows, electro-magneto-hydrodynamics, nonlinear elasticity problems
- Make use of Julia's interfacing capabilities to acces more complex algorithms on top of forward simulation
- Optimization
- Bifurcation analysis
- Machine Learning
- ...
"""
# ╔═╡ df0cd404-85da-11eb-3274-51394b5edfa8
md"""
# Package environent
"""
# ╔═╡ f94316ca-85cc-11eb-1d6b-8ba91fe99cb5
TableOfContents(depth=4,title="")
# ╔═╡ 00000000-0000-0000-0000-000000000001
PLUTO_PROJECT_TOML_CONTENTS = """
[deps]
AbstractTrees = "1520ce14-60c1-5f80-bbc7-55ef81b5835c"
DifferentialEquations = "0c46a032-eb83-5123-abaf-570d42b7fbaa"
ExtendableGrids = "cfc395e8-590f-11e8-1f13-43a2532b2fa8"
ForwardDiff = "f6369f11-7733-5829-9624-2563aa707210"
GradientRobustMultiPhysics = "0802c0ca-1768-4022-988c-6dd5f9588a11"
GridVisualize = "5eed8a63-0fb0-45eb-886d-8d5a387d12b8"
LinearAlgebra = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e"
PlutoUI = "7f904dfe-b85e-4ff6-b463-dae2292396a8"
Printf = "de0858da-6303-5e67-8744-51eddeeeb8d7"
PyPlot = "d330b81b-6aea-500a-939a-2ce795aea3ee"
SimplexGridFactory = "57bfcd06-606e-45d6-baf4-4ba06da0efd5"
Triangulate = "f7e6ffb2-c36d-4f8f-a77e-16e897189344"
VoronoiFVM = "82b139dc-5afc-11e9-35da-9b9bdfd336f3"
[compat]
AbstractTrees = "~0.3.4"
DifferentialEquations = "~6.20.0"
ExtendableGrids = "~0.7.9"
ForwardDiff = "~0.10.23"
GradientRobustMultiPhysics = "~0.4.1"
GridVisualize = "~0.1.7"
PlutoUI = "~0.7.19"
PyPlot = "~2.10.0"
SimplexGridFactory = "~0.5.3"
Triangulate = "~2.1.0"
VoronoiFVM = "~0.10.12"
"""
# ╔═╡ 00000000-0000-0000-0000-000000000002
PLUTO_MANIFEST_TOML_CONTENTS = """
# This file is machine-generated - editing it directly is not advised
[[AbstractPlutoDingetjes]]
deps = ["Pkg"]
git-tree-sha1 = "0bc60e3006ad95b4bb7497698dd7c6d649b9bc06"
uuid = "6e696c72-6542-2067-7265-42206c756150"
version = "1.1.1"
[[AbstractTrees]]
git-tree-sha1 = "03e0550477d86222521d254b741d470ba17ea0b5"
uuid = "1520ce14-60c1-5f80-bbc7-55ef81b5835c"
version = "0.3.4"
[[Adapt]]
deps = ["LinearAlgebra"]
git-tree-sha1 = "84918055d15b3114ede17ac6a7182f68870c16f7"
uuid = "79e6a3ab-5dfb-504d-930d-738a2a938a0e"
version = "3.3.1"
[[ArgCheck]]
git-tree-sha1 = "dedbbb2ddb876f899585c4ec4433265e3017215a"
uuid = "dce04be8-c92d-5529-be00-80e4d2c0e197"
version = "2.1.0"
[[ArgTools]]
uuid = "0dad84c5-d112-42e6-8d28-ef12dabb789f"
[[ArnoldiMethod]]
deps = ["LinearAlgebra", "Random", "StaticArrays"]
git-tree-sha1 = "62e51b39331de8911e4a7ff6f5aaf38a5f4cc0ae"
uuid = "ec485272-7323-5ecc-a04f-4719b315124d"
version = "0.2.0"
[[ArrayInterface]]
deps = ["Compat", "IfElse", "LinearAlgebra", "Requires", "SparseArrays", "Static"]
git-tree-sha1 = "e527b258413e0c6d4f66ade574744c94edef81f8"
uuid = "4fba245c-0d91-5ea0-9b3e-6abc04ee57a9"
version = "3.1.40"
[[ArrayLayouts]]
deps = ["FillArrays", "LinearAlgebra", "SparseArrays"]
git-tree-sha1 = "e1ba79094cae97b688fb42d31cbbfd63a69706e4"
uuid = "4c555306-a7a7-4459-81d9-ec55ddd5c99a"
version = "0.7.8"
[[Artifacts]]
uuid = "56f22d72-fd6d-98f1-02f0-08ddc0907c33"
[[AutoHashEquals]]
git-tree-sha1 = "45bb6705d93be619b81451bb2006b7ee5d4e4453"
uuid = "15f4f7f2-30c1-5605-9d31-71845cf9641f"
version = "0.2.0"
[[BandedMatrices]]
deps = ["ArrayLayouts", "FillArrays", "LinearAlgebra", "Random", "SparseArrays"]
git-tree-sha1 = "ce68f8c2162062733f9b4c9e3700d5efc4a8ec47"
uuid = "aae01518-5342-5314-be14-df237901396f"
version = "0.16.11"
[[BangBang]]
deps = ["Compat", "ConstructionBase", "Future", "InitialValues", "LinearAlgebra", "Requires", "Setfield", "Tables", "ZygoteRules"]
git-tree-sha1 = "0ad226aa72d8671f20d0316e03028f0ba1624307"
uuid = "198e06fe-97b7-11e9-32a5-e1d131e6ad66"
version = "0.3.32"
[[Base64]]
uuid = "2a0f44e3-6c83-55bd-87e4-b1978d98bd5f"
[[Baselet]]
git-tree-sha1 = "aebf55e6d7795e02ca500a689d326ac979aaf89e"
uuid = "9718e550-a3fa-408a-8086-8db961cd8217"
version = "0.1.1"
[[BenchmarkTools]]
deps = ["JSON", "Logging", "Printf", "Statistics", "UUIDs"]
git-tree-sha1 = "9e62e66db34540a0c919d72172cc2f642ac71260"
uuid = "6e4b80f9-dd63-53aa-95a3-0cdb28fa8baf"
version = "0.5.0"
[[Bijections]]
git-tree-sha1 = "705e7822597b432ebe152baa844b49f8026df090"
uuid = "e2ed5e7c-b2de-5872-ae92-c73ca462fb04"
version = "0.1.3"
[[BitTwiddlingConvenienceFunctions]]
deps = ["Static"]
git-tree-sha1 = "bc1317f71de8dce26ea67fcdf7eccc0d0693b75b"
uuid = "62783981-4cbd-42fc-bca8-16325de8dc4b"
version = "0.1.1"
[[BoundaryValueDiffEq]]
deps = ["BandedMatrices", "DiffEqBase", "FiniteDiff", "ForwardDiff", "LinearAlgebra", "NLsolve", "Reexport", "SparseArrays"]
git-tree-sha1 = "fe34902ac0c3a35d016617ab7032742865756d7d"
uuid = "764a87c0-6b3e-53db-9096-fe964310641d"
version = "2.7.1"
[[CEnum]]
git-tree-sha1 = "215a9aa4a1f23fbd05b92769fdd62559488d70e9"
uuid = "fa961155-64e5-5f13-b03f-caf6b980ea82"
version = "0.4.1"
[[CPUSummary]]
deps = ["Hwloc", "IfElse", "Static"]
git-tree-sha1 = "87b0c9c6ee0124d6c1f4ce8cb035dcaf9f90b803"
uuid = "2a0fbf3d-bb9c-48f3-b0a9-814d99fd7ab9"
version = "0.1.6"
[[CSTParser]]
deps = ["Tokenize"]
git-tree-sha1 = "f9a6389348207faf5e5c62cbc7e89d19688d338a"
uuid = "00ebfdb7-1f24-5e51-bd34-a7502290713f"
version = "3.3.0"
[[Cassette]]
git-tree-sha1 = "6ce3cd755d4130d43bab24ea5181e77b89b51839"
uuid = "7057c7e9-c182-5462-911a-8362d720325c"
version = "0.3.9"
[[ChainRulesCore]]
deps = ["Compat", "LinearAlgebra", "SparseArrays"]
git-tree-sha1 = "f885e7e7c124f8c92650d61b9477b9ac2ee607dd"
uuid = "d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4"
version = "1.11.1"
[[ChangesOfVariables]]
deps = ["LinearAlgebra", "Test"]
git-tree-sha1 = "9a1d594397670492219635b35a3d830b04730d62"
uuid = "9e997f8a-9a97-42d5-a9f1-ce6bfc15e2c0"
version = "0.1.1"
[[CloseOpenIntervals]]
deps = ["ArrayInterface", "Static"]
git-tree-sha1 = "7b8f09d58294dc8aa13d91a8544b37c8a1dcbc06"
uuid = "fb6a15b2-703c-40df-9091-08a04967cfa9"
version = "0.1.4"
[[ColorSchemes]]
deps = ["ColorTypes", "Colors", "FixedPointNumbers", "Random"]
git-tree-sha1 = "a851fec56cb73cfdf43762999ec72eff5b86882a"
uuid = "35d6a980-a343-548e-a6ea-1d62b119f2f4"
version = "3.15.0"
[[ColorTypes]]
deps = ["FixedPointNumbers", "Random"]
git-tree-sha1 = "024fe24d83e4a5bf5fc80501a314ce0d1aa35597"
uuid = "3da002f7-5984-5a60-b8a6-cbb66c0b333f"
version = "0.11.0"
[[Colors]]
deps = ["ColorTypes", "FixedPointNumbers", "Reexport"]
git-tree-sha1 = "417b0ed7b8b838aa6ca0a87aadf1bb9eb111ce40"
uuid = "5ae59095-9a9b-59fe-a467-6f913c188581"
version = "0.12.8"
[[Combinatorics]]
git-tree-sha1 = "08c8b6831dc00bfea825826be0bc8336fc369860"
uuid = "861a8166-3701-5b0c-9a16-15d98fcdc6aa"
version = "1.0.2"
[[CommonMark]]
deps = ["Crayons", "JSON", "URIs"]
git-tree-sha1 = "393ac9df4eb085c2ab12005fc496dae2e1da344e"
uuid = "a80b9123-70ca-4bc0-993e-6e3bcb318db6"
version = "0.8.3"
[[CommonSolve]]
git-tree-sha1 = "68a0743f578349ada8bc911a5cbd5a2ef6ed6d1f"
uuid = "38540f10-b2f7-11e9-35d8-d573e4eb0ff2"
version = "0.2.0"
[[CommonSubexpressions]]
deps = ["MacroTools", "Test"]
git-tree-sha1 = "7b8a93dba8af7e3b42fecabf646260105ac373f7"
uuid = "bbf7d656-a473-5ed7-a52c-81e309532950"
version = "0.3.0"
[[Compat]]
deps = ["Base64", "Dates", "DelimitedFiles", "Distributed", "InteractiveUtils", "LibGit2", "Libdl", "LinearAlgebra", "Markdown", "Mmap", "Pkg", "Printf", "REPL", "Random", "SHA", "Serialization", "SharedArrays", "Sockets", "SparseArrays", "Statistics", "Test", "UUIDs", "Unicode"]
git-tree-sha1 = "dce3e3fea680869eaa0b774b2e8343e9ff442313"
uuid = "34da2185-b29b-5c13-b0c7-acf172513d20"
version = "3.40.0"
[[CompilerSupportLibraries_jll]]
deps = ["Artifacts", "Libdl"]
uuid = "e66e0078-7015-5450-92f7-15fbd957f2ae"
[[CompositeTypes]]
git-tree-sha1 = "d5b014b216dc891e81fea299638e4c10c657b582"
uuid = "b152e2b5-7a66-4b01-a709-34e65c35f657"
version = "0.1.2"
[[CompositionsBase]]
git-tree-sha1 = "455419f7e328a1a2493cabc6428d79e951349769"
uuid = "a33af91c-f02d-484b-be07-31d278c5ca2b"
version = "0.1.1"
[[Conda]]
deps = ["JSON", "VersionParsing"]
git-tree-sha1 = "299304989a5e6473d985212c28928899c74e9421"
uuid = "8f4d0f93-b110-5947-807f-2305c1781a2d"
version = "1.5.2"
[[ConstructionBase]]
deps = ["LinearAlgebra"]
git-tree-sha1 = "f74e9d5388b8620b4cee35d4c5a618dd4dc547f4"
uuid = "187b0558-2788-49d3-abe0-74a17ed4e7c9"
version = "1.3.0"
[[Crayons]]
git-tree-sha1 = "3f71217b538d7aaee0b69ab47d9b7724ca8afa0d"
uuid = "a8cc5b0e-0ffa-5ad4-8c14-923d3ee1735f"
version = "4.0.4"
[[DEDataArrays]]
deps = ["ArrayInterface", "DocStringExtensions", "LinearAlgebra", "RecursiveArrayTools", "SciMLBase", "StaticArrays"]
git-tree-sha1 = "31186e61936fbbccb41d809ad4338c9f7addf7ae"
uuid = "754358af-613d-5f8d-9788-280bf1605d4c"
version = "0.2.0"
[[DataAPI]]
git-tree-sha1 = "cc70b17275652eb47bc9e5f81635981f13cea5c8"
uuid = "9a962f9c-6df0-11e9-0e5d-c546b8b5ee8a"
version = "1.9.0"
[[DataStructures]]
deps = ["Compat", "InteractiveUtils", "OrderedCollections"]
git-tree-sha1 = "7d9d316f04214f7efdbb6398d545446e246eff02"
uuid = "864edb3b-99cc-5e75-8d2d-829cb0a9cfe8"
version = "0.18.10"
[[DataValueInterfaces]]
git-tree-sha1 = "bfc1187b79289637fa0ef6d4436ebdfe6905cbd6"
uuid = "e2d170a0-9d28-54be-80f0-106bbe20a464"
version = "1.0.0"
[[Dates]]
deps = ["Printf"]
uuid = "ade2ca70-3891-5945-98fb-dc099432e06a"
[[DefineSingletons]]
git-tree-sha1 = "77b4ca280084423b728662fe040e5ff8819347c5"
uuid = "244e2a9f-e319-4986-a169-4d1fe445cd52"
version = "0.1.1"
[[DelayDiffEq]]
deps = ["ArrayInterface", "DataStructures", "DiffEqBase", "LinearAlgebra", "Logging", "NonlinearSolve", "OrdinaryDiffEq", "Printf", "RecursiveArrayTools", "Reexport", "UnPack"]
git-tree-sha1 = "6eba402e968317b834c28cd47499dd1b572dd093"
uuid = "bcd4f6db-9728-5f36-b5f7-82caef46ccdb"
version = "5.31.1"
[[DelimitedFiles]]
deps = ["Mmap"]
uuid = "8bb1440f-4735-579b-a4ab-409b98df4dab"
[[DensityInterface]]
deps = ["InverseFunctions", "Test"]
git-tree-sha1 = "80c3e8639e3353e5d2912fb3a1916b8455e2494b"
uuid = "b429d917-457f-4dbc-8f4c-0cc954292b1d"
version = "0.4.0"
[[DiffEqBase]]
deps = ["ArrayInterface", "ChainRulesCore", "DEDataArrays", "DataStructures", "Distributions", "DocStringExtensions", "FastBroadcast", "ForwardDiff", "FunctionWrappers", "IterativeSolvers", "LabelledArrays", "LinearAlgebra", "Logging", "MuladdMacro", "NonlinearSolve", "Parameters", "PreallocationTools", "Printf", "RecursiveArrayTools", "RecursiveFactorization", "Reexport", "Requires", "SciMLBase", "Setfield", "SparseArrays", "StaticArrays", "Statistics", "SuiteSparse", "ZygoteRules"]
git-tree-sha1 = "5c3d877ddfc2da61ce5cc1f5ce330ff97789c57c"
uuid = "2b5f629d-d688-5b77-993f-72d75c75574e"
version = "6.76.0"
[[DiffEqCallbacks]]
deps = ["DataStructures", "DiffEqBase", "ForwardDiff", "LinearAlgebra", "NLsolve", "OrdinaryDiffEq", "Parameters", "RecipesBase", "RecursiveArrayTools", "StaticArrays"]
git-tree-sha1 = "35bc7f8be9dd2155336fe999b11a8f5e44c0d602"
uuid = "459566f4-90b8-5000-8ac3-15dfb0a30def"
version = "2.17.0"
[[DiffEqFinancial]]
deps = ["DiffEqBase", "DiffEqNoiseProcess", "LinearAlgebra", "Markdown", "RandomNumbers"]
git-tree-sha1 = "db08e0def560f204167c58fd0637298e13f58f73"
uuid = "5a0ffddc-d203-54b0-88ba-2c03c0fc2e67"
version = "2.4.0"
[[DiffEqJump]]
deps = ["ArrayInterface", "Compat", "DataStructures", "DiffEqBase", "FunctionWrappers", "Graphs", "LinearAlgebra", "PoissonRandom", "Random", "RandomNumbers", "RecursiveArrayTools", "Reexport", "StaticArrays", "TreeViews", "UnPack"]
git-tree-sha1 = "0aa2d003ec9efe2a93f93ae722de05a870ffc0b2"
uuid = "c894b116-72e5-5b58-be3c-e6d8d4ac2b12"
version = "8.0.0"
[[DiffEqNoiseProcess]]
deps = ["DiffEqBase", "Distributions", "LinearAlgebra", "Optim", "PoissonRandom", "QuadGK", "Random", "Random123", "RandomNumbers", "RecipesBase", "RecursiveArrayTools", "Requires", "ResettableStacks", "SciMLBase", "StaticArrays", "Statistics"]
git-tree-sha1 = "d6839a44a268c69ef0ed927b22a6f43c8a4c2e73"
uuid = "77a26b50-5914-5dd7-bc55-306e6241c503"
version = "5.9.0"
[[DiffEqPhysics]]
deps = ["DiffEqBase", "DiffEqCallbacks", "ForwardDiff", "LinearAlgebra", "Printf", "Random", "RecipesBase", "RecursiveArrayTools", "Reexport", "StaticArrays"]
git-tree-sha1 = "8f23c6f36f6a6eb2cbd6950e28ec7c4b99d0e4c9"
uuid = "055956cb-9e8b-5191-98cc-73ae4a59e68a"
version = "3.9.0"
[[DiffResults]]
deps = ["StaticArrays"]
git-tree-sha1 = "c18e98cba888c6c25d1c3b048e4b3380ca956805"
uuid = "163ba53b-c6d8-5494-b064-1a9d43ac40c5"
version = "1.0.3"
[[DiffRules]]
deps = ["LogExpFunctions", "NaNMath", "Random", "SpecialFunctions"]
git-tree-sha1 = "3287dacf67c3652d3fed09f4c12c187ae4dbb89a"
uuid = "b552c78f-8df3-52c6-915a-8e097449b14b"
version = "1.4.0"
[[DifferentialEquations]]
deps = ["BoundaryValueDiffEq", "DelayDiffEq", "DiffEqBase", "DiffEqCallbacks", "DiffEqFinancial", "DiffEqJump", "DiffEqNoiseProcess", "DiffEqPhysics", "DimensionalPlotRecipes", "LinearAlgebra", "MultiScaleArrays", "OrdinaryDiffEq", "ParameterizedFunctions", "Random", "RecursiveArrayTools", "Reexport", "SteadyStateDiffEq", "StochasticDiffEq", "Sundials"]
git-tree-sha1 = "91df208ee040be7960c408d4681bf91974bcb4f4"
uuid = "0c46a032-eb83-5123-abaf-570d42b7fbaa"
version = "6.20.0"
[[DimensionalPlotRecipes]]
deps = ["LinearAlgebra", "RecipesBase"]
git-tree-sha1 = "af883a26bbe6e3f5f778cb4e1b81578b534c32a6"
uuid = "c619ae07-58cd-5f6d-b883-8f17bd6a98f9"
version = "1.2.0"
[[Distances]]
deps = ["LinearAlgebra", "Statistics", "StatsAPI"]
git-tree-sha1 = "837c83e5574582e07662bbbba733964ff7c26b9d"
uuid = "b4f34e82-e78d-54a5-968a-f98e89d6e8f7"
version = "0.10.6"
[[Distributed]]
deps = ["Random", "Serialization", "Sockets"]
uuid = "8ba89e20-285c-5b6f-9357-94700520ee1b"
[[Distributions]]
deps = ["ChainRulesCore", "DensityInterface", "FillArrays", "LinearAlgebra", "PDMats", "Printf", "QuadGK", "Random", "SparseArrays", "SpecialFunctions", "Statistics", "StatsBase", "StatsFuns", "Test"]
git-tree-sha1 = "dc6f530de935bb3c3cd73e99db5b4698e58b2fcf"
uuid = "31c24e10-a181-5473-b8eb-7969acd0382f"
version = "0.25.31"
[[DocStringExtensions]]
deps = ["LibGit2"]
git-tree-sha1 = "b19534d1895d702889b219c382a6e18010797f0b"
uuid = "ffbed154-4ef7-542d-bbb7-c09d3a79fcae"
version = "0.8.6"
[[DomainSets]]
deps = ["CompositeTypes", "IntervalSets", "LinearAlgebra", "StaticArrays", "Statistics"]
git-tree-sha1 = "5f5f0b750ac576bcf2ab1d7782959894b304923e"
uuid = "5b8099bc-c8ec-5219-889f-1d9e522a28bf"
version = "0.5.9"
[[Downloads]]
deps = ["ArgTools", "LibCURL", "NetworkOptions"]
uuid = "f43a241f-c20a-4ad4-852c-f6b1247861c6"
[[DynamicPolynomials]]
deps = ["DataStructures", "Future", "LinearAlgebra", "MultivariatePolynomials", "MutableArithmetics", "Pkg", "Reexport", "Test"]
git-tree-sha1 = "1b4665a7e303eaa7e03542cfaef0730cb056cb00"
uuid = "7c1d4256-1411-5781-91ec-d7bc3513ac07"
version = "0.3.21"
[[EarCut_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "3f3a2501fa7236e9b911e0f7a588c657e822bb6d"
uuid = "5ae413db-bbd1-5e63-b57d-d24a61df00f5"
version = "2.2.3+0"
[[ElasticArrays]]
deps = ["Adapt"]
git-tree-sha1 = "a0fcc1bb3c9ceaf07e1d0529c9806ce94be6adf9"
uuid = "fdbdab4c-e67f-52f5-8c3f-e7b388dad3d4"
version = "1.2.9"
[[EllipsisNotation]]
deps = ["ArrayInterface"]
git-tree-sha1 = "9aad812fb7c4c038da7cab5a069f502e6e3ae030"
uuid = "da5c29d0-fa7d-589e-88eb-ea29b0a81949"
version = "1.1.1"
[[ExponentialUtilities]]
deps = ["ArrayInterface", "LinearAlgebra", "Printf", "Requires", "SparseArrays"]
git-tree-sha1 = "cb39752c2a1f83bbe0fda393c51c480a296042ad"
uuid = "d4d017d3-3776-5f7e-afef-a10c40355c18"
version = "1.10.1"
[[ExprTools]]
git-tree-sha1 = "b7e3d17636b348f005f11040025ae8c6f645fe92"
uuid = "e2ba6199-217a-4e67-a87a-7c52f15ade04"
version = "0.1.6"
[[ExtendableGrids]]
deps = ["AbstractTrees", "Dates", "DocStringExtensions", "ElasticArrays", "InteractiveUtils", "LinearAlgebra", "Printf", "Random", "SparseArrays", "Test"]
git-tree-sha1 = "5a42a9371dd5ad1a00ec27c63c5eccc8e38dab43"
uuid = "cfc395e8-590f-11e8-1f13-43a2532b2fa8"
version = "0.7.9"
[[ExtendableSparse]]
deps = ["DocStringExtensions", "LinearAlgebra", "Printf", "SparseArrays", "Test"]
git-tree-sha1 = "ead69f021a6b37642f8c85a5b2b2d95aec40afd7"
uuid = "95c220a8-a1cf-11e9-0c77-dbfce5f500b3"
version = "0.3.7"
[[FastBroadcast]]
deps = ["LinearAlgebra", "Polyester", "Static"]
git-tree-sha1 = "e32a81c505ab234c992ca978f31ed8b0dabbc327"
uuid = "7034ab61-46d4-4ed7-9d0f-46aef9175898"
version = "0.1.11"
[[FastClosures]]
git-tree-sha1 = "acebe244d53ee1b461970f8910c235b259e772ef"
uuid = "9aa1b823-49e4-5ca5-8b0f-3971ec8bab6a"
version = "0.3.2"
[[FileIO]]
deps = ["Pkg", "Requires", "UUIDs"]
git-tree-sha1 = "2db648b6712831ecb333eae76dbfd1c156ca13bb"
uuid = "5789e2e9-d7fb-5bc7-8068-2c6fae9b9549"
version = "1.11.2"
[[FillArrays]]
deps = ["LinearAlgebra", "Random", "SparseArrays", "Statistics"]
git-tree-sha1 = "8756f9935b7ccc9064c6eef0bff0ad643df733a3"
uuid = "1a297f60-69ca-5386-bcde-b61e274b549b"
version = "0.12.7"
[[FiniteDiff]]
deps = ["ArrayInterface", "LinearAlgebra", "Requires", "SparseArrays", "StaticArrays"]
git-tree-sha1 = "8b3c09b56acaf3c0e581c66638b85c8650ee9dca"
uuid = "6a86dc24-6348-571c-b903-95158fe2bd41"
version = "2.8.1"
[[FixedPointNumbers]]
deps = ["Statistics"]
git-tree-sha1 = "335bfdceacc84c5cdf16aadc768aa5ddfc5383cc"
uuid = "53c48c17-4a7d-5ca2-90c5-79b7896eea93"
version = "0.8.4"
[[Formatting]]
deps = ["Printf"]
git-tree-sha1 = "8339d61043228fdd3eb658d86c926cb282ae72a8"
uuid = "59287772-0a20-5a39-b81b-1366585eb4c0"
version = "0.4.2"
[[ForwardDiff]]
deps = ["CommonSubexpressions", "DiffResults", "DiffRules", "LinearAlgebra", "LogExpFunctions", "NaNMath", "Preferences", "Printf", "Random", "SpecialFunctions", "StaticArrays"]
git-tree-sha1 = "6406b5112809c08b1baa5703ad274e1dded0652f"
uuid = "f6369f11-7733-5829-9624-2563aa707210"
version = "0.10.23"
[[FunctionWrappers]]
git-tree-sha1 = "241552bc2209f0fa068b6415b1942cc0aa486bcc"
uuid = "069b7b12-0de2-55c6-9aab-29f3d0a68a2e"
version = "1.1.2"
[[Future]]
deps = ["Random"]
uuid = "9fa8497b-333b-5362-9e8d-4d0656e87820"
[[GeometryBasics]]
deps = ["EarCut_jll", "IterTools", "LinearAlgebra", "StaticArrays", "StructArrays", "Tables"]
git-tree-sha1 = "15ff9a14b9e1218958d3530cc288cf31465d9ae2"
uuid = "5c1252a2-5f33-56bf-86c9-59e7332b4326"
version = "0.3.13"
[[GradientRobustMultiPhysics]]
deps = ["BenchmarkTools", "DiffResults", "DocStringExtensions", "ExtendableGrids", "ExtendableSparse", "ForwardDiff", "GridVisualize", "LinearAlgebra", "Printf", "SparseArrays", "StaticArrays", "SuiteSparse", "Test"]
git-tree-sha1 = "4dd7e32409b3632804ffbc0d814756841290124e"
uuid = "0802c0ca-1768-4022-988c-6dd5f9588a11"
version = "0.4.1"
[[Graphs]]
deps = ["ArnoldiMethod", "DataStructures", "Distributed", "Inflate", "LinearAlgebra", "Random", "SharedArrays", "SimpleTraits", "SparseArrays", "Statistics"]
git-tree-sha1 = "92243c07e786ea3458532e199eb3feee0e7e08eb"
uuid = "86223c79-3864-5bf0-83f7-82e725a168b6"
version = "1.4.1"
[[GridVisualize]]
deps = ["ColorSchemes", "Colors", "DocStringExtensions", "ElasticArrays", "ExtendableGrids", "GeometryBasics", "LinearAlgebra", "PkgVersion", "Printf", "StaticArrays"]
git-tree-sha1 = "39eef7772fbe0945ebd9662f12c4239490cb63e4"
uuid = "5eed8a63-0fb0-45eb-886d-8d5a387d12b8"
version = "0.1.7"
[[HostCPUFeatures]]
deps = ["BitTwiddlingConvenienceFunctions", "IfElse", "Libdl", "Static"]
git-tree-sha1 = "8f0dc80088981ab55702b04bba38097a44a1a3a9"
uuid = "3e5b6fbb-0976-4d2c-9146-d79de83f2fb0"
version = "0.1.5"
[[Hwloc]]
deps = ["Hwloc_jll"]
git-tree-sha1 = "92d99146066c5c6888d5a3abc871e6a214388b91"
uuid = "0e44f5e4-bd66-52a0-8798-143a42290a1d"
version = "2.0.0"
[[Hwloc_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "3395d4d4aeb3c9d31f5929d32760d8baeee88aaf"
uuid = "e33a78d0-f292-5ffc-b300-72abe9b543c8"
version = "2.5.0+0"
[[Hyperscript]]
deps = ["Test"]
git-tree-sha1 = "8d511d5b81240fc8e6802386302675bdf47737b9"
uuid = "47d2ed2b-36de-50cf-bf87-49c2cf4b8b91"
version = "0.0.4"
[[HypertextLiteral]]
git-tree-sha1 = "2b078b5a615c6c0396c77810d92ee8c6f470d238"
uuid = "ac1192a8-f4b3-4bfe-ba22-af5b92cd3ab2"
version = "0.9.3"
[[IOCapture]]
deps = ["Logging", "Random"]
git-tree-sha1 = "f7be53659ab06ddc986428d3a9dcc95f6fa6705a"
uuid = "b5f81e59-6552-4d32-b1f0-c071b021bf89"
version = "0.2.2"
[[IfElse]]
git-tree-sha1 = "debdd00ffef04665ccbb3e150747a77560e8fad1"
uuid = "615f187c-cbe4-4ef1-ba3b-2fcf58d6d173"
version = "0.1.1"
[[Inflate]]
git-tree-sha1 = "f5fc07d4e706b84f72d54eedcc1c13d92fb0871c"
uuid = "d25df0c9-e2be-5dd7-82c8-3ad0b3e990b9"
version = "0.1.2"
[[InitialValues]]
git-tree-sha1 = "7f6a4508b4a6f46db5ccd9799a3fc71ef5cad6e6"
uuid = "22cec73e-a1b8-11e9-2c92-598750a2cf9c"
version = "0.2.11"
[[InteractiveUtils]]
deps = ["Markdown"]
uuid = "b77e0a4c-d291-57a0-90e8-8db25a27a240"
[[IntervalSets]]
deps = ["Dates", "EllipsisNotation", "Statistics"]
git-tree-sha1 = "3cc368af3f110a767ac786560045dceddfc16758"
uuid = "8197267c-284f-5f27-9208-e0e47529a953"
version = "0.5.3"
[[InverseFunctions]]
deps = ["Test"]
git-tree-sha1 = "a7254c0acd8e62f1ac75ad24d5db43f5f19f3c65"
uuid = "3587e190-3f89-42d0-90ee-14403ec27112"
version = "0.1.2"
[[IrrationalConstants]]
git-tree-sha1 = "7fd44fd4ff43fc60815f8e764c0f352b83c49151"
uuid = "92d709cd-6900-40b7-9082-c6be49f344b6"
version = "0.1.1"
[[IterTools]]
git-tree-sha1 = "05110a2ab1fc5f932622ffea2a003221f4782c18"
uuid = "c8e1da08-722c-5040-9ed9-7db0dc04731e"
version = "1.3.0"
[[IterativeSolvers]]
deps = ["LinearAlgebra", "Printf", "Random", "RecipesBase", "SparseArrays"]
git-tree-sha1 = "1169632f425f79429f245113b775a0e3d121457c"
uuid = "42fd0dbc-a981-5370-80f2-aaf504508153"
version = "0.9.2"
[[IteratorInterfaceExtensions]]
git-tree-sha1 = "a3f24677c21f5bbe9d2a714f95dcd58337fb2856"
uuid = "82899510-4779-5014-852e-03e436cf321d"
version = "1.0.0"
[[JLD2]]
deps = ["DataStructures", "FileIO", "MacroTools", "Mmap", "Pkg", "Printf", "Reexport", "TranscodingStreams", "UUIDs"]
git-tree-sha1 = "46b7834ec8165c541b0b5d1c8ba63ec940723ffb"
uuid = "033835bb-8acc-5ee8-8aae-3f567f8a3819"
version = "0.4.15"
[[JLLWrappers]]
deps = ["Preferences"]
git-tree-sha1 = "642a199af8b68253517b80bd3bfd17eb4e84df6e"
uuid = "692b3bcd-3c85-4b1f-b108-f13ce0eb3210"
version = "1.3.0"
[[JSON]]
deps = ["Dates", "Mmap", "Parsers", "Unicode"]
git-tree-sha1 = "8076680b162ada2a031f707ac7b4953e30667a37"
uuid = "682c06a0-de6a-54ab-a142-c8b1cf79cde6"
version = "0.21.2"
[[JuliaFormatter]]
deps = ["CSTParser", "CommonMark", "DataStructures", "Pkg", "Tokenize"]
git-tree-sha1 = "e45015cdba3dea9ce91a573079a5706e73a5e895"
uuid = "98e50ef6-434e-11e9-1051-2b60c6c9e899"
version = "0.19.0"
[[LaTeXStrings]]
git-tree-sha1 = "f2355693d6778a178ade15952b7ac47a4ff97996"
uuid = "b964fa9f-0449-5b57-a5c2-d3ea65f4040f"
version = "1.3.0"
[[LabelledArrays]]
deps = ["ArrayInterface", "LinearAlgebra", "MacroTools", "StaticArrays"]
git-tree-sha1 = "fa07d4ee13edf79a6ac2575ad28d9f43694e1190"
uuid = "2ee39098-c373-598a-b85f-a56591580800"
version = "1.6.6"
[[Latexify]]
deps = ["Formatting", "InteractiveUtils", "LaTeXStrings", "MacroTools", "Markdown", "Printf", "Requires"]
git-tree-sha1 = "a8f4f279b6fa3c3c4f1adadd78a621b13a506bce"
uuid = "23fbe1c1-3f47-55db-b15f-69d7ec21a316"
version = "0.15.9"
[[LayoutPointers]]
deps = ["ArrayInterface", "LinearAlgebra", "ManualMemory", "SIMDTypes", "Static"]
git-tree-sha1 = "83b56449c39342a47f3fcdb3bc782bd6d66e1d97"
uuid = "10f19ff3-798f-405d-979b-55457f8fc047"
version = "0.1.4"
[[LibCURL]]
deps = ["LibCURL_jll", "MozillaCACerts_jll"]
uuid = "b27032c2-a3e7-50c8-80cd-2d36dbcbfd21"
[[LibCURL_jll]]
deps = ["Artifacts", "LibSSH2_jll", "Libdl", "MbedTLS_jll", "Zlib_jll", "nghttp2_jll"]
uuid = "deac9b47-8bc7-5906-a0fe-35ac56dc84c0"
[[LibGit2]]
deps = ["Base64", "NetworkOptions", "Printf", "SHA"]
uuid = "76f85450-5226-5b5a-8eaa-529ad045b433"
[[LibSSH2_jll]]
deps = ["Artifacts", "Libdl", "MbedTLS_jll"]
uuid = "29816b5a-b9ab-546f-933c-edad1886dfa8"
[[Libdl]]
uuid = "8f399da3-3557-5675-b5ff-fb832c97cbdb"
[[LineSearches]]
deps = ["LinearAlgebra", "NLSolversBase", "NaNMath", "Parameters", "Printf"]
git-tree-sha1 = "f27132e551e959b3667d8c93eae90973225032dd"
uuid = "d3d80556-e9d4-5f37-9878-2ab0fcc64255"
version = "7.1.1"
[[LinearAlgebra]]
deps = ["Libdl"]
uuid = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e"
[[LogExpFunctions]]
deps = ["ChainRulesCore", "ChangesOfVariables", "DocStringExtensions", "InverseFunctions", "IrrationalConstants", "LinearAlgebra"]
git-tree-sha1 = "be9eef9f9d78cecb6f262f3c10da151a6c5ab827"
uuid = "2ab3a3ac-af41-5b50-aa03-7779005ae688"
version = "0.3.5"
[[Logging]]
uuid = "56ddb016-857b-54e1-b83d-db4d58db5568"
[[LoopVectorization]]
deps = ["ArrayInterface", "CPUSummary", "CloseOpenIntervals", "DocStringExtensions", "HostCPUFeatures", "IfElse", "LayoutPointers", "LinearAlgebra", "OffsetArrays", "PolyesterWeave", "Requires", "SIMDDualNumbers", "SLEEFPirates", "Static", "ThreadingUtilities", "UnPack", "VectorizationBase"]
git-tree-sha1 = "9d8ce46c7727debdfd65be244f22257abf7d8739"
uuid = "bdcacae8-1622-11e9-2a5c-532679323890"
version = "0.12.98"
[[MacroTools]]
deps = ["Markdown", "Random"]
git-tree-sha1 = "3d3e902b31198a27340d0bf00d6ac452866021cf"
uuid = "1914dd2f-81c6-5fcd-8719-6d5c9610ff09"
version = "0.5.9"
[[ManualMemory]]
git-tree-sha1 = "9cb207b18148b2199db259adfa923b45593fe08e"
uuid = "d125e4d3-2237-4719-b19c-fa641b8a4667"
version = "0.1.6"
[[Markdown]]
deps = ["Base64"]
uuid = "d6f4376e-aef5-505a-96c1-9c027394607a"
[[MbedTLS_jll]]
deps = ["Artifacts", "Libdl"]
uuid = "c8ffd9c3-330d-5841-b78e-0817d7145fa1"
[[Metatheory]]
deps = ["AutoHashEquals", "DataStructures", "Dates", "DocStringExtensions", "Parameters", "Reexport", "TermInterface", "ThreadsX", "TimerOutputs"]
git-tree-sha1 = "0d3b2feb3168e4deb78361d3b5bb5c2e51ea5271"
uuid = "e9d8d322-4543-424a-9be4-0cc815abe26c"
version = "1.3.2"
[[MicroCollections]]
deps = ["BangBang", "Setfield"]
git-tree-sha1 = "4f65bdbbe93475f6ff9ea6969b21532f88d359be"
uuid = "128add7d-3638-4c79-886c-908ea0c25c34"
version = "0.1.1"
[[Missings]]
deps = ["DataAPI"]
git-tree-sha1 = "bf210ce90b6c9eed32d25dbcae1ebc565df2687f"
uuid = "e1d29d7a-bbdc-5cf2-9ac0-f12de2c33e28"
version = "1.0.2"
[[Mmap]]
uuid = "a63ad114-7e13-5084-954f-fe012c677804"
[[ModelingToolkit]]
deps = ["AbstractTrees", "ArrayInterface", "ConstructionBase", "DataStructures", "DiffEqBase", "DiffEqCallbacks", "DiffEqJump", "DiffRules", "Distributed", "Distributions", "DocStringExtensions", "DomainSets", "Graphs", "IfElse", "InteractiveUtils", "JuliaFormatter", "LabelledArrays", "Latexify", "Libdl", "LinearAlgebra", "MacroTools", "NaNMath", "NonlinearSolve", "RecursiveArrayTools", "Reexport", "Requires", "RuntimeGeneratedFunctions", "SafeTestsets", "SciMLBase", "Serialization", "Setfield", "SparseArrays", "SpecialFunctions", "StaticArrays", "SymbolicUtils", "Symbolics", "UnPack", "Unitful"]
git-tree-sha1 = "c9d6d91b6a976b668309691ea21a459d7bcf4f59"
uuid = "961ee093-0014-501f-94e3-6117800e7a78"
version = "7.1.2"
[[MozillaCACerts_jll]]
uuid = "14a3606d-f60d-562e-9121-12d972cd8159"
[[MuladdMacro]]
git-tree-sha1 = "c6190f9a7fc5d9d5915ab29f2134421b12d24a68"
uuid = "46d2c3a1-f734-5fdb-9937-b9b9aeba4221"
version = "0.2.2"
[[MultiScaleArrays]]
deps = ["DiffEqBase", "FiniteDiff", "ForwardDiff", "LinearAlgebra", "OrdinaryDiffEq", "Random", "RecursiveArrayTools", "SparseDiffTools", "Statistics", "StochasticDiffEq", "TreeViews"]
git-tree-sha1 = "258f3be6770fe77be8870727ba9803e236c685b8"
uuid = "f9640e96-87f6-5992-9c3b-0743c6a49ffa"
version = "1.8.1"
[[MultivariatePolynomials]]
deps = ["DataStructures", "LinearAlgebra", "MutableArithmetics"]
git-tree-sha1 = "45c9940cec79dedcdccc73cc6dd09ea8b8ab142c"
uuid = "102ac46a-7ee4-5c85-9060-abc95bfdeaa3"
version = "0.3.18"
[[MutableArithmetics]]
deps = ["LinearAlgebra", "SparseArrays", "Test"]
git-tree-sha1 = "8d9496b2339095901106961f44718920732616bb"
uuid = "d8a4904e-b15c-11e9-3269-09a3773c0cb0"
version = "0.2.22"
[[NLSolversBase]]
deps = ["DiffResults", "Distributed", "FiniteDiff", "ForwardDiff"]
git-tree-sha1 = "50310f934e55e5ca3912fb941dec199b49ca9b68"
uuid = "d41bc354-129a-5804-8e4c-c37616107c6c"
version = "7.8.2"
[[NLsolve]]
deps = ["Distances", "LineSearches", "LinearAlgebra", "NLSolversBase", "Printf", "Reexport"]
git-tree-sha1 = "019f12e9a1a7880459d0173c182e6a99365d7ac1"
uuid = "2774e3e8-f4cf-5e23-947b-6d7e65073b56"
version = "4.5.1"
[[NaNMath]]
git-tree-sha1 = "bfe47e760d60b82b66b61d2d44128b62e3a369fb"
uuid = "77ba4419-2d1f-58cd-9bb1-8ffee604a2e3"
version = "0.3.5"
[[NetworkOptions]]
uuid = "ca575930-c2e3-43a9-ace4-1e988b2c1908"
[[NonlinearSolve]]
deps = ["ArrayInterface", "FiniteDiff", "ForwardDiff", "IterativeSolvers", "LinearAlgebra", "RecursiveArrayTools", "RecursiveFactorization", "Reexport", "SciMLBase", "Setfield", "StaticArrays", "UnPack"]
git-tree-sha1 = "e9ffc92217b8709e0cf7b8808f6223a4a0936c95"
uuid = "8913a72c-1f9b-4ce2-8d82-65094dcecaec"
version = "0.3.11"
[[OffsetArrays]]
deps = ["Adapt"]
git-tree-sha1 = "043017e0bdeff61cfbb7afeb558ab29536bbb5ed"
uuid = "6fe1bfb0-de20-5000-8ca7-80f57d26f881"
version = "1.10.8"
[[OpenBLAS_jll]]
deps = ["Artifacts", "CompilerSupportLibraries_jll", "Libdl"]
uuid = "4536629a-c528-5b80-bd46-f80d51c5b363"
[[OpenLibm_jll]]
deps = ["Artifacts", "Libdl"]
uuid = "05823500-19ac-5b8b-9628-191a04bc5112"
[[OpenSpecFun_jll]]
deps = ["Artifacts", "CompilerSupportLibraries_jll", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "13652491f6856acfd2db29360e1bbcd4565d04f1"
uuid = "efe28fd5-8261-553b-a9e1-b2916fc3738e"
version = "0.5.5+0"
[[Optim]]
deps = ["Compat", "FillArrays", "ForwardDiff", "LineSearches", "LinearAlgebra", "NLSolversBase", "NaNMath", "Parameters", "PositiveFactorizations", "Printf", "SparseArrays", "StatsBase"]
git-tree-sha1 = "35d435b512fbab1d1a29138b5229279925eba369"
uuid = "429524aa-4258-5aef-a3af-852621145aeb"
version = "1.5.0"
[[OrderedCollections]]
git-tree-sha1 = "85f8e6578bf1f9ee0d11e7bb1b1456435479d47c"
uuid = "bac558e1-5e72-5ebc-8fee-abe8a469f55d"
version = "1.4.1"
[[OrdinaryDiffEq]]
deps = ["Adapt", "ArrayInterface", "DataStructures", "DiffEqBase", "DocStringExtensions", "ExponentialUtilities", "FastClosures", "FiniteDiff", "ForwardDiff", "LinearAlgebra", "Logging", "LoopVectorization", "MacroTools", "MuladdMacro", "NLsolve", "Polyester", "PreallocationTools", "RecursiveArrayTools", "Reexport", "SparseArrays", "SparseDiffTools", "StaticArrays", "UnPack"]
git-tree-sha1 = "6f76c887ddfd3f2a018ef1ee00a17b46bcf4886e"
uuid = "1dea7af3-3e70-54e6-95c3-0bf5283fa5ed"
version = "5.67.0"
[[PDMats]]
deps = ["LinearAlgebra", "SparseArrays", "SuiteSparse"]
git-tree-sha1 = "ee26b350276c51697c9c2d88a072b339f9f03d73"
uuid = "90014a1f-27ba-587c-ab20-58faa44d9150"
version = "0.11.5"
[[ParameterizedFunctions]]
deps = ["DataStructures", "DiffEqBase", "DocStringExtensions", "Latexify", "LinearAlgebra", "ModelingToolkit", "Reexport", "SciMLBase"]
git-tree-sha1 = "3baa1ad75b77f406988be4dc0364e01cf16127e7"
uuid = "65888b18-ceab-5e60-b2b9-181511a3b968"
version = "5.12.2"
[[Parameters]]
deps = ["OrderedCollections", "UnPack"]
git-tree-sha1 = "34c0e9ad262e5f7fc75b10a9952ca7692cfc5fbe"
uuid = "d96e819e-fc66-5662-9728-84c9c7592b0a"
version = "0.12.3"
[[Parsers]]
deps = ["Dates"]
git-tree-sha1 = "ae4bbcadb2906ccc085cf52ac286dc1377dceccc"
uuid = "69de0a69-1ddd-5017-9359-2bf0b02dc9f0"
version = "2.1.2"
[[Pkg]]
deps = ["Artifacts", "Dates", "Downloads", "LibGit2", "Libdl", "Logging", "Markdown", "Printf", "REPL", "Random", "SHA", "Serialization", "TOML", "Tar", "UUIDs", "p7zip_jll"]
uuid = "44cfe95a-1eb2-52ea-b672-e2afdf69b78f"
[[PkgVersion]]
deps = ["Pkg"]
git-tree-sha1 = "a7a7e1a88853564e551e4eba8650f8c38df79b37"
uuid = "eebad327-c553-4316-9ea0-9fa01ccd7688"
version = "0.1.1"
[[PlutoUI]]
deps = ["AbstractPlutoDingetjes", "Base64", "Dates", "Hyperscript", "HypertextLiteral", "IOCapture", "InteractiveUtils", "JSON", "Logging", "Markdown", "Random", "Reexport", "UUIDs"]
git-tree-sha1 = "e071adf21e165ea0d904b595544a8e514c8bb42c"
uuid = "7f904dfe-b85e-4ff6-b463-dae2292396a8"
version = "0.7.19"
[[PoissonRandom]]
deps = ["Random", "Statistics", "Test"]
git-tree-sha1 = "44d018211a56626288b5d3f8c6497d28c26dc850"
uuid = "e409e4f3-bfea-5376-8464-e040bb5c01ab"
version = "0.4.0"
[[Polyester]]
deps = ["ArrayInterface", "BitTwiddlingConvenienceFunctions", "CPUSummary", "IfElse", "ManualMemory", "PolyesterWeave", "Requires", "Static", "StrideArraysCore", "ThreadingUtilities"]
git-tree-sha1 = "892b8d9dd3c7987a4d0fd320f0a421dd90b5d09d"
uuid = "f517fe37-dbe3-4b94-8317-1923a5111588"
version = "0.5.4"
[[PolyesterWeave]]
deps = ["BitTwiddlingConvenienceFunctions", "CPUSummary", "IfElse", "Static", "ThreadingUtilities"]
git-tree-sha1 = "a3ff99bf561183ee20386aec98ab8f4a12dc724a"
uuid = "1d0040c9-8b98-4ee7-8388-3f51789ca0ad"
version = "0.1.2"
[[PositiveFactorizations]]
deps = ["LinearAlgebra"]
git-tree-sha1 = "17275485f373e6673f7e7f97051f703ed5b15b20"
uuid = "85a6dd25-e78a-55b7-8502-1745935b8125"
version = "0.2.4"
[[PreallocationTools]]
deps = ["Adapt", "ArrayInterface", "ForwardDiff", "LabelledArrays"]
git-tree-sha1 = "ba819074442cd4c9bda1a3d905ec305f8acb37f2"
uuid = "d236fae5-4411-538c-8e31-a6e3d9e00b46"
version = "0.2.0"
[[Preferences]]
deps = ["TOML"]
git-tree-sha1 = "00cfd92944ca9c760982747e9a1d0d5d86ab1e5a"
uuid = "21216c6a-2e73-6563-6e65-726566657250"
version = "1.2.2"
[[Printf]]
deps = ["Unicode"]
uuid = "de0858da-6303-5e67-8744-51eddeeeb8d7"
[[PyCall]]
deps = ["Conda", "Dates", "Libdl", "LinearAlgebra", "MacroTools", "Serialization", "VersionParsing"]
git-tree-sha1 = "4ba3651d33ef76e24fef6a598b63ffd1c5e1cd17"
uuid = "438e738f-606a-5dbb-bf0a-cddfbfd45ab0"
version = "1.92.5"
[[PyPlot]]
deps = ["Colors", "LaTeXStrings", "PyCall", "Sockets", "Test", "VersionParsing"]
git-tree-sha1 = "14c1b795b9d764e1784713941e787e1384268103"
uuid = "d330b81b-6aea-500a-939a-2ce795aea3ee"
version = "2.10.0"
[[QuadGK]]
deps = ["DataStructures", "LinearAlgebra"]
git-tree-sha1 = "78aadffb3efd2155af139781b8a8df1ef279ea39"
uuid = "1fd47b50-473d-5c70-9696-f719f8f3bcdc"
version = "2.4.2"
[[REPL]]
deps = ["InteractiveUtils", "Markdown", "Sockets", "Unicode"]
uuid = "3fa0cd96-eef1-5676-8a61-b3b8758bbffb"
[[Random]]
deps = ["Serialization"]
uuid = "9a3f8284-a2c9-5f02-9a11-845980a1fd5c"
[[Random123]]
deps = ["Libdl", "Random", "RandomNumbers"]
git-tree-sha1 = "0e8b146557ad1c6deb1367655e052276690e71a3"
uuid = "74087812-796a-5b5d-8853-05524746bad3"
version = "1.4.2"
[[RandomNumbers]]
deps = ["Random", "Requires"]
git-tree-sha1 = "043da614cc7e95c703498a491e2c21f58a2b8111"
uuid = "e6cf234a-135c-5ec9-84dd-332b85af5143"
version = "1.5.3"
[[RecipesBase]]
git-tree-sha1 = "44a75aa7a527910ee3d1751d1f0e4148698add9e"
uuid = "3cdcf5f2-1ef4-517c-9805-6587b60abb01"
version = "1.1.2"
[[RecursiveArrayTools]]
deps = ["ArrayInterface", "ChainRulesCore", "DocStringExtensions", "FillArrays", "LinearAlgebra", "RecipesBase", "Requires", "StaticArrays", "Statistics", "ZygoteRules"]
git-tree-sha1 = "c944fa4adbb47be43376359811c0a14757bdc8a8"
uuid = "731186ca-8d62-57ce-b412-fbd966d074cd"
version = "2.20.0"
[[RecursiveFactorization]]
deps = ["LinearAlgebra", "LoopVectorization", "Polyester", "StrideArraysCore", "TriangularSolve"]
git-tree-sha1 = "b7edd69c796b30985ea6dfeda8504cdb7cf77e9f"
uuid = "f2c3362d-daeb-58d1-803e-2bc74f2840b4"
version = "0.2.5"
[[Reexport]]
git-tree-sha1 = "45e428421666073eab6f2da5c9d310d99bb12f9b"
uuid = "189a3867-3050-52da-a836-e630ba90ab69"
version = "1.2.2"
[[Referenceables]]
deps = ["Adapt"]
git-tree-sha1 = "e681d3bfa49cd46c3c161505caddf20f0e62aaa9"
uuid = "42d2dcc6-99eb-4e98-b66c-637b7d73030e"
version = "0.1.2"
[[Requires]]
deps = ["UUIDs"]
git-tree-sha1 = "4036a3bd08ac7e968e27c203d45f5fff15020621"
uuid = "ae029012-a4dd-5104-9daa-d747884805df"
version = "1.1.3"
[[ResettableStacks]]
deps = ["StaticArrays"]
git-tree-sha1 = "256eeeec186fa7f26f2801732774ccf277f05db9"
uuid = "ae5879a3-cd67-5da8-be7f-38c6eb64a37b"
version = "1.1.1"
[[Rmath]]
deps = ["Random", "Rmath_jll"]
git-tree-sha1 = "bf3188feca147ce108c76ad82c2792c57abe7b1f"
uuid = "79098fc4-a85e-5d69-aa6a-4863f24498fa"
version = "0.7.0"
[[Rmath_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "68db32dff12bb6127bac73c209881191bf0efbb7"
uuid = "f50d1b31-88e8-58de-be2c-1cc44531875f"
version = "0.3.0+0"
[[RuntimeGeneratedFunctions]]
deps = ["ExprTools", "SHA", "Serialization"]
git-tree-sha1 = "cdc1e4278e91a6ad530770ebb327f9ed83cf10c4"
uuid = "7e49a35a-f44a-4d26-94aa-eba1b4ca6b47"
version = "0.5.3"
[[SHA]]
uuid = "ea8e919c-243c-51af-8825-aaa63cd721ce"
[[SIMDDualNumbers]]
deps = ["ForwardDiff", "IfElse", "SLEEFPirates", "VectorizationBase"]
git-tree-sha1 = "62c2da6eb66de8bb88081d20528647140d4daa0e"
uuid = "3cdde19b-5bb0-4aaf-8931-af3e248e098b"
version = "0.1.0"
[[SIMDTypes]]
git-tree-sha1 = "330289636fb8107c5f32088d2741e9fd7a061a5c"
uuid = "94e857df-77ce-4151-89e5-788b33177be4"
version = "0.1.0"
[[SLEEFPirates]]
deps = ["IfElse", "Static", "VectorizationBase"]
git-tree-sha1 = "1410aad1c6b35862573c01b96cd1f6dbe3979994"
uuid = "476501e8-09a2-5ece-8869-fb82de89a1fa"
version = "0.6.28"
[[SafeTestsets]]
deps = ["Test"]
git-tree-sha1 = "36ebc5622c82eb9324005cc75e7e2cc51181d181"
uuid = "1bc83da4-3b8d-516f-aca4-4fe02f6d838f"
version = "0.0.1"
[[SciMLBase]]
deps = ["ArrayInterface", "CommonSolve", "ConstructionBase", "Distributed", "DocStringExtensions", "IteratorInterfaceExtensions", "LinearAlgebra", "Logging", "RecipesBase", "RecursiveArrayTools", "StaticArrays", "Statistics", "Tables", "TreeViews"]
git-tree-sha1 = "ad2c7f08e332cc3bb05d33026b71fa0ef66c009a"
uuid = "0bca4576-84f4-4d90-8ffe-ffa030f20462"
version = "1.19.4"
[[Serialization]]
uuid = "9e88b42a-f829-5b0c-bbe9-9e923198166b"
[[Setfield]]
deps = ["ConstructionBase", "Future", "MacroTools", "Requires"]
git-tree-sha1 = "def0718ddbabeb5476e51e5a43609bee889f285d"
uuid = "efcf1570-3423-57d1-acb7-fd33fddbac46"
version = "0.8.0"
[[SharedArrays]]
deps = ["Distributed", "Mmap", "Random", "Serialization"]
uuid = "1a1011a3-84de-559e-8e89-a11a2f7dc383"
[[SimpleTraits]]
deps = ["InteractiveUtils", "MacroTools"]
git-tree-sha1 = "5d7e3f4e11935503d3ecaf7186eac40602e7d231"
uuid = "699a6c99-e7fa-54fc-8d76-47d257e15c1d"
version = "0.9.4"
[[SimplexGridFactory]]
deps = ["DocStringExtensions", "ElasticArrays", "ExtendableGrids", "GridVisualize", "LinearAlgebra", "Printf", "Test"]
git-tree-sha1 = "9789d88e28d43355d1c4293943d320dc1a755de8"
uuid = "57bfcd06-606e-45d6-baf4-4ba06da0efd5"
version = "0.5.3"
[[Sockets]]
uuid = "6462fe0b-24de-5631-8697-dd941f90decc"
[[SortingAlgorithms]]
deps = ["DataStructures"]
git-tree-sha1 = "b3363d7460f7d098ca0912c69b082f75625d7508"
uuid = "a2af1166-a08f-5f64-846c-94a0d3cef48c"
version = "1.0.1"
[[SparseArrays]]
deps = ["LinearAlgebra", "Random"]
uuid = "2f01184e-e22b-5df5-ae63-d93ebab69eaf"
[[SparseDiffTools]]
deps = ["Adapt", "ArrayInterface", "Compat", "DataStructures", "FiniteDiff", "ForwardDiff", "Graphs", "LinearAlgebra", "Requires", "SparseArrays", "StaticArrays", "VertexSafeGraphs"]
git-tree-sha1 = "f87076b43379cb0bd9f421cfe7c649fb510d8e4e"
uuid = "47a9eef4-7e08-11e9-0b38-333d64bd3804"
version = "1.18.1"
[[SparsityDetection]]
deps = ["Cassette", "DocStringExtensions", "LinearAlgebra", "SparseArrays", "SpecialFunctions"]
git-tree-sha1 = "9e182a311d169cb9fe0c6501aa252983215fe692"
uuid = "684fba80-ace3-11e9-3d08-3bc7ed6f96df"
version = "0.3.4"
[[SpecialFunctions]]
deps = ["ChainRulesCore", "IrrationalConstants", "LogExpFunctions", "OpenLibm_jll", "OpenSpecFun_jll"]
git-tree-sha1 = "f0bccf98e16759818ffc5d97ac3ebf87eb950150"
uuid = "276daf66-3868-5448-9aa4-cd146d93841b"
version = "1.8.1"
[[SplittablesBase]]
deps = ["Setfield", "Test"]
git-tree-sha1 = "39c9f91521de844bad65049efd4f9223e7ed43f9"
uuid = "171d559e-b47b-412a-8079-5efa626c420e"
version = "0.1.14"
[[Static]]
deps = ["IfElse"]
git-tree-sha1 = "e7bc80dc93f50857a5d1e3c8121495852f407e6a"
uuid = "aedffcd0-7271-4cad-89d0-dc628f76c6d3"
version = "0.4.0"
[[StaticArrays]]
deps = ["LinearAlgebra", "Random", "Statistics"]
git-tree-sha1 = "3c76dde64d03699e074ac02eb2e8ba8254d428da"
uuid = "90137ffa-7385-5640-81b9-e52037218182"
version = "1.2.13"
[[Statistics]]
deps = ["LinearAlgebra", "SparseArrays"]
uuid = "10745b16-79ce-11e8-11f9-7d13ad32a3b2"
[[StatsAPI]]
git-tree-sha1 = "1958272568dc176a1d881acb797beb909c785510"
uuid = "82ae8749-77ed-4fe6-ae5f-f523153014b0"
version = "1.0.0"
[[StatsBase]]
deps = ["DataAPI", "DataStructures", "LinearAlgebra", "LogExpFunctions", "Missings", "Printf", "Random", "SortingAlgorithms", "SparseArrays", "Statistics", "StatsAPI"]
git-tree-sha1 = "eb35dcc66558b2dda84079b9a1be17557d32091a"
uuid = "2913bbd2-ae8a-5f71-8c99-4fb6c76f3a91"
version = "0.33.12"
[[StatsFuns]]
deps = ["ChainRulesCore", "InverseFunctions", "IrrationalConstants", "LogExpFunctions", "Reexport", "Rmath", "SpecialFunctions"]
git-tree-sha1 = "385ab64e64e79f0cd7cfcf897169b91ebbb2d6c8"
uuid = "4c63d2b9-4356-54db-8cca-17b64c39e42c"
version = "0.9.13"
[[SteadyStateDiffEq]]
deps = ["DiffEqBase", "DiffEqCallbacks", "LinearAlgebra", "NLsolve", "Reexport", "SciMLBase"]
git-tree-sha1 = "3e057e1f9f12d18cac32011aed9e61eef6c1c0ce"
uuid = "9672c7b4-1e72-59bd-8a11-6ac3964bc41f"
version = "1.6.6"
[[StochasticDiffEq]]
deps = ["Adapt", "ArrayInterface", "DataStructures", "DiffEqBase", "DiffEqJump", "DiffEqNoiseProcess", "DocStringExtensions", "FillArrays", "FiniteDiff", "ForwardDiff", "LinearAlgebra", "Logging", "MuladdMacro", "NLsolve", "OrdinaryDiffEq", "Random", "RandomNumbers", "RecursiveArrayTools", "Reexport", "SparseArrays", "SparseDiffTools", "StaticArrays", "UnPack"]
git-tree-sha1 = "d6756d0c66aecd5d57ad9d305d7c2526fb5922d9"
uuid = "789caeaf-c7a9-5a7d-9973-96adeb23e2a0"
version = "6.41.0"
[[StrideArraysCore]]
deps = ["ArrayInterface", "CloseOpenIntervals", "IfElse", "LayoutPointers", "ManualMemory", "Requires", "SIMDTypes", "Static", "ThreadingUtilities"]
git-tree-sha1 = "12cf3253ebd8e2a3214ae171fbfe51e7e8d8ad28"
uuid = "7792a7ef-975c-4747-a70f-980b88e8d1da"
version = "0.2.9"
[[StructArrays]]
deps = ["Adapt", "DataAPI", "StaticArrays", "Tables"]
git-tree-sha1 = "2ce41e0d042c60ecd131e9fb7154a3bfadbf50d3"
uuid = "09ab397b-f2b6-538f-b94a-2f83cf4a842a"
version = "0.6.3"
[[SuiteSparse]]
deps = ["Libdl", "LinearAlgebra", "Serialization", "SparseArrays"]
uuid = "4607b0f0-06f3-5cda-b6b1-a6196a1729e9"
[[SuiteSparse_jll]]
deps = ["Artifacts", "Libdl", "OpenBLAS_jll"]
uuid = "bea87d4a-7f5b-5778-9afe-8cc45184846c"
[[Sundials]]
deps = ["CEnum", "DataStructures", "DiffEqBase", "Libdl", "LinearAlgebra", "Logging", "Reexport", "SparseArrays", "Sundials_jll"]
git-tree-sha1 = "12d529a67c232bd27e9868fbcfad4997435786a5"
uuid = "c3572dad-4567-51f8-b174-8c6c989267f4"
version = "4.6.0"
[[Sundials_jll]]
deps = ["CompilerSupportLibraries_jll", "Libdl", "OpenBLAS_jll", "Pkg", "SuiteSparse_jll"]
git-tree-sha1 = "013ff4504fc1d475aa80c63b455b6b3a58767db2"
uuid = "fb77eaff-e24c-56d4-86b1-d163f2edb164"
version = "5.2.0+1"
[[SymbolicUtils]]
deps = ["AbstractTrees", "Bijections", "ChainRulesCore", "Combinatorics", "ConstructionBase", "DataStructures", "DocStringExtensions", "DynamicPolynomials", "IfElse", "LabelledArrays", "LinearAlgebra", "Metatheory", "MultivariatePolynomials", "NaNMath", "Setfield", "SparseArrays", "SpecialFunctions", "StaticArrays", "TermInterface", "TimerOutputs"]
git-tree-sha1 = "5255e65d129c8edbde92fd2ede515e61098f93df"
uuid = "d1185830-fcd6-423d-90d6-eec64667417b"
version = "0.18.1"
[[Symbolics]]
deps = ["ConstructionBase", "DataStructures", "DiffRules", "Distributions", "DocStringExtensions", "DomainSets", "IfElse", "Latexify", "Libdl", "LinearAlgebra", "MacroTools", "Metatheory", "NaNMath", "RecipesBase", "Reexport", "Requires", "RuntimeGeneratedFunctions", "SciMLBase", "Setfield", "SparseArrays", "SpecialFunctions", "StaticArrays", "SymbolicUtils", "TermInterface", "TreeViews"]
git-tree-sha1 = "56272fc85e8d99332149fece99284ee31a9fa101"
uuid = "0c5d862f-8b57-4792-8d23-62f2024744c7"
version = "4.1.0"
[[TOML]]
deps = ["Dates"]
uuid = "fa267f1f-6049-4f14-aa54-33bafae1ed76"
[[TableTraits]]
deps = ["IteratorInterfaceExtensions"]
git-tree-sha1 = "c06b2f539df1c6efa794486abfb6ed2022561a39"
uuid = "3783bdb8-4a98-5b6b-af9a-565f29a5fe9c"
version = "1.0.1"
[[Tables]]
deps = ["DataAPI", "DataValueInterfaces", "IteratorInterfaceExtensions", "LinearAlgebra", "TableTraits", "Test"]
git-tree-sha1 = "fed34d0e71b91734bf0a7e10eb1bb05296ddbcd0"
uuid = "bd369af6-aec1-5ad0-b16a-f7cc5008161c"
version = "1.6.0"
[[Tar]]
deps = ["ArgTools", "SHA"]
uuid = "a4e569a6-e804-4fa4-b0f3-eef7a1d5b13e"
[[TermInterface]]
git-tree-sha1 = "7aa601f12708243987b88d1b453541a75e3d8c7a"
uuid = "8ea1fca8-c5ef-4a55-8b96-4e9afe9c9a3c"
version = "0.2.3"
[[Test]]
deps = ["InteractiveUtils", "Logging", "Random", "Serialization"]
uuid = "8dfed614-e22c-5e08-85e1-65c5234f0b40"
[[ThreadingUtilities]]
deps = ["ManualMemory"]
git-tree-sha1 = "03013c6ae7f1824131b2ae2fc1d49793b51e8394"
uuid = "8290d209-cae3-49c0-8002-c8c24d57dab5"
version = "0.4.6"
[[ThreadsX]]
deps = ["ArgCheck", "BangBang", "ConstructionBase", "InitialValues", "MicroCollections", "Referenceables", "Setfield", "SplittablesBase", "Transducers"]
git-tree-sha1 = "abcff3ac31c7894550566be533b512f8b059104f"
uuid = "ac1d9e8a-700a-412c-b207-f0111f4b6c0d"
version = "0.1.8"
[[TimerOutputs]]
deps = ["ExprTools", "Printf"]
git-tree-sha1 = "7cb456f358e8f9d102a8b25e8dfedf58fa5689bc"
uuid = "a759f4b9-e2f1-59dc-863e-4aeb61b1ea8f"
version = "0.5.13"
[[Tokenize]]
git-tree-sha1 = "0952c9cee34988092d73a5708780b3917166a0dd"
uuid = "0796e94c-ce3b-5d07-9a54-7f471281c624"
version = "0.5.21"
[[TranscodingStreams]]
deps = ["Random", "Test"]
git-tree-sha1 = "216b95ea110b5972db65aa90f88d8d89dcb8851c"
uuid = "3bb67fe8-82b1-5028-8e26-92a6c54297fa"
version = "0.9.6"
[[Transducers]]
deps = ["Adapt", "ArgCheck", "BangBang", "Baselet", "CompositionsBase", "DefineSingletons", "Distributed", "InitialValues", "Logging", "Markdown", "MicroCollections", "Requires", "Setfield", "SplittablesBase", "Tables"]
git-tree-sha1 = "bccb153150744d476a6a8d4facf5299325d5a442"
uuid = "28d57a85-8fef-5791-bfe6-a80928e7c999"
version = "0.4.67"
[[TreeViews]]
deps = ["Test"]
git-tree-sha1 = "8d0d7a3fe2f30d6a7f833a5f19f7c7a5b396eae6"
uuid = "a2a6695c-b41b-5b7d-aed9-dbfdeacea5d7"
version = "0.3.0"
[[Triangle_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "bfdd9ef1004eb9d407af935a6f36a4e0af711369"
uuid = "5639c1d2-226c-5e70-8d55-b3095415a16a"
version = "1.6.1+0"
[[TriangularSolve]]
deps = ["CloseOpenIntervals", "IfElse", "LayoutPointers", "LinearAlgebra", "LoopVectorization", "Polyester", "Static", "VectorizationBase"]
git-tree-sha1 = "ec9a310324dd2c546c07f33a599ded9c1d00a420"
uuid = "d5829a12-d9aa-46ab-831f-fb7c9ab06edf"
version = "0.1.8"
[[Triangulate]]
deps = ["DocStringExtensions", "Libdl", "Printf", "Test", "Triangle_jll"]
git-tree-sha1 = "2b4f716b192c0c615d96d541ee029e85666388cb"
uuid = "f7e6ffb2-c36d-4f8f-a77e-16e897189344"
version = "2.1.0"
[[URIs]]
git-tree-sha1 = "97bbe755a53fe859669cd907f2d96aee8d2c1355"
uuid = "5c2747f8-b7ea-4ff2-ba2e-563bfd36b1d4"
version = "1.3.0"
[[UUIDs]]
deps = ["Random", "SHA"]
uuid = "cf7118a7-6976-5b1a-9a39-7adc72f591a4"
[[UnPack]]
git-tree-sha1 = "387c1f73762231e86e0c9c5443ce3b4a0a9a0c2b"
uuid = "3a884ed6-31ef-47d7-9d2a-63182c4928ed"
version = "1.0.2"
[[Unicode]]
uuid = "4ec0a83e-493e-50e2-b9ac-8f72acf5a8f5"
[[Unitful]]
deps = ["ConstructionBase", "Dates", "LinearAlgebra", "Random"]
git-tree-sha1 = "0992ed0c3ef66b0390e5752fe60054e5ff93b908"
uuid = "1986cc42-f94f-5a68-af5c-568840ba703d"
version = "1.9.2"
[[VectorizationBase]]
deps = ["ArrayInterface", "CPUSummary", "HostCPUFeatures", "Hwloc", "IfElse", "LayoutPointers", "Libdl", "LinearAlgebra", "SIMDTypes", "Static"]
git-tree-sha1 = "5239606cf3552aff43d79ecc75b1af1ce4625109"
uuid = "3d5dd08c-fd9d-11e8-17fa-ed2836048c2f"
version = "0.21.21"
[[VersionParsing]]
git-tree-sha1 = "e575cf85535c7c3292b4d89d89cc29e8c3098e47"
uuid = "81def892-9a0e-5fdd-b105-ffc91e053289"
version = "1.2.1"
[[VertexSafeGraphs]]
deps = ["Graphs"]
git-tree-sha1 = "8351f8d73d7e880bfc042a8b6922684ebeafb35c"
uuid = "19fa3120-7c27-5ec5-8db8-b0b0aa330d6f"
version = "0.2.0"
[[VoronoiFVM]]
deps = ["DiffResults", "DocStringExtensions", "ExtendableGrids", "ExtendableSparse", "ForwardDiff", "GridVisualize", "IterativeSolvers", "JLD2", "LinearAlgebra", "Printf", "RecursiveArrayTools", "SparseArrays", "SparseDiffTools", "SparsityDetection", "StaticArrays", "SuiteSparse", "Test"]
git-tree-sha1 = "679fd7b10ea44e39eb9e83b256c410eb75d96ffc"
uuid = "82b139dc-5afc-11e9-35da-9b9bdfd336f3"
version = "0.10.12"
[[Zlib_jll]]
deps = ["Libdl"]
uuid = "83775a58-1f1d-513f-b197-d71354ab007a"
[[ZygoteRules]]
deps = ["MacroTools"]
git-tree-sha1 = "8c1a8e4dfacb1fd631745552c8db35d0deb09ea0"
uuid = "700de1a5-db45-46bc-99cf-38207098b444"
version = "0.2.2"
[[nghttp2_jll]]
deps = ["Artifacts", "Libdl"]
uuid = "8e850ede-7688-5339-a07c-302acd2aaf8d"
[[p7zip_jll]]
deps = ["Artifacts", "Libdl"]
uuid = "3f19e933-33d8-53b3-aaab-bd5110c3b7a0"
"""
# ╔═╡ Cell order:
# ╟─b7d13a60-8370-11eb-3a14-1df66337bc34
# ╟─6c221d04-863c-11eb-0bf8-41f7a6288b66
# ╟─68847d40-863c-11eb-18d3-e1060d831230
# ╟─b0581c08-863c-11eb-0d81-d59ac5f24479
# ╟─0d1ef53a-85c8-11eb-13ef-952df60b51b0
# ╟─174e53bc-863f-11eb-169d-2fe8a9b2adfb
# ╟─d2f59d32-863a-11eb-2ffe-37e8d2a06d27
# ╟─7cb4be3c-8372-11eb-17cc-ad4f68a34e72
# ╟─3a462e56-8371-11eb-0503-bf8ebd33276b
# ╟─00bcd2be-8373-11eb-368e-61b2cdc2ab74
# ╟─d0c8331e-840b-11eb-249b-5bba159d0d60
# ╟─3b05b78a-83e9-11eb-3d9e-8dda5fb67594
# ╟─151c3696-840e-11eb-0cd6-d91971fcf502
# ╟─5062ea76-83e9-11eb-26ad-cb5cb7746014
# ╟─0d9b6474-85e8-11eb-24a1-e7c037afb546
# ╟─47127b3a-83e9-11eb-22cf-9904b800edeb
# ╟─2f1894e0-842c-11eb-2489-ab7cbaa2fe68
# ╟─86f5e288-85b4-11eb-133e-25e1fbe363da
# ╟─5dd7b7b6-8634-11eb-37d0-f13485dca6a0
# ╟─568527e0-8374-11eb-17b8-7d100bbd8e37
# ╠═c42de0a2-8374-11eb-2bf2-e11a848bf099
# ╠═296637fc-8376-11eb-0fef-050bf60bb7ff
# ╟─045e2078-8641-11eb-188f-a98971dc8155
# ╠═8aa0565e-85cd-11eb-32de-739cf53f6419
# ╟─8773d184-8375-11eb-0e52-53c2df5dff93
# ╠═ebf09b36-8374-11eb-06a5-f3baec9932c2
# ╟─caf52886-8375-11eb-3cf8-a949cf8a3a25
# ╟─f7f2cb36-8375-11eb-0c40-c5063c068bef
# ╟─9507b252-837a-11eb-332e-117ceb07cf2b
# ╟─5d5cef6a-85ba-11eb-263e-0dcbcb148ac0
# ╟─6fb193dc-837b-11eb-0380-3136d173692b
# ╟─69e51df4-8379-11eb-12c6-93e6d605be60
# ╠═b7872370-8376-11eb-0abb-5ba2ba60697f
# ╟─ccbd1974-8642-11eb-39db-212dcf3821fc
# ╠═bd938738-8379-11eb-2e7b-3521b0c4d225
# ╟─192ee390-8379-11eb-1666-9bd411478d4d
# ╠═04d59916-8379-11eb-0c09-d91190563a84
# ╟─3e02d072-837a-11eb-2838-259e4228d577
# ╠═e134f5a6-8378-11eb-0766-657ab2915de3
# ╟─9eae6a52-837b-11eb-1f08-ff6a44398858
# ╟─518b68fe-8643-11eb-3243-719110f74026
# ╠═544c6a08-81dd-11eb-301f-df0c8194d88f
# ╟─92e1351e-837c-11eb-3b02-33ccb80a48d8
# ╠═63e18f7a-837c-11eb-0285-b76ef6d38a1f
# ╠═549161a6-81df-11eb-2de0-f5629bcd3005
# ╟─563e9540-840d-11eb-2a8b-5fca30564841
# ╟─bfe00216-81e7-11eb-16a1-3f1436253097
# ╠═d05f97e2-85ba-11eb-06ea-c933332c0630
# ╠═244e9f36-837e-11eb-1a02-a1989909f58f
# ╟─255b62e0-8380-11eb-1c58-7fb1c067f0e5
# ╠═ff99425c-837f-11eb-2217-e54e40a5a314
# ╟─1fc5d0ee-85bb-11eb-25d8-69151e6dafc2
# ╠═5ab844b2-8380-11eb-3eff-f562f445b06f
# ╠═8214acb2-8380-11eb-2d24-1bef38c4e1da
# ╠═919677d6-8380-11eb-3e1c-152fea8b92ec
# ╠═c41db0b8-8380-11eb-14cc-71af2cd90a9f
# ╟─71e783ea-8381-11eb-3eaa-5142de7bbd68
# ╟─d39e6472-8594-11eb-07d6-8961306a6a44
# ╟─d6076ec0-8594-11eb-154d-1dc03499315f
# ╟─dc76902a-85c8-11eb-24a5-5b456ad625d9
# ╟─eedfd550-85cd-11eb-1bbf-4daf6fc4d019
# ╟─5e0307a2-85be-11eb-2295-3d1f2b01256b
# ╟─d0e82116-85bf-11eb-1580-c5cb1efc1ba1
# ╟─b1d732c0-8381-11eb-0d91-eb04784ec1cb
# ╠═092e6940-8598-11eb-335d-9fd32dadd468
# ╟─62cc9dea-8382-11eb-0552-f3858008c864
# ╠═be46f34a-8383-11eb-2972-87f7ef807ebe
# ╟─488377d4-8593-11eb-2f16-1b031f62537b
# ╟─07923cf2-85c9-11eb-0563-3b29940f50bb
# ╟─ad3a5aac-8382-11eb-140b-c10660fd8c61
# ╟─99ce60fa-85e2-11eb-29af-a5f0feb65191
# ╠═ae80e57c-85e2-11eb-1297-3b0219a7af3b
# ╟─89607c62-85e2-11eb-25b7-8b5cb4771d02
# ╠═9c94a022-8382-11eb-38ad-adc4d894e517
# ╟─dca25088-8382-11eb-0584-399677021678
# ╠═d2bfa708-8382-11eb-3bab-07447ecb4adb
# ╠═845f6460-8382-11eb-21b0-b7082bdd66e3
# ╟─7b954d3c-8593-11eb-0cfc-2b1a0e51d6e6
# ╠═5c82b6bc-8383-11eb-192e-71e5336e0425
# ╠═3aed6f3c-85be-11eb-30ae-6170b11fc0a1
# ╟─01415fe2-8644-11eb-1fad-51fc9957aea8
# ╟─1a6fbeb4-8644-11eb-00d9-832a003ccd4b
# ╟─61666f48-8644-11eb-36a6-35129059c0fd
# ╟─79a8c4a4-8593-11eb-0e16-99a6cff3040e
# ╠═cf503e46-85bb-11eb-2ae7-e959707a01a9
# ╠═d84c89de-8384-11eb-28aa-132d56751734
# ╠═20fc42e6-8385-11eb-1b8d-c70dcb798cff
# ╠═ffd27a44-8385-11eb-150e-2f9a8bc48ec7
# ╟─c7cf0430-85bc-11eb-1527-b152703c025c
# ╠═099134de-85be-11eb-2aed-812180c08921
# ╠═528624f4-85c3-11eb-1579-cb4852b9904b
# ╟─52fc31d1-d41b-410d-bb07-17b991d34f05
# ╟─c06c99c8-85bc-11eb-29b5-694d7fab6673
# ╟─0c0a4210-8386-11eb-08a2-ff3625833da3
# ╟─51a150ee-8388-11eb-33e2-fb03cf4c0c76
# ╟─be8470e0-8594-11eb-2d55-657b74d82ccb
# ╟─50602f28-85da-11eb-1f03-5d33ec4ee42e
# ╟─913c1c76-8645-11eb-24b6-47bc88ad6f5d
# ╟─da9158d6-85ce-11eb-3494-6bbd1b790284
# ╟─4563f38a-8389-11eb-0596-81019d2948c8
# ╠═134530ae-85c2-11eb-1556-a3aa72624a7a
# ╟─b6dacce0-838c-11eb-18ca-fd4e85901bde
# ╠═f9479696-838a-11eb-22cd-13f069f2dc9a
# ╟─f95fed4c-85c2-11eb-2b76-a94551adbec1
# ╠═87dca836-85b3-11eb-1d28-73c08f594823
# ╠═f50ae9c4-838b-11eb-1822-499d9f4afbe4
# ╠═0bfe0312-838c-11eb-06d2-dbefd908b8ae
# ╟─b272ebcc-85c3-11eb-1fad-bf71ffde1a6c
# ╟─f6a6c162-b795-46e3-9229-ecad67836fb3
# ╟─05910082-85c4-11eb-2bd2-556c9e2c1975
# ╠═f572f800-8388-11eb-2774-95a3ff9a3ad6
# ╟─4fdf3a96-85c4-11eb-2f44-bd15bdf02dec
# ╠═4cf131ae-85c4-11eb-28c6-a9d9a73d681e
# ╟─c0f97390-85c4-11eb-2398-8d96e73caae2
# ╠═e9ce479c-85c3-11eb-0a14-e10dfe1dceb9
# ╟─a0161bd8-85c4-11eb-2366-45621bbe59b4
# ╠═ebcd0b92-8388-11eb-02f3-99334d45c9be
# ╟─3199edda-85c5-11eb-2da5-0dafc6cd7b84
# ╠═95c2ce84-85c3-11eb-37a7-bf13754d062c
# ╟─d3d7a9e4-838a-11eb-3e70-9525fb60e1c1
# ╠═0eb76256-8389-11eb-2e40-0d4e94c1d18d
# ╟─fb4690e2-838e-11eb-38e9-29168d5f6360
# ╟─4d14735c-8647-11eb-2891-91d1bc0fe717
# ╟─4446bc76-8647-11eb-3d4b-af4000b83024
# ╟─07658648-8596-11eb-12f2-7564ab864a2e
# ╟─df0cd404-85da-11eb-3274-51394b5edfa8
# ╠═e44bb844-85cc-11eb-05c9-cdaaa914d6c1
# ╠═f94316ca-85cc-11eb-1d6b-8ba91fe99cb5
# ╟─00000000-0000-0000-0000-000000000001
# ╟─00000000-0000-0000-0000-000000000002
| PDELib | https://github.com/WIAS-BERLIN/PDELib.jl.git |
|
[
"MIT"
] | 0.3.0 | 2fca7ee903e9c45871c1948e6b5fffdf359e2da3 | code | 6148 | #=
# 2D Lid-driven cavity (AD-Newton)
([source code](SOURCE_URL))
This example solves the lid-driven cavity problem where one seeks
a velocity ``\mathbf{u}`` and pressure ``\mathbf{p}`` of the incompressible Navier--Stokes problem
```math
\begin{aligned}
- \mu \Delta \mathbf{u} + (\mathbf{u} \cdot \nabla) \mathbf{u} + \nabla p & = 0\\
\mathrm{div}(u) & = 0
\end{aligned}
```
where ``\mathbf{u} = (1,0)`` along the top boundary of a square domain.
This examples highlights the use of automatic differentation to obtain Newton derivatives of nonlinear PDEOperators. The user can
switch between a Newton obtained by automatic differentation (ADnewton = true) and a 'manual' Newton scheme (ADnewton = false). The runtime
of the manual newton is slightly faster, but requires much more code input from the user that is more prone to errors.
=#
using PDELib
using Printf
function fe_liddrivencavity_autonewton(; verbosity = 0, Plotter = nothing, ADnewton = true, nref=2)
function boundary_data_top!(result)
result[1] = 1;
result[2] = 0;
end
## grid
xgrid = uniform_refine(grid_unitsquare(Triangle2D), nref);
## problem parameters
viscosity = 1e-2
maxIterations = 50 # termination criterion 1 for nonlinear mode
maxResidual = 1e-12 # termination criterion 2 for nonlinear mode
broken_p = false
## choose one of these (inf-sup stable) finite element type pairs
#FETypes = [H1P2{2,2}, H1P1{1}] # Taylor--Hood
#FETypes = [H1P2B{2,2}, H1P1{1}]; broken_p = true # P2-bubble
#FETypes = [H1CR{2}, H1P0{1}] # Crouzeix--Raviart
#FETypes = [H1MINI{2,2}, H1P1{1}] # MINI element on triangles only
FETypes = [H1BR{2}, H1P0{1}]; broken_p = true # Bernardi--Raugel
#####################################################################################
#####################################################################################
## negotiate data functions to the package
user_function_bnd = DataFunction(boundary_data_top!, [2,2]; name = "u_bnd", dependencies = "", quadorder = 0)
## load linear Stokes problem prototype and assign data
## we are adding the nonlinar convection term ourself below
## to discuss the details
StokesProblem = IncompressibleNavierStokesProblem(2; viscosity = viscosity, nonlinear = false)
add_boundarydata!(StokesProblem, 1, [1,2,4], HomogeneousDirichletBoundary)
add_boundarydata!(StokesProblem, 1, [3], BestapproxDirichletBoundary; data = user_function_bnd)
## store matrix of Laplace operator for nonlinear solver
StokesProblem.LHSOperators[1,1][1].store_operator = true
## add Newton for convection term
if ADnewton
## AUTOMATIC DIFFERENTATION
## requries kernel function for NonlinearForm action (u * grad) u
function ugradu_kernel_AD(result, input)
## input = [u, grad(u)]
## compute (u * grad) u = grad(u)*u
for j = 1 : 2
result[j] = 0.0
for k = 1 : 2
result[j] += input[k]*input[2 + (j-1)*2+k]
end
end
return nothing
end
action_kernel = ActionKernel(ugradu_kernel_AD, [2,6]; dependencies = "", quadorder = 1)
## generate and add nonlinear PDEOperator (modifications to RHS are taken care of automatically)
NLConvectionOperator = GenerateNonlinearForm("(u * grad) u * v", [Identity, Gradient], [1,1], Identity, action_kernel; ADnewton = true)
add_operator!(StokesProblem, [1,1], NLConvectionOperator)
else
## MANUAL DIFFERENTATION
## uses the following kernel function for the linearised convection operator
function ugradu_kernel_nonAD(result, input_current, input_ansatz)
## input_current = [current, grad(current)]
## input_ansatz = [ansatz, grad(ansatz)]
## compute (current * grad) ansatz + (current * grad) ansatz
for j = 1 : 2
result[j] = 0.0
for k = 1 : 2
result[j] += input_current[k]*input_ansatz[2 + (j-1)*2+k]
result[j] += input_ansatz[k]*input_current[2 + (j-1)*2+k]
end
end
return nothing
end
## and a similar kernel function for the right-hand side
function ugradu_kernel_rhs(result, input_current)
## input_current = [current, grad(current)]
## input_ansatz = [ansatz, grad(ansatz)]
## compute (current * grad) current
for j = 1 : 2
result[j] = 0.0
for k = 1 : 2
result[j] += input_current[k]*input_current[2 + (j-1)*2+k]
end
end
return nothing
end
newton_action_kernel = NLActionKernel(ugradu_kernel_nonAD, [2,6]; dependencies = "", quadorder = 1)
action_kernel_rhs = ActionKernel(ugradu_kernel_rhs, [2,6]; dependencies = "", quadorder = 1)
## generate and add nonlinear PDEOperator (modifications to RHS are taken care of by optional arguments)
NLConvectionOperator = GenerateNonlinearForm("(u * grad) u * v", [Identity, Gradient], [1,1], Identity, newton_action_kernel; ADnewton = false, action_kernel_rhs = action_kernel_rhs)
add_operator!(StokesProblem, [1,1], NLConvectionOperator)
end
## generate FESpaces
FESpaceVelocity = FESpace{FETypes[1]}(xgrid)
FESpacePressure = FESpace{FETypes[2]}(xgrid; broken = broken_p)
Solution = FEVector{Float64}("Stokes velocity",FESpaceVelocity)
append!(Solution,"Stokes pressure",FESpacePressure)
## show configuration and solve Stokes problem
Base.show(StokesProblem)
GradientRobustMultiPhysics.solve!(Solution, StokesProblem; verbosity = verbosity, maxIterations = maxIterations, maxResidual = maxResidual)
## plot
GradientRobustMultiPhysics.plot(Solution, [1,2], [Identity, Identity]; Plotter = Plotter, verbosity = verbosity, use_subplots = true)
true
end
| PDELib | https://github.com/WIAS-BERLIN/PDELib.jl.git |
|
[
"MIT"
] | 0.3.0 | 2fca7ee903e9c45871c1948e6b5fffdf359e2da3 | code | 1384 | using PDELib
using Triangulate
function fv_laplace_circle(;Plotter=nothing,nref=0)
function circle!(builder, center, radius; n=20*2^nref)
points=[point!(builder, center[1]+radius*sin(t),center[2]+radius*cos(t)) for t in range(0,2π,length=n)]
for i=1:n-1
facet!(builder,points[i],points[i+1])
end
facet!(builder,points[end],points[1])
end
builder=SimplexGridBuilder(Generator=Triangulate)
cellregion!(builder,1)
maxvolume!(builder,0.1)
regionpoint!(builder,0,0)
facetregion!(builder,1)
circle!(builder,(0,0),1)
facetregion!(builder,2)
circle!(builder,(-0.2,-0.2),0.2)
holepoint!(builder,-0.2,-0.2)
grid=simplexgrid(builder,maxvolume=0.1*4.0^(-nref))
function flux(f,u0,edge)
u=unknowns(edge,u0)
f[1]=u[1,1]-u[1,2]
end
physics=VoronoiFVM.Physics(num_species=1,flux=flux)
sys=VoronoiFVM.System(grid,physics)
ispec=1
enable_species!(sys,ispec,[1])
boundary_dirichlet!(sys,ispec,1,0.0)
boundary_dirichlet!(sys,ispec,2,1.0)
inival=unknowns(sys,inival=0)
solution=unknowns(sys)
VoronoiFVM.solve!(solution,inival,sys)
visualizer=GridVisualizer(Plotter=Plotter,layout=(1,2),resolution=(800,400))
gridplot!(visualizer[1,1],grid)
scalarplot!(visualizer[1,2],grid,solution[1,:])
reveal(visualizer)
true
end
| PDELib | https://github.com/WIAS-BERLIN/PDELib.jl.git |
|
[
"MIT"
] | 0.3.0 | 2fca7ee903e9c45871c1948e6b5fffdf359e2da3 | code | 614 | using PDELib
function fv_laplace_rect(;Plotter=nothing)
nspecies=1
ispec=1
X=collect(0:0.2:1)
function g!(f,u0,edge)
u=unknowns(edge,u0)
f[1]=u[1,1]-u[1,2]
end
grid=simplexgrid(X,X)
physics=VoronoiFVM.Physics(num_species=nspecies,flux=g!)
sys=VoronoiFVM.System(grid,physics)
enable_species!(sys,ispec,[1])
boundary_dirichlet!(sys,ispec,1,0.0)
boundary_dirichlet!(sys,ispec,3,1.0)
inival=unknowns(sys,inival=0)
solution=unknowns(sys)
VoronoiFVM.solve!(solution,inival,sys)
scalarplot(grid,solution[1,:],Plotter=Plotter)
true
end
| PDELib | https://github.com/WIAS-BERLIN/PDELib.jl.git |
|
[
"MIT"
] | 0.3.0 | 2fca7ee903e9c45871c1948e6b5fffdf359e2da3 | code | 244 | module PDELib
using Reexport
@reexport using ExtendableGrids
@reexport using GridVisualize
@reexport using ExtendableSparse
@reexport using SimplexGridFactory
@reexport using VoronoiFVM
@reexport using GradientRobustMultiPhysics
end # module
| PDELib | https://github.com/WIAS-BERLIN/PDELib.jl.git |
|
[
"MIT"
] | 0.3.0 | 2fca7ee903e9c45871c1948e6b5fffdf359e2da3 | code | 1074 | using Test
using PDELib
import Pluto, Pkg
function runtest(t)
include(joinpath(@__DIR__,"..","examples",t*".jl"))
eval(Meta.parse("$(t)()"))
end
@testset "VoronoiFVM" begin
@test runtest("fv_laplace_rect")
@test runtest("fv_laplace_circle")
end
@testset "GradientRobustMultiPhysics" begin
@info "GradientRobustMultiPhysics tests disabled in the moment"
# @test runtest("fe_liddrivencavity_autonewton")
end
function testnotebook(name)
input=joinpath(@__DIR__,"..","examples",name*".jl")
notebook=Pluto.load_notebook_nobackup(input)
session = Pluto.ServerSession();
notebook = Pluto.SessionActions.open(session,input; run_async=false)
errored=false
for c in notebook.cells
if c.errored
errored=true
@error "Error in $(c.cell_id): $(c.output.body[:msg])\n $(c.code)"
end
end
!errored
end
notebooks=["Pluto-GridsAndVisualization",
"Pluto-MultECatGrids"]
@testset "Notebooks" begin
for notebook in notebooks
@test testnotebook(notebook)
end
end
| PDELib | https://github.com/WIAS-BERLIN/PDELib.jl.git |
|
[
"MIT"
] | 0.3.0 | 2fca7ee903e9c45871c1948e6b5fffdf359e2da3 | code | 458 | using Pkg
Pkg.activate(".")
Pkg.instantiate()
using Pluto
using PDELib
Pkg.update()
notebooks=["examples/Pluto-GridsAndVisualization.jl",
"examples/Pluto-MultECatGrids.jl"]
for notebook in notebooks
println("Updating packages in $(notebook):")
Pluto.activate_notebook_environment(notebook)
Pkg.update()
Pkg.status()
run(`git diff $(notebook)`)
println("Updating of $(notebook) done\n")
Pkg.activate(".")
end
| PDELib | https://github.com/WIAS-BERLIN/PDELib.jl.git |
|
[
"MIT"
] | 0.3.0 | 2fca7ee903e9c45871c1948e6b5fffdf359e2da3 | docs | 3172 | [](https://github.com/WIAS-BERLIN/PDELib.jl/actions)
[](https://wias-berlin.github.io/PDELib.jl/dev/)
PDELib.jl
=========
This is a meta package which re-exports several Julia packages
developed and maintained by the [WIAS](https://www.wias-berlin.de) research group [Numerical
Mathematics and Scientific Computing](https://www.wias-berlin.de/research/rgs/fg3/) and various coauthors,
inspired by [pdelib](https://pdelib.org) which was implemented in C++ and python.
The final workflow for maintaining this meta package has not yet been established.
Currently, it is advisable to add the packages listed below one-by-one.
## Packages re-exported
- [VoronoiFVM.jl](https://github.com/j-fu/VoronoiFVM.jl): a finite volume solver for systems of nonlinear PDEs
- [GradientRobustMultiPhysics.jl](https://github.com/chmerdon/GradientRobustMultiPhysics.jl): finite element library implementing gradient robust FEM
- [ExtendableGrids.jl](https://github.com/j-fu/ExtendableGrids.jl): unstructured grid management library
- [GridVisualize.jl](https://github.com/j-fu/GridVisualize.jl): grid and function visualization related to ExtendableGrids.jl
- [SimplexGridFactory.jl](https://github.com/j-fu/SimplexGridFactory.jl): unified high level mesh generator interface
- [ExtendableSparse.jl](https://github.com/j-fu/ExtendableSparse.jl): convenient and efficient sparse matrix assembly
## Packages associated
- [PlutoVista.jl](https://github.com/j-fu/PlutoVista.jl): Backend for using GridVisualize.jl in Pluto notebooks based on Plotly.js and vtk.js
- [VoronoiFVMDiffEq.jl](https://github.com/j-fu/VoronoiFVMDiffEq.jl): glue package for using VoronoiFVM.jl together with DifferentialEquations.jl
- [GridVisualizeTools.jl](https://github.com/j-fu/GridVisualizeTools.jl): some tools for GridVisualize.jl and PlutoVista.jl
## Additional packages maintained
Not part of PDELib.jl, but maintained as part of the project:
- [Triangulate.jl](https://github.com/JuliaGeometry/Triangulate.jl), [Triangle_jll.jl](https://github.com/JuliaBinaryWrappers/Triangle_jll.jl): Julia wrapper and binary package of the [Triangle](https://www.cs.cmu.edu/~quake/triangle.html) triangle mesh generator by J. Shewchuk
- [TetGen.jl](https://github.com/JuliaGeometry/TetGen.jl),[TetGen_jll.jl](https://github.com/JuliaBinaryWrappers/TetGen_jll.jl): (co-maintained with [S. Danisch](https://github.com/SimonDanisch)): Julia wrapper binary package of the [TetGen](http://www.tetgen.org) tetrahedral mesh generator by H. Si.
## Documentation and examples
Some examples are collected in the [examples](https://github.com/WIAS-BERLIN/PDELib.jl/tree/main/examples) subdirectory.
More up-to-date examples and documentation are found in the respective package repositories, mainly in
- [VoronoiFVM.jl](https://j-fu.github.io/VoronoiFVM.jl/stable/)
- [GradientRobustMultiPhysics.jl](https://chmerdon.github.io/GradientRobustMultiPhysics.jl/stable/)
- [VoronoiFVMDiffEq.jl](https://j-fu.github.io/VoronoiFVMDiffEq.jl/stable/)
| PDELib | https://github.com/WIAS-BERLIN/PDELib.jl.git |
|
[
"MIT"
] | 0.3.0 | 2fca7ee903e9c45871c1948e6b5fffdf359e2da3 | docs | 88 | ````@eval
using Markdown
Markdown.parse("""
$(read("../../README.md",String))
""")
````
| PDELib | https://github.com/WIAS-BERLIN/PDELib.jl.git |
|
[
"MIT"
] | 0.3.0 | 2fca7ee903e9c45871c1948e6b5fffdf359e2da3 | docs | 455 | # Introductory material
## Grid generation and visualization
- Pluto notebook: [source](https://raw.githubusercontent.com/WIAS-BERLIN/PDELib.jl/main/examples/GridsAndVisualization.jl)
[html](GridsAndVisualization.html)
```@raw html
<iframe id="installation" height="300" src="https://www.youtube.com/embed/dw1djnkWWDQ" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen=""></iframe>
```
| PDELib | https://github.com/WIAS-BERLIN/PDELib.jl.git |
|
[
"MIT"
] | 0.2.5 | 963a3f28a2e65bb87a68033ea4a616002406037d | code | 673 | using Documenter, OneHotArrays
DocMeta.setdocmeta!(OneHotArrays, :DocTestSetup, :(using OneHotArrays); recursive = true)
makedocs(sitename = "OneHotArrays.jl",
doctest = false,
pages = ["Overview" => "index.md",
"Reference" => "reference.md"],
format = Documenter.HTML(
canonical = "https://fluxml.ai/OneHotArrays.jl/stable/",
# analytics = "UA-36890222-9",
assets = ["assets/flux.css"],
prettyurls = get(ENV, "CI", nothing) == "true"
),
)
deploydocs(repo = "github.com/FluxML/OneHotArrays.jl.git",
target = "build",
push_preview = true)
| OneHotArrays | https://github.com/FluxML/OneHotArrays.jl.git |
|
[
"MIT"
] | 0.2.5 | 963a3f28a2e65bb87a68033ea4a616002406037d | code | 292 | module OneHotArrays
using Adapt
using ChainRulesCore
using GPUArraysCore
using LinearAlgebra
using Compat: Compat
using NNlib
export onehot, onehotbatch, onecold,
OneHotArray, OneHotVector, OneHotMatrix, OneHotLike
include("array.jl")
include("onehot.jl")
include("linalg.jl")
end
| OneHotArrays | https://github.com/FluxML/OneHotArrays.jl.git |
|
[
"MIT"
] | 0.2.5 | 963a3f28a2e65bb87a68033ea4a616002406037d | code | 6548 | """
OneHotArray{T, N, M, I} <: AbstractArray{Bool, M}
OneHotArray(indices, L)
A one-hot `M`-dimensional array with `L` labels (i.e. `size(A, 1) == L` and `sum(A, dims=1) == 1`)
stored as a compact `N == M-1`-dimensional array of indices.
Typically constructed by [`onehot`](@ref) and [`onehotbatch`](@ref).
Parameter `I` is the type of the underlying storage, and `T` its eltype.
"""
struct OneHotArray{T<:Integer, N, var"N+1", I<:Union{T, AbstractArray{T, N}}} <: AbstractArray{Bool, var"N+1"}
indices::I
nlabels::Int
end
OneHotArray{T, N, I}(indices, L::Int) where {T, N, I} = OneHotArray{T, N, N+1, I}(indices, L)
OneHotArray(indices::T, L::Int) where {T<:Integer} = OneHotArray{T, 0, 1, T}(indices, L)
OneHotArray(indices::I, L::Int) where {T, N, I<:AbstractArray{T, N}} = OneHotArray{T, N, N+1, I}(indices, L)
_indices(x::OneHotArray) = x.indices
_indices(x::Base.ReshapedArray{<:Any, <:Any, <:OneHotArray}) =
reshape(parent(x).indices, x.dims[2:end])
"""
OneHotVector{T} = OneHotArray{T, 0, 1, T}
OneHotVector(indices, L)
A one-hot vector with `L` labels (i.e. `length(A) == L` and `count(A) == 1`) typically constructed by [`onehot`](@ref).
Stored efficiently as a single index of type `T`, usually `UInt32`.
"""
const OneHotVector{T} = OneHotArray{T, 0, 1, T}
OneHotVector(idx, L) = OneHotArray(idx, L)
"""
OneHotMatrix{T, I} = OneHotArray{T, 1, 2, I}
OneHotMatrix(indices, L)
A one-hot matrix (with `L` labels) typically constructed using [`onehotbatch`](@ref).
Stored efficiently as a vector of indices with type `I` and eltype `T`.
"""
const OneHotMatrix{T, I} = OneHotArray{T, 1, 2, I}
OneHotMatrix(indices, L) = OneHotArray(indices, L)
# use this type so reshaped arrays hit fast paths
# e.g. argmax
const OneHotLike{T, N, var"N+1", I} =
Union{OneHotArray{T, N, var"N+1", I},
Base.ReshapedArray{Bool, var"N+1", <:OneHotArray{T, <:Any, <:Any, I}}}
_isonehot(x::OneHotArray) = true
_isonehot(x::Base.ReshapedArray{<:Any, <:Any, <:OneHotArray}) = (size(x, 1) == parent(x).nlabels)
_check_nlabels(L, xs::OneHotLike...) = all(size.(xs, 1) .== L)
_nlabels(x::OneHotArray) = size(x, 1)
function _nlabels(x::OneHotLike, xs::OneHotLike...)
L = size(x, 1)
_check_nlabels(L, xs...) ||
throw(DimensionMismatch("The number of labels are not the same for all one-hot arrays."))
return L
end
Base.size(x::OneHotArray) = (x.nlabels, size(x.indices)...)
function Base.getindex(x::OneHotArray{<:Any, N}, i::Int, I::Vararg{Int, N}) where N
@boundscheck (1 <= i <= x.nlabels) || throw(BoundsError(x, (i, I...)))
return x.indices[I...] .== i
end
# the method above is faster on the CPU but will scalar index on the GPU
# so we define the method below to pass the extra indices directly to GPU array
function Base.getindex(x::OneHotArray{<:Any, N, <:Any, <:AbstractGPUArray},
i::Int,
I::Vararg{Any, N}) where N
@boundscheck (1 <= i <= x.nlabels) || throw(BoundsError(x, (i, I...)))
return x.indices[I...] .== i
end
function Base.getindex(x::OneHotArray{<:Any, N}, ::Colon, I::Vararg{Any, N}) where N
return OneHotArray(x.indices[I...], x.nlabels)
end
Base.getindex(x::OneHotArray, ::Colon) = BitVector(reshape(x, :))
Base.getindex(x::OneHotArray{<:Any, N}, ::Colon, ::Vararg{Colon, N}) where N = x
function Base.showarg(io::IO, x::OneHotArray, toplevel)
print(io, ndims(x) == 1 ? "OneHotVector(" : ndims(x) == 2 ? "OneHotMatrix(" : "OneHotArray(")
Base.showarg(io, x.indices, false)
print(io, ')')
toplevel && print(io, " with eltype Bool")
return nothing
end
# this is from /LinearAlgebra/src/diagonal.jl, official way to print the dots:
function Base.replace_in_print_matrix(x::OneHotLike, i::Integer, j::Integer, s::AbstractString)
x[i,j] ? s : _isonehot(x) ? Base.replace_with_centered_mark(s) : s
end
# copy CuArray versions back before trying to print them:
for fun in (:show, :print_array) # print_array is used by 3-arg show
@eval begin
Base.$fun(io::IO, X::OneHotLike{T, N, var"N+1", <:AbstractGPUArray}) where {T, N, var"N+1"} =
Base.$fun(io, adapt(Array, X))
Base.$fun(io::IO, X::LinearAlgebra.AdjOrTrans{Bool, <:OneHotLike{T, N, <:Any, <:AbstractGPUArray}}) where {T, N} =
Base.$fun(io, adapt(Array, X))
end
end
_onehot_bool_type(::OneHotLike{<:Any, <:Any, var"N+1", <:Union{Integer, AbstractArray}}) where {var"N+1"} = Array{Bool, var"N+1"}
_onehot_bool_type(::OneHotLike{<:Any, <:Any, var"N+1", <:AbstractGPUArray}) where {var"N+1"} = AbstractGPUArray{Bool, var"N+1"}
_notall_onehot(x::OneHotArray, xs::OneHotArray...) = false
_notall_onehot(x::OneHotLike, xs::OneHotLike...) = any(x -> !_isonehot(x), (x, xs...))
function Base.cat(x::OneHotLike{<:Any, <:Any, N}, xs::OneHotLike...; dims::Int) where N
if isone(dims) || _notall_onehot(x, xs...)
return cat(map(x -> convert(_onehot_bool_type(x), x), (x, xs...))...; dims = dims)
else
L = _nlabels(x, xs...)
return OneHotArray(cat(_indices(x), _indices.(xs)...; dims = dims - 1), L)
end
end
Base.hcat(x::OneHotLike, xs::OneHotLike...) = cat(x, xs...; dims = 2)
Base.vcat(x::OneHotLike, xs::OneHotLike...) =
vcat(map(x -> convert(_onehot_bool_type(x), x), (x, xs...))...)
# optimized concatenation for matrices and vectors of same parameters
Base.hcat(x::OneHotMatrix, xs::OneHotMatrix...) =
OneHotMatrix(reduce(vcat, _indices.(xs); init = _indices(x)), _nlabels(x, xs...))
Base.hcat(x::OneHotVector, xs::OneHotVector...) =
OneHotMatrix(reduce(vcat, _indices.(xs); init = _indices(x)), _nlabels(x, xs...))
if isdefined(Base, :stack)
import Base: _stack
else
import Compat: _stack
end
function _stack(::Colon, xs::AbstractArray{<:OneHotArray})
n = _nlabels(first(xs))
all(x -> _nlabels(x)==n, xs) || throw(DimensionMismatch("The number of labels are not the same for all one-hot arrays."))
OneHotArray(Compat.stack(_indices, xs), n)
end
Adapt.adapt_structure(T, x::OneHotArray) = OneHotArray(adapt(T, _indices(x)), x.nlabels)
function Base.BroadcastStyle(::Type{<:OneHotArray{<:Any, <:Any, var"N+1", T}}) where {var"N+1", T <: AbstractGPUArray}
# We want CuArrayStyle{N+1}(). There's an AbstractGPUArrayStyle but it doesn't do what we need.
S = Base.BroadcastStyle(T)
typeof(S)(Val{var"N+1"}())
end
Base.map(f, x::OneHotLike) = Base.broadcast(f, x)
Base.argmax(x::OneHotLike; dims = Colon()) =
(_isonehot(x) && dims == 1) ?
reshape(CartesianIndex.(_indices(x), CartesianIndices(_indices(x))), 1, size(_indices(x))...) :
invoke(argmax, Tuple{AbstractArray}, x; dims = dims)
| OneHotArrays | https://github.com/FluxML/OneHotArrays.jl.git |
|
[
"MIT"
] | 0.2.5 | 963a3f28a2e65bb87a68033ea4a616002406037d | code | 1561 | function Base.:(*)(A::AbstractMatrix, B::OneHotLike)
_isonehot(B) || return invoke(*, Tuple{AbstractMatrix, AbstractMatrix}, A, B)
size(A, 2) == size(B, 1) || throw(DimensionMismatch("Matrix column must correspond with OneHot size: $(size(A, 2)) != $(size(B, 1))"))
return A[:, onecold(B)]
end
function Base.:(*)(A::AbstractMatrix, B::OneHotLike{<:Any, 1})
_isonehot(B) || return invoke(*, Tuple{AbstractMatrix, AbstractMatrix}, A, B)
size(A, 2) == size(B, 1) || throw(DimensionMismatch("Matrix column must correspond with OneHot size: $(size(A, 2)) != $(size(B, 1))"))
return NNlib.gather(A, _indices(B))
end
function Base.:(*)(A::AbstractMatrix, B::Adjoint{Bool, <:OneHotMatrix})
B_dim = length(_indices(parent(B)))
size(A, 2) == B_dim || throw(DimensionMismatch("Matrix column must correspond with OneHot size: $(size(A, 2)) != $B_dim"))
return NNlib.scatter(+, A, _indices(parent(B)), dstsize=(size(A,1), size(B,2)))
end
for wrapper in [:Adjoint, :Transpose]
@eval begin
function Base.:*(A::$wrapper{<:Any, <:AbstractMatrix{T}}, b::OneHotVector) where T
size(A, 2) == length(b) ||
throw(DimensionMismatch("Matrix column must correspond with OneHot size: $(size(A, 2)) != $(length(b))"))
return A[:, onecold(b)]
end
function Base.:*(A::$wrapper{<:Number, <:AbstractVector{T}}, b::OneHotVector) where T
size(A, 2) == length(b) ||
throw(DimensionMismatch("Matrix column must correspond with OneHot size: $(size(A, 2)) != $(length(b))"))
return A[onecold(b)]
end
end
end
| OneHotArrays | https://github.com/FluxML/OneHotArrays.jl.git |
|
[
"MIT"
] | 0.2.5 | 963a3f28a2e65bb87a68033ea4a616002406037d | code | 6277 | """
onehot(x, labels, [default])
Returns a [`OneHotVector`](@ref) which is roughly a sparse representation of `x .== labels`.
Instead of storing say `Vector{Bool}`, it stores the index of the first occurrence
of `x` in `labels`. If `x` is not found in labels, then it either returns `onehot(default, labels)`,
or gives an error if no default is given.
See also [`onehotbatch`](@ref) to apply this to many `x`s,
and [`onecold`](@ref) to reverse either of these, as well as to generalise `argmax`.
# Examples
```jldoctest
julia> β = onehot(:b, (:a, :b, :c))
3-element OneHotVector(::UInt32) with eltype Bool:
⋅
1
⋅
julia> αβγ = (onehot(0, 0:2), β, onehot(:z, [:a, :b, :c], :c)) # uses default
(Bool[1, 0, 0], Bool[0, 1, 0], Bool[0, 0, 1])
julia> hcat(αβγ...) # preserves sparsity
3×3 OneHotMatrix(::Vector{UInt32}) with eltype Bool:
1 ⋅ ⋅
⋅ 1 ⋅
⋅ ⋅ 1
```
"""
function onehot(x, labels)
i = _findval(x, labels)
isnothing(i) && error("Value $x is not in labels")
OneHotVector{UInt32}(i, length(labels))
end
function onehot(x, labels, default)
i = _findval(x, labels)
isnothing(i) && return onehot(default, labels)
OneHotVector{UInt32}(i, length(labels))
end
_findval(val, labels) = findfirst(isequal(val), labels)
# Fast unrolled method for tuples:
function _findval(val, labels::Tuple, i::Integer=1)
ifelse(isequal(val, first(labels)), i, _findval(val, Base.tail(labels), i+1))
end
_findval(val, labels::Tuple{}, i::Integer) = nothing
"""
onehotbatch(xs, labels, [default])
Returns a [`OneHotMatrix`](@ref) where `k`th column of the matrix is [`onehot(xs[k], labels)`](@ref onehot).
This is a sparse matrix, which stores just a `Vector{UInt32}` containing the indices of the
nonzero elements.
If one of the inputs in `xs` is not found in `labels`, that column is `onehot(default, labels)`
if `default` is given, else an error.
If `xs` has more dimensions, `N = ndims(xs) > 1`, then the result is an
`AbstractArray{Bool, N+1}` which is one-hot along the first dimension,
i.e. `result[:, k...] == onehot(xs[k...], labels)`.
Note that `xs` can be any iterable, such as a string. And that using a tuple
for `labels` will often speed up construction, certainly for less than 32 classes.
# Examples
```jldoctest
julia> oh = onehotbatch("abracadabra", 'a':'e', 'e')
5×11 OneHotMatrix(::Vector{UInt32}) with eltype Bool:
1 ⋅ ⋅ 1 ⋅ 1 ⋅ 1 ⋅ ⋅ 1
⋅ 1 ⋅ ⋅ ⋅ ⋅ ⋅ ⋅ 1 ⋅ ⋅
⋅ ⋅ ⋅ ⋅ 1 ⋅ ⋅ ⋅ ⋅ ⋅ ⋅
⋅ ⋅ ⋅ ⋅ ⋅ ⋅ 1 ⋅ ⋅ ⋅ ⋅
⋅ ⋅ 1 ⋅ ⋅ ⋅ ⋅ ⋅ ⋅ 1 ⋅
julia> reshape(1:15, 3, 5) * oh # this matrix multiplication is done efficiently
3×11 Matrix{Int64}:
1 4 13 1 7 1 10 1 4 13 1
2 5 14 2 8 2 11 2 5 14 2
3 6 15 3 9 3 12 3 6 15 3
```
"""
onehotbatch(data, labels, default...) = _onehotbatch(data, length(labels) < 32 ? Tuple(labels) : labels, default...)
function _onehotbatch(data, labels)
indices = UInt32[something(_findval(i, labels), 0) for i in data]
if 0 in indices
for x in data
isnothing(_findval(x, labels)) && error("Value $x not found in labels")
end
end
return OneHotArray(indices, length(labels))
end
function _onehotbatch(data, labels, default)
default_index = _findval(default, labels)
isnothing(default_index) && error("Default value $default is not in labels")
indices = UInt32[something(_findval(i, labels), default_index) for i in data]
return OneHotArray(indices, length(labels))
end
function onehotbatch(data::AbstractArray{<:Integer}, labels::AbstractUnitRange{<:Integer})
lo, hi = extrema(data)
lo < first(labels) && error("Value $lo not found in labels")
hi > last(labels) && error("Value $hi not found in labels")
offset = 1 - first(labels)
indices = UInt32.(data .+ offset)
return OneHotArray(indices, length(labels))
end
# That bounds check with extrema synchronises on GPU, much slower than rest of the function,
# hence add a special method, with a less helpful error message:
function onehotbatch(data::AbstractGPUArray{<:Integer}, labels::AbstractUnitRange{<:Integer})
offset = 1 - first(labels)
indices = map(data) do datum
i = UInt32(datum + offset)
checkbounds(labels, i)
i
end
return OneHotArray(indices, length(labels))
end
"""
onecold(y::AbstractArray, labels = 1:size(y,1))
Roughly the inverse operation of [`onehot`](@ref) or [`onehotbatch`](@ref):
This finds the index of the largest element of `y`, or each column of `y`,
and looks them up in `labels`.
If `labels` are not specified, the default is integers `1:size(y,1)` --
the same operation as `argmax(y, dims=1)` but sometimes a different return type.
# Examples
```jldoctest
julia> onecold([false, true, false])
2
julia> onecold([0.3, 0.2, 0.5], (:a, :b, :c))
:c
julia> onecold([ 1 0 0 1 0 1 0 1 0 0 1
0 1 0 0 0 0 0 0 1 0 0
0 0 0 0 1 0 0 0 0 0 0
0 0 0 0 0 0 1 0 0 0 0
0 0 1 0 0 0 0 0 0 1 0 ], 'a':'e') |> String
"abeacadabea"
```
"""
function onecold(y::AbstractVector, labels = 1:length(y))
nl = length(labels)
ny = length(y)
nl == ny || throw(DimensionMismatch("onecold got $nl labels for a vector of length $ny, these must agree"))
ymax, i = findmax(y)
ymax isa Number && isnan(ymax) && throw(ArgumentError("maximum value found by onecold is $ymax"))
labels[i]
end
function onecold(y::AbstractArray, labels = 1:size(y, 1))
nl = length(labels)
ny = size(y, 1)
nl == ny || throw(DimensionMismatch("onecold got $nl labels for an array with size(y, 1) == $ny, these must agree"))
indices = _fast_argmax(y)
xs = isbits(labels) ? indices : collect(indices) # non-bit type cannot be handled by CUDA
return map(xi -> labels[xi[1]], xs)
end
_fast_argmax(x::AbstractArray) = dropdims(argmax(x; dims = 1); dims = 1)
_fast_argmax(x::OneHotArray) = _indices(x)
function _fast_argmax(x::OneHotLike)
if _isonehot(x)
return _indices(x)
else
return _fast_argmax(convert(_onehot_bool_type(x), x))
end
end
ChainRulesCore.@non_differentiable onehot(::Any...)
ChainRulesCore.@non_differentiable onehotbatch(::Any...)
ChainRulesCore.@non_differentiable onecold(::Any...)
ChainRulesCore.@non_differentiable (::Type{<:OneHotArray})(indices::Any, L::Int)
| OneHotArrays | https://github.com/FluxML/OneHotArrays.jl.git |
|
[
"MIT"
] | 0.2.5 | 963a3f28a2e65bb87a68033ea4a616002406037d | code | 3672 | ov = OneHotVector(rand(1:10), 10)
ov2 = OneHotVector(rand(1:11), 11)
om = OneHotMatrix(rand(1:10, 5), 10)
om2 = OneHotMatrix(rand(1:11, 5), 11)
oa = OneHotArray(rand(1:10, 5, 5), 10)
# sizes
@testset "Base.size" begin
@test size(ov) == (10,)
@test size(om) == (10, 5)
@test size(oa) == (10, 5, 5)
end
@testset "Indexing" begin
# vector indexing
@test ov[3] == (ov.indices == 3)
@test ov[:] == ov
# matrix indexing
@test om[3, 3] == (om.indices[3] == 3)
@test om[:, 3] == OneHotVector(om.indices[3], 10)
@test om[3, :] == (om.indices .== 3)
@test om[:, :] == om
@test om[:] == reshape(om, :)
# array indexing
@test oa[3, 3, 3] == (oa.indices[3, 3] == 3)
@test oa[:, 3, 3] == OneHotVector(oa.indices[3, 3], 10)
@test oa[3, :, 3] == (oa.indices[:, 3] .== 3)
@test oa[3, :, :] == (oa.indices .== 3)
@test oa[:, 3, :] == OneHotMatrix(oa.indices[3, :], 10)
@test oa[:, :, :] == oa
@test oa[:] == reshape(oa, :)
# cartesian indexing
@test oa[CartesianIndex(3, 3, 3)] == oa[3, 3, 3]
# linear indexing
@test om[11] == om[1, 2]
@test oa[52] == oa[2, 1, 2]
# bounds checks
@test_throws BoundsError ov[0]
@test_throws BoundsError om[2, -1]
@test_throws BoundsError oa[11, 5, 5]
@test_throws BoundsError oa[:, :]
end
@testset "Concatenating" begin
# vector cat
@test hcat(ov, ov) == OneHotMatrix(vcat(ov.indices, ov.indices), 10)
@test hcat(ov, ov) isa OneHotMatrix
@test vcat(ov, ov) == vcat(collect(ov), collect(ov))
@test cat(ov, ov; dims = 3) == OneHotArray(cat(ov.indices, ov.indices; dims = 2), 10)
# matrix cat
@test hcat(om, om) == OneHotMatrix(vcat(om.indices, om.indices), 10)
@test hcat(om, om) isa OneHotMatrix
@test vcat(om, om) == vcat(collect(om), collect(om))
@test cat(om, om; dims = 3) == OneHotArray(cat(om.indices, om.indices; dims = 2), 10)
# array cat
@test cat(oa, oa; dims = 3) == OneHotArray(cat(oa.indices, oa.indices; dims = 2), 10)
@test cat(oa, oa; dims = 3) isa OneHotArray
@test cat(oa, oa; dims = 1) == cat(collect(oa), collect(oa); dims = 1)
# stack
@test stack([ov, ov]) == hcat(ov, ov)
@test stack([ov, ov, ov]) isa OneHotMatrix
@test stack([om, om]) == cat(om, om; dims = 3)
@test stack([om, om]) isa OneHotArray
@test stack([oa, oa, oa, oa]) isa OneHotArray
# proper error handling of inconsistent sizes
@test_throws DimensionMismatch hcat(ov, ov2)
@test_throws DimensionMismatch hcat(om, om2)
end
@testset "Base.reshape" begin
# reshape test
@test reshape(oa, 10, 25) isa OneHotLike
@test reshape(oa, 10, :) isa OneHotLike
@test reshape(oa, :, 25) isa OneHotLike
@test reshape(oa, 50, :) isa OneHotLike
@test reshape(oa, 5, 10, 5) isa OneHotLike
@test reshape(oa, (10, 25)) isa OneHotLike
@testset "w/ cat" begin
r = reshape(oa, 10, :)
@test hcat(r, r) isa OneHotArray
@test vcat(r, r) isa Array{Bool}
end
@testset "w/ argmax" begin
r = reshape(oa, 10, :)
@test argmax(r) == argmax(OneHotMatrix(reshape(oa.indices, :), 10))
@test OneHotArrays._fast_argmax(r) == collect(reshape(oa.indices, :))
end
end
@testset "Base.argmax" begin
# argmax test
@test argmax(ov) == argmax(convert(Array{Bool}, ov))
@test argmax(om) == argmax(convert(Array{Bool}, om))
@test argmax(om; dims = 1) == argmax(convert(Array{Bool}, om); dims = 1)
@test argmax(om; dims = 2) == argmax(convert(Array{Bool}, om); dims = 2)
@test argmax(oa; dims = 1) == argmax(convert(Array{Bool}, oa); dims = 1)
@test argmax(oa; dims = 3) == argmax(convert(Array{Bool}, oa); dims = 3)
end
@testset "Forward map to broadcast" begin
@test map(identity, oa) == oa
@test map(x -> 2 * x, oa) == 2 .* oa
end
| OneHotArrays | https://github.com/FluxML/OneHotArrays.jl.git |
|
[
"MIT"
] | 0.2.5 | 963a3f28a2e65bb87a68033ea4a616002406037d | code | 2074 |
# Tests from Flux, probably not the optimal testset organisation!
@testset "CUDA" begin
x = randn(5, 5)
cx = cu(x)
@test cx isa CuArray
@test_skip onecold(cu([1.0, 2.0, 3.0])) == 3 # passes with CuArray with Julia 1.6, but fails with JLArray
x = onehotbatch([1, 2, 3], 1:3)
cx = cu(x)
@test cx isa OneHotMatrix && cx.indices isa CuArray
@test (cx .+ 1) isa CuArray
xs = rand(5, 5)
ys = onehotbatch(1:5,1:5)
@test collect(cu(xs) .+ cu(ys)) ≈ collect(xs .+ ys)
end
@testset "onehot gpu" begin
y = onehotbatch(ones(3), 1:2) |> cu;
@test (repr("text/plain", y); true)
gA = rand(3, 2) |> cu;
if VERSION >= v"1.9" && CUDA.functional()
@test gradient(A -> sum(A * y), gA)[1] isa CuArray
else
@test_broken gradient(A -> sum(A * y), gA)[1] isa CuArray # fails with JLArray, bug in Zygote?
end
end
@testset "onehotbatch(::CuArray, ::UnitRange)" begin
y1 = onehotbatch([1, 3, 0, 2], 0:9) |> cu
y2 = onehotbatch([1, 3, 0, 2] |> cu, 0:9)
@test y1.indices == y2.indices
@test_broken y1 == y2 # issue 28
if !CUDA.functional()
# Here CUDA gives an error which @test_throws does not notice,
# although with JLArrays @test_throws it's fine.
@test_throws Exception onehotbatch([1, 3, 0, 2] |> cu, 1:10)
@test_throws Exception onehotbatch([1, 3, 0, 2] |> cu, -2:2)
end
end
@testset "onecold gpu" begin
y = onehotbatch(ones(3), 1:10) |> cu;
l = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
@test onecold(y) isa CuArray
@test y[3,:] isa CuArray
@test onecold(y, l) == ['a', 'a', 'a']
end
@testset "onehot forward map to broadcast" begin
oa = OneHotArray(rand(1:10, 5, 5), 10) |> cu
@test all(map(identity, oa) .== oa)
@test all(map(x -> 2 * x, oa) .== 2 .* oa)
end
@testset "show gpu" begin
x = onehotbatch([1, 2, 3], 1:3)
cx = cu(x)
# 3-arg show
@test contains(repr("text/plain", cx), "1 ⋅ ⋅")
@test contains(repr("text/plain", cx), string(typeof(cx.indices)))
# 2-arg show, https://github.com/FluxML/Flux.jl/issues/1905
@test repr(cx) == "Bool[1 0 0; 0 1 0; 0 0 1]"
end
| OneHotArrays | https://github.com/FluxML/OneHotArrays.jl.git |
|
[
"MIT"
] | 0.2.5 | 963a3f28a2e65bb87a68033ea4a616002406037d | code | 1511 | @testset "abstractmatrix onehotvector multiplication" begin
A = [1 3 5; 2 4 6; 3 6 9]
v = [1, 2, 3, 4, 5]
X = reshape(v, (5, 1))
b1 = OneHotVector(1, 3)
b2 = OneHotVector(3, 5)
@test A * b1 == A[:,1]
@test b1' * A == Array(b1') * A
@test A' * b1 == A' * Array(b1)
@test v' * b2 == v' * Array(b2)
@test transpose(X) * b2 == transpose(X) * Array(b2)
@test transpose(v) * b2 == transpose(v) * Array(b2)
@test_throws DimensionMismatch A*b2
end
@testset "AbstractMatrix-OneHotMatrix multiplication" begin
A = [1 3 5; 2 4 6; 3 6 9]
v = [1, 2, 3, 4, 5]
X = reshape(v, (5, 1))
b1 = OneHotMatrix([1, 1, 2, 2], 3)
b2 = OneHotMatrix([2, 4, 1, 3], 5)
b3 = OneHotMatrix([1, 1, 2], 4)
b4 = reshape(OneHotMatrix([1 2 3; 2 2 1], 3), 3, :)
b5 = reshape(b4, 6, :)
b6 = reshape(OneHotMatrix([1 2 2; 2 2 1], 2), 3, :)
b7 = reshape(OneHotMatrix([1 2 3; 1 2 3], 3), 6, :)
@test A * b1 == A[:,[1, 1, 2, 2]]
@test b1' * A == Array(b1') * A
@test A' * b1 == A' * Array(b1)
@test A * b3' == A * Array(b3')
@test transpose(X) * b2 == transpose(X) * Array(b2)
@test A * b4 == A[:,[1, 2, 2, 2, 3, 1]]
@test A * b5' == hcat(A[:,[1, 2, 3, 3]], A[:,1]+A[:,2], zeros(Int64, 3))
@test A * b6 == hcat(A[:,1], 2*A[:,2], A[:,2], A[:,1]+A[:,2])
@test A * b7' == A[:,[1, 2, 3, 1, 2, 3]]
@test_throws DimensionMismatch A*b1'
@test_throws DimensionMismatch A*b2
@test_throws DimensionMismatch A*b2'
@test_throws DimensionMismatch A*b6'
@test_throws DimensionMismatch A*b7
end
| OneHotArrays | https://github.com/FluxML/OneHotArrays.jl.git |
|
[
"MIT"
] | 0.2.5 | 963a3f28a2e65bb87a68033ea4a616002406037d | code | 2697 | @testset "onehot constructors" begin
@test onehot(20, 10:10:30) == [false, true, false]
@test onehot(20, (10,20,30)) == [false, true, false]
@test onehot(40, (10,20,30), 20) == [false, true, false]
@test_throws Exception onehot('d', 'a':'c')
@test_throws Exception onehot(:d, (:a, :b, :c))
@test_throws Exception onehot('d', 'a':'c', 'e')
@test_throws Exception onehot(:d, (:a, :b, :c), :e)
@test onehotbatch([20, 10], 10:10:30) == Bool[0 1; 1 0; 0 0]
@test onehotbatch([20, 10], (10,20,30)) == Bool[0 1; 1 0; 0 0]
@test onehotbatch([40, 10], (10,20,30), 20) == Bool[0 1; 1 0; 0 0]
@test onehotbatch("abc", 'a':'c') == Bool[1 0 0; 0 1 0; 0 0 1]
@test onehotbatch("zbc", ('a', 'b', 'c'), 'a') == Bool[1 0 0; 0 1 0; 0 0 1]
@test onehotbatch([10, 20], [30, 40, 50], 30) == Bool[1 1; 0 0; 0 0]
@test_throws Exception onehotbatch([:a, :d], [:a, :b, :c])
@test_throws Exception onehotbatch([:a, :d], (:a, :b, :c))
@test_throws Exception onehotbatch([:a, :d], [:a, :b, :c], :e)
@test_throws Exception onehotbatch([:a, :d], (:a, :b, :c), :e)
floats = (0.0, -0.0, NaN, -NaN, Inf, -Inf)
@test onecold(onehot(0.0, floats)) == 1
@test onecold(onehot(-0.0, floats)) == 2 # as it uses isequal
@test onecold(onehot(Inf, floats)) == 5
# UnitRange fast path
@test onehotbatch([1,3,0,4], 0:4) == onehotbatch([1,3,0,4], Tuple(0:4))
@test onehotbatch([2 3 7 4], 2:7) == onehotbatch([2 3 7 4], Tuple(2:7))
@test_throws Exception onehotbatch([2, -1], 0:4)
@test_throws Exception onehotbatch([2, 5], 0:4)
# inferrabiltiy tests
@test @inferred(onehot(20, 10:10:30)) == [false, true, false]
@test @inferred(onehot(40, (10,20,30), 20)) == [false, true, false]
@test @inferred(onehotbatch([20, 10], 10:10:30)) == Bool[0 1; 1 0; 0 0]
@test @inferred(onehotbatch([40, 10], (10,20,30), 20)) == Bool[0 1; 1 0; 0 0]
end
@testset "onecold" begin
a = [1, 2, 5, 3.]
A = [1 20 5; 2 7 6; 3 9 10; 2 1 14]
labels = ['A', 'B', 'C', 'D']
@test onecold(a) == 3
@test onecold(A) == [3, 1, 4]
@test onecold(a, labels) == 'C'
@test onecold(a, Tuple(labels)) == 'C'
@test onecold(A, labels) == ['C', 'A', 'D']
@test onecold(A, Tuple(labels)) == ['C', 'A', 'D']
data = [:b, :a, :c]
labels = [:a, :b, :c]
hot = onehotbatch(data, labels)
cold = onecold(hot, labels)
@test cold == data
@test_throws DimensionMismatch onecold([0.3, 0.2], (:a, :b, :c))
@test_throws DimensionMismatch onecold([0.3, 0.2, 0.5, 0.99], (:a, :b, :c))
@test_throws ArgumentError onecold([0.3, NaN, 0.5], (:a, :b, :c))
end
@testset "onehotbatch indexing" begin
y = onehotbatch(ones(3), 1:10)
@test y[:,1] isa OneHotVector
@test y[:,:] isa OneHotMatrix
end
| OneHotArrays | https://github.com/FluxML/OneHotArrays.jl.git |
|
[
"MIT"
] | 0.2.5 | 963a3f28a2e65bb87a68033ea4a616002406037d | code | 604 | using OneHotArrays
using Test
using Compat: stack
@testset "OneHotArray" begin
include("array.jl")
end
@testset "Constructors" begin
include("onehot.jl")
end
@testset "Linear Algebra" begin
include("linalg.jl")
end
using Zygote
import CUDA
if CUDA.functional()
using CUDA # exports CuArray, etc
CUDA.allowscalar(false)
@info "starting CUDA tests"
else
@info "CUDA not functional, testing with JLArrays instead"
using JLArrays # fake GPU array, for testing
JLArrays.allowscalar(false)
cu = jl
CuArray{T,N} = JLArray{T,N}
end
@testset "GPUArrays" begin
include("gpu.jl")
end
| OneHotArrays | https://github.com/FluxML/OneHotArrays.jl.git |
|
[
"MIT"
] | 0.2.5 | 963a3f28a2e65bb87a68033ea4a616002406037d | docs | 1192 | <img align="right" width="200px" src="https://github.com/FluxML/OneHotArrays.jl/raw/main/docs/src/assets/logo.png">
# OneHotArrays.jl
[](https://fluxml.ai/OneHotArrays.jl/dev/)
[](https://github.com/FluxML/OneHotArrays.jl/actions/workflows/CI.yml)
This package provides memory efficient one-hot array encodings.
It was originally part of [Flux.jl](https://github.com/FluxML/Flux.jl).
```julia
julia> using OneHotArrays
julia> m = onehotbatch([10, 20, 30, 10, 10], 10:10:40)
4×5 OneHotMatrix(::Vector{UInt32}) with eltype Bool:
1 ⋅ ⋅ 1 1
⋅ 1 ⋅ ⋅ ⋅
⋅ ⋅ 1 ⋅ ⋅
⋅ ⋅ ⋅ ⋅ ⋅
julia> dump(m)
OneHotMatrix{UInt32, 4, Vector{UInt32}}
indices: Array{UInt32}((5,)) UInt32[0x00000001, 0x00000002, 0x00000003, 0x00000001, 0x00000001]
julia> @which rand(100, 4) * m
*(A::AbstractMatrix, B::Union{OneHotArray{var"#s14", L, 1, var"N+1", I}, Base.ReshapedArray{Bool, var"N+1", <:OneHotArray{var"#s14", L, <:Any, <:Any, I}}} where {var"#s14", var"N+1", I}) where L
@ OneHotArrays ~/.julia/dev/OneHotArrays/src/linalg.jl:7
```
| OneHotArrays | https://github.com/FluxML/OneHotArrays.jl.git |
|
[
"MIT"
] | 0.2.5 | 963a3f28a2e65bb87a68033ea4a616002406037d | docs | 1673 | # OneHotArrays.jl
[](https://github.com/FluxML/OneHotArrays.jl/actions/workflows/CI.yml)
Memory efficient one-hot array encodings (primarily for use in machine-learning contexts like Flux.jl).
## Usage
One-hot arrays are boolean arrays where only a single element in the first dimension is `true` (i.e. "hot"). OneHotArrays.jl stores such arrays efficiently by encoding a N-dimensional array of booleans as a (N - 1)-dimensional array of integers. For example, the one-hot vector below only uses a single `UInt32` for storage.
```julia
julia> β = onehot(:b, (:a, :b, :c))
3-element OneHotVector(::UInt32) with eltype Bool:
⋅
1
⋅
```
As seen above, the one-hot encoding can be useful for representing labeled data. The label `:b` is encoded into a 3-element vector where the "hot" element indicates the label from the set `(:a, :b, :c)`.
We can also encode a batch of one-hot vectors or reverse the encoding.
```julia
julia> oh = onehotbatch("abracadabra", 'a':'e', 'e')
5×11 OneHotMatrix(::Vector{UInt32}) with eltype Bool:
1 ⋅ ⋅ 1 ⋅ 1 ⋅ 1 ⋅ ⋅ 1
⋅ 1 ⋅ ⋅ ⋅ ⋅ ⋅ ⋅ 1 ⋅ ⋅
⋅ ⋅ ⋅ ⋅ 1 ⋅ ⋅ ⋅ ⋅ ⋅ ⋅
⋅ ⋅ ⋅ ⋅ ⋅ ⋅ 1 ⋅ ⋅ ⋅ ⋅
⋅ ⋅ 1 ⋅ ⋅ ⋅ ⋅ ⋅ ⋅ 1 ⋅
julia> Flux.onecold(β, (:a, :b, :c))
:b
julia> Flux.onecold([0.3, 0.2, 0.5], (:a, :b, :c))
:c
```
In addition to functions for encoding and decoding data as one-hot, this package provides numerous "fast-paths" for linear algebraic operations with one-hot arrays. For example, multiplying by a matrix by a one-hot vector triggers an indexing operation instead of a matrix multiplication.
| OneHotArrays | https://github.com/FluxML/OneHotArrays.jl.git |
|
[
"MIT"
] | 0.2.5 | 963a3f28a2e65bb87a68033ea4a616002406037d | docs | 84 | # Reference
```@autodocs
Modules = [OneHotArrays]
Order = [:function, :type]
```
| OneHotArrays | https://github.com/FluxML/OneHotArrays.jl.git |
|
[
"MIT"
] | 0.1.3 | c311a14a10c0717994d1c007bb859979a647b528 | code | 990 | using Documenter
using RegularizedCovarianceMatrices
DocMeta.setdocmeta!(RegularizedCovarianceMatrices, :DocTestSetup, :(using RegularizedCovarianceMatrices); recursive = true)
makedocs(
sitename = "RegularizedCovarianceMatrices",
modules = [RegularizedCovarianceMatrices],
authors = "Raphael Araujo Sampaio and Joaquim Dias Garcia and Marcus Poggi and Thibaut Vidal",
repo = "https://github.com/raphasampaio/RegularizedCovarianceMatrices.jl/blob/{commit}{path}#{line}",
doctest = true,
clean = true,
format = Documenter.HTML(
prettyurls = get(ENV, "CI", "false") == "true",
canonical = "https://raphasampaio.github.io/RegularizedCovarianceMatrices.jl",
edit_link = "main",
assets = [
"assets/favicon.ico",
],
),
pages = [
"Home" => "index.md"
],
)
deploydocs(
repo = "github.com/raphasampaio/RegularizedCovarianceMatrices.jl.git",
devbranch = "main",
push_preview = true,
)
| RegularizedCovarianceMatrices | https://github.com/raphasampaio/RegularizedCovarianceMatrices.jl.git |
|
[
"MIT"
] | 0.1.3 | c311a14a10c0717994d1c007bb859979a647b528 | code | 78 | import Pkg
Pkg.instantiate()
using JuliaFormatter
format(dirname(@__DIR__))
| RegularizedCovarianceMatrices | https://github.com/raphasampaio/RegularizedCovarianceMatrices.jl.git |
|
[
"MIT"
] | 0.1.3 | c311a14a10c0717994d1c007bb859979a647b528 | code | 289 | import Pkg
Pkg.instantiate()
using Revise
Pkg.activate(dirname(@__DIR__))
Pkg.instantiate()
using RegularizedCovarianceMatrices
@info("""
This session is using RegularizedCovarianceMatrices.jl with Revise.jl.
For more information visit https://timholy.github.io/Revise.jl/stable/.
""")
| RegularizedCovarianceMatrices | https://github.com/raphasampaio/RegularizedCovarianceMatrices.jl.git |
|
[
"MIT"
] | 0.1.3 | c311a14a10c0717994d1c007bb859979a647b528 | code | 348 | module RegularizedCovarianceMatrices
using LinearAlgebra
using Statistics
export
CovarianceMatrixEstimator,
EmpiricalCovarianceMatrix,
ShrunkCovarianceMatrix,
OASCovarianceMatrix,
LedoitWolfCovarianceMatrix
include("estimator.jl")
include("empirical.jl")
include("shrunk.jl")
include("oas.jl")
include("ledoitwolf.jl")
end
| RegularizedCovarianceMatrices | https://github.com/raphasampaio/RegularizedCovarianceMatrices.jl.git |
|
[
"MIT"
] | 0.1.3 | c311a14a10c0717994d1c007bb859979a647b528 | code | 1192 | struct EmpiricalCovarianceMatrix <: CovarianceMatrixEstimator
n::Int
d::Int
cache1::Matrix{Float64}
cache2::Matrix{Float64}
end
function EmpiricalCovarianceMatrix(n::Integer = 0, d::Integer = 0)
return EmpiricalCovarianceMatrix(n, d, zeros(n, d), zeros(n, d))
end
function fit(
estimator::EmpiricalCovarianceMatrix,
X::AbstractMatrix{<:Real};
mu::AbstractVector{<:Real} = get_mu(X)
)
return empirical(estimator, X, mu = mu)
end
function fit(
estimator::EmpiricalCovarianceMatrix,
X::AbstractMatrix{<:Real},
weights::AbstractVector{<:Real};
mu::AbstractVector{<:Real} = get_mu(X, weights)
)
return empirical(estimator, X, weights, mu = mu)
end
function fit!(
estimator::EmpiricalCovarianceMatrix,
X::AbstractMatrix{<:Real},
covariance::AbstractMatrix{<:Real},
mu::AbstractVector{<:Real}
)
empirical!(estimator, X, covariance, mu)
return
end
function fit!(
estimator::EmpiricalCovarianceMatrix,
X::AbstractMatrix{<:Real},
weights::AbstractVector{<:Real},
covariance::AbstractMatrix{<:Real},
mu::AbstractVector{<:Real}
)
empirical!(estimator, X, weights, covariance, mu)
return
end
| RegularizedCovarianceMatrices | https://github.com/raphasampaio/RegularizedCovarianceMatrices.jl.git |
|
[
"MIT"
] | 0.1.3 | c311a14a10c0717994d1c007bb859979a647b528 | code | 4474 | abstract type CovarianceMatrixEstimator end
function empirical(
estimator::CovarianceMatrixEstimator,
X::AbstractMatrix{<:Real};
mu::AbstractVector{<:Real} = get_mu(X)
)
n, d = size(X)
translated = (X .- mu')
covariance = (translated' * translated) ./ n
return covariance, mu
end
function empirical(
estimator::CovarianceMatrixEstimator,
X::AbstractMatrix{<:Real},
weights::AbstractVector{<:Real};
mu::AbstractVector{<:Real} = get_mu(X, weights)
)
translated = X .- mu'
covariance = (translated' * (weights .* translated)) ./ sum(weights)
return covariance, mu
end
function empirical!(
estimator::CovarianceMatrixEstimator,
X::AbstractMatrix{<:Real},
covariance::AbstractMatrix{<:Real},
mu::AbstractVector{<:Real}
)
n, d = size(X)
@assert n == estimator.n
@assert d == estimator.d
update_mu!(X, mu)
estimator.cache1 .= X .- mu'
mul!(covariance, estimator.cache1', estimator.cache1)
covariance ./= n
return
end
function empirical!(
estimator::CovarianceMatrixEstimator,
X::AbstractMatrix{<:Real},
weights::AbstractVector{<:Real},
covariance::AbstractMatrix{<:Real},
mu::AbstractVector{<:Real}
)
n, d = size(X)
@assert n == estimator.n
@assert d == estimator.d
update_mu!(X, weights, mu)
estimator.cache1 .= X .- mu'
estimator.cache2 .= weights .* estimator.cache1
mul!(covariance, estimator.cache1', estimator.cache2)
covariance ./= sum(weights)
return
end
function shrunk(
estimator::CovarianceMatrixEstimator,
X::AbstractMatrix{<:Real};
mu::AbstractVector{<:Real} = get_mu(X),
λ::Float64 = 0.1
)
covariance, mu = empirical(estimator, X, mu = mu)
shrunk = shrunk_matrix(covariance, λ)
return Symmetric(shrunk), mu
end
function shrunk(
estimator::CovarianceMatrixEstimator,
X::AbstractMatrix{<:Real},
weights::AbstractVector{<:Real};
mu::AbstractVector{<:Real} = get_mu(X, weights),
λ::Float64 = 0.1
)
covariance, mu = empirical(estimator, X, weights, mu = mu)
shrunk = shrunk_matrix(covariance, λ)
return Symmetric(shrunk), mu
end
function shrunk!(
estimator::CovarianceMatrixEstimator,
X::AbstractMatrix{<:Real},
covariance::AbstractMatrix{<:Real},
mu::AbstractVector{<:Real};
λ::Float64 = 0.1
)
empirical!(estimator, X, covariance, mu)
shrunk_matrix!(covariance, λ)
return
end
function shrunk!(
estimator::CovarianceMatrixEstimator,
X::AbstractMatrix{<:Real},
weights::AbstractVector{<:Real},
covariance::AbstractMatrix{<:Real},
mu::AbstractVector{<:Real};
λ::Float64 = 0.1
)
empirical!(estimator, X, weights, covariance, mu)
shrunk_matrix!(covariance, λ)
return
end
function get_mu(X::AbstractMatrix{<:Real})
return dropdims(sum(X, dims = 1) / size(X, 1), dims = 1)
end
function get_mu(X::AbstractMatrix{<:Real}, weights::AbstractVector{<:Real})
return dropdims(sum(X .* weights, dims = 1) / sum(weights), dims = 1)
end
function update_mu!(X::AbstractMatrix{<:Real}, mu::AbstractVector{<:Real})
n, d = size(X)
for i in 1:d
mu[i] = 0
for j in 1:n
mu[i] += X[j, i]
end
mu[i] /= n
end
end
function update_mu!(
X::AbstractMatrix{<:Real},
weights::AbstractVector{<:Real},
mu::AbstractVector{<:Real}
)
n, d = size(X)
sum_weights = sum(weights)
for i in 1:d
mu[i] = 0
for j in 1:n
mu[i] += weights[j] * X[j, i]
end
mu[i] /= sum_weights
end
end
function shrunk_matrix(covariance::AbstractMatrix{<:Real}, λ::Float64)
d = size(covariance, 2)
trace_mean = tr(covariance) / d
shrunk = (1.0 - λ) * covariance
for i in 1:d
shrunk[i, i] += λ * trace_mean
end
return shrunk
end
function shrunk_matrix!(covariance::AbstractMatrix{<:Real}, λ::Float64)
d = size(covariance, 2)
trace_shrinkage = λ * (tr(covariance) / d)
covariance .= (1.0 - λ) .* covariance
for i in 1:d
covariance[i, i] += trace_shrinkage
end
return
end
function translate_to_zero!(X::AbstractMatrix{<:Real}, mu::AbstractVector{<:Real})
n, d = size(X)
for j in 1:d, i in 1:n
X[i, j] = X[i, j] - mu[j]
end
end
function translate_to_mu!(X::AbstractMatrix{<:Real}, mu::AbstractVector{<:Real})
n, d = size(X)
for j in 1:d, i in 1:n
X[i, j] = X[i, j] + mu[j]
end
end
| RegularizedCovarianceMatrices | https://github.com/raphasampaio/RegularizedCovarianceMatrices.jl.git |
|
[
"MIT"
] | 0.1.3 | c311a14a10c0717994d1c007bb859979a647b528 | code | 2818 | struct LedoitWolfCovarianceMatrix <: CovarianceMatrixEstimator
n::Int
d::Int
cache1::Matrix{Float64}
cache2::Matrix{Float64}
cache3::Matrix{Float64}
function LedoitWolfCovarianceMatrix(n::Integer = 0, d::Integer = 0)
return new(n, d, zeros(n, d), zeros(n, d), zeros(d, d))
end
end
function get_shrinkage(
estimator::LedoitWolfCovarianceMatrix,
X::AbstractMatrix{<:Real},
mu::AbstractVector{<:Real}
)
n, d = size(X)
@assert n == estimator.n
@assert d == estimator.d
estimator.cache1 .= X .- mu'
estimator.cache2 .= estimator.cache1 .^ 2
trace_mean = 0
trace_sum = 0
for i in 1:d
s = 0
for j in 1:n
s += estimator.cache2[j, i]
end
trace_sum += s / n
end
trace_mean = trace_sum / d
mul!(estimator.cache3, estimator.cache2', estimator.cache2)
beta_coefficients = sum(estimator.cache3)
mul!(estimator.cache3, estimator.cache1', estimator.cache1)
estimator.cache3 .= estimator.cache3 .^ 2
delta_coefficients = sum(estimator.cache3) / (n^2)
beta = 1.0 / (n * d) * (beta_coefficients / n - delta_coefficients)
delta = (delta_coefficients - 2.0 * trace_mean * trace_sum + d * trace_mean .^ 2) / d
beta = min(beta, delta)
return (beta <= 0) ? 0.0 : beta / delta
end
function fit(
estimator::LedoitWolfCovarianceMatrix,
X::AbstractMatrix{<:Real},
weights = ones(size(X, 1)),
mu = dropdims(sum(X .* weights, dims = 1) / sum(weights), dims = 1)
)
n = size(X, 1)
d = size(X, 2)
translate_to_zero!(X, mu)
X2 = X .^ 2
trace = sum(X2, dims = 1) / n
trace_mean = sum(trace) / d
beta_coefficients = 0.0
delta_coefficients = 0.0
delta_coefficients += sum((X' * X) .^ 2)
delta_coefficients /= (n^2)
beta_coefficients += sum(X2' * X2)
beta = 1.0 / (n * d) * (beta_coefficients / n - delta_coefficients)
delta = delta_coefficients - 2.0 * trace_mean * sum(trace) + d * trace_mean .^ 2
delta /= d
beta = min(beta, delta)
λ = (beta == 0) ? 0.0 : beta / delta
translate_to_mu!(X, mu)
return shrunk(estimator, X, weights, mu = mu, λ = λ)
end
function fit!(
estimator::LedoitWolfCovarianceMatrix,
X::AbstractMatrix{<:Real},
covariance::AbstractMatrix{<:Real},
mu::AbstractVector{<:Real}
)
update_mu!(X, mu)
λ = get_shrinkage(estimator, X, mu)
return shrunk!(estimator, X, covariance, mu, λ = λ)
end
function fit!(
estimator::LedoitWolfCovarianceMatrix,
X::AbstractMatrix{<:Real},
weights::AbstractVector{<:Real},
covariance::AbstractMatrix{<:Real},
mu::AbstractVector{<:Real}
)
update_mu!(X, weights, mu)
λ = get_shrinkage(estimator, X, mu)
shrunk!(estimator, X, weights, covariance, mu, λ = λ)
return
end
| RegularizedCovarianceMatrices | https://github.com/raphasampaio/RegularizedCovarianceMatrices.jl.git |
|
[
"MIT"
] | 0.1.3 | c311a14a10c0717994d1c007bb859979a647b528 | code | 2025 | struct OASCovarianceMatrix <: CovarianceMatrixEstimator
n::Int
d::Int
cache1::Matrix{Float64}
cache2::Matrix{Float64}
cache3::Matrix{Float64}
function OASCovarianceMatrix(n::Integer = 0, d::Integer = 0)
return new(n, d, zeros(n, d), zeros(n, d), zeros(d, d))
end
end
function get_shrinkage(
estimator::OASCovarianceMatrix,
X::AbstractMatrix{<:Real},
covariance::AbstractMatrix{<:Real}
)
n, d = size(X)
@assert n == estimator.n
@assert d == estimator.d
trace_mean = tr(covariance) / d
estimator.cache3 .= covariance .^ 2
alpha = mean(estimator.cache3)
num = alpha + trace_mean^2
den = (n + 1.0) * (alpha - (trace_mean^2) / d)
return (den == 0) ? 1.0 : min(num / den, 1.0)
end
function fit(
estimator::OASCovarianceMatrix,
X::AbstractMatrix{<:Real},
weights::AbstractVector{<:Real} = ones(size(X, 1)),
mu::AbstractVector{<:Real} = get_mu(X, weights)
)
n, d = size(X)
translate_to_zero!(X, mu)
covariance, _ = empirical(estimator, X, weights, mu = zeros(d))
trace_mean = tr(covariance) / d
alpha = mean(covariance .^ 2)
num = alpha + trace_mean^2
den = (n + 1.0) * (alpha - (trace_mean^2) / d)
λ = (den == 0) ? 1.0 : min(num / den, 1.0)
shrunk = shrunk_matrix(covariance, λ)
translate_to_mu!(X, mu)
return Symmetric(shrunk), mu
end
function fit!(
estimator::OASCovarianceMatrix,
X::AbstractMatrix{<:Real},
covariance::AbstractMatrix{<:Real},
mu::AbstractVector{<:Real}
)
empirical!(estimator, X, covariance, mu)
λ = get_shrinkage(estimator, X, covariance)
shrunk_matrix!(covariance, λ)
return
end
function fit!(
estimator::OASCovarianceMatrix,
X::AbstractMatrix{<:Real},
weights::AbstractVector{<:Real},
covariance::AbstractMatrix{<:Real},
mu::AbstractVector{<:Real}
)
empirical!(estimator, X, weights, covariance, mu)
λ = get_shrinkage(estimator, X, covariance)
shrunk_matrix!(covariance, λ)
return
end
| RegularizedCovarianceMatrices | https://github.com/raphasampaio/RegularizedCovarianceMatrices.jl.git |
|
[
"MIT"
] | 0.1.3 | c311a14a10c0717994d1c007bb859979a647b528 | code | 1256 | struct ShrunkCovarianceMatrix <: CovarianceMatrixEstimator
n::Int
d::Int
λ::Float64
cache1::Matrix{Float64}
cache2::Matrix{Float64}
function ShrunkCovarianceMatrix(n::Integer = 0, d::Integer = 0; λ::Float64 = 0.1)
return new(n, d, λ, zeros(n, d), zeros(n, d))
end
end
function fit(
estimator::ShrunkCovarianceMatrix,
X::AbstractMatrix{<:Real};
mu::AbstractVector{<:Real} = get_mu(X)
)
return shrunk(estimator, X, mu = mu, λ = estimator.λ)
end
function fit(
estimator::ShrunkCovarianceMatrix,
X::AbstractMatrix{<:Real},
weights::AbstractVector{<:Real};
mu::AbstractVector{<:Real} = get_mu(X, weights)
)
return shrunk(estimator, X, weights, mu = mu, λ = estimator.λ)
end
function fit!(
estimator::ShrunkCovarianceMatrix,
X::AbstractMatrix{<:Real},
covariance::AbstractMatrix{<:Real},
mu::AbstractVector{<:Real}
)
shrunk!(estimator, X, covariance, mu, λ = estimator.λ)
return
end
function fit!(
estimator::ShrunkCovarianceMatrix,
X::AbstractMatrix{<:Real},
weights::AbstractVector{<:Real},
covariance::AbstractMatrix{<:Real},
mu::AbstractVector{<:Real}
)
shrunk!(estimator, X, weights, covariance, mu, λ = estimator.λ)
return
end
| RegularizedCovarianceMatrices | https://github.com/raphasampaio/RegularizedCovarianceMatrices.jl.git |
|
[
"MIT"
] | 0.1.3 | c311a14a10c0717994d1c007bb859979a647b528 | code | 2026 | function test_empirical()
size = 10
dimensions = [2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048]
Random.seed!(1)
for i in 1:size, n in dimensions, d in dimensions
if n > d
X = rand(n, d)
X_copy = copy(X)
weights = rand(n)
weights_copy = copy(weights)
estimator = EmpiricalCovarianceMatrix(n, d)
@timeit "rcm" covariance, mu = RegularizedCovarianceMatrices.fit(estimator, X)
@test X == X_copy
@timeit "base" covariance_base = Statistics.cov(X, corrected = false)
@test X == X_copy
@test covariance ≈ covariance_base
@timeit "statsbase" covariance_statsbase = StatsBase.cov(X, corrected = false)
@test X == X_copy
@test covariance ≈ covariance_statsbase
mu_inplace = zeros(d)
covariance_inplace = zeros(d, d)
estimator = EmpiricalCovarianceMatrix(n, d)
@timeit "rcm in-place" RegularizedCovarianceMatrices.fit!(estimator, X, covariance_inplace, mu_inplace)
@test X == X_copy
@test covariance ≈ covariance_inplace
@test mu ≈ mu_inplace
@timeit "rcm weighted" covariance, mu = RegularizedCovarianceMatrices.fit(estimator, X, weights)
@test X == X_copy
@test weights == weights_copy
@timeit "statsbase weighted" covariance_statsbase = StatsBase.cov(X, Weights(weights), corrected = false)
@test X == X_copy
@test weights == weights_copy
@test covariance ≈ covariance_statsbase
mu_inplace = zeros(d)
covariance_inplace = zeros(d, d)
@timeit "rcm weighted in-place" RegularizedCovarianceMatrices.fit!(estimator, X, weights, covariance_inplace, mu_inplace)
@test X == X_copy
@test weights == weights_copy
@test covariance ≈ covariance_inplace
@test mu ≈ mu_inplace
end
end
end | RegularizedCovarianceMatrices | https://github.com/raphasampaio/RegularizedCovarianceMatrices.jl.git |
|
[
"MIT"
] | 0.1.3 | c311a14a10c0717994d1c007bb859979a647b528 | code | 530 | using RegularizedCovarianceMatrices
using Aqua
using Random
using Statistics
using StatsBase
using Test
using TimerOutputs
include("empirical.jl")
function test_all()
reset_timer!()
@testset "Aqua.jl" begin
@testset "Ambiguities" begin
Aqua.test_ambiguities(RegularizedCovarianceMatrices, recursive = false)
end
Aqua.test_all(RegularizedCovarianceMatrices, ambiguities = false)
end
@timeit "empirical" test_empirical()
print_timer(sortby = :firstexec)
end
test_all()
| RegularizedCovarianceMatrices | https://github.com/raphasampaio/RegularizedCovarianceMatrices.jl.git |
|
[
"MIT"
] | 0.1.3 | c311a14a10c0717994d1c007bb859979a647b528 | docs | 2153 | # RegularizedCovarianceMatrices.jl
<div align="center">
<a href="/docs/src/assets/">
<img src="/docs/src/assets/logo.svg" width=250px alt="RegularizedCovarianceMatrices.jl" />
</a>
<br>
<br>
<a href="https://raphasampaio.github.io/RegularizedCovarianceMatrices.jl/stable">
<img src="https://img.shields.io/badge/docs-stable-blue.svg" alt="Stable">
</a>
<a href="https://raphasampaio.github.io/RegularizedCovarianceMatrices.jl/dev">
<img src="https://img.shields.io/badge/docs-dev-blue.svg" alt="Dev">
</a>
<a href="https://pkgs.genieframework.com?packages=RegularizedCovarianceMatrices">
<img src="https://shields.io/endpoint?url=https://pkgs.genieframework.com/api/v1/badge/RegularizedCovarianceMatrices/label:-sep:">
</a>
<br>
<a href="https://juliahub.com/ui/Packages/RegularizedCovarianceMatrices/0JHdO">
<img src="https://juliahub.com/docs/RegularizedCovarianceMatrices/version.svg" alt="Version"/>
</a>
<a href="https://github.com/raphasampaio/RegularizedCovarianceMatrices.jl/actions/workflows/CI.yml">
<img src="https://github.com/raphasampaio/RegularizedCovarianceMatrices.jl/actions/workflows/CI.yml/badge.svg" alt="CI"/>
</a>
<a href="https://codecov.io/gh/raphasampaio/RegularizedCovarianceMatrices.jl">
<img src="https://codecov.io/gh/raphasampaio/RegularizedCovarianceMatrices.jl/branch/main/graph/badge.svg" alt="Coverage"/>
</a>
<a href="https://github.com/JuliaTesting/Aqua.jl">
<img src="https://raw.githubusercontent.com/JuliaTesting/Aqua.jl/master/badge.svg" alt="Coverage"/>
</a>
</div>
## Introduction
RegularizedCovarianceMatrices.jl is a Julia package that implements several regularized covariance matrices estimations.
## Getting Started
### Installation
```julia
julia> ] add RegularizedCovarianceMatrices
```
### Example
```julia
using RegularizedCovarianceMatrices
n = 100
d = 2
data = rand(n, d)
estimator = ShrunkCovarianceMatrix(n, d, 0.1)
covariance_matrix = RegularizedCovarianceMatrices.fit(estimator, data)
```
| RegularizedCovarianceMatrices | https://github.com/raphasampaio/RegularizedCovarianceMatrices.jl.git |
|
[
"MIT"
] | 0.1.3 | c311a14a10c0717994d1c007bb859979a647b528 | docs | 574 | # RegularizedCovarianceMatrices
## Installation
```julia
using Pkg
Pkg.add("RegularizedCovarianceMatrices")
```
## Citing
If you find RegularizedCovarianceMatrices useful in your work, we kindly request that you cite the following paper ([preprint](https://arxiv.org/abs/2302.02450)):
```bibtex
@article{sampaio2023regularization,
title={Regularization and Global Optimization in Model-Based Clustering},
author={Sampaio, Raphael Araujo and Garcia, Joaquim Dias and Poggi, Marcus and Vidal, Thibaut},
journal={arXiv preprint arXiv:2302.02450},
year={2023}
}
``` | RegularizedCovarianceMatrices | https://github.com/raphasampaio/RegularizedCovarianceMatrices.jl.git |
|
[
"MIT"
] | 0.1.1 | b5e118a01e694c88297e93b9fe87db92e85a0a0b | code | 297 | module BoundaryValueProblemsPlotsExt
using Plots
using BoundaryValueProblems
function Plots.plot(sol::BoundaryValueSolution{<:Number, 1})
plot(sol.u, sol.cache.space)
end
function Plots.plot(sol::BoundaryValueSolution{<:Number, 2}; a = 45, b = 60)
plot(sol.u, sol.cache.space)
end
end
| BoundaryValueProblems | https://github.com/CalculustJL/BoundaryValueProblems.jl.git |
|
[
"MIT"
] | 0.1.1 | b5e118a01e694c88297e93b9fe87db92e85a0a0b | code | 1436 | """
Boundary Value Problem Interface for `CalculustJL`
"""
module BoundaryValueProblems
using DocStringExtensions
using Reexport
@reexport using SciMLBase
@reexport using CalculustCore
using SciMLOperators: AbstractSciMLOperator, IdentityOperator
using CalculustCore.Domains: AbstractDomain
using CalculustCore.Spaces: AbstractSpace, AbstractDiscretization
using UnPack: @unpack
using LinearAlgebra
using LinearSolve
@static if !isdefined(Base, :get_extension)
import Requires
end
@static if !isdefined(Base, :get_extension)
function __init__()
Requires.@require Plots = "91a5bcdd-55d7-5caf-9e0b-520d859cae80" begin
include("../ext/BoundaryValueProblemsPlotsExt.jl")
end
end
end
"""
$TYPEDEF
"""
abstract type AbstractBoundaryCondition{T} end
"""
$TYPEDEF
"""
abstract type AbstractBoundaryValueProblem <: SciMLBase.DEProblem end
"""
$TYPEDEF
"""
abstract type AbstractBoundaryValueCache <: SciMLBase.DECache end
"""
$TYPEDEF
"""
abstract type AbstractBoundaryValueAlgorithm <: SciMLBase.DEAlgorithm end
include("utils.jl")
include("conditions.jl")
include("types.jl")
include("make_lhs_rhs.jl")
include("problem.jl")
export
# boundary conditions
DirichletBC, NeumannBC, RobinBC, PeriodicBC,
# boundary vale problem
BoundaryValueProblem, BoundaryValueSolution,
# boundary value algorithms
LinearBoundaryValueAlg, NonlinearBoundaryValueAlg
end
| BoundaryValueProblems | https://github.com/CalculustJL/BoundaryValueProblems.jl.git |
|
[
"MIT"
] | 0.1.1 | b5e118a01e694c88297e93b9fe87db92e85a0a0b | code | 576 | #
###
# Boundary Condition Types
###
"""
$TYPEDEF
u(x) = f(x), x ∈ ∂Ω
Defaults to homogeneous.
"""
Base.@kwdef struct DirichletBC{F}
f::F = (points...) -> zero(first(points))
end
"""
$SIGNATURES
(n⋅∇)u(x) = f(x), x ∈ ∂Ω
Defaults to homogeneous.
"""
Base.@kwdef struct NeumannBC{F}
f::F = (points...) -> zero(first(points))
end
"""
$SIGNATURES
f1(x)u(x) + f2(x)(n⋅∇)u(x) = f3(x), x ∈ ∂Ω
"""
struct RobinBC{F1, F2, F3}
f1::F1
f2::F2
f3::F3
end
"""
$SIGNATURES
Periodic Boundary Condition
"""
Base.@kwdef struct PeriodicBC{Ttag}
tag::Ttag
end
#
| BoundaryValueProblems | https://github.com/CalculustJL/BoundaryValueProblems.jl.git |
|
[
"MIT"
] | 0.1.1 | b5e118a01e694c88297e93b9fe87db92e85a0a0b | code | 1999 | #
###
# boundary masks
###
function dirichlet_mask(space::AbstractSpace, dom::AbstractDomain, indices, bc_dict)
tags = boundary_tags(dom)
x = points(space) |> first
M = similar(x, Bool) * false .+ true |> vec
for i in 1:num_boundaries(dom)
tag = tags[i]
bc = bc_dict[tag]
if bc isa DirichletBC
idx = indices[i]
set_val!(M, false, idx)
end
end
DiagonalOperator(M)
end
function boundary_antimasks(space::AbstractSpace, dom::AbstractDomain, indices)
glo_num = global_numbering(space)
antimasks = []
for i in 1:num_boundaries(dom)
M = similar(glo_num, Bool) * false |> vec
idx = indices[i]
set_val!(M, true, idx)
push!(antimasks, M)
end
DiagonalOperator.(antimasks)
end
###
# form LHS, RHS
###
function makeLHS(op::AbstractSciMLOperator, bc::AbstractBoundaryCondition)
@unpack mask_dir, amask_dir = bc
#TODO
"""
how to empty dirichlet row? -
https://github.com/vpuri3/PDEInterfaces.jl/issues/1
is having the construct u := u_inhom + u_hom the only way?
then would have to interpolate u_inhom into interior.
what are the consequences?
"""
mask_dir * op + amask_dir
end
function makeRHS(f, bc::AbstractBoundaryCondition)
@unpack bc_dict, antimasks, mask_dir, space, discr = bc
M = massOp(space, discr)
b = M * f
dirichlet = zero(b)
neumann = zero(b)
robin = zero(b)
pts = points(space)
dom = domain(space)
tags = boundary_tags(dom)
for i in 1:num_boundaries(dom)
tag = tags[i]
bc = bc_dict[tag]
amask = antimasks[i]
if bc isa DirichletBC
dirichlet += amask * bc.f(pts...)
elseif bc isa NeumannBC
neumann += amask * bc.f(pts...)
elseif bc isa RobinBC
# TODO
elseif bc isa PeriodicBC
continue
end
end
(mask_dir * b) + dirichlet - neumann + robin
end
#
| BoundaryValueProblems | https://github.com/CalculustJL/BoundaryValueProblems.jl.git |
|
[
"MIT"
] | 0.1.1 | b5e118a01e694c88297e93b9fe87db92e85a0a0b | code | 5399 | #
struct BoundaryValueProblem{
isinplace,
T,
F,
fType,
uType,
Tbcs,
Tspace <: AbstractSpace{T},
Tdiscr <: AbstractDiscretization,
P,
K
} <: AbstractBoundaryValueProblem
"""Neumann Operator"""
op::F
"""Right-hand-side forcing vector"""
f::fType
"""Initial guess"""
u0::uType
"""Boundary condition object"""
bc_dict::Tbcs
"""Function space"""
space::Tspace
"""Discretization"""
discr::Tdiscr
"""Parameters"""
p::P
"""Keyword arguments"""
kwargs::K
SciMLBase.@add_kwonly function BoundaryValueProblem(op::AbstractSciMLOperator,
f,
bc_dict::Dict,
space::AbstractSpace{T},
discr::AbstractDiscretization,
p = SciMLBase.NullParameters();
u0 = nothing,
kwargs...) where {T}
new{true,
eltype(space),
typeof(op),
typeof(f),
typeof(u0),
typeof(bc_dict),
typeof(space),
typeof(discr),
typeof(p),
typeof(kwargs)
}(op, f, u0, bc_dict, space, discr, p, kwargs)
end
end
function Base.summary(io::IO, prob::BoundaryValueProblem)
type_color, no_color = SciMLBase.get_colorizers(io)
print(io,
type_color, nameof(typeof(prob)),
no_color, " with uType ",
type_color, typeof(prob.u0),
no_color, " with AType ",
type_color, typeof(prob.op),
no_color, ". In-place: ",
type_color, SciMLBase.isinplace(prob),
no_color)
end
function Base.show(io::IO, mime::MIME"text/plain", A::BoundaryValueProblem)
summary(io, A)
println(io)
println(io, "u0: ")
show(io, mime, A.u0)
println(io, "Neumann Operator: ")
show(io, mime, A.op)
println(io, "Forcing Vector: ")
show(io, mime, A.f)
println(io, "Boundary Conditions: ")
show(io, mime, A.bc_dict)
println(io, "Function Space: ")
show(io, mime, A.space)
end
struct BoundaryValueCache{Top, Tu, Tbc, Tsp, Tdi, Talg} <: AbstractBoundaryValueCache
"""Neumann Operator"""
op::Top
"""Right-hand-side forcing vector"""
f::Tu
"""Initial guess"""
u::Tu
"""Boundary condition object"""
bc::Tbc
"""Function space"""
space::Tsp
"""Discretization"""
discr::Tdi
"""Algorithm"""
alg::Talg
end
struct BoundaryValueSolution{T, D, uType, R, A, C} #<: SciMLBase.AbstractDAESolution{T,D}
u::uType
resid::R
alg::A
retcode::Symbol
iters::Int
cache::C
function BoundaryValueSolution(u, resid, alg, retcode, iters, cache)
@unpack space = cache
new{
eltype(space),
ndims(space),
typeof(u),
typeof(resid),
typeof(alg),
typeof(cache)
}(u, resid, alg, retcode, iters, cache)
end
end
function build_bv_solution(alg, u, resid, cache; retcode = :Default, iters = nothing)
BoundaryValueSolution(u, resid, alg, retcode, iters, cache)
end
Base.@kwdef struct LinearBoundaryValueAlg{Tl} <: AbstractBoundaryValueAlgorithm
linalg::Tl = nothing
end
#TODO integrate NonlinearSolve.jl with LinearSolve.jl first
Base.@kwdef struct NonlinearBoundaryValueAlg{Tnl} <: AbstractBoundaryValueAlgorithm
nlalg::Tnl = nothing
end
function SciMLBase.solve(cache::BoundaryValueCache; kwargs...)
@unpack op, f, u, bc, space, alg = cache
@unpack linalg = alg
lhsOp = makeLHS(op, bc)
lhsOp = cache_operator(lhsOp, f)
rhs = makeRHS(f, bc)
linprob = LinearProblem(lhsOp, rhs; u0 = vec(u))
linsol = solve(linprob, linalg; kwargs...)
resid = norm(lhsOp * linsol.u - rhs, Inf)
build_bv_solution(alg, u, resid, cache; iters = linsol.iters)
end
function SciMLBase.init(prob::AbstractBoundaryValueProblem,
alg::AbstractBoundaryValueAlgorithm = nothing;
abstol = default_tol(eltype(prob.op)),
reltol = default_tol(eltype(prob.op)),
maxiters = length(prob.f),
verbose = false,
kwargs...)
@unpack op, f, u0, bc_dict, space, discr = prob
alg = alg isa Nothing ? LinearBoundaryValueAlg() : alg
u = u0 isa Nothing ? zero(f) : u0
bc = BoundaryCondition(bc_dict, space, discr)
BoundaryValueCache(op, f, u, bc, space, discr, alg)
end
function SciMLBase.solve(prob::BoundaryValueProblem, args...; kwargs...)
solve(init(prob, nothing, args...; kwargs...))
end
function SciMLBase.solve(prob::BoundaryValueProblem,
alg::Union{AbstractBoundaryValueAlgorithm, Nothing}, args...;
kwargs...)
solve(init(prob, alg, args...; kwargs...); kwargs...)
end
#
| BoundaryValueProblems | https://github.com/CalculustJL/BoundaryValueProblems.jl.git |
|
[
"MIT"
] | 0.1.1 | b5e118a01e694c88297e93b9fe87db92e85a0a0b | code | 1166 | #
"""
$TYPEDEF
$FIELDS
"""
struct BoundaryCondition{T,
Tdict,
Tamasks,
Tmask,
Tamask,
Tspace <: AbstractSpace{T},
Tdiscr <: AbstractDiscretization
} <: AbstractBoundaryCondition{T}
"""Dict(Domain_bdry_tag => BCType)"""
bc_dict::Tdict
"""Vector(boundary_antimasks); antimask = id - mask"""
antimasks::Tamasks
"""Diagonal Mask operator hiding Dirichlet boundaries"""
mask_dir::Tmask
"""antimask for dirichlet BC"""
amask_dir::Tamask
"""Function space"""
space::Tspace
""" Discretization """
discr::Tdiscr
end
"""
$SIGNATURES
"""
function BoundaryCondition(bc_dict::Dict, V::AbstractSpace,
discr::AbstractDiscretization)
dom = domain(V)
indices = boundary_nodes(V)
antimasks = boundary_antimasks(V, dom, indices)
mask_dir = dirichlet_mask(V, dom, indices, bc_dict)
amask_dir = IdentityOperator(length(V)) - mask_dir
BoundaryCondition(bc_dict, antimasks, mask_dir, amask_dir, V, discr)
end
#
| BoundaryValueProblems | https://github.com/CalculustJL/BoundaryValueProblems.jl.git |
|
[
"MIT"
] | 0.1.1 | b5e118a01e694c88297e93b9fe87db92e85a0a0b | code | 228 | #
using LinearSolve: default_tol
function set_val!(M, val, idx)
len = length(idx)
if len < 1
M
elseif len == 1
M[idx] = val
else
M[idx] = [val for i in 1:length(idx)]
end
M
end
| BoundaryValueProblems | https://github.com/CalculustJL/BoundaryValueProblems.jl.git |
|
[
"MIT"
] | 0.1.1 | b5e118a01e694c88297e93b9fe87db92e85a0a0b | code | 115 | using BoundaryValueProblems
using Test
@testset "BoundaryValueProblems.jl" begin
# Write your tests here.
end
| BoundaryValueProblems | https://github.com/CalculustJL/BoundaryValueProblems.jl.git |
|
[
"MIT"
] | 0.1.1 | b5e118a01e694c88297e93b9fe87db92e85a0a0b | docs | 253 | # BoundaryValueProblems
[](https://github.com/CalculustJL/BoundaryValueProblems.jl/actions/workflows/CI.yml?query=branch%3Amaster)
| BoundaryValueProblems | https://github.com/CalculustJL/BoundaryValueProblems.jl.git |
|
[
"MPL-2.0"
] | 0.12.1 | c68e031e469f1898bb779cbc3c401e1640ecc0c4 | code | 448 | using Documenter, JSOSolvers
makedocs(
modules = [JSOSolvers],
doctest = true,
linkcheck = true,
format = Documenter.HTML(
prettyurls = get(ENV, "CI", nothing) == "true",
assets = ["assets/style.css"],
),
sitename = "JSOSolvers.jl",
pages = ["index.md", "solvers.md", "internal.md", "reference.md"],
)
deploydocs(
repo = "github.com/JuliaSmoothOptimizers/JSOSolvers.jl.git",
push_preview = true,
devbranch = "main",
)
| JSOSolvers | https://github.com/JuliaSmoothOptimizers/JSOSolvers.jl.git |
|
[
"MPL-2.0"
] | 0.12.1 | c68e031e469f1898bb779cbc3c401e1640ecc0c4 | code | 2065 | module JSOSolvers
# stdlib
using LinearAlgebra, Logging, Printf
# JSO packages
using Krylov, LinearOperators, NLPModels, NLPModelsModifiers, SolverCore, SolverTools
import SolverCore.solve!
export solve!
const Callback_docstring = "
The callback is called at each iteration.
The expected signature of the callback is `callback(nlp, solver, stats)`, and its output is ignored.
Changing any of the input arguments will affect the subsequent iterations.
In particular, setting `stats.status = :user` will stop the algorithm.
All relevant information should be available in `nlp` and `solver`.
Notably, you can access, and modify, the following:
- `solver.x`: current iterate;
- `solver.gx`: current gradient;
- `stats`: structure holding the output of the algorithm (`GenericExecutionStats`), which contains, among other things:
- `stats.dual_feas`: norm of the residual, for instance, the norm of the gradient for unconstrained problems;
- `stats.iter`: current iteration counter;
- `stats.objective`: current objective function value;
- `stats.status`: current status of the algorithm. Should be `:unknown` unless the algorithm attained a stopping criterion. Changing this to anything will stop the algorithm, but you should use `:user` to properly indicate the intention.
- `stats.elapsed_time`: elapsed time in seconds.
"
"""
normM!(n, x, M, z)
Weighted norm of `x` with respect to `M`, i.e., `z = sqrt(x' * M * x)`. Uses `z` as workspace.
"""
function normM!(n, x, M, z)
if M === I
return nrm2(n, x)
else
mul!(z, M, x)
return √(x ⋅ z)
end
end
# Unconstrained solvers
include("lbfgs.jl")
include("trunk.jl")
include("fomo.jl")
# Unconstrained solvers for NLS
include("trunkls.jl")
# List of keywords accepted by TRONTrustRegion
const tron_keys = (
:max_radius,
:acceptance_threshold,
:decrease_threshold,
:increase_threshold,
:large_decrease_factor,
:small_decrease_factor,
:increase_factor,
)
# Bound-constrained solvers
include("tron.jl")
# Bound-constrained solvers for NLS
include("tronls.jl")
end
| JSOSolvers | https://github.com/JuliaSmoothOptimizers/JSOSolvers.jl.git |
|
[
"MPL-2.0"
] | 0.12.1 | c68e031e469f1898bb779cbc3c401e1640ecc0c4 | code | 16129 | export fomo, FomoSolver, FoSolver, fo, R2, TR, tr_step, r2_step
abstract type AbstractFirstOrderSolver <: AbstractOptimizationSolver end
abstract type AbstractFOMethod end
struct tr_step <: AbstractFOMethod end
struct r2_step <: AbstractFOMethod end
"""
fomo(nlp; kwargs...)
A First-Order with MOmentum (FOMO) model-based method for unconstrained optimization. Supports quadratic regularization and trust region method with linear model.
# Algorithm description
The step is computed along
d = - (1-βmax) .* ∇f(xk) - βmax .* mk
with mk the memory of past gradients (initialized at 0), and updated at each successful iteration as
mk .= ∇f(xk) .* (1 - βmax) .+ mk .* βmax
and βmax ∈ [0,β] chosen as to ensure d is gradient-related, i.e., the following 2 conditions are satisfied:
(1-βmax) .* ∇f(xk) + βmax .* ∇f(xk)ᵀmk ≥ θ1 * ‖∇f(xk)‖² (1)
‖∇f(xk)‖ ≥ θ2 * ‖(1-βmax) *. ∇f(xk) + βmax .* mk‖ (2)
In the nonmonotone case, (1) rewrites
(1-βmax) .* ∇f(xk) + βmax .* ∇f(xk)ᵀmk + (fm - fk)/μk ≥ θ1 * ‖∇f(xk)‖²,
with fm the largest objective value over the last M successful iterations, and fk = f(xk).
# Advanced usage
For advanced usage, first define a `FomoSolver` to preallocate the memory used in the algorithm, and then call `solve!`:
solver = FomoSolver(nlp)
solve!(solver, nlp; kwargs...)
**No momentum**: if the user does not whish to use momentum (`β` = 0), it is recommended to use the memory-optimized `fo` method.
# Arguments
- `nlp::AbstractNLPModel{T, V}` is the model to solve, see `NLPModels.jl`.
# Keyword arguments
- `x::V = nlp.meta.x0`: the initial guess.
- `atol::T = √eps(T)`: absolute tolerance.
- `rtol::T = √eps(T)`: relative tolerance: algorithm stops when ‖∇f(xᵏ)‖ ≤ atol + rtol * ‖∇f(x⁰)‖.
- `η1 = eps(T)^(1/4)`, `η2 = T(0.95)`: step acceptance parameters.
- `γ1 = T(1/2)`, `γ2 = T(2)`: regularization update parameters.
- `γ3 = T(1/2)` : momentum factor βmax update parameter in case of unsuccessful iteration.
- `αmax = 1/eps(T)`: maximum step parameter for fomo algorithm.
- `max_eval::Int = -1`: maximum number of objective evaluations.
- `max_time::Float64 = 30.0`: maximum time limit in seconds.
- `max_iter::Int = typemax(Int)`: maximum number of iterations.
- `β = T(0.9) ∈ [0,1)`: target decay rate for the momentum.
- `θ1 = T(0.1)`: momentum contribution parameter for convergence condition (1).
- `θ2 = T(eps(T)^(1/3))`: momentum contribution parameter for convergence condition (2).
- `M = 1` : requires objective decrease over the `M` last iterates (nonmonotone context). `M=1` implies monotone behaviour.
- `verbose::Int = 0`: if > 0, display iteration details every `verbose` iteration.
- `step_backend = r2_step()`: step computation mode. Options are `r2_step()` for quadratic regulation step and `tr_step()` for first-order trust-region.
# Output
The value returned is a `GenericExecutionStats`, see `SolverCore.jl`.
# Callback
$(Callback_docstring)
The callback is called at each iteration.
The expected signature of the callback is `callback(nlp, solver, stats)`, and its output is ignored.
Changing any of the input arguments will affect the subsequent iterations.
In particular, setting `stats.status = :user || stats.stats = :unknown` will stop the algorithm.
All relevant information should be available in `nlp` and `solver`.
Notably, you can access, and modify, the following:
- `solver.x`: current iterate;
- `solver.gx`: current gradient;
- `stats`: structure holding the output of the algorithm (`GenericExecutionStats`), which contains, among other things:
- `stats.dual_feas`: norm of current gradient;
- `stats.iter`: current iteration counter;
- `stats.objective`: current objective function value;
- `stats.status`: current status of the algorithm. Should be `:unknown` unless the algorithm has attained a stopping criterion. Changing this to anything will stop the algorithm, but you should use `:user` to properly indicate the intention.
- `stats.elapsed_time`: elapsed time in seconds.
# Examples
## `fomo`
```jldoctest
using JSOSolvers, ADNLPModels
nlp = ADNLPModel(x -> sum(x.^2), ones(3))
stats = fomo(nlp)
# output
"Execution stats: first-order stationary"
```
```jldoctest
using JSOSolvers, ADNLPModels
nlp = ADNLPModel(x -> sum(x.^2), ones(3))
solver = FomoSolver(nlp);
stats = solve!(solver, nlp)
# output
"Execution stats: first-order stationary"
```
"""
mutable struct FomoSolver{T, V} <: AbstractFirstOrderSolver
x::V
g::V
c::V
m::V
d::V
p::V
o::V
α::T
end
function FomoSolver(nlp::AbstractNLPModel{T, V}; M::Int = 1) where {T, V}
x = similar(nlp.meta.x0)
g = similar(nlp.meta.x0)
c = similar(nlp.meta.x0)
m = fill!(similar(nlp.meta.x0), 0)
d = fill!(similar(nlp.meta.x0), 0)
p = similar(nlp.meta.x0)
o = fill!(Vector{T}(undef, M), -Inf)
return FomoSolver{T, V}(x, g, c, m, d, p, o, T(0))
end
@doc (@doc FomoSolver) function fomo(
nlp::AbstractNLPModel{T, V};
M::Int = 1,
kwargs...,
) where {T, V}
solver = FomoSolver(nlp; M)
solver_specific = Dict(:avgβmax => T(0.0))
stats = GenericExecutionStats(nlp; solver_specific = solver_specific)
return solve!(solver, nlp, stats; kwargs...)
end
function SolverCore.reset!(solver::FomoSolver{T}) where {T}
fill!(solver.m, 0)
fill!(solver.o, -Inf)
solver
end
SolverCore.reset!(solver::FomoSolver, ::AbstractNLPModel) = reset!(solver)
"""
fo(nlp; kwargs...)
R2(nlp; kwargs...)
TR(nlp; kwargs...)
A First-Order (FO) model-based method for unconstrained optimization. Supports quadratic regularization and trust region method with linear model.
For advanced usage, first define a `FomoSolver` to preallocate the memory used in the algorithm, and then call `solve!`:
solver = FoSolver(nlp)
solve!(solver, nlp; kwargs...)
`R2` and `TR` runs `fo` with the dedicated `step_backend` keyword argument.
# Arguments
- `nlp::AbstractNLPModel{T, V}` is the model to solve, see `NLPModels.jl`.
# Keyword arguments
- `x::V = nlp.meta.x0`: the initial guess.
- `atol::T = √eps(T)`: absolute tolerance.
- `rtol::T = √eps(T)`: relative tolerance: algorithm stops when ‖∇f(xᵏ)‖ ≤ atol + rtol * ‖∇f(x⁰)‖.
- `η1 = eps(T)^(1/4)`, `η2 = T(0.95)`: step acceptance parameters.
- `γ1 = T(1/2)`, `γ2 = T(2)`: regularization update parameters.
- `αmax = 1/eps(T)`: maximum step parameter for fomo algorithm.
- `max_eval::Int = -1`: maximum number of evaluation of the objective function.
- `max_time::Float64 = 30.0`: maximum time limit in seconds.
- `max_iter::Int = typemax(Int)`: maximum number of iterations.
- `M = 1` : requires objective decrease over the `M` last iterates (nonmonotone context). `M=1` implies monotone behaviour.
- `verbose::Int = 0`: if > 0, display iteration details every `verbose` iteration.
- `step_backend = r2_step()`: step computation mode. Options are `r2_step()` for quadratic regulation step and `tr_step()` for first-order trust-region.
# Output
The value returned is a `GenericExecutionStats`, see `SolverCore.jl`.
# Callback
$(Callback_docstring)
# Examples
```jldoctest
using JSOSolvers, ADNLPModels
nlp = ADNLPModel(x -> sum(x.^2), ones(3))
stats = fo(nlp) # run with step_backend = r2_step(), equivalent to R2(nlp)
# output
"Execution stats: first-order stationary"
```
```jldoctest
using JSOSolvers, ADNLPModels
nlp = ADNLPModel(x -> sum(x.^2), ones(3))
solver = FoSolver(nlp);
stats = solve!(solver, nlp)
# output
"Execution stats: first-order stationary"
```
"""
mutable struct FoSolver{T, V} <: AbstractFirstOrderSolver
x::V
g::V
c::V
o::V
α::T
end
function FoSolver(nlp::AbstractNLPModel{T, V}; M::Int = 1) where {T, V}
x = similar(nlp.meta.x0)
g = similar(nlp.meta.x0)
c = similar(nlp.meta.x0)
o = fill!(Vector{T}(undef, M), -Inf)
return FoSolver{T, V}(x, g, c, o, T(0))
end
"""
`R2Solver` is deprecated, please check the documentation of `R2`.
"""
mutable struct R2Solver{T, V} <: AbstractOptimizationSolver end
Base.@deprecate R2Solver(nlp::AbstractNLPModel; kwargs...) FoSolver(
nlp::AbstractNLPModel;
M = 1,
kwargs...,
)
@doc (@doc FoSolver) function fo(nlp::AbstractNLPModel{T, V}; M::Int = 1, kwargs...) where {T, V}
solver = FoSolver(nlp; M)
stats = GenericExecutionStats(nlp)
return solve!(solver, nlp, stats; step_backend = r2_step(), kwargs...)
end
@doc (@doc FoSolver) function R2(nlp::AbstractNLPModel{T, V}; kwargs...) where {T, V}
fo(nlp; step_backend = r2_step(), kwargs...)
end
@doc (@doc FoSolver) function TR(nlp::AbstractNLPModel{T, V}; kwargs...) where {T, V}
fo(nlp; step_backend = tr_step(), kwargs...)
end
function SolverCore.reset!(solver::FoSolver{T}) where {T}
fill!(solver.o, -Inf)
solver
end
SolverCore.reset!(solver::FoSolver, ::AbstractNLPModel) = reset!(solver)
function SolverCore.solve!(
solver::Union{FoSolver, FomoSolver},
nlp::AbstractNLPModel{T, V},
stats::GenericExecutionStats{T, V};
callback = (args...) -> nothing,
x::V = nlp.meta.x0,
atol::T = √eps(T),
rtol::T = √eps(T),
η1::T = T(eps(T)^(1 / 4)),
η2::T = T(0.95),
γ1::T = T(1 / 2),
γ2::T = T(2),
γ3::T = T(1 / 2),
αmax::T = 1 / eps(T),
max_time::Float64 = 30.0,
max_eval::Int = -1,
max_iter::Int = typemax(Int),
β::T = T(0.9),
θ1::T = T(0.1),
θ2::T = T(eps(T)^(1 / 3)),
verbose::Int = 0,
step_backend = r2_step(),
) where {T, V}
use_momentum = typeof(solver) <: FomoSolver
is_r2 = typeof(step_backend) <: r2_step
unconstrained(nlp) || error("fomo should only be called on unconstrained problems.")
reset!(stats)
start_time = time()
set_time!(stats, 0.0)
x = solver.x .= x
∇fk = solver.g
c = solver.c
momentum = use_momentum ? solver.m : nothing # not used if no momentum
d = use_momentum ? solver.d : solver.g # g = d if no momentum
p = use_momentum ? solver.p : nothing # not used if no momentum
set_iter!(stats, 0)
f0 = obj(nlp, x)
set_objective!(stats, f0)
obj_mem = solver.o
M = length(obj_mem)
mem_ind = 0
obj_mem[mem_ind + 1] = stats.objective
max_obj_mem = stats.objective
grad!(nlp, x, ∇fk)
norm_∇fk = norm(∇fk)
set_dual_residual!(stats, norm_∇fk)
solver.α = init_alpha(norm_∇fk, step_backend)
# Stopping criterion:
fmin = min(-one(T), f0) / eps(T)
unbounded = f0 < fmin
ϵ = atol + rtol * norm_∇fk
optimal = norm_∇fk ≤ ϵ
step_param_name = is_r2 ? "σ" : "Δ"
if optimal
@info("Optimal point found at initial point")
if is_r2
@info @sprintf "%5s %9s %7s %7s " "iter" "f" "‖∇f‖" step_param_name
@info @sprintf "%5d %9.2e %7.1e %7.1e" stats.iter stats.objective norm_∇fk 1 / solver.α
else
@info @sprintf "%5s %9s %7s %7s " "iter" "f" "‖∇f‖" step_param_name
@info @sprintf "%5d %9.2e %7.1e %7.1e" stats.iter stats.objective norm_∇fk solver.α
end
else
if verbose > 0 && mod(stats.iter, verbose) == 0
step_param = is_r2 ? 1 / solver.α : solver.α
if !use_momentum
@info @sprintf "%5s %9s %7s %7s %7s " "iter" "f" "‖∇f‖" step_param_name "ρk"
infoline =
@sprintf "%5d %9.2e %7.1e %7.1e %7.1e" stats.iter stats.objective norm_∇fk step_param ' '
else
@info @sprintf "%5s %9s %7s %7s %7s %7s " "iter" "f" "‖∇f‖" step_param_name "ρk" "βmax"
infoline =
@sprintf "%5d %9.2e %7.1e %7.1e %7.1e %7.1e" stats.iter stats.objective norm_∇fk step_param ' ' 0
end
end
end
set_status!(
stats,
get_status(
nlp,
elapsed_time = stats.elapsed_time,
optimal = optimal,
unbounded = unbounded,
max_eval = max_eval,
iter = stats.iter,
max_iter = max_iter,
max_time = max_time,
),
)
callback(nlp, solver, stats)
done = stats.status != :unknown
d .= ∇fk
norm_d = norm_∇fk
βmax = T(0)
ρk = T(0)
avgβmax = T(0)
siter::Int = 0
oneT = T(1)
mdot∇f = T(0) # dot(momentum,∇fk)
while !done
μk = step_mult(solver.α, norm_d, step_backend)
c .= x .- μk .* d
step_underflow = x == c # step addition underfow on every dimensions, should happen before solver.α == 0
ΔTk = ((oneT - βmax) * norm_∇fk^2 + βmax * mdot∇f) * μk # = dot(d,∇fk) * μk with momentum, ‖∇fk‖²μk without momentum
fck = obj(nlp, c)
unbounded = fck < fmin
ρk = (max_obj_mem - fck) / (max_obj_mem - stats.objective + ΔTk)
# Update regularization parameters
if ρk >= η2
solver.α = min(αmax, γ2 * solver.α)
elseif ρk < η1
solver.α = solver.α * γ1
if use_momentum
βmax *= γ3
d .= ∇fk .* (oneT - βmax) .+ momentum .* βmax
end
end
# Acceptance of the new candidate
if ρk >= η1
x .= c
if use_momentum
momentum .= ∇fk .* (oneT - β) .+ momentum .* β
end
set_objective!(stats, fck)
mem_ind = (mem_ind + 1) % M
obj_mem[mem_ind + 1] = stats.objective
max_obj_mem = maximum(obj_mem)
grad!(nlp, x, ∇fk)
norm_∇fk = norm(∇fk)
if use_momentum
mdot∇f = dot(momentum, ∇fk)
p .= momentum .- ∇fk
βmax = find_beta(p, mdot∇f, norm_∇fk, μk, stats.objective, max_obj_mem, β, θ1, θ2)
d .= ∇fk .* (oneT - βmax) .+ momentum .* βmax
norm_d = norm(d)
avgβmax += βmax
siter += 1
end
end
set_iter!(stats, stats.iter + 1)
set_time!(stats, time() - start_time)
set_dual_residual!(stats, norm_∇fk)
optimal = norm_∇fk ≤ ϵ
if verbose > 0 && mod(stats.iter, verbose) == 0
@info infoline
step_param = is_r2 ? 1 / solver.α : solver.α
if !use_momentum
infoline =
@sprintf "%5d %9.2e %7.1e %7.1e %7.1e" stats.iter stats.objective norm_∇fk step_param ρk
else
infoline =
@sprintf "%5d %9.2e %7.1e %7.1e %7.1e %7.1e" stats.iter stats.objective norm_∇fk step_param ρk βmax
end
end
set_status!(
stats,
get_status(
nlp,
elapsed_time = stats.elapsed_time,
optimal = optimal,
unbounded = unbounded,
max_eval = max_eval,
iter = stats.iter,
max_iter = max_iter,
max_time = max_time,
),
)
callback(nlp, solver, stats)
step_underflow && set_status!(stats, :small_step)
solver.α == 0 && set_status!(stats, :exception) # :small_nlstep exception should happen before
done = stats.status != :unknown
end
if use_momentum
avgβmax /= siter
set_solver_specific!(stats, :avgβmax, avgβmax)
end
set_solution!(stats, x)
return stats
end
"""
find_beta(m, mdot∇f, norm_∇f, μk, fk, max_obj_mem, β, θ1, θ2)
Compute βmax which saturates the contribution of the momentum term to the gradient.
`βmax` is computed such that the two gradient-related conditions (first one is relaxed in the nonmonotone case) are ensured:
1. (1-βmax) * ‖∇f(xk)‖² + βmax * ∇f(xk)ᵀm + (max_obj_mem - fk)/μk ≥ θ1 * ‖∇f(xk)‖²
2. ‖∇f(xk)‖ ≥ θ2 * ‖(1-βmax) * ∇f(xk) .+ βmax .* m‖
with `m` the momentum term and `mdot∇f = ∇f(xk)ᵀm`, `fk` the model at s=0, `max_obj_mem` the largest objective value over the last M successful iterations.
"""
function find_beta(
p::V,
mdot∇f::T,
norm_∇f::T,
μk::T,
fk::T,
max_obj_mem::T,
β::T,
θ1::T,
θ2::T,
) where {T, V}
n1 = norm_∇f^2 - mdot∇f
n2 = norm(p)
β1 = n1 > 0 ? ((1 - θ1) * norm_∇f^2 - (fk - max_obj_mem) / μk) / n1 : β
β2 = n2 != 0 ? (1 - θ2) * norm_∇f / n2 : β
return min(β, min(β1, β2))
end
"""
init_alpha(norm_∇fk::T, ::r2_step)
init_alpha(norm_∇fk::T, ::tr_step)
Initialize `α` step size parameter.
Ensure first step is the same for quadratic regularization and trust region methods.
"""
function init_alpha(norm_∇fk::T, ::r2_step) where {T}
1 / 2^round(log2(norm_∇fk + 1))
end
function init_alpha(norm_∇fk::T, ::tr_step) where {T}
norm_∇fk / 2^round(log2(norm_∇fk + 1))
end
"""
step_mult(α::T, norm_∇fk::T, ::r2_step)
step_mult(α::T, norm_∇fk::T, ::tr_step)
Compute step size multiplier: `α` for quadratic regularization(`::r2` and `::R2og`) and `α/norm_∇fk` for trust region (`::tr`).
"""
function step_mult(α::T, norm_∇fk::T, ::r2_step) where {T}
α
end
function step_mult(α::T, norm_∇fk::T, ::tr_step) where {T}
α / norm_∇fk
end
| JSOSolvers | https://github.com/JuliaSmoothOptimizers/JSOSolvers.jl.git |
|
[
"MPL-2.0"
] | 0.12.1 | c68e031e469f1898bb779cbc3c401e1640ecc0c4 | code | 5941 | export lbfgs, LBFGSSolver
"""
lbfgs(nlp; kwargs...)
An implementation of a limited memory BFGS line-search method for unconstrained minimization.
For advanced usage, first define a `LBFGSSolver` to preallocate the memory used in the algorithm, and then call `solve!`.
solver = LBFGSSolver(nlp; mem::Int = 5)
solve!(solver, nlp; kwargs...)
# Arguments
- `nlp::AbstractNLPModel{T, V}` represents the model to solve, see `NLPModels.jl`.
The keyword arguments may include
- `x::V = nlp.meta.x0`: the initial guess.
- `mem::Int = 5`: memory parameter of the `lbfgs` algorithm.
- `atol::T = √eps(T)`: absolute tolerance.
- `rtol::T = √eps(T)`: relative tolerance, the algorithm stops when ‖∇f(xᵏ)‖ ≤ atol + rtol * ‖∇f(x⁰)‖.
- `max_eval::Int = -1`: maximum number of objective function evaluations.
- `max_time::Float64 = 30.0`: maximum time limit in seconds.
- `max_iter::Int = typemax(Int)`: maximum number of iterations.
- `τ₁::T = T(0.9999)`: slope factor in the Wolfe condition when performing the line search.
- `bk_max:: Int = 25`: maximum number of backtracks when performing the line search.
- `verbose::Int = 0`: if > 0, display iteration details every `verbose` iteration.
- `verbose_subsolver::Int = 0`: if > 0, display iteration information every `verbose_subsolver` iteration of the subsolver.
# Output
The returned value is a `GenericExecutionStats`, see `SolverCore.jl`.
# Callback
$(Callback_docstring)
# Examples
```jldoctest
using JSOSolvers, ADNLPModels
nlp = ADNLPModel(x -> sum(x.^2), ones(3));
stats = lbfgs(nlp)
# output
"Execution stats: first-order stationary"
```
```jldoctest
using JSOSolvers, ADNLPModels
nlp = ADNLPModel(x -> sum(x.^2), ones(3));
solver = LBFGSSolver(nlp; mem = 5);
stats = solve!(solver, nlp)
# output
"Execution stats: first-order stationary"
```
"""
mutable struct LBFGSSolver{T, V, Op <: AbstractLinearOperator{T}, M <: AbstractNLPModel{T, V}} <:
AbstractOptimizationSolver
x::V
xt::V
gx::V
gt::V
d::V
H::Op
h::LineModel{T, V, M}
end
function LBFGSSolver(nlp::M; mem::Int = 5) where {T, V, M <: AbstractNLPModel{T, V}}
nvar = nlp.meta.nvar
x = V(undef, nvar)
d = V(undef, nvar)
xt = V(undef, nvar)
gx = V(undef, nvar)
gt = V(undef, nvar)
H = InverseLBFGSOperator(T, nvar, mem = mem, scaling = true)
h = LineModel(nlp, x, d)
Op = typeof(H)
return LBFGSSolver{T, V, Op, M}(x, xt, gx, gt, d, H, h)
end
function SolverCore.reset!(solver::LBFGSSolver)
reset!(solver.H)
end
function SolverCore.reset!(solver::LBFGSSolver, nlp::AbstractNLPModel)
reset!(solver.H)
solver.h = LineModel(nlp, solver.x, solver.d)
solver
end
@doc (@doc LBFGSSolver) function lbfgs(
nlp::AbstractNLPModel;
x::V = nlp.meta.x0,
mem::Int = 5,
kwargs...,
) where {V}
solver = LBFGSSolver(nlp; mem = mem)
return solve!(solver, nlp; x = x, kwargs...)
end
function SolverCore.solve!(
solver::LBFGSSolver{T, V},
nlp::AbstractNLPModel{T, V},
stats::GenericExecutionStats{T, V};
callback = (args...) -> nothing,
x::V = nlp.meta.x0,
atol::T = √eps(T),
rtol::T = √eps(T),
max_eval::Int = -1,
max_iter::Int = typemax(Int),
max_time::Float64 = 30.0,
τ₁::T = T(0.9999),
bk_max::Int = 25,
verbose::Int = 0,
verbose_subsolver::Int = 0,
) where {T, V}
if !(nlp.meta.minimize)
error("lbfgs only works for minimization problem")
end
if !unconstrained(nlp)
error("lbfgs should only be called for unconstrained problems. Try tron instead")
end
reset!(stats)
start_time = time()
set_time!(stats, 0.0)
n = nlp.meta.nvar
solver.x .= x
x = solver.x
xt = solver.xt
∇f = solver.gx
∇ft = solver.gt
d = solver.d
h = solver.h
H = solver.H
reset!(H)
f, ∇f = objgrad!(nlp, x, ∇f)
∇fNorm = nrm2(n, ∇f)
ϵ = atol + rtol * ∇fNorm
set_iter!(stats, 0)
set_objective!(stats, f)
set_dual_residual!(stats, ∇fNorm)
verbose > 0 && @info log_header(
[:iter, :f, :dual, :slope, :bk],
[Int, T, T, T, Int],
hdr_override = Dict(:f => "f(x)", :dual => "‖∇f‖", :slope => "∇fᵀd"),
)
verbose > 0 && @info log_row(Any[stats.iter, f, ∇fNorm, T, Int])
optimal = ∇fNorm ≤ ϵ
fmin = min(-one(T), f) / eps(T)
unbounded = f < fmin
set_status!(
stats,
get_status(
nlp,
elapsed_time = stats.elapsed_time,
optimal = optimal,
unbounded = unbounded,
max_eval = max_eval,
iter = stats.iter,
max_iter = max_iter,
max_time = max_time,
),
)
callback(nlp, solver, stats)
done = stats.status != :unknown
while !done
mul!(d, H, ∇f, -one(T), zero(T))
slope = dot(n, d, ∇f)
if slope ≥ 0
@error "not a descent direction" slope
set_status!(stats, :not_desc)
done = true
continue
end
# Perform improved Armijo linesearch.
t, good_grad, ft, nbk, nbW =
armijo_wolfe(h, f, slope, ∇ft, τ₁ = τ₁, bk_max = bk_max, verbose = Bool(verbose_subsolver))
copyaxpy!(n, t, d, x, xt)
good_grad || grad!(nlp, xt, ∇ft)
# Update L-BFGS approximation.
d .*= t
@. ∇f = ∇ft - ∇f
push!(H, d, ∇f)
# Move on.
x .= xt
f = ft
∇f .= ∇ft
∇fNorm = nrm2(n, ∇f)
set_iter!(stats, stats.iter + 1)
verbose > 0 &&
mod(stats.iter, verbose) == 0 &&
@info log_row(Any[stats.iter, f, ∇fNorm, slope, nbk])
set_objective!(stats, f)
set_time!(stats, time() - start_time)
set_dual_residual!(stats, ∇fNorm)
optimal = ∇fNorm ≤ ϵ
unbounded = f < fmin
set_status!(
stats,
get_status(
nlp,
elapsed_time = stats.elapsed_time,
optimal = optimal,
unbounded = unbounded,
max_eval = max_eval,
iter = stats.iter,
max_iter = max_iter,
max_time = max_time,
),
)
callback(nlp, solver, stats)
done = stats.status != :unknown
end
verbose > 0 && @info log_row(Any[stats.iter, f, ∇fNorm])
set_solution!(stats, x)
stats
end
| JSOSolvers | https://github.com/JuliaSmoothOptimizers/JSOSolvers.jl.git |
|
[
"MPL-2.0"
] | 0.12.1 | c68e031e469f1898bb779cbc3c401e1640ecc0c4 | code | 15034 | # Some parts of this code were adapted from
# https://github.com/PythonOptimizers/NLP.py/blob/develop/nlp/optimize/tron.py
export tron, TronSolver
tron(nlp::AbstractNLPModel; variant = :Newton, kwargs...) = tron(Val(variant), nlp; kwargs...)
"""
tron(nlp; kwargs...)
A pure Julia implementation of a trust-region solver for bound-constrained optimization:
min f(x) s.t. ℓ ≦ x ≦ u
For advanced usage, first define a `TronSolver` to preallocate the memory used in the algorithm, and then call `solve!`:
solver = TronSolver(nlp; kwargs...)
solve!(solver, nlp; kwargs...)
# Arguments
- `nlp::AbstractNLPModel{T, V}` represents the model to solve, see `NLPModels.jl`.
The keyword arguments may include
- `x::V = nlp.meta.x0`: the initial guess.
- `μ₀::T = T(1e-2)`: algorithm parameter in (0, 0.5).
- `μ₁::T = one(T)`: algorithm parameter in (0, +∞).
- `σ::T = T(10)`: algorithm parameter in (1, +∞).
- `max_eval::Int = -1`: maximum number of objective function evaluations.
- `max_time::Float64 = 30.0`: maximum time limit in seconds.
- `max_iter::Int = typemax(Int)`: maximum number of iterations.
- `max_cgiter::Int = 50`: subproblem's iteration limit.
- `use_only_objgrad::Bool = false`: If `true`, the algorithm uses only the function `objgrad` instead of `obj` and `grad`.
- `cgtol::T = T(0.1)`: subproblem tolerance.
- `atol::T = √eps(T)`: absolute tolerance.
- `rtol::T = √eps(T)`: relative tolerance, the algorithm stops when ‖x - Proj(x - ∇f(xᵏ))‖ ≤ atol + rtol * ‖∇f(x⁰)‖. Proj denotes here the projection over the bounds.
- `verbose::Int = 0`: if > 0, display iteration details every `verbose` iteration.
- `subsolver_verbose::Int = 0`: if > 0, display iteration information every `subsolver_verbose` iteration of the subsolver.
The keyword arguments of `TronSolver` are passed to the [`TRONTrustRegion`](https://github.com/JuliaSmoothOptimizers/SolverTools.jl/blob/main/src/trust-region/tron-trust-region.jl) constructor.
# Output
The value returned is a `GenericExecutionStats`, see `SolverCore.jl`.
# Callback
$(Callback_docstring)
# References
TRON is described in
Chih-Jen Lin and Jorge J. Moré, *Newton's Method for Large Bound-Constrained
Optimization Problems*, SIAM J. Optim., 9(4), 1100–1127, 1999.
DOI: 10.1137/S1052623498345075
# Examples
```jldoctest; output = false
using JSOSolvers, ADNLPModels
nlp = ADNLPModel(x -> sum(x), ones(3), zeros(3), 2 * ones(3));
stats = tron(nlp)
# output
"Execution stats: first-order stationary"
```
```jldoctest; output = false
using JSOSolvers, ADNLPModels
nlp = ADNLPModel(x -> sum(x), ones(3), zeros(3), 2 * ones(3));
solver = TronSolver(nlp);
stats = solve!(solver, nlp)
# output
"Execution stats: first-order stationary"
```
"""
mutable struct TronSolver{
T,
V <: AbstractVector{T},
Op <: AbstractLinearOperator{T},
Aop <: AbstractLinearOperator{T},
} <: AbstractOptimizationSolver
x::V
xc::V
temp::V
gx::V
gt::V
gn::V
gpx::V
s::V
Hs::V
H::Op
tr::TRONTrustRegion{T, V}
ifix::BitVector
cg_solver::CgSolver{T, T, V}
cg_rhs::V
cg_op_diag::V
cg_op::LinearOperator{T}
ZHZ::Aop
end
function TronSolver(
nlp::AbstractNLPModel{T, V};
max_radius::T = min(one(T) / sqrt(2 * eps(T)), T(100)),
kwargs...,
) where {T, V <: AbstractVector{T}}
nvar = nlp.meta.nvar
x = V(undef, nvar)
xc = V(undef, nvar)
temp = V(undef, nvar)
gx = V(undef, nvar)
gt = V(undef, nvar)
gn = isa(nlp, QuasiNewtonModel) ? V(undef, nvar) : V(undef, 0)
gpx = V(undef, nvar)
s = V(undef, nvar)
Hs = V(undef, nvar)
H = hess_op!(nlp, xc, Hs)
Op = typeof(H)
tr = TRONTrustRegion(gt, min(one(T), max_radius - eps(T)); max_radius = max_radius, kwargs...)
ifix = BitVector(undef, nvar)
cg_rhs = V(undef, nvar)
cg_op_diag = V(undef, nvar)
cg_op = opDiagonal(cg_op_diag)
ZHZ = cg_op' * H * cg_op
cg_solver = CgSolver(ZHZ, Hs)
return TronSolver{T, V, Op, typeof(ZHZ)}(
x,
xc,
temp,
gx,
gt,
gn,
gpx,
s,
Hs,
H,
tr,
ifix,
cg_solver,
cg_rhs,
cg_op_diag,
cg_op,
ZHZ,
)
end
function SolverCore.reset!(solver::TronSolver)
solver.tr.good_grad = false
solver
end
function SolverCore.reset!(solver::TronSolver, nlp::AbstractNLPModel)
@assert (length(solver.gn) == 0) || isa(nlp, QuasiNewtonModel)
solver.H = hess_op!(nlp, solver.xc, solver.Hs)
solver.ZHZ = solver.cg_op' * solver.H * solver.cg_op
solver.tr.good_grad = false
solver
end
@doc (@doc TronSolver) function tron(
::Val{:Newton},
nlp::AbstractNLPModel{T, V};
x::V = nlp.meta.x0,
kwargs...,
) where {T, V}
dict = Dict(kwargs)
subsolver_keys = intersect(keys(dict), tron_keys)
subsolver_kwargs = Dict(k => dict[k] for k in subsolver_keys)
solver = TronSolver(nlp; subsolver_kwargs...)
for k in subsolver_keys
pop!(dict, k)
end
return solve!(solver, nlp; x = x, dict...)
end
function SolverCore.solve!(
solver::TronSolver{T, V},
nlp::AbstractNLPModel{T, V},
stats::GenericExecutionStats{T, V};
callback = (args...) -> nothing,
x::V = nlp.meta.x0,
μ₀::T = T(1e-2),
μ₁::T = one(T),
σ::T = T(10),
max_eval::Int = -1,
max_iter::Int = typemax(Int),
max_time::Float64 = 30.0,
max_cgiter::Int = 50,
use_only_objgrad::Bool = false,
cgtol::T = T(0.1),
atol::T = √eps(T),
rtol::T = √eps(T),
verbose::Int = 0,
subsolver_verbose::Int = 0,
) where {T, V <: AbstractVector{T}}
if !(nlp.meta.minimize)
error("tron only works for minimization problem")
end
if !(unconstrained(nlp) || bound_constrained(nlp))
error("tron should only be called for unconstrained or bound-constrained problems")
end
reset!(stats)
ℓ = nlp.meta.lvar
u = nlp.meta.uvar
n = nlp.meta.nvar
if (verbose > 0 && !(u ≥ x ≥ ℓ))
@warn "Warning: Initial guess is not within bounds."
end
start_time = time()
set_time!(stats, 0.0)
solver.x .= x
x = solver.x
xc = solver.xc
gx = solver.gx
gt = solver.gt
gn = solver.gn
gpx = solver.gpx
s = solver.s
Hs = solver.Hs
H = solver.H
x .= max.(ℓ, min.(x, u))
fx, _ = objgrad!(nlp, x, gx)
# gt = use_only_objgrad ? zeros(T, n) : T[]
num_success_iters = 0
# Optimality measure
project_step!(gpx, x, gx, ℓ, u, -one(T))
πx = nrm2(n, gpx)
ϵ = atol + rtol * πx
fmin = min(-one(T), fx) / eps(T)
optimal = πx <= ϵ
unbounded = fx < fmin
set_iter!(stats, 0)
set_objective!(stats, fx)
set_dual_residual!(stats, πx)
if isa(nlp, QuasiNewtonModel)
gn .= gx
end
αC = one(T)
tr = solver.tr
tr.radius = tr.initial_radius = min(max(one(T), πx / 10), tr.max_radius)
verbose > 0 && @info log_header(
[:iter, :f, :dual, :radius, :ratio, :cgstatus],
[Int, T, T, T, T, String],
hdr_override = Dict(:f => "f(x)", :dual => "π", :radius => "Δ"),
)
verbose > 0 && @info log_row([stats.iter, fx, πx, T, T, String])
set_status!(
stats,
get_status(
nlp,
elapsed_time = stats.elapsed_time,
optimal = optimal,
unbounded = unbounded,
max_eval = max_eval,
iter = stats.iter,
max_iter = max_iter,
max_time = max_time,
),
)
callback(nlp, solver, stats)
done = stats.status != :unknown
while !done
# Current iteration
xc .= x # implicitly update H = hess_op!(nlp, xc, Hs)
fc = fx
Δ = tr.radius
αC, s, cauchy_status = cauchy!(x, H, gx, Δ, αC, ℓ, u, s, Hs, μ₀ = μ₀, μ₁ = μ₁, σ = σ)
if cauchy_status != :success
stats.status = cauchy_status
done = true
continue
end
cginfo = projected_newton!(
solver,
x,
H,
gx,
Δ,
cgtol,
ℓ,
u,
s,
Hs,
max_cgiter = max_cgiter,
max_time = max_time - stats.elapsed_time,
subsolver_verbose = subsolver_verbose,
)
slope = dot(n, gx, s)
qs = dot(n, s, Hs) / 2 + slope
fx = if use_only_objgrad
objgrad!(nlp, x, gt)[1]
else
obj(nlp, x)
end
ared, pred = aredpred!(tr, nlp, fc, fx, qs, x, s, slope)
if pred ≥ 0
stats.status = :neg_pred
done = true
continue
end
tr.ratio = ared / pred
if acceptable(tr)
num_success_iters += 1
if use_only_objgrad
gx .= gt
else
grad!(nlp, x, gx)
end
project_step!(gpx, x, gx, ℓ, u, -one(T))
πx = nrm2(n, gpx)
if isa(nlp, QuasiNewtonModel)
gn .-= gx
gn .*= -1 # gn = ∇f(xₖ₊₁) - ∇f(xₖ)
push!(nlp, s, gn)
gn .= gx
end
end
if !acceptable(tr)
fx = fc
x .= xc
end
set_iter!(stats, stats.iter + 1)
verbose > 0 &&
mod(stats.iter, verbose) == 0 &&
@info log_row([stats.iter, fx, πx, Δ, tr.ratio, cginfo])
s_norm = nrm2(n, s)
if num_success_iters == 0
tr.radius = min(Δ, s_norm)
end
# Update the trust region
update!(tr, s_norm)
optimal = πx <= ϵ
unbounded = fx < fmin
set_objective!(stats, fx)
set_time!(stats, time() - start_time)
set_dual_residual!(stats, πx)
set_status!(
stats,
get_status(
nlp,
elapsed_time = stats.elapsed_time,
optimal = optimal,
unbounded = unbounded,
max_eval = max_eval,
iter = stats.iter,
max_iter = max_iter,
max_time = max_time,
),
)
callback(nlp, solver, stats)
done = stats.status != :unknown
end
verbose > 0 && @info log_row(Any[stats.iter, fx, πx, tr.radius])
set_solution!(stats, x)
stats
end
"""`s = projected_line_search!(x, H, g, d, ℓ, u, Hs; μ₀ = 1e-2)`
Performs a projected line search, searching for a step size `t` such that
0.5sᵀHs + sᵀg ≦ μ₀sᵀg,
where `s = P(x + t * d) - x`, while remaining on the same face as `x + d`.
Backtracking is performed from t = 1.0. `x` is updated in place.
"""
function projected_line_search!(
x::AbstractVector{T},
H::Union{AbstractMatrix, AbstractLinearOperator},
g::AbstractVector{T},
d::AbstractVector{T},
ℓ::AbstractVector{T},
u::AbstractVector{T},
Hs::AbstractVector{T},
s::AbstractVector{T};
μ₀::Real = T(1e-2),
) where {T <: Real}
α = one(T)
_, brkmin, _ = breakpoints(x, d, ℓ, u)
nsteps = 0
s .= zero(T)
Hs .= zero(T)
search = true
while search && α > brkmin
nsteps += 1
project_step!(s, x, d, ℓ, u, α)
slope, qs = compute_Hs_slope_qs!(Hs, H, s, g)
if qs <= μ₀ * slope
search = false
else
α /= 2
end
end
if α < 1 && α < brkmin
α = brkmin
project_step!(s, x, d, ℓ, u, α)
slope, qs = compute_Hs_slope_qs!(Hs, H, s, g)
end
project_step!(s, x, d, ℓ, u, α)
x .= x .+ s
return s
end
"""`α, s = cauchy!(x, H, g, Δ, ℓ, u, s, Hs; μ₀ = 1e-2, μ₁ = 1.0, σ=10.0)`
Computes a Cauchy step `s = P(x - α g) - x` for
min q(s) = ¹/₂sᵀHs + gᵀs s.t. ‖s‖ ≦ μ₁Δ, ℓ ≦ x + s ≦ u,
with the sufficient decrease condition
q(s) ≦ μ₀sᵀg.
"""
function cauchy!(
x::AbstractVector{T},
H::Union{AbstractMatrix, AbstractLinearOperator},
g::AbstractVector{T},
Δ::Real,
α::Real,
ℓ::AbstractVector{T},
u::AbstractVector{T},
s::AbstractVector{T},
Hs::AbstractVector{T};
μ₀::Real = T(1e-2),
μ₁::Real = one(T),
σ::Real = T(10),
) where {T <: Real}
# TODO: Use brkmin to care for g direction
s .= .-g
_, _, brkmax = breakpoints(x, s, ℓ, u)
n = length(x)
s .= zero(T)
Hs .= zero(T)
status = :success
project_step!(s, x, g, ℓ, u, -α)
# Interpolate or extrapolate
s_norm = nrm2(n, s)
if s_norm > μ₁ * Δ
interp = true
else
slope, qs = compute_Hs_slope_qs!(Hs, H, s, g)
interp = qs >= μ₀ * slope
end
if interp
search = true
while search
α /= σ
project_step!(s, x, g, ℓ, u, -α)
s_norm = nrm2(n, s)
if s_norm <= μ₁ * Δ
slope, qs = compute_Hs_slope_qs!(Hs, H, s, g)
search = qs >= μ₀ * slope
end
# TODO: Correctly assess why this fails
if α < sqrt(nextfloat(zero(α)))
search = false
status = :small_step
end
end
else
search = true
αs = α
while search && α <= brkmax
α *= σ
project_step!(s, x, g, ℓ, u, -α)
s_norm = nrm2(n, s)
if s_norm <= μ₁ * Δ
slope, qs = compute_Hs_slope_qs!(Hs, H, s, g)
if qs <= μ₀ * slope
αs = α
end
else
search = false
end
end
# Recover the last successful step
α = αs
s = project_step!(s, x, g, ℓ, u, -α)
end
return α, s, status
end
"""
projected_newton!(solver, x, H, g, Δ, cgtol, ℓ, u, s, Hs; max_time = Inf, max_cgiter = 50, subsolver_verbose = 0)
Compute an approximate solution `d` for
min q(d) = ¹/₂dᵀHs + dᵀg s.t. ℓ ≦ x + d ≦ u, ‖d‖ ≦ Δ
starting from `s`. The steps are computed using the conjugate gradient method
projected on the active bounds.
"""
function projected_newton!(
solver::TronSolver{T},
x::AbstractVector{T},
H::Union{AbstractMatrix, AbstractLinearOperator},
g::AbstractVector{T},
Δ::T,
cgtol::T,
ℓ::AbstractVector{T},
u::AbstractVector{T},
s::AbstractVector{T},
Hs::AbstractVector{T};
max_cgiter::Int = 50,
max_time::Float64 = Inf,
subsolver_verbose = 0,
) where {T <: Real}
start_time, elapsed_time = time(), 0.0
n = length(x)
status = ""
cg_solver, cgs_rhs = solver.cg_solver, solver.cg_rhs
cg_op_diag, ZHZ = solver.cg_op_diag, solver.ZHZ
w = solver.temp
ifix = solver.ifix
mul!(Hs, H, s)
# Projected Newton Step
exit_optimal, exit_pcg, exit_itmax, exit_time = false, false, false, false
iters = 0
x .= x .+ s
project!(x, x, ℓ, u)
while !(exit_optimal || exit_pcg || exit_itmax || exit_time)
active!(ifix, x, ℓ, u)
if sum(ifix) == n
exit_optimal = true
continue
end
gfnorm = 0
for i = 1:n
cgs_rhs[i] = ifix[i] ? 0 : -g[i]
gfnorm += cgs_rhs[i]^2
cgs_rhs[i] -= ifix[i] ? 0 : Hs[i]
cg_op_diag[i] = ifix[i] ? 0 : 1 # implictly changes cg_op and so ZHZ
end
Krylov.cg!(
cg_solver,
ZHZ,
cgs_rhs,
radius = Δ,
rtol = cgtol,
atol = zero(T),
timemax = max_time - elapsed_time,
verbose = subsolver_verbose,
)
st, stats = cg_solver.x, cg_solver.stats
status = stats.status
iters += 1
# Projected line search
cgs_rhs .*= -1
projected_line_search!(x, ZHZ, cgs_rhs, st, ℓ, u, Hs, w)
s .+= w
mul!(Hs, H, s)
newnorm = 0
for i = 1:n
cgs_rhs[i] = ifix[i] ? 0 : Hs[i] + g[i]
newnorm += cgs_rhs[i]^2
end
if √newnorm <= cgtol * √gfnorm
exit_optimal = true
elseif status == "on trust-region boundary"
exit_pcg = true
elseif iters >= max_cgiter
exit_itmax = true
end
elapsed_time = time() - start_time
exit_time = elapsed_time >= max_time
end
status = if exit_optimal
"stationary point found"
elseif exit_pcg
"on trust-region boundary"
elseif exit_itmax
"maximum number of iterations"
elseif exit_time
"time limit exceeded"
else
status # unknown
end
return status
end
| JSOSolvers | https://github.com/JuliaSmoothOptimizers/JSOSolvers.jl.git |
|
[
"MPL-2.0"
] | 0.12.1 | c68e031e469f1898bb779cbc3c401e1640ecc0c4 | code | 16178 | export TronSolverNLS
const tronls_allowed_subsolvers = [CglsSolver, CrlsSolver, LsqrSolver, LsmrSolver]
tron(nls::AbstractNLSModel; variant = :GaussNewton, kwargs...) = tron(Val(variant), nls; kwargs...)
"""
tron(nls; kwargs...)
A pure Julia implementation of a trust-region solver for bound-constrained
nonlinear least-squares problems:
min ½‖F(x)‖² s.t. ℓ ≦ x ≦ u
For advanced usage, first define a `TronSolverNLS` to preallocate the memory used in the algorithm, and then call `solve!`:
solver = TronSolverNLS(nls, subsolver_type::Type{<:KrylovSolver} = LsmrSolver; kwargs...)
solve!(solver, nls; kwargs...)
# Arguments
- `nls::AbstractNLSModel{T, V}` represents the model to solve, see `NLPModels.jl`.
The keyword arguments may include
- `x::V = nlp.meta.x0`: the initial guess.
- `subsolver_type::Symbol = LsmrSolver`: `Krylov.jl` method used as subproblem solver, see `JSOSolvers.tronls_allowed_subsolvers` for a list.
- `μ₀::T = T(1e-2)`: algorithm parameter in (0, 0.5).
- `μ₁::T = one(T)`: algorithm parameter in (0, +∞).
- `σ::T = T(10)`: algorithm parameter in (1, +∞).
- `max_eval::Int = -1`: maximum number of objective function evaluations.
- `max_time::Float64 = 30.0`: maximum time limit in seconds.
- `max_iter::Int = typemax(Int)`: maximum number of iterations.
- `max_cgiter::Int = 50`: subproblem iteration limit.
- `cgtol::T = T(0.1)`: subproblem tolerance.
- `atol::T = √eps(T)`: absolute tolerance.
- `rtol::T = √eps(T)`: relative tolerance, the algorithm stops when ‖x - Proj(x - ∇f(xᵏ))‖ ≤ atol + rtol * ‖∇f(x⁰)‖. Proj denotes here the projection over the bounds.
- `Fatol::T = √eps(T)`: absolute tolerance on the residual.
- `Frtol::T = eps(T)`: relative tolerance on the residual, the algorithm stops when ‖F(xᵏ)‖ ≤ Fatol + Frtol * ‖F(x⁰)‖.
- `verbose::Int = 0`: if > 0, display iteration details every `verbose` iteration.
- `subsolver_verbose::Int = 0`: if > 0, display iteration information every `subsolver_verbose` iteration of the subsolver.
The keyword arguments of `TronSolverNLS` are passed to the [`TRONTrustRegion`](https://github.com/JuliaSmoothOptimizers/SolverTools.jl/blob/main/src/trust-region/tron-trust-region.jl) constructor.
# Output
The value returned is a `GenericExecutionStats`, see `SolverCore.jl`.
# Callback
$(Callback_docstring)
# References
This is an adaptation for bound-constrained nonlinear least-squares problems of the TRON method described in
Chih-Jen Lin and Jorge J. Moré, *Newton's Method for Large Bound-Constrained
Optimization Problems*, SIAM J. Optim., 9(4), 1100–1127, 1999.
DOI: 10.1137/S1052623498345075
# Examples
```jldoctest; output = false
using JSOSolvers, ADNLPModels
F(x) = [x[1] - 1.0; 10 * (x[2] - x[1]^2)]
x0 = [-1.2; 1.0]
nls = ADNLSModel(F, x0, 2, zeros(2), 0.5 * ones(2))
stats = tron(nls)
# output
"Execution stats: first-order stationary"
```
```jldoctest; output = false
using JSOSolvers, ADNLPModels
F(x) = [x[1] - 1.0; 10 * (x[2] - x[1]^2)]
x0 = [-1.2; 1.0]
nls = ADNLSModel(F, x0, 2, zeros(2), 0.5 * ones(2))
solver = TronSolverNLS(nls)
stats = solve!(solver, nls)
# output
"Execution stats: first-order stationary"
```
"""
mutable struct TronSolverNLS{
T,
V <: AbstractVector{T},
Sub <: KrylovSolver{T, T, V},
Op <: AbstractLinearOperator{T},
Aop <: AbstractLinearOperator{T},
} <: AbstractOptimizationSolver
x::V
xc::V
temp::V
gx::V
gt::V
gpx::V
s::V
tr::TRONTrustRegion{T, V}
Fx::V
Fc::V
Av::V
Atv::V
A::Op
As::V
ifix::BitVector
ls_rhs::V
ls_op_diag::V
ls_op::LinearOperator{T}
AZ::Aop
ls_subsolver::Sub
end
function TronSolverNLS(
nlp::AbstractNLSModel{T, V};
subsolver_type::Type{<:KrylovSolver} = LsmrSolver,
max_radius::T = min(one(T) / sqrt(2 * eps(T)), T(100)),
kwargs...,
) where {T, V <: AbstractVector{T}}
subsolver_type in tronls_allowed_subsolvers ||
error("subproblem solver must be one of $(tronls_allowed_subsolvers)")
nvar = nlp.meta.nvar
nequ = nlp.nls_meta.nequ
x = V(undef, nvar)
xc = V(undef, nvar)
temp = V(undef, nvar)
gx = V(undef, nvar)
gt = V(undef, nvar)
gpx = V(undef, nvar)
s = V(undef, nvar)
tr = TRONTrustRegion(gt, min(one(T), max_radius - eps(T)); max_radius = max_radius, kwargs...)
Fx = V(undef, nequ)
Fc = V(undef, nequ)
Av = V(undef, nequ)
Atv = V(undef, nvar)
A = jac_op_residual!(nlp, xc, Av, Atv)
As = V(undef, nequ)
ifix = BitVector(undef, nvar)
ls_rhs = V(undef, nequ)
ls_op_diag = V(undef, nvar)
ls_op = opDiagonal(ls_op_diag)
AZ = A * ls_op
ls_subsolver = subsolver_type(AZ, As)
Sub = typeof(ls_subsolver)
return TronSolverNLS{T, V, Sub, typeof(A), typeof(AZ)}(
x,
xc,
temp,
gx,
gt,
gpx,
s,
tr,
Fx,
Fc,
Av,
Atv,
A,
As,
ifix,
ls_rhs,
ls_op_diag,
ls_op,
AZ,
ls_subsolver,
)
end
function SolverCore.reset!(solver::TronSolverNLS)
solver.tr.good_grad = false
solver
end
function SolverCore.reset!(solver::TronSolverNLS, nlp::AbstractNLPModel)
solver.A = jac_op_residual!(nlp, solver.xc, solver.Av, solver.Atv)
solver.AZ = solver.A * solver.ls_op
reset!(solver)
solver
end
@doc (@doc TronSolverNLS) function tron(
::Val{:GaussNewton},
nlp::AbstractNLSModel{T, V};
x::V = nlp.meta.x0,
subsolver_type::Type{<:KrylovSolver} = LsmrSolver,
kwargs...,
) where {T, V}
dict = Dict(kwargs)
subsolver_keys = intersect(keys(dict), tron_keys)
subsolver_kwargs = Dict(k => dict[k] for k in subsolver_keys)
solver = TronSolverNLS(nlp, subsolver_type = subsolver_type; subsolver_kwargs...)
for k in subsolver_keys
pop!(dict, k)
end
return solve!(solver, nlp; x = x, dict...)
end
function SolverCore.solve!(
solver::TronSolverNLS{T, V},
nlp::AbstractNLSModel{T, V},
stats::GenericExecutionStats{T, V};
callback = (args...) -> nothing,
x::V = nlp.meta.x0,
μ₀::Real = T(1e-2),
μ₁::Real = one(T),
σ::Real = T(10),
max_eval::Int = -1,
max_iter::Int = typemax(Int),
max_time::Real = 30.0,
max_cgiter::Int = 50,
cgtol::T = T(0.1),
atol::T = √eps(T),
rtol::T = √eps(T),
Fatol::T = √eps(T),
Frtol::T = eps(T),
verbose::Int = 0,
subsolver_verbose::Int = 0,
) where {T, V <: AbstractVector{T}}
if !(nlp.meta.minimize)
error("tron only works for minimization problem")
end
if !(unconstrained(nlp) || bound_constrained(nlp))
error("tron should only be called for unconstrained or bound-constrained problems")
end
reset!(stats)
ℓ = nlp.meta.lvar
u = nlp.meta.uvar
n = nlp.meta.nvar
m = nlp.nls_meta.nequ
if (verbose > 0 && !(u ≥ x ≥ ℓ))
@warn "Warning: Initial guess is not within bounds."
end
start_time = time()
set_time!(stats, 0.0)
solver.x .= x
x = solver.x
xc = solver.xc
gx = solver.gx
# Preallocation
s = solver.s
As = solver.As
Ax = solver.A
gpx = solver.gpx
Fx, Fc = solver.Fc, solver.Fx
x .= max.(ℓ, min.(x, u))
residual!(nlp, x, Fx)
fx, gx = objgrad!(nlp, x, gx, Fx, recompute = false)
gt = solver.gt
num_success_iters = 0
# Optimality measure
project_step!(gpx, x, gx, ℓ, u, -one(T))
πx = nrm2(n, gpx)
ϵ = atol + rtol * πx
fmin = min(-one(T), fx) / eps(T)
optimal = πx <= ϵ
unbounded = fx < fmin
ϵF = Fatol + Frtol * 2 * √fx
project_step!(gpx, x, x, ℓ, u, zero(T)) # Proj(x) - x
small_residual = (norm(gpx) <= ϵ) && (2 * √fx <= ϵF)
set_iter!(stats, 0)
set_objective!(stats, fx)
set_dual_residual!(stats, πx)
αC = one(T)
tr = solver.tr
tr.radius = tr.initial_radius = min(max(one(T), πx / 10), tr.max_radius)
verbose > 0 && @info log_header(
[:iter, :f, :dual, :radius, :ratio, :cgstatus],
[Int, T, T, T, T, String],
hdr_override = Dict(:f => "f(x)", :dual => "π", :radius => "Δ"),
)
verbose > 0 && @info log_row([stats.iter, fx, πx, T, T, String])
set_status!(
stats,
get_status(
nlp,
elapsed_time = stats.elapsed_time,
optimal = optimal,
small_residual = small_residual,
unbounded = unbounded,
max_eval = max_eval,
iter = stats.iter,
max_iter = max_iter,
max_time = max_time,
),
)
callback(nlp, solver, stats)
done = stats.status != :unknown
while !done
# Current iteration
xc .= x # implicitly update Ax
fc = fx
Fc .= Fx
Δ = tr.radius
αC, s, cauchy_status = cauchy_ls!(x, Ax, Fx, gx, Δ, αC, ℓ, u, s, As, μ₀ = μ₀, μ₁ = μ₁, σ = σ)
if cauchy_status != :success
@error "Cauchy step returned: $cauchy_status"
stats.status = cauchy_status
done = true
continue
end
cginfo = projected_gauss_newton!(
solver,
x,
Ax,
Fx,
Δ,
cgtol,
s,
ℓ,
u,
As,
max_cgiter = max_cgiter,
max_time = max_time - stats.elapsed_time,
subsolver_verbose = subsolver_verbose,
)
slope = dot(m, Fx, As)
qs = dot(As, As) / 2 + slope
residual!(nlp, x, Fx)
fx = obj(nlp, x, Fx, recompute = false)
ared, pred = aredpred!(tr, nlp, Fx, fc, fx, qs, x, s, slope)
if pred ≥ 0
stats.status = :neg_pred
done = true
continue
end
tr.ratio = ared / pred
s_norm = nrm2(n, s)
if num_success_iters == 0
tr.radius = min(Δ, s_norm)
end
# Update the trust region
update!(tr, s_norm)
if acceptable(tr)
num_success_iters += 1
if tr.good_grad
gx .= tr.gt
tr.good_grad = false
else
grad!(nlp, x, gx, Fx, recompute = false)
end
project_step!(gpx, x, gx, ℓ, u, -one(T))
πx = nrm2(n, gpx)
end
# No post-iteration
if !acceptable(tr)
Fx .= Fc
fx = fc
x .= xc
end
set_iter!(stats, stats.iter + 1)
set_objective!(stats, fx)
set_time!(stats, time() - start_time)
set_dual_residual!(stats, πx)
optimal = πx <= ϵ
project_step!(gpx, x, x, ℓ, u, zero(T)) # Proj(x) - x
small_residual = (norm(gpx) <= ϵ) && (2 * √fx <= ϵF)
unbounded = fx < fmin
verbose > 0 &&
mod(stats.iter, verbose) == 0 &&
@info log_row([stats.iter, fx, πx, Δ, tr.ratio, cginfo])
set_status!(
stats,
get_status(
nlp,
elapsed_time = stats.elapsed_time,
optimal = optimal,
small_residual = small_residual,
unbounded = unbounded,
max_eval = max_eval,
iter = stats.iter,
max_iter = max_iter,
max_time = max_time,
),
)
callback(nlp, solver, stats)
done = stats.status != :unknown
end
verbose > 0 && @info log_row(Any[stats.iter, fx, πx, tr.radius])
set_solution!(stats, x)
stats
end
"""`s = projected_line_search_ls!(x, A, g, d, ℓ, u, As, s; μ₀ = 1e-2)`
Performs a projected line search, searching for a step size `t` such that
½‖As + Fx‖² ≤ ½‖Fx‖² + μ₀FxᵀAs
where `s = P(x + t * d) - x`, while remaining on the same face as `x + d`.
Backtracking is performed from t = 1.0. `x` is updated in place.
"""
function projected_line_search_ls!(
x::AbstractVector{T},
A::Union{AbstractMatrix, AbstractLinearOperator},
Fx::AbstractVector{T},
d::AbstractVector{T},
ℓ::AbstractVector{T},
u::AbstractVector{T},
As::AbstractVector{T},
s::AbstractVector{T};
μ₀::Real = T(1e-2),
) where {T <: Real}
α = one(T)
_, brkmin, _ = breakpoints(x, d, ℓ, u)
nsteps = 0
n = length(x)
m = length(Fx)
s .= zero(T)
As .= zero(T)
search = true
while search && α > brkmin
nsteps += 1
project_step!(s, x, d, ℓ, u, α)
slope, qs = compute_As_slope_qs!(As, A, s, Fx)
if qs <= μ₀ * slope
search = false
else
α /= 2
end
end
if α < 1 && α < brkmin
α = brkmin
project_step!(s, x, d, ℓ, u, α)
slope, qs = compute_As_slope_qs!(As, A, s, Fx)
end
project_step!(s, x, d, ℓ, u, α)
x .= x .+ s
return s
end
"""`α, s = cauchy_ls!(x, A, Fx, g, Δ, ℓ, u, s, As; μ₀ = 1e-2, μ₁ = 1.0, σ=10.0)`
Computes a Cauchy step `s = P(x - α g) - x` for
min q(s) = ½‖As + Fx‖² - ½‖Fx‖² s.t. ‖s‖ ≦ μ₁Δ, ℓ ≦ x + s ≦ u,
with the sufficient decrease condition
q(s) ≦ μ₀gᵀs,
where g = AᵀFx.
"""
function cauchy_ls!(
x::AbstractVector{T},
A::Union{AbstractMatrix, AbstractLinearOperator},
Fx::AbstractVector{T},
g::AbstractVector{T},
Δ::Real,
α::Real,
ℓ::AbstractVector{T},
u::AbstractVector{T},
s::AbstractVector{T},
As::AbstractVector{T};
μ₀::Real = T(1e-2),
μ₁::Real = one(T),
σ::Real = T(10),
) where {T <: Real}
# TODO: Use brkmin to care for g direction
s .= .-g
_, _, brkmax = breakpoints(x, s, ℓ, u)
n = length(x)
s .= zero(T)
As .= zero(T)
status = :success
project_step!(s, x, g, ℓ, u, -α)
# Interpolate or extrapolate
s_norm = nrm2(n, s)
if s_norm > μ₁ * Δ
interp = true
else
slope, qs = compute_As_slope_qs!(As, A, s, Fx)
interp = qs >= μ₀ * slope
end
if interp
search = true
while search
α /= σ
project_step!(s, x, g, ℓ, u, -α)
s_norm = nrm2(n, s)
if s_norm <= μ₁ * Δ
slope, qs = compute_As_slope_qs!(As, A, s, Fx)
search = qs >= μ₀ * slope
end
# TODO: Correctly assess why this fails
if α < sqrt(nextfloat(zero(α)))
search = false
status = :small_step
end
end
else
search = true
αs = α
while search && α <= brkmax
α *= σ
project_step!(s, x, g, ℓ, u, -α)
s_norm = nrm2(n, s)
if s_norm <= μ₁ * Δ
slope, qs = compute_As_slope_qs!(As, A, s, Fx)
if qs <= μ₀ * slope
αs = α
end
else
search = false
end
end
# Recover the last successful step
α = αs
s = project_step!(s, x, g, ℓ, u, -α)
end
return α, s, status
end
"""
projected_gauss_newton!(solver, x, A, Fx, Δ, gctol, s, max_cgiter, ℓ, u; max_cgiter = 50, max_time = Inf, subsolver_verbose = 0)
Compute an approximate solution `d` for
min q(d) = ½‖Ad + Fx‖² - ½‖Fx‖² s.t. ℓ ≦ x + d ≦ u, ‖d‖ ≦ Δ
starting from `s`. The steps are computed using the conjugate gradient method
projected on the active bounds.
"""
function projected_gauss_newton!(
solver::TronSolverNLS{T},
x::AbstractVector{T},
A::Union{AbstractMatrix, AbstractLinearOperator},
Fx::AbstractVector{T},
Δ::T,
cgtol::T,
s::AbstractVector{T},
ℓ::AbstractVector{T},
u::AbstractVector{T},
As::AbstractVector{T};
max_cgiter::Int = 50,
max_time::Float64 = Inf,
subsolver_verbose = 0,
) where {T <: Real}
start_time, elapsed_time = time(), 0.0
n = length(x)
status = ""
w = solver.temp
ls_rhs = solver.ls_rhs
ls_op_diag, AZ = solver.ls_op_diag, solver.AZ
ifix = solver.ifix
ls_subsolver = solver.ls_subsolver
mul!(As, A, s)
Fxnorm = norm(Fx)
# Projected Newton Step
exit_optimal, exit_pcg, exit_itmax, exit_time = false, false, false, false
iters = 0
x .= x .+ s
project!(x, x, ℓ, u)
while !(exit_optimal || exit_pcg || exit_itmax || exit_time)
active!(ifix, x, ℓ, u)
if sum(ifix) == n
exit_optimal = true
continue
end
for i = 1:n
ls_op_diag[i] = ifix[i] ? 0 : 1 # implictly changes ls_op and so AZ
end
ls_rhs .= .-As .- Fx
Krylov.solve!(
ls_subsolver,
AZ,
ls_rhs,
radius = Δ,
rtol = cgtol,
atol = zero(T),
timemax = max_time - elapsed_time,
verbose = subsolver_verbose,
)
st, stats = ls_subsolver.x, ls_subsolver.stats
iters += 1
status = stats.status
# Projected line search
ls_rhs .*= -1
projected_line_search_ls!(x, AZ, ls_rhs, st, ℓ, u, As, w)
s .+= w
mul!(As, A, s)
ls_rhs .= .-As .- Fx
mul!(w, AZ', ls_rhs)
if norm(w) <= cgtol * Fxnorm
exit_optimal = true
elseif status == "on trust-region boundary"
exit_pcg = true
elseif iters >= max_cgiter
exit_itmax = true
end
elapsed_time = time() - start_time
exit_time = elapsed_time >= max_time
end
status = if exit_optimal
"stationary point found"
elseif exit_pcg
"on trust-region boundary"
elseif exit_itmax
"maximum number of iterations"
elseif exit_time
"time limit exceeded"
else
status # unknown
end
return status
end
| JSOSolvers | https://github.com/JuliaSmoothOptimizers/JSOSolvers.jl.git |
|
[
"MPL-2.0"
] | 0.12.1 | c68e031e469f1898bb779cbc3c401e1640ecc0c4 | code | 10965 | export trunk, TrunkSolver
trunk(nlp::AbstractNLPModel; variant = :Newton, kwargs...) = trunk(Val(variant), nlp; kwargs...)
"""
trunk(nlp; kwargs...)
A trust-region solver for unconstrained optimization using exact second derivatives.
For advanced usage, first define a `TrunkSolver` to preallocate the memory used in the algorithm, and then call `solve!`:
solver = TrunkSolver(nlp, subsolver_type::Type{<:KrylovSolver} = CgSolver)
solve!(solver, nlp; kwargs...)
# Arguments
- `nlp::AbstractNLPModel{T, V}` represents the model to solve, see `NLPModels.jl`.
The keyword arguments may include
- `subsolver_logger::AbstractLogger = NullLogger()`: subproblem's logger.
- `x::V = nlp.meta.x0`: the initial guess.
- `atol::T = √eps(T)`: absolute tolerance.
- `rtol::T = √eps(T)`: relative tolerance, the algorithm stops when ‖∇f(xᵏ)‖ ≤ atol + rtol * ‖∇f(x⁰)‖.
- `max_eval::Int = -1`: maximum number of objective function evaluations.
- `max_time::Float64 = 30.0`: maximum time limit in seconds.
- `max_iter::Int = typemax(Int)`: maximum number of iterations.
- `bk_max::Int = 10`: algorithm parameter.
- `monotone::Bool = true`: algorithm parameter.
- `nm_itmax::Int = 25`: algorithm parameter.
- `verbose::Int = 0`: if > 0, display iteration information every `verbose` iteration.
- `subsolver_verbose::Int = 0`: if > 0, display iteration information every `subsolver_verbose` iteration of the subsolver.
- `M`: linear operator that models a Hermitian positive-definite matrix of size `n`; passed to Krylov subsolvers.
# Output
The returned value is a `GenericExecutionStats`, see `SolverCore.jl`.
# Callback
$(Callback_docstring)
# References
This implementation follows the description given in
A. R. Conn, N. I. M. Gould, and Ph. L. Toint,
Trust-Region Methods, volume 1 of MPS/SIAM Series on Optimization.
SIAM, Philadelphia, USA, 2000.
DOI: 10.1137/1.9780898719857
The main algorithm follows the basic trust-region method described in Section 6.
The backtracking linesearch follows Section 10.3.2.
The nonmonotone strategy follows Section 10.1.3, Algorithm 10.1.2.
# Examples
```jldoctest; output = false
using JSOSolvers, ADNLPModels
nlp = ADNLPModel(x -> sum(x.^2), ones(3))
stats = trunk(nlp)
# output
"Execution stats: first-order stationary"
```
```jldoctest; output = false
using JSOSolvers, ADNLPModels
nlp = ADNLPModel(x -> sum(x.^2), ones(3))
solver = TrunkSolver(nlp)
stats = solve!(solver, nlp)
# output
"Execution stats: first-order stationary"
```
"""
mutable struct TrunkSolver{
T,
V <: AbstractVector{T},
Sub <: KrylovSolver{T, T, V},
Op <: AbstractLinearOperator{T},
} <: AbstractOptimizationSolver
x::V
xt::V
gx::V
gt::V
gn::V
Hs::V
subsolver::Sub
H::Op
tr::TrustRegion{T, V}
end
function TrunkSolver(
nlp::AbstractNLPModel{T, V};
subsolver_type::Type{<:KrylovSolver} = CgSolver,
) where {T, V <: AbstractVector{T}}
nvar = nlp.meta.nvar
x = V(undef, nvar)
xt = V(undef, nvar)
gx = V(undef, nvar)
gt = V(undef, nvar)
gn = isa(nlp, QuasiNewtonModel) ? V(undef, nvar) : V(undef, 0)
Hs = V(undef, nvar)
subsolver = subsolver_type(nvar, nvar, V)
Sub = typeof(subsolver)
H = hess_op!(nlp, x, Hs)
Op = typeof(H)
tr = TrustRegion(gt, one(T))
return TrunkSolver{T, V, Sub, Op}(x, xt, gx, gt, gn, Hs, subsolver, H, tr)
end
function SolverCore.reset!(solver::TrunkSolver)
solver.tr.good_grad = false
solver.tr.radius = solver.tr.initial_radius
solver
end
function SolverCore.reset!(solver::TrunkSolver, nlp::AbstractNLPModel)
@assert (length(solver.gn) == 0) || isa(nlp, QuasiNewtonModel)
solver.H = hess_op!(nlp, solver.x, solver.Hs)
solver.tr.good_grad = false
solver.tr.radius = solver.tr.initial_radius
solver
end
@doc (@doc TrunkSolver) function trunk(
::Val{:Newton},
nlp::AbstractNLPModel;
x::V = nlp.meta.x0,
subsolver_type::Type{<:KrylovSolver} = CgSolver,
kwargs...,
) where {V}
solver = TrunkSolver(nlp, subsolver_type = subsolver_type)
return solve!(solver, nlp; x = x, kwargs...)
end
function SolverCore.solve!(
solver::TrunkSolver{T, V},
nlp::AbstractNLPModel{T, V},
stats::GenericExecutionStats{T, V};
callback = (args...) -> nothing,
subsolver_logger::AbstractLogger = NullLogger(),
x::V = nlp.meta.x0,
atol::T = √eps(T),
rtol::T = √eps(T),
max_eval::Int = -1,
max_iter::Int = typemax(Int),
max_time::Float64 = 30.0,
bk_max::Int = 10,
monotone::Bool = true,
nm_itmax::Int = 25,
verbose::Int = 0,
subsolver_verbose::Int = 0,
M = I,
) where {T, V <: AbstractVector{T}}
if !(nlp.meta.minimize)
error("trunk only works for minimization problem")
end
if !unconstrained(nlp)
error("trunk should only be called for unconstrained problems. Try tron instead")
end
reset!(stats)
start_time = time()
set_time!(stats, 0.0)
n = nlp.meta.nvar
solver.x .= x
x = solver.x
xt = solver.xt
∇f = solver.gx
∇fn = solver.gn
Hs = solver.Hs
subsolver = solver.subsolver
H = solver.H
tr = solver.tr
cgtol = one(T) # Must be ≤ 1.
# Armijo linesearch parameter.
β = eps(T)^T(1 / 4)
f = obj(nlp, x)
grad!(nlp, x, ∇f)
isa(nlp, QuasiNewtonModel) && (∇fn .= ∇f)
∇fNorm2 = norm(∇f)
∇fNormM = normM!(n, ∇f, M, Hs)
ϵ = atol + rtol * ∇fNorm2
tr = solver.tr
tr.radius = min(max(∇fNormM / 10, one(T)), T(100))
# Non-monotone mode parameters.
# fmin: current best overall objective value
# nm_iter: number of successful iterations since fmin was first attained
# fref: objective value at reference iteration
# σref: cumulative model decrease over successful iterations since the reference iteration
fmin = fref = fcur = f
σref = σcur = zero(T)
nm_iter = 0
set_iter!(stats, 0)
set_objective!(stats, f)
set_dual_residual!(stats, ∇fNorm2)
optimal = ∇fNorm2 ≤ ϵ
fmin = min(-one(T), f) / eps(T)
unbounded = f < fmin
verbose > 0 && @info log_header(
[:iter, :f, :dual, :radius, :ratio, :inner, :bk, :cgstatus],
[Int, T, T, T, T, Int, Int, String],
hdr_override = Dict(:f => "f(x)", :dual => "π", :radius => "Δ"),
)
verbose > 0 && @info log_row([stats.iter, f, ∇fNorm2, T, T, Int, Int, String])
set_status!(
stats,
get_status(
nlp,
elapsed_time = stats.elapsed_time,
optimal = optimal,
unbounded = unbounded,
max_eval = max_eval,
iter = stats.iter,
max_iter = max_iter,
max_time = max_time,
),
)
callback(nlp, solver, stats)
done = stats.status != :unknown
while !done
# Compute inexact solution to trust-region subproblem
# minimize g's + 1/2 s'Hs subject to ‖s‖_M ≤ radius.
# In this particular case, we may use an operator with preallocation.
cgtol = max(rtol, min(T(0.1), √∇fNormM, T(0.9) * cgtol))
∇f .*= -1
Krylov.solve!(
subsolver,
H,
∇f,
atol = atol,
rtol = cgtol,
radius = tr.radius,
itmax = max(2 * n, 50),
timemax = max_time - stats.elapsed_time,
verbose = subsolver_verbose,
M = M,
)
s, cg_stats = subsolver.x, subsolver.stats
# Compute actual vs. predicted reduction.
sNorm = nrm2(n, s)
copyaxpy!(n, one(T), s, x, xt)
slope = -dot(n, s, ∇f)
mul!(Hs, H, s)
curv = dot(n, s, Hs)
Δq = slope + curv / 2
ft = obj(nlp, xt)
ared, pred = aredpred!(tr, nlp, f, ft, Δq, xt, s, slope)
if pred ≥ 0
stats.status = :neg_pred
done = true
continue
end
tr.ratio = ared / pred
if !monotone
ared_hist, pred_hist = aredpred!(tr, nlp, fref, ft, σref + Δq, xt, s, slope)
if pred_hist ≥ 0
stats.status = :neg_pred
done = true
continue
end
ρ_hist = ared_hist / pred_hist
tr.ratio = max(tr.ratio, ρ_hist)
end
bk = 0
if !acceptable(tr)
# Perform backtracking linesearch along s
# Scaling s to the trust-region boundary, as recommended in
# Algorithm 10.3.2 of the Trust-Region book
# appears to deteriorate results.
# BLAS.scal!(n, tr.radius / sNorm, s, 1)
# slope *= tr.radius / sNorm
# sNorm = tr.radius
if slope ≥ 0
@error "not a descent direction: slope = $slope, ‖∇f‖ = $∇fNorm2"
stats.status = :not_desc
done = true
continue
end
α = one(T)
while (bk < bk_max) && (ft > f + β * α * slope)
bk = bk + 1
α /= T(1.2)
copyaxpy!(n, α, s, x, xt)
ft = obj(nlp, xt)
end
sNorm *= α
scal!(n, α, s)
slope *= α
Δq = slope + α * α * curv / 2
ared, pred = aredpred!(tr, nlp, f, ft, Δq, xt, s, slope)
if pred ≥ 0
stats.status = :neg_pred
done = true
continue
end
tr.ratio = ared / pred
if !monotone
ared_hist, pred_hist = aredpred!(tr, nlp, fref, ft, σref + Δq, xt, s, slope)
if pred_hist ≥ 0
stats.status = :neg_pred
done = true
continue
end
ρ_hist = ared_hist / pred_hist
tr.ratio = max(tr.ratio, ρ_hist)
end
end
set_iter!(stats, stats.iter + 1)
if acceptable(tr)
# Update non-monotone mode parameters.
if !monotone
σref = σref + Δq
σcur = σcur + Δq
if ft < fmin
# New overall best objective value found.
fcur = ft
fmin = ft
σcur = zero(T)
nm_iter = 0
else
nm_iter = nm_iter + 1
if ft > fcur
fcur = ft
σcur = zero(T)
end
if nm_iter ≥ nm_itmax
fref = fcur
σref = σcur
end
end
end
x .= xt
f = ft
if !tr.good_grad
grad!(nlp, x, ∇f)
else
∇f .= tr.gt
tr.good_grad = false
end
∇fNorm2 = nrm2(n, ∇f)
∇fNormM = normM!(n, ∇f, M, Hs)
set_objective!(stats, f)
set_time!(stats, time() - start_time)
set_dual_residual!(stats, ∇fNorm2)
if isa(nlp, QuasiNewtonModel)
∇fn .-= ∇f
∇fn .*= -1 # = ∇f(xₖ₊₁) - ∇f(xₖ)
push!(nlp, s, ∇fn)
∇fn .= ∇f
end
verbose > 0 &&
mod(stats.iter, verbose) == 0 &&
@info log_row([
stats.iter,
f,
∇fNorm2,
tr.radius,
tr.ratio,
cg_stats.niter,
bk,
cg_stats.status,
])
end
# Move on.
update!(tr, sNorm)
optimal = ∇fNorm2 ≤ ϵ
unbounded = f < fmin
set_status!(
stats,
get_status(
nlp,
elapsed_time = stats.elapsed_time,
optimal = optimal,
unbounded = unbounded,
max_eval = max_eval,
iter = stats.iter,
max_iter = max_iter,
max_time = max_time,
),
)
callback(nlp, solver, stats)
done = stats.status != :unknown
end
verbose > 0 && @info log_row(Any[stats.iter, f, ∇fNorm2, tr.radius])
set_solution!(stats, x)
stats
end
| JSOSolvers | https://github.com/JuliaSmoothOptimizers/JSOSolvers.jl.git |
|
[
"MPL-2.0"
] | 0.12.1 | c68e031e469f1898bb779cbc3c401e1640ecc0c4 | code | 11599 | export TrunkSolverNLS
const trunkls_allowed_subsolvers = [CglsSolver, CrlsSolver, LsqrSolver, LsmrSolver]
trunk(nlp::AbstractNLSModel; variant = :GaussNewton, kwargs...) =
trunk(Val(variant), nlp; kwargs...)
"""
trunk(nls; kwargs...)
A pure Julia implementation of a trust-region solver for nonlinear least-squares problems:
min ½‖F(x)‖²
For advanced usage, first define a `TrunkSolverNLS` to preallocate the memory used in the algorithm, and then call `solve!`:
solver = TrunkSolverNLS(nls, subsolver_type::Type{<:KrylovSolver} = LsmrSolver)
solve!(solver, nls; kwargs...)
# Arguments
- `nls::AbstractNLSModel{T, V}` represents the model to solve, see `NLPModels.jl`.
The keyword arguments may include
- `x::V = nlp.meta.x0`: the initial guess.
- `atol::T = √eps(T)`: absolute tolerance.
- `rtol::T = √eps(T)`: relative tolerance, the algorithm stops when ‖∇f(xᵏ)‖ ≤ atol + rtol * ‖∇f(x⁰)‖.
- `Fatol::T = √eps(T)`: absolute tolerance on the residual.
- `Frtol::T = eps(T)`: relative tolerance on the residual, the algorithm stops when ‖F(xᵏ)‖ ≤ Fatol + Frtol * ‖F(x⁰)‖.
- `max_eval::Int = -1`: maximum number of objective function evaluations.
- `max_time::Float64 = 30.0`: maximum time limit in seconds.
- `max_iter::Int = typemax(Int)`: maximum number of iterations.
- `bk_max::Int = 10`: algorithm parameter.
- `monotone::Bool = true`: algorithm parameter.
- `nm_itmax::Int = 25`: algorithm parameter.
- `verbose::Int = 0`: if > 0, display iteration details every `verbose` iteration.
- `subsolver_verbose::Int = 0`: if > 0, display iteration information every `subsolver_verbose` iteration of the subsolver.
See `JSOSolvers.trunkls_allowed_subsolvers` for a list of available `KrylovSolver`.
# Output
The value returned is a `GenericExecutionStats`, see `SolverCore.jl`.
# Callback
$(Callback_docstring)
# References
This implementation follows the description given in
A. R. Conn, N. I. M. Gould, and Ph. L. Toint,
Trust-Region Methods, volume 1 of MPS/SIAM Series on Optimization.
SIAM, Philadelphia, USA, 2000.
DOI: 10.1137/1.9780898719857
The main algorithm follows the basic trust-region method described in Section 6.
The backtracking linesearch follows Section 10.3.2.
The nonmonotone strategy follows Section 10.1.3, Algorithm 10.1.2.
# Examples
```jldoctest; output = false
using JSOSolvers, ADNLPModels
F(x) = [x[1] - 1.0; 10 * (x[2] - x[1]^2)]
x0 = [-1.2; 1.0]
nls = ADNLSModel(F, x0, 2)
stats = trunk(nls)
# output
"Execution stats: first-order stationary"
```
```jldoctest; output = false
using JSOSolvers, ADNLPModels
F(x) = [x[1] - 1.0; 10 * (x[2] - x[1]^2)]
x0 = [-1.2; 1.0]
nls = ADNLSModel(F, x0, 2)
solver = TrunkSolverNLS(nls)
stats = solve!(solver, nls)
# output
"Execution stats: first-order stationary"
```
"""
mutable struct TrunkSolverNLS{
T,
V <: AbstractVector{T},
Sub <: KrylovSolver{T, T, V},
Op <: AbstractLinearOperator{T},
} <: AbstractOptimizationSolver
x::V
xt::V
temp::V
gx::V
gt::V
tr::TrustRegion{T, V}
Fx::V
rt::V
Av::V
Atv::V
A::Op
subsolver::Sub
end
function TrunkSolverNLS(
nlp::AbstractNLPModel{T, V};
subsolver_type::Type{<:KrylovSolver} = LsmrSolver,
) where {T, V <: AbstractVector{T}}
subsolver_type in trunkls_allowed_subsolvers ||
error("subproblem solver must be one of $(trunkls_allowed_subsolvers)")
nvar = nlp.meta.nvar
nequ = nlp.nls_meta.nequ
x = V(undef, nvar)
xt = V(undef, nvar)
temp = V(undef, nequ)
gx = V(undef, nvar)
gt = V(undef, nvar)
tr = TrustRegion(gt, one(T))
Fx = V(undef, nequ)
rt = V(undef, nequ)
Av = V(undef, nequ)
Atv = V(undef, nvar)
A = jac_op_residual!(nlp, x, Av, Atv)
Op = typeof(A)
subsolver = subsolver_type(nequ, nvar, V)
Sub = typeof(subsolver)
return TrunkSolverNLS{T, V, Sub, Op}(x, xt, temp, gx, gt, tr, rt, Fx, Av, Atv, A, subsolver)
end
function SolverCore.reset!(solver::TrunkSolverNLS)
solver.tr.good_grad = false
solver.tr.radius = solver.tr.initial_radius
solver
end
function SolverCore.reset!(solver::TrunkSolverNLS, nlp::AbstractNLSModel)
solver.A = jac_op_residual!(nlp, solver.x, solver.Av, solver.Atv)
solver.tr.good_grad = false
solver.tr.radius = solver.tr.initial_radius
solver
end
@doc (@doc TrunkSolverNLS) function trunk(
::Val{:GaussNewton},
nlp::AbstractNLSModel;
x::V = nlp.meta.x0,
subsolver_type::Type{<:KrylovSolver} = LsmrSolver,
kwargs...,
) where {V}
solver = TrunkSolverNLS(nlp, subsolver_type = subsolver_type)
return solve!(solver, nlp; x = x, kwargs...)
end
function SolverCore.solve!(
solver::TrunkSolverNLS{T, V},
nlp::AbstractNLPModel{T, V},
stats::GenericExecutionStats{T, V};
callback = (args...) -> nothing,
x::V = nlp.meta.x0,
atol::Real = √eps(T),
rtol::Real = √eps(T),
Fatol::T = zero(T),
Frtol::T = zero(T),
max_eval::Int = -1,
max_iter::Int = typemax(Int),
max_time::Float64 = 30.0,
bk_max::Int = 10,
monotone::Bool = true,
nm_itmax::Int = 25,
verbose::Int = 0,
subsolver_verbose::Int = 0,
) where {T, V <: AbstractVector{T}}
if !(nlp.meta.minimize)
error("trunk only works for minimization problem")
end
if !unconstrained(nlp)
error("trunk should only be called for unconstrained problems. Try tron instead")
end
reset!(stats)
start_time = time()
set_time!(stats, 0.0)
solver.x .= x
x = solver.x
∇f = solver.gx
subsolver = solver.subsolver
n = nlp.nls_meta.nvar
m = nlp.nls_meta.nequ
cgtol = one(T) # Must be ≤ 1.
# Armijo linesearch parameter.
β = eps(T)^T(1 / 4)
r, rt = solver.Fx, solver.rt
residual!(nlp, x, r)
f, ∇f = objgrad!(nlp, x, ∇f, r, recompute = false)
# preallocate storage for products with A and A'
A = solver.A # jac_op_residual!(nlp, x, Av, Atv)
mul!(∇f, A', r)
∇fNorm2 = nrm2(n, ∇f)
ϵ = atol + rtol * ∇fNorm2
ϵF = Fatol + Frtol * 2 * √f
tr = solver.tr
tr.radius = min(max(∇fNorm2 / 10, one(T)), T(100))
# Non-monotone mode parameters.
# fmin: current best overall objective value
# nm_iter: number of successful iterations since fmin was first attained
# fref: objective value at reference iteration
# σref: cumulative model decrease over successful iterations since the reference iteration
fmin = fref = fcur = f
σref = σcur = zero(T)
nm_iter = 0
# Preallocate xt.
xt = solver.xt
temp = solver.temp
optimal = ∇fNorm2 ≤ ϵ
small_residual = 2 * √f ≤ ϵF
set_iter!(stats, 0)
set_objective!(stats, f)
set_dual_residual!(stats, ∇fNorm2)
verbose > 0 && @info log_header(
[:iter, :f, :dual, :radius, :step, :ratio, :inner, :bk, :cgstatus],
[Int, T, T, T, T, T, Int, Int, String],
hdr_override = Dict(:f => "f(x)", :dual => "‖∇f‖", :radius => "Δ"),
)
verbose > 0 && @info log_row([stats.iter, f, ∇fNorm2, T, T, T, Int, Int, String])
set_status!(
stats,
get_status(
nlp,
elapsed_time = stats.elapsed_time,
optimal = optimal,
small_residual = small_residual,
max_eval = max_eval,
max_iter = max_iter,
max_time = max_time,
),
)
callback(nlp, solver, stats)
done = stats.status != :unknown
while !done
# Compute inexact solution to trust-region subproblem
# minimize g's + 1/2 s'Hs subject to ‖s‖ ≤ radius.
# In this particular case, we may use an operator with preallocation.
cgtol = max(rtol, min(T(0.1), 9 * cgtol / 10, sqrt(∇fNorm2)))
temp .= .-r
Krylov.solve!(
subsolver,
A,
temp,
atol = atol,
rtol = cgtol,
radius = tr.radius,
itmax = max(2 * (n + m), 50),
timemax = max_time - stats.elapsed_time,
verbose = subsolver_verbose,
)
s, cg_stats = subsolver.x, subsolver.stats
# Compute actual vs. predicted reduction.
sNorm = nrm2(n, s)
copyaxpy!(n, one(T), s, x, xt)
# slope = dot(∇f, s)
mul!(temp, A, s)
slope = dot(r, temp)
curv = dot(temp, temp)
Δq = slope + curv / 2
residual!(nlp, xt, rt)
ft = obj(nlp, x, rt, recompute = false)
ared, pred = aredpred!(tr, nlp, rt, f, ft, Δq, xt, s, slope)
if pred ≥ 0
stats.status = :neg_pred
done = true
continue
end
tr.ratio = ared / pred
if !monotone
ared_hist, pred_hist = aredpred!(tr, nlp, rt, fref, ft, σref + Δq, xt, s, slope)
if pred_hist ≥ 0
stats.status = :neg_pred
done = true
continue
end
ρ_hist = ared_hist / pred_hist
tr.ratio = max(tr.ratio, ρ_hist)
end
bk = 0
if !acceptable(tr)
# Perform backtracking linesearch along s
# Scaling s to the trust-region boundary, as recommended in
# Algorithm 10.3.2 of the Trust-Region book
# appears to deteriorate results.
# BLAS.scal!(n, tr.radius / sNorm, s, 1)
# slope *= tr.radius / sNorm
# sNorm = tr.radius
if slope ≥ 0
@error "not a descent direction" slope ∇fNorm2 sNorm
stats.status = :not_desc
done = true
continue
end
α = one(T)
while (bk < bk_max) && (ft > f + β * α * slope)
bk = bk + 1
α /= T(1.2)
copyaxpy!(n, α, s, x, xt)
residual!(nlp, xt, rt)
ft = obj(nlp, x, rt, recompute = false)
end
sNorm *= α
scal!(n, α, s)
slope *= α
Δq = slope + α * α * curv / 2
ared, pred = aredpred!(tr, nlp, rt, f, ft, Δq, xt, s, slope)
if pred ≥ 0
stats.status = :neg_pred
done = true
continue
end
tr.ratio = ared / pred
if !monotone
ared_hist, pred_hist = aredpred!(tr, nlp, rt, fref, ft, σref + Δq, xt, s, slope)
if pred_hist ≥ 0
stats.status = :neg_pred
done = true
continue
end
ρ_hist = ared_hist / pred_hist
tr.ratio = max(tr.ratio, ρ_hist)
end
end
set_iter!(stats, stats.iter + 1)
if acceptable(tr)
# Update non-monotone mode parameters.
if !monotone
σref = σref + Δq
σcur = σcur + Δq
if ft < fmin
# New overall best objective value found.
fcur = ft
fmin = ft
σcur = zero(T)
nm_iter = 0
else
nm_iter = nm_iter + 1
if ft > fcur
fcur = ft
σcur = zero(T)
end
if nm_iter >= nm_itmax
fref = fcur
σref = σcur
end
end
end
x .= xt # update A implicitly
r .= rt
f = ft
if tr.good_grad
∇f .= tr.gt
tr.good_grad = false
else
grad!(nlp, x, ∇f, r, recompute = false)
end
∇fNorm2 = nrm2(n, ∇f)
end
# Move on.
update!(tr, sNorm)
set_objective!(stats, f)
set_time!(stats, time() - start_time)
set_dual_residual!(stats, ∇fNorm2)
verbose > 0 &&
mod(stats.iter, verbose) == 0 &&
@info log_row([
stats.iter,
f,
∇fNorm2,
tr.radius,
sNorm,
tr.ratio,
length(cg_stats.residuals),
bk,
cg_stats.status,
])
optimal = ∇fNorm2 ≤ ϵ
small_residual = 2 * √f ≤ ϵF
set_status!(
stats,
get_status(
nlp,
elapsed_time = stats.elapsed_time,
optimal = optimal,
small_residual = small_residual,
max_eval = max_eval,
iter = stats.iter,
max_iter = max_iter,
max_time = max_time,
),
)
callback(nlp, solver, stats)
done = stats.status != :unknown
end
verbose > 0 && @info log_row(Any[stats.iter, f, ∇fNorm2, tr.radius])
set_solution!(stats, x)
stats
end
| JSOSolvers | https://github.com/JuliaSmoothOptimizers/JSOSolvers.jl.git |
|
[
"MPL-2.0"
] | 0.12.1 | c68e031e469f1898bb779cbc3c401e1640ecc0c4 | code | 2575 | """
@wrappedallocs(expr)
Given an expression, this macro wraps that expression inside a new function
which will evaluate that expression and measure the amount of memory allocated
by the expression. Wrapping the expression in a new function allows for more
accurate memory allocation detection when using global variables (e.g. when
at the REPL).
For example, `@wrappedallocs(x + y)` produces:
```julia
function g(x1, x2)
@allocated x1 + x2
end
g(x, y)
```
You can use this macro in a unit test to verify that a function does not
allocate:
```
@test @wrappedallocs(x + y) == 0
```
"""
macro wrappedallocs(expr)
argnames = [gensym() for a in expr.args]
quote
function g($(argnames...))
@allocated $(Expr(expr.head, argnames...))
end
$(Expr(:call, :g, [esc(a) for a in expr.args]...))
end
end
if Sys.isunix()
@testset "Allocation tests" begin
@testset "$symsolver" for symsolver in
(:LBFGSSolver, :FoSolver, :FomoSolver, :TrunkSolver, :TronSolver)
for model in NLPModelsTest.nlp_problems
nlp = eval(Meta.parse(model))()
if unconstrained(nlp) || (bound_constrained(nlp) && (symsolver == :TronSolver))
if (symsolver == :FoSolver || symsolver == :FomoSolver)
solver = eval(symsolver)(nlp; M = 2) # nonmonotone configuration allocates extra memory
else
solver = eval(symsolver)(nlp)
end
if symsolver == :FomoSolver
T = eltype(nlp.meta.x0)
stats = GenericExecutionStats(nlp, solver_specific = Dict(:avgβmax => T(0)))
else
stats = GenericExecutionStats(nlp)
end
with_logger(NullLogger()) do
SolverCore.solve!(solver, nlp, stats)
reset!(solver)
reset!(nlp)
al = @wrappedallocs SolverCore.solve!(solver, nlp, stats)
@test al == 0
end
end
end
end
@testset "$symsolver" for symsolver in (:TrunkSolverNLS, :TronSolverNLS)
for model in NLPModelsTest.nls_problems
nlp = eval(Meta.parse(model))()
if unconstrained(nlp) || (bound_constrained(nlp) && (symsolver == :TronSolverNLS))
solver = eval(symsolver)(nlp)
stats = GenericExecutionStats(nlp)
with_logger(NullLogger()) do
SolverCore.solve!(solver, nlp, stats)
reset!(solver)
reset!(nlp)
al = @wrappedallocs SolverCore.solve!(solver, nlp, stats)
@test al == 0
end
end
end
end
end
end
| JSOSolvers | https://github.com/JuliaSmoothOptimizers/JSOSolvers.jl.git |
|
[
"MPL-2.0"
] | 0.12.1 | c68e031e469f1898bb779cbc3c401e1640ecc0c4 | code | 1614 | using ADNLPModels, JSOSolvers, LinearAlgebra, Logging #, Plots
@testset "Test callback" begin
f(x) = (x[1] - 1)^2 + 4 * (x[2] - x[1]^2)^2
nlp = ADNLPModel(f, [-1.2; 1.0])
X = [nlp.meta.x0[1]]
Y = [nlp.meta.x0[2]]
function cb(nlp, solver, stats)
x = solver.x
push!(X, x[1])
push!(Y, x[2])
if stats.iter == 8
stats.status = :user
end
end
stats = with_logger(NullLogger()) do
R2(nlp, callback = cb)
end
@test stats.iter == 8
stats = with_logger(NullLogger()) do
lbfgs(nlp, callback = cb)
end
@test stats.iter == 8
stats = with_logger(NullLogger()) do
trunk(nlp, callback = cb)
end
@test stats.iter == 8
stats = with_logger(NullLogger()) do
tron(nlp, callback = cb)
end
@test stats.iter == 8
stats = with_logger(NullLogger()) do
fomo(nlp, callback = cb)
end
@test stats.iter == 8
end
@testset "Test callback for NLS" begin
F(x) = [x[1] - 1; 2 * (x[2] - x[1]^2)]
nls = ADNLSModel(F, [-1.2; 1.0], 2)
function cb(nlp, solver, stats)
if stats.iter == 8
stats.status = :user
end
end
stats = with_logger(NullLogger()) do
trunk(nls, callback = cb)
end
@test stats.iter == 8
stats = with_logger(NullLogger()) do
tron(nls, callback = cb)
end
@test stats.iter == 8
end
@testset "Testing Solver Values" begin
f(x) = (x[1] - 1)^2 + 4 * (x[2] - x[1]^2)^2
nlp = ADNLPModel(f, [-1.2; 1.0])
function cb(nlp, solver, stats)
if stats.iter == 4
@test solver.α > 0.0
stats.status = :user
end
end
stats = with_logger(NullLogger()) do
R2(nlp, callback = cb)
end
end
| JSOSolvers | https://github.com/JuliaSmoothOptimizers/JSOSolvers.jl.git |
|
[
"MPL-2.0"
] | 0.12.1 | c68e031e469f1898bb779cbc3c401e1640ecc0c4 | code | 2078 | function consistency()
f = x -> (x[1] - 1)^2 + 100 * (x[2] - x[1]^2)^2
unlp = ADNLPModel(f, zeros(2))
F = x -> [x[1] - 1; 10 * (x[2] - x[1]^2)]
unls = ADNLSModel(F, zeros(2), 2)
#trunk and tron have special features for QuasiNewtonModel
qnlp = LBFGSModel(unlp)
qnls = LBFGSModel(unls)
@testset "Consistency" begin
args = Pair{Symbol, Number}[:atol => 1e-6, :rtol => 1e-6, :max_eval => 20000, :max_time => 60.0]
@testset "NLP with $mtd" for mtd in [trunk, lbfgs, tron, R2, fomo]
with_logger(NullLogger()) do
reset!(unlp)
stats = mtd(unlp; args...)
@test stats isa GenericExecutionStats
@test stats.status == :first_order
reset!(unlp)
stats = mtd(unlp; max_eval = 1)
@test stats.status == :max_eval
slow_nlp = ADNLPModel(x -> begin
sleep(0.1)
f(x)
end, unlp.meta.x0)
stats = mtd(slow_nlp; max_time = 0.0)
@test stats.status == :max_time
end
end
@testset "Quasi-Newton NLP with $mtd" for mtd in [trunk, lbfgs, tron, R2, fomo]
with_logger(NullLogger()) do
reset!(qnlp)
stats = mtd(qnlp; args...)
@test stats isa GenericExecutionStats
@test stats.status == :first_order
end
end
@testset "NLS with $mtd" for mtd in [trunk]
with_logger(NullLogger()) do
stats = mtd(unls; args...)
@test stats isa GenericExecutionStats
@test stats.status == :first_order
reset!(unls)
stats = mtd(unls; max_eval = 1)
@test stats.status == :max_eval
slow_nls = ADNLSModel(x -> begin
sleep(0.1)
F(x)
end, unls.meta.x0, nls_meta(unls).nequ)
stats = mtd(slow_nls; max_time = 0.0)
@test stats.status == :max_time
end
end
@testset "Quasi-Newton NLS with $mtd" for mtd in [trunk]
with_logger(NullLogger()) do
stats = mtd(qnls; args...)
@test stats isa GenericExecutionStats
@test stats.status == :first_order
end
end
end
end
consistency()
| JSOSolvers | https://github.com/JuliaSmoothOptimizers/JSOSolvers.jl.git |
|
[
"MPL-2.0"
] | 0.12.1 | c68e031e469f1898bb779cbc3c401e1640ecc0c4 | code | 1830 | mutable struct DummyModel{T, S} <: AbstractNLPModel{T, S}
meta::NLPModelMeta{T, S}
end
mutable struct DummyNLSModel{T, S} <: AbstractNLSModel{T, S}
meta::NLPModelMeta{T, S}
end
function test_incompatible()
@testset "Incompatible problems should throw error" begin
solvers = Dict(:lbfgs => [:unc], :trunk => [:unc], :tron => [:unc, :bnd])
problems = Dict(
:unc => ADNLPModel(x -> 0, zeros(2)),
:bnd => ADNLPModel(x -> 0, zeros(2), zeros(2), ones(2)),
:equ => ADNLPModel(x -> 0, zeros(2), x -> [0.0], [0.0], [0.0]),
:ine => ADNLPModel(x -> 0, zeros(2), x -> [0.0], [-Inf], [0.0]),
:gen => ADNLPModel(x -> 0, zeros(2), x -> [0.0; 0.0], [-Inf; 0.0], zeros(2)),
)
for (ptype, problem) in problems, (solver, types_accepted) in solvers
@testset "Testing that $solver on problem type $ptype raises error: " begin
if !(ptype in types_accepted)
@test_throws ErrorException eval(solver)(problem)
end
end
end
nlp = DummyModel(NLPModelMeta(1, minimize = false))
@testset for solver in keys(solvers)
@test_throws ErrorException eval(solver)(nlp)
end
solvers = Dict(:trunk => [:unc], :tron => [:unc, :bnd])
problems = Dict(
:unc => ADNLSModel(x -> [0], zeros(2), 1),
:bnd => ADNLSModel(x -> [0], zeros(2), 1, zeros(2), ones(2)),
)
for (ptype, problem) in problems, (solver, types_accepted) in solvers
@testset "Testing that $solver on problem type $ptype raises error: " begin
if !(ptype in types_accepted)
@test_throws ErrorException eval(solver)(problem)
end
end
end
nls = DummyNLSModel(NLPModelMeta(1, minimize = false))
@testset for solver in keys(solvers)
@test_throws ErrorException eval(solver)(nls)
end
end
end
test_incompatible()
| JSOSolvers | https://github.com/JuliaSmoothOptimizers/JSOSolvers.jl.git |
|
[
"MPL-2.0"
] | 0.12.1 | c68e031e469f1898bb779cbc3c401e1640ecc0c4 | code | 1276 | @testset "objgrad on tron" begin
struct MyProblem <: AbstractNLPModel{Float64, Vector{Float64}}
meta::NLPModelMeta{Float64, Vector{Float64}}
counters::Counters
end
function MyProblem()
meta = NLPModelMeta{Float64, Vector{Float64}}(
2, # nvar
x0 = [0.1; 0.1],
lvar = zeros(2),
uvar = ones(2),
)
MyProblem(meta, Counters())
end
function NLPModels.objgrad!(::MyProblem, x::AbstractVector, g::AbstractVector)
f = (x[1] - 1)^2 + 100 * (x[2] - x[1]^2)^2
g[1] = 2 * (x[1] - 1) - 400 * x[1] * (x[2] - x[1]^2)
g[2] = 200 * (x[2] - x[1]^2)
f, g
end
function NLPModels.hprod!(
::MyProblem,
x::AbstractVector,
v::AbstractVector,
Hv::AbstractVector;
obj_weight = 1.0,
)
Hv[1] =
obj_weight * (2 - 400 * (x[2] - x[1]^2) + 800 * x[1]^2) * v[1] - 400obj_weight * x[1] * v[2]
Hv[2] = 200obj_weight * v[2] - 400obj_weight * x[1] * v[1]
Hv
end
nlp = MyProblem()
output = with_logger(NullLogger()) do
tron(nlp, use_only_objgrad = true)
end
@test isapprox(output.solution, ones(2), rtol = 1e-4)
@test output.dual_feas < 1e-4
@test output.objective < 1e-4
with_logger(NullLogger()) do
@test_throws MethodError tron(nlp, use_only_objgrad = false)
end
end
| JSOSolvers | https://github.com/JuliaSmoothOptimizers/JSOSolvers.jl.git |
|
[
"MPL-2.0"
] | 0.12.1 | c68e031e469f1898bb779cbc3c401e1640ecc0c4 | code | 2843 | @testset "Test restart with a different initial guess: $fun" for (fun, s) in (
(:R2, :FoSolver),
(:fomo, :FomoSolver),
(:lbfgs, :LBFGSSolver),
(:tron, :TronSolver),
(:trunk, :TrunkSolver),
)
f(x) = (x[1] - 1)^2 + 4 * (x[2] - x[1]^2)^2
nlp = ADNLPModel(f, [-1.2; 1.0])
stats = GenericExecutionStats(nlp)
solver = eval(s)(nlp)
stats = SolverCore.solve!(solver, nlp, stats)
@test stats.status == :first_order
@test isapprox(stats.solution, [1.0; 1.0], atol = 1e-6)
nlp.meta.x0 .= 2.0
SolverCore.reset!(solver)
stats = SolverCore.solve!(solver, nlp, stats, atol = 1e-10, rtol = 1e-10)
@test stats.status == :first_order
@test isapprox(stats.solution, [1.0; 1.0], atol = 1e-6)
end
@testset "Test restart NLS with a different initial guess: $fun" for (fun, s) in (
(:tron, :TronSolverNLS),
(:trunk, :TrunkSolverNLS),
)
F(x) = [x[1] - 1; 2 * (x[2] - x[1]^2)]
nlp = ADNLSModel(F, [-1.2; 1.0], 2)
stats = GenericExecutionStats(nlp)
solver = eval(s)(nlp)
stats = SolverCore.solve!(solver, nlp, stats)
@test stats.status == :first_order
@test isapprox(stats.solution, [1.0; 1.0], atol = 1e-6)
nlp.meta.x0 .= 2.0
SolverCore.reset!(solver)
stats = SolverCore.solve!(solver, nlp, stats, atol = 1e-10, rtol = 1e-10)
@test stats.status == :first_order
@test isapprox(stats.solution, [1.0; 1.0], atol = 1e-6)
end
@testset "Test restart with a different problem: $fun" for (fun, s) in (
(:R2, :FoSolver),
(:fomo, :FomoSolver),
(:lbfgs, :LBFGSSolver),
(:tron, :TronSolver),
(:trunk, :TrunkSolver),
)
f(x) = (x[1] - 1)^2 + 4 * (x[2] - x[1]^2)^2
nlp = ADNLPModel(f, [-1.2; 1.0])
stats = GenericExecutionStats(nlp)
solver = eval(s)(nlp)
stats = SolverCore.solve!(solver, nlp, stats)
@test stats.status == :first_order
@test isapprox(stats.solution, [1.0; 1.0], atol = 1e-6)
f2(x) = (x[1])^2 + 4 * (x[2] - x[1]^2)^2
nlp = ADNLPModel(f2, [-1.2; 1.0])
SolverCore.reset!(solver, nlp)
stats = SolverCore.solve!(solver, nlp, stats, atol = 1e-10, rtol = 1e-10)
@test stats.status == :first_order
@test isapprox(stats.solution, [0.0; 0.0], atol = 1e-6)
end
@testset "Test restart NLS with a different problem: $fun" for (fun, s) in (
(:tron, :TronSolverNLS),
(:trunk, :TrunkSolverNLS),
)
F(x) = [x[1] - 1; 2 * (x[2] - x[1]^2)]
nlp = ADNLSModel(F, [-1.2; 1.0], 2)
stats = GenericExecutionStats(nlp)
solver = eval(s)(nlp)
stats = SolverCore.solve!(solver, nlp, stats)
@test stats.status == :first_order
@test isapprox(stats.solution, [1.0; 1.0], atol = 1e-6)
F2(x) = [x[1]; 2 * (x[2] - x[1]^2)]
nlp = ADNLSModel(F2, [-1.2; 1.0], 2)
SolverCore.reset!(solver, nlp)
stats = SolverCore.solve!(solver, nlp, stats, atol = 1e-10, rtol = 1e-10)
@test stats.status == :first_order
@test isapprox(stats.solution, [0.0; 0.0], atol = 1e-6)
end
| JSOSolvers | https://github.com/JuliaSmoothOptimizers/JSOSolvers.jl.git |
|
[
"MPL-2.0"
] | 0.12.1 | c68e031e469f1898bb779cbc3c401e1640ecc0c4 | code | 3102 | # stdlib
using Printf, LinearAlgebra, Logging, SparseArrays, Test
# additional packages
using ADNLPModels, Krylov, LinearOperators, NLPModels, NLPModelsModifiers, SolverCore, SolverTools
using NLPModelsTest
# this package
using JSOSolvers
@testset "Test small residual checks $solver" for solver in (:TrunkSolverNLS, :TronSolverNLS)
nls = ADNLSModel(x -> [x[1] - 1; sin(x[2])], [-1.2; 1.0], 2)
stats = GenericExecutionStats(nls)
solver = eval(solver)(nls)
SolverCore.solve!(solver, nls, stats, atol = 0.0, rtol = 0.0, Fatol = 1e-6, Frtol = 0.0)
@test stats.status_reliable && stats.status == :small_residual
@test stats.objective_reliable && isapprox(stats.objective, 0, atol = 1e-6)
end
@testset "Test iteration limit" begin
@testset "$fun" for fun in (R2, fomo, lbfgs, tron, trunk)
f(x) = (x[1] - 1)^2 + 4 * (x[2] - x[1]^2)^2
nlp = ADNLPModel(f, [-1.2; 1.0])
stats = eval(fun)(nlp, max_iter = 1)
@test stats.status == :max_iter
end
@testset "$(fun)-NLS" for fun in (tron, trunk)
f(x) = [x[1] - 1; 2 * (x[2] - x[1]^2)]
nlp = ADNLSModel(f, [-1.2; 1.0], 2)
stats = eval(fun)(nlp, max_iter = 1)
@test stats.status == :max_iter
end
end
@testset "Test unbounded below" begin
@testset "$fun" for fun in (R2, fomo, lbfgs, tron, trunk)
T = Float64
x0 = [T(0)]
f(x) = -exp(x[1])
nlp = ADNLPModel(f, x0)
stats = eval(fun)(nlp)
@test stats.status == :unbounded
@test stats.objective < -one(T) / eps(T)
end
end
include("restart.jl")
include("callback.jl")
include("consistency.jl")
include("test_solvers.jl")
if VERSION ≥ v"1.7"
include("allocs.jl")
@testset "Test warning for infeasible initial guess" begin
nlp = ADNLPModel(x -> (x[1] - 1)^2 + sin(x[2])^2, [-1.2; 1.0], zeros(2), ones(2))
@test_warn "Warning: Initial guess is not within bounds." tron(nlp, verbose = 1)
nls = ADNLSModel(x -> [x[1] - 1; sin(x[2])], [-1.2; 1.0], 2, zeros(2), ones(2))
@test_warn "Warning: Initial guess is not within bounds." tron(nls, verbose = 1)
end
end
include("objgrad-on-tron.jl")
@testset "Test max_radius in TRON" begin
max_radius = 0.00314
increase_factor = 5.0
function cb(nlp, solver, stats)
@test solver.tr.radius ≤ max_radius
end
nlp = ADNLPModel(x -> 100 * (x[2] - x[1]^2)^2 + (x[1] - 1)^2, [-1.2; 1.0])
stats = tron(nlp, max_radius = max_radius, increase_factor = increase_factor, callback = cb)
nls = ADNLSModel(x -> [100 * (x[2] - x[1]^2); x[1] - 1], [-1.2; 1.0], 2)
stats = tron(nls, max_radius = max_radius, increase_factor = increase_factor, callback = cb)
end
@testset "Preconditioner in Trunk" begin
x0 = [-1.2; 1.0]
nlp = ADNLPModel(x -> 100 * (x[2] - x[1]^2)^2 + (x[1] - 1)^2, x0)
function DiagPrecon(x)
H = Matrix(hess(nlp, x))
λmin = minimum(eigvals(H))
Diagonal(H + λmin * I)
end
M = DiagPrecon(x0)
function LinearAlgebra.ldiv!(y, M::Diagonal, x)
y .= M \ x
end
function callback(nlp, solver, stats)
M[:] = DiagPrecon(solver.x)
end
stats = trunk(nlp, callback = callback, M = M)
@test stats.status == :first_order
end
| JSOSolvers | https://github.com/JuliaSmoothOptimizers/JSOSolvers.jl.git |
|
[
"MPL-2.0"
] | 0.12.1 | c68e031e469f1898bb779cbc3c401e1640ecc0c4 | code | 2379 | using SolverTest
function tests()
@testset "Testing NLP solvers" begin
@testset "Unconstrained solvers" begin
@testset "$name" for (name, solver) in [
("trunk+cg", (nlp; kwargs...) -> trunk(nlp, subsolver_type = CgSolver; kwargs...)),
("lbfgs", lbfgs),
("tron", tron),
("R2", R2),
("fomo_r2", fomo),
("fomo_tr", (nlp; kwargs...) -> fomo(nlp, step_backend = JSOSolvers.tr_step(); kwargs...)),
]
unconstrained_nlp(solver)
multiprecision_nlp(solver, :unc)
end
@testset "$name : nonmonotone configuration" for (name, solver) in [
("R2", (nlp; kwargs...) -> R2(nlp, M = 2; kwargs...)),
("fomo_r2", (nlp; kwargs...) -> fomo(nlp, M = 2; kwargs...)),
(
"fomo_tr",
(nlp; kwargs...) -> fomo(nlp, M = 2, step_backend = JSOSolvers.tr_step(); kwargs...),
),
]
unconstrained_nlp(solver)
multiprecision_nlp(solver, :unc)
end
end
@testset "Bound-constrained solvers" begin
@testset "$solver" for solver in [tron]
bound_constrained_nlp(solver)
multiprecision_nlp(solver, :unc)
multiprecision_nlp(solver, :bnd)
end
end
end
@testset "Testing NLS solvers" begin
@testset "Unconstrained solvers" begin
@testset "$name" for (name, solver) in [
("trunk+cgls", (nls; kwargs...) -> trunk(nls, subsolver_type = CglsSolver; kwargs...)), # trunk with cgls due to multiprecision
("trunk full Hessian", (nls; kwargs...) -> trunk(nls, variant = :Newton; kwargs...)),
("tron+cgls", (nls; kwargs...) -> tron(nls, subsolver_type = CglsSolver; kwargs...)),
("tron full Hessian", (nls; kwargs...) -> tron(nls, variant = :Newton; kwargs...)),
]
unconstrained_nls(solver)
multiprecision_nls(solver, :unc)
end
end
@testset "Bound-constrained solvers" begin
@testset "$name" for (name, solver) in [
("tron+cgls", (nls; kwargs...) -> tron(nls, subsolver_type = CglsSolver; kwargs...)),
("tron full Hessian", (nls; kwargs...) -> tron(nls, variant = :Newton; kwargs...)),
]
bound_constrained_nls(solver)
multiprecision_nls(solver, :unc)
multiprecision_nls(solver, :bnd)
end
end
end
end
tests()
include("solvers/trunkls.jl")
include("incompatible.jl")
| JSOSolvers | https://github.com/JuliaSmoothOptimizers/JSOSolvers.jl.git |
|
[
"MPL-2.0"
] | 0.12.1 | c68e031e469f1898bb779cbc3c401e1640ecc0c4 | code | 1350 | # TODO: After all subsolvers handle multiprecision, drop this file and use
# `unconstrained-nls`
@testset "Simple test" begin
model = ADNLSModel(x -> [10 * (x[2] - x[1]^2), 1 - x[1]], [-2.0, 1.0], 2)
for subsolver in JSOSolvers.tronls_allowed_subsolvers
stats = tron(model, subsolver = subsolver)
@test stats.status == :first_order
@test stats.solution_reliable
isapprox(stats.solution, ones(2), rtol = 1e-4)
@test stats.objective_reliable
@test isapprox(stats.objective, 0, atol = 1e-6)
@test neval_jac_residual(model) == 0
stline = statsline(stats, [:objective, :dual_feas, :elapsed_time, :iter, :status])
reset!(model)
end
@test_throws ErrorException tron(model, subsolver = :minres)
end
@testset "Larger test" begin
n = 30
model = ADNLSModel(
x -> [[10 * (x[i + 1] - x[i]^2) for i = 1:(n - 1)]; [x[i] - 1 for i = 1:(n - 1)]],
(1:n) ./ (n + 1),
2n - 2,
)
for subsolver in JSOSolvers.tronls_allowed_subsolvers
stats = with_logger(NullLogger()) do
tron(model, subsolver = subsolver)
end
@test stats.status == :first_order
@test stats.objective_reliable
@test isapprox(stats.objective, 0, atol = 1e-6)
@test neval_jac_residual(model) == 0
stline = statsline(stats, [:objective, :dual_feas, :elapsed_time, :iter, :status])
reset!(model)
end
end
| JSOSolvers | https://github.com/JuliaSmoothOptimizers/JSOSolvers.jl.git |
|
[
"MPL-2.0"
] | 0.12.1 | c68e031e469f1898bb779cbc3c401e1640ecc0c4 | code | 1425 | # TODO: After all subsolvers handle multiprecision, drop this file and use
# `unconstrained-nls`
@testset "Simple test" begin
model = ADNLSModel(x -> [10 * (x[2] - x[1]^2), 1 - x[1]], [-2.0, 1.0], 2)
for subsolver in JSOSolvers.trunkls_allowed_subsolvers
stats = with_logger(NullLogger()) do
trunk(model, subsolver_type = subsolver)
end
@test stats.status == :first_order
@test stats.solution_reliable
isapprox(stats.solution, ones(2), rtol = 1e-4)
@test stats.objective_reliable
@test isapprox(stats.objective, 0, atol = 1e-6)
@test neval_jac_residual(model) == 0
stline = statsline(stats, [:objective, :dual_feas, :elapsed_time, :iter, :status])
reset!(model)
end
@test_throws ErrorException trunk(model, subsolver_type = MinresSolver)
end
@testset "Larger test" begin
n = 30
model = ADNLSModel(
x -> [[10 * (x[i + 1] - x[i]^2) for i = 1:(n - 1)]; [x[i] - 1 for i = 1:(n - 1)]],
collect(1:n) ./ (n + 1),
2n - 2,
)
for subsolver in JSOSolvers.trunkls_allowed_subsolvers
stats = with_logger(NullLogger()) do
trunk(model, subsolver_type = subsolver)
end
@test stats.status == :first_order
@test stats.objective_reliable
@test isapprox(stats.objective, 0, atol = 1e-6)
@test neval_jac_residual(model) == 0
stline = statsline(stats, [:objective, :dual_feas, :elapsed_time, :iter, :status])
reset!(model)
end
end
| JSOSolvers | https://github.com/JuliaSmoothOptimizers/JSOSolvers.jl.git |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.