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.1.1
5aa07104cc57e5aeaaa14891afcac7d0c95f28b7
code
4648
""" make_twospirals(; n_samples::Int = 2000, start_degrees::Int = 90, total_degrees::Int = 570, noise::Float64 = 0.2 Generate two spirals dataset. Return a Nx3 matrix, where each line contains the X,Y coordinates and the class of an instance. # Arguments - `n_samples::Int = 2000`: The total number of points generated. - `start_degrees::Int = 90`: Determines how far from the origin the spirals start. - `total_degrees::Int = 570`: Controls the lenght of the spirals. - `noise::Float64 = 0.2`: Determines the noise in the dataset. Reference: [link](https://la.mathworks.com/matlabcentral/fileexchange/41459-6-functions-for-generating-artificial-datasets) """ function make_twospirals(; n_samples::Int = 2000, start_degrees::Int = 90, total_degrees::Int = 570, noise::Float64 = 0.2) start_degrees = deg2rad(start_degrees); N1 = floor(Int, n_samples / 2); N2 = n_samples - N1; n = start_degrees .+ sqrt.(rand(N1,1)) .* deg2rad(total_degrees); d1 = [-cos.(n).*n + rand(N1,1).*noise sin.(n).*n+rand(N1,1).*noise]; n = start_degrees .+ sqrt.(rand(N2,1)) .* deg2rad(total_degrees); d2 = [cos.(n).*n+rand(N2,1)*noise -sin.(n).*n+rand(N2,1)*noise]; features = [d1; d2] labels = [zeros(Int, N1); ones(Int, N2)] return convert(features, labels); end """ make_halfkernel(; n_samples::Int = 1000, minx::Int = -20, r1::Int = 20, r2::Int = 35, noise::Float64 = 4.0, ratio::Float64 = 0.6) Generates two half ellipses, one inside the other # Arguments - `n_samples::Int = 1000`: The total number of points generated - `r1::Int = 20`: - `r2::Int = 35`: - `minx::Int = -20`: - `noise::Float64 = 0.2`: Determines the noise in the dataset. - `ratio::Float64 = 0.6)`: Reference: [link](https://la.mathworks.com/matlabcentral/fileexchange/41459-6-functions-for-generating-artificial-datasets) """ function make_halfkernel(; n_samples::Int = 1000, minx::Int = -20, r1::Int = 20, r2::Int = 35, noise::Float64 = 4.0, ratio::Float64 = 0.6) N = floor(Int, n_samples / 2) phi1 = rand(N, 1) * pi inner = [minx .+ r1 .* sin.(phi1) .- .5 .* noise .+ noise .* rand(N, 1) r1 .* ratio .* cos.(phi1) .- .5 .* noise .+ noise .* rand(N,1)] l1 = ones(Int, N) phi2 = rand(N,1) * pi outer = [minx .+ r2 .* sin.(phi2) .- .5 .* noise .+ noise .* rand(N,1) r2 .* ratio .* cos.(phi2) .- .5 .* noise .+ noise .* rand(N,1)] l2 = zeros(Int, N) features = [inner; outer] labels = [l1; l2] return convert(features, labels) end """ make_outlier(;n_samples::Int = 600, r::Int = 20, dist::Int = 30, outliers::Float64 = 0.04, noise::Float64 = 5.0) Generates outlier dataset. # Arguments - `n_samples::600 = 1000`: The total number of points generated. - `r::Int = 20`: Radius of lateral blobs. - `dist::Int = 30`: Determine the distance between the labels. - `noise::Float64 = 5.0`: Determines the noise in the dataset. Reference: [link](https://la.mathworks.com/matlabcentral/fileexchange/41459-6-functions-for-generating-artificial-datasets) """ function make_outlier(;n_samples::Int = 600, r::Int = 20, dist::Int = 30, outliers::Float64 = 0.04, noise::Float64 = 5.0) n1 = round(Int, (n_samples * (0.5 - outliers)) ) n2 = n1 n3 = round(Int, n_samples * outliers) n4 = n_samples - n1 - n2 - n3 phi1 = rand(n1, 1) * pi r1 = sqrt.(rand(n1, 1)) * r p1 = [ -dist .+ (r1 .* sin.(phi1)) r1 .* cos.(phi1)] l1 = zeros(Int, n1) phi2 = rand(n2, 1) * pi r2 = sqrt.(rand(n2, 1)) * r p2 = [ dist .- r2.*sin.(phi2) r2.*cos.(phi2)] l2 = 3 * ones(Int, n2) p3 = [ rand(n3, 1) * noise dist .+ rand(n3, 1) * noise ] l3 = 2 * ones(Int, n3) p4 = [ rand(n4, 1) * noise -dist .+ rand(n4, 1) * noise ] l4 = ones(Int, n4) features = [p1; p2; p3; p4] labels = [l1; l2; l3; l4] return convert(features, labels) end
SyntheticDatasets
https://github.com/ATISLabs/SyntheticDatasets.jl.git
[ "MIT" ]
0.1.1
5aa07104cc57e5aeaaa14891afcac7d0c95f28b7
code
26965
""" make_moons(; n_samples::Union{Tuple{Int, Int}, Int} = 100, shuffle = true, noise = nothing, random_state = nothing)::DataFrame Make two interleaving half circles. Sklearn interface to make_moons. # Arguments - `n_samples::Union{Tuple{Int, Int}, Int} = 100`: If int, the total number of points generated. If two-element tuple, number of points in each of two moons. - `shuffle::Bool = true`: Whether to shuffle the samples. - `noise::Union{Nothing, Float64} = nothing`: Standard deviation of Gaussian noise added to the data. - `random_state::Union{Int, Nothing} = nothing`: Determines random number generation for dataset shuffling and noise. Reference: [link](https://scikit-learn.org/stable/modules/generated/sklearn.datasets.make_moons.html) """ function make_moons(; n_samples::Union{Tuple{Int, Int}, Int} = 100, shuffle::Bool = true, noise::Union{Nothing, Float64} = nothing, random_state::Union{Int, Nothing} = nothing)::DataFrame (features, labels) = datasets.make_moons( n_samples=n_samples, shuffle = shuffle, noise = noise, random_state = random_state) return convert(features, labels) end """ make_blobs(; n_samples::Union{Int, Array{Int, 1}} = 100, n_features::Int = 2, centers::Union{Int, Union{Nothing, Array{Float64, 2}}} = nothing, cluster_std::Union{Float64, Array{Float64, 1}} = 1.0, center_box = (-10.0, 10.0), shuffle::Bool = true, random_state::Union{Int, Nothing} = nothing)::DataFrame Generate isotropic Gaussian blobs for clustering. Sklearn interface to make_blobs. # Arguments - `n_samples = 100`: If int, it is the total number of points equally divided among clusters. If array-like, each element of the sequence indicates the number of samples per cluster. - `n_features = 2`: The number of features for each sample. - `centers::Union{Int, Union{Nothing, Array{Float64, 2}}} = nothing`: The number of centers to generate, or the fixed center locations. If n_samples is an int and centers is None, 3 centers are generated. If n_samples is array-like, centers must be either None or an array of length equal to the length of n_samples. - `cluster_std::Union{Float64, Array{Float64, 1}} = 1.0`: The standard deviation of the clusters. - `center_box::Tuple{Float64, Float64} = (-10.0, 10.0)`: The bounding box for each cluster center when centers are generated at random. - `shuffle::Bool = true`: Shuffle the samples. - `random_state::Union{Int, Nothing} = nothing`: Determines random number generation for dataset shuffling and noise. Reference: [link](https://scikit-learn.org/stable/modules/generated/sklearn.datasets.make_blobs.html) """ function make_blobs(; n_samples::Union{Int, Array{Int, 1}} = 100, n_features::Int = 2, centers::Union{Int, Union{Nothing, Array{Float64, 2}}} = nothing, cluster_std::Union{Float64, Array{Float64, 1}} = 1.0, center_box::Tuple{Float64, Float64} = (-10.0, 10.0), shuffle::Bool = true, random_state::Union{Int, Nothing} = nothing)::DataFrame (features, labels) = datasets.make_blobs( n_samples = n_samples, n_features = n_features, centers = centers, cluster_std = cluster_std, center_box = center_box, shuffle = shuffle, random_state = random_state, return_centers = false) return convert(features, labels) end """ make_s_curve(; n_samples::Int = 100, noise = nothing, random_state = nothing)::DataFrame Generate an S curve dataset. Sklearn interface to make_s_curve. # Arguments - `n_samples::Int = 100`: The number of sample points on the S curve. - `noise::Union{Nothing, Float64} = nothing`: Standard deviation of Gaussian noise added to the data. - `random_state::Union{Int, Nothing} = nothing`: Determines random number generation for dataset creation. Pass an int for reproducible output across multiple function calls. Reference: [link](https://scikit-learn.org/stable/modules/generated/sklearn.datasets.make_s_curve.html) """ function make_s_curve(; n_samples::Int = 100, noise::Float64 = 0.0, random_state::Union{Int, Nothing} = nothing)::DataFrame (features, labels) = datasets.make_s_curve( n_samples = n_samples, noise = noise, random_state = random_state) return convert(features, labels) end """ function make_circles(; n_samples::Int = 100, shuffle::Bool = true, noise::Float64 = 0.0, random_state::Union{Int, Nothing} = nothing, factor::Float64 = 0.8)::DataFrame Make a large circle containing a smaller circle in 2d. Sklearn interface to make_circles. # Arguments - `n_samples::Union{Int, Tuple{Int, Int}} = 100`: If int, it is the total number of points generated. For odd numbers, the inner circle will have one point more than the outer circle. If two-element tuple, number of points in outer circle and inner circle. - `shuffle::Bool = true`: Whether to shuffle the samples. - `noise::Union{Nothing, Float64} = nothing`: Standard deviation of Gaussian noise added to the data. - `random_state::Union{Int, Nothing} = nothing`: Determines random number generation for dataset shuffling and noise. Pass an int for reproducible output across multiple function calls. - `factor::Float64 = 0.8`: Scale factor between inner and outer circle. Reference: [link](https://scikit-learn.org/stable/modules/generated/sklearn.datasets.make_circles.html) """ function make_circles(; n_samples::Union{Int, Tuple{Int, Int}} = 100, shuffle::Bool = true, noise::Union{Nothing, Float64} = nothing, random_state::Union{Int, Nothing} = nothing, factor::Float64 = 0.8)::DataFrame (features, labels) = datasets.make_circles( n_samples = n_samples, shuffle = shuffle, noise = noise, random_state = random_state, factor = factor) return convert(features, labels) end """ make_regression(; n_samples::Int = 100, n_features::Int = 100, n_informative::Int = 10, n_targets::Int = 1, bias::Float64 = 0.0, effective_rank::Union{Int, Nothing} = nothing, tail_strength::Float64 = 0.5, noise::Float64 = 0.0, shuffle::Bool = true, coef::Bool = false, random_state::Union{Int, Nothing}= nothing) Generate a random regression problem. Sklearn interface to make_regression. # Arguments - `n_samples::Int = 100`: The number of samples. - `n_features::Int = 2`: The number of features. - `n_informative::Int = 10`: The number of informative features, i.e., the number of features used to build the linear model used to generate the output. - `n_targets::Int = 1`: The number of regression targets, i.e., the dimension of the y output vector associated with a sample. By default, the output is a scalar. - `bias::Float = 0.0`: The bias term in the underlying linear model. - `effective_rank::Union{Int, Nothing} = nothing`: If not `nothing`, the approximate number of singular vectors required to explain most of the input data by linear combinations. Using this kind of singular spectrum in the input allows the generator to reproduce the correlations often observed in practice. If `nothing`, the input set is well conditioned, centered and gaussian with unit variance. - `tail_strength::Float = 0.5`: The relative importance of the fat noisy tail of the singular values profile if effective_rank is not None. - `noise::Union{Nothing, Float64} = nothing`: Standard deviation of Gaussian noise added to the data. - `shuffle::Bool = true`: Shuffle the samples and the features. - `coef::Bool = false`: If `true`, the coefficients of the underlying linear model are returned. - `random_state::Union{Int, Nothing} = nothing`: Determines random number generation for dataset shuffling and noise. Reference: [link](https://scikit-learn.org/stable/modules/generated/sklearn.datasets.make_regression.html) """ function make_regression(; n_samples::Int = 100, n_features::Int = 100, n_informative::Int = 10, n_targets::Int = 1, bias::Float64 = 0.0, effective_rank::Union{Int, Nothing} = nothing, tail_strength::Float64 = 0.5, noise::Float64 = 0.0, shuffle::Bool = true, coef::Bool = false, random_state::Union{Int, Nothing}= nothing) (features, labels) = datasets.make_regression( n_samples = n_samples, n_features = n_features, n_informative = n_informative, n_targets = n_targets, bias = bias, effective_rank = effective_rank, tail_strength = tail_strength, noise = noise, shuffle = shuffle, coef = coef, random_state = random_state) return convert(features, labels) end """ function make_classification(; n_samples::Int = 100, n_features::Int = 20, n_informative::Int = 2, n_redundant::Int = 2, n_repeated::Int = 0, n_classes::Int = 2, n_clusters_per_class::Int = 2, weights::Union{Nothing, Array{Float64,1}} = nothing, flip_y::Float64 = 0.01, class_sep::Float64 = 1.0, hypercube::Bool = true, shift::Union{Nothing, Array{Float64,1}} = 0.0, scale::Union{Nothing, Array{Float64,1}} = 1.0, shuffle::Bool = true, random_state::Union{Int, Nothing} = nothing) Generate a random n-class classification problem. Sklearn interface to make_classification. #Arguments - `n_samples::Int = 100`: The number of samples. - `n_features::Int = 20`: The total number of features. These comprise `n_informative` informative features, `n_redundant` redundant features, `n_repeated` duplicated features and `n_features-n_informative-n_redundant-n_repeated` useless features drawn at random. - `n_informative::Int = 2`: The number of informative features. Each class is composed of a number of gaussian clusters each located around the vertices of a hypercube in a subspace of dimension `n_informative`. For each cluster, informative features are drawn independently from N(0, 1) and then randomly linearly combined within each cluster in order to add covariance. The clusters are then placed on the vertices of the hypercube. - `n_redundant::Int = 2`: The number of redundant features. These features are generated as random linear combinations of the informative features. - `n_repeated::Int = 0`: The number of duplicated features, drawn randomly from the informative and the redundant features. - `n_classes::Int = 2`: The number of classes (or labels) of the classification problem. - `n_clusters_per_class::Int = 2`: The number of clusters per class. - `weights::Union{Nothing, Array{Float64,1}} = nothing`: - `flip_y::Float64 = 0.01`: The fraction of samples whose class is assigned randomly. Larger values introduce noise in the labels and make the classification task harder. Note that the default setting flip_y > 0 might lead to less than n_classes in y in some cases. - `class_sep::Float64 = 1.0`: The factor multiplying the hypercube size. Larger values spread out the clusters/classes and make the classification task easier. - `hypercube::Bool = true`: If True, the clusters are put on the vertices of a hypercube. If False, the clusters are put on the vertices of a random polytope. - `shift::Union{Nothing, Array{Float64,1}} = 0.0`: Shift features by the specified value. If None, then features are shifted by a random value drawn in [-class_sep, class_sep]. - `scale::Union{Nothing, Array{Float64,1}} = 1.0`: Multiply features by the specified value. If None, then features are scaled by a random value drawn in [1, 100]. Note that scaling happens after shifting. - `shuffle::Bool = true`: Shuffle the samples and the features. - `random_state::Union{Int, Nothing} = nothing`: Determines random number generation for dataset creation. Pass an int for reproducible output across multiple function calls. See Glossary. Reference: [link](https://scikit-learn.org/stable/modules/generated/sklearn.datasets.make_classification.html) """ function make_classification(; n_samples::Int = 100, n_features::Int = 20, n_informative::Int = 2, n_redundant::Int = 2, n_repeated::Int = 0, n_classes::Int = 2, n_clusters_per_class::Int = 2, weights::Union{Nothing, Array{Float64,1}} = nothing, flip_y::Float64 = 0.01, class_sep::Float64 = 1.0, hypercube::Bool = true, shift::Union{Nothing, Float64, Array{Float64,1}} = 0.0, scale::Union{Nothing, Float64, Array{Float64,1}} = 1.0, shuffle::Bool = true, random_state::Union{Int, Nothing} = nothing) (features, labels) = datasets.make_classification( n_samples = n_samples, n_features = n_features, n_informative = n_informative, n_redundant = n_redundant, n_repeated = n_repeated, n_classes = n_classes, n_clusters_per_class = n_clusters_per_class, weights = weights, flip_y = flip_y, class_sep = class_sep, hypercube = hypercube, shift = shift, scale = scale, shuffle = shuffle, random_state = random_state) return convert(features, labels) end """ function make_friedman1(; n_samples::Int = 100, n_features::Int = 10, noise::Float64 = 0.0, random_state::Union{Int, Nothing} = nothing)::DataFrame Generate the “Friedman #1” regression problem. Sklearn interface to make_regression. #Arguments - `n_samples::Int = 100`: The number of samples. - `n_features::Int = 10`: The number of features. Should be at least 5. - `noise::Union{Nothing, Float64} = nothing`: The standard deviation of the gaussian noise applied to the output. - `random_state::Union{Int, Nothing} = nothing`: Determines random number generation for dataset noise. Pass an int for reproducible output across multiple function calls. Reference: [link](https://scikit-learn.org/stable/modules/generated/sklearn.datasets.make_friedman1.html) """ function make_friedman1(; n_samples::Int = 100, n_features::Int = 10, noise::Float64 = 0.0, random_state::Union{Int, Nothing} = nothing)::DataFrame (features, labels) = datasets.make_friedman1( n_samples = n_samples, n_features = n_features, noise = noise, random_state = random_state) return convert(features, labels) end """ function make_friedman2(; n_samples::Int = 100, noise::Float64 = 0.0, random_state::Union{Int, Nothing} = nothing)::DataFrame Generate the “Friedman #2” regression problem. Sklearn interface to make_friedman2. #Arguments - `n_samples::Int = 100`: The number of samples. - `n_features::Int = 10`: The number of features. Should be at least 5. - `noise::Union{Nothing, Float64} = nothing`: The standard deviation of the gaussian noise applied to the output. - `random_state::Union{Int, Nothing} = nothing`: Determines random number generation for dataset noise. Pass an int for reproducible output across multiple function calls. Reference: [link](https://scikit-learn.org/stable/modules/generated/sklearn.datasets.make_friedman2.html) """ function make_friedman2(; n_samples::Int = 100, noise::Float64 = 0.0, random_state::Union{Int, Nothing} = nothing)::DataFrame (features, labels) = datasets.make_friedman2( n_samples = n_samples, noise = noise, random_state = random_state) return convert(features, labels) end """ function make_friedman3(; n_samples::Int = 100, noise::Float64 = 0.0, random_state::Union{Int, Nothing} = nothing)::DataFrame Generate the “Friedman #3” regression problem. Sklearn interface to make_friedman3. #Arguments - `n_samples::Int = 100`: The number of samples. - `noise::Union{Nothing, Float64} = nothing`: The standard deviation of the gaussian noise applied to the output. - `random_state::Union{Int, Nothing} = nothing`: Determines random number generation for dataset noise. Pass an int for reproducible output across multiple function calls. Reference: [link](https://scikit-learn.org/stable/modules/generated/sklearn.datasets.make_friedman3.html) """ function make_friedman3(; n_samples::Int = 100, noise::Float64 = 0.0, random_state::Union{Int, Nothing} = nothing)::DataFrame (features, labels) = datasets.make_friedman3( n_samples = n_samples, noise = noise, random_state = random_state) return convert(features, labels) end """ function make_low_rank_matrix(; n_samples::Int =100, n_features::Int =100, effective_rank::Int =10, tail_strength::Float64 =0.5, random_state::Union{Int, Nothing} = nothing) Generate a mostly low rank matrix with bell-shaped singular values #Arguments - `n_samples::Int = 100`: The number of samples. - `n_features::Int = 20`: The total number of features. These comprise `n_informative` informative features, `n_redundant` redundant features, `n_repeated` duplicated features and `n_features-n_informative-n_redundant-n_repeated` useless features drawn at random. - `effective_rank::Int = 10`: The approximate number of singular vectors required to explain most of the data by linear combinations. - `tail_strength::Float64 = 0.5`: The relative importance of the fat noisy tail of the singular values profile. - `random_state::Union{Int, Nothing} = nothing`: Determines random number generation for dataset creation. Pass an int for reproducible output across multiple function calls. See Glossary. Reference: [link](https://scikit-learn.org/stable/modules/generated/sklearn.datasets.make_low_rank_matrix.html) """ function make_low_rank_matrix(; n_samples::Int = 100, n_features::Int = 100, effective_rank::Int = 10, tail_strength::Float64 = 0.5, random_state::Union{Int, Nothing} = nothing) features = datasets.make_low_rank_matrix( n_samples = n_samples, n_features = n_features, effective_rank = effective_rank, tail_strength = tail_strength, random_state = random_state) return features end """ function make_swiss_roll(; n_samples::Int = 100, noise::Float64 = 0.0, random_state::Union{Int,Nothing} = nothing) Generate a swiss roll dataset. #Arguments - `n_samples::Int = 100`: The number of samples. - `noise::Float64 = 0.0 : Standard deviation of Gaussian noise added to the data. - `random_state::Union{Int, Nothing} = nothing`: Determines random number generation for dataset creation. Pass an int for reproducible output across multiple function calls. See Glossary. Reference: [link](https://scikit-learn.org/stable/modules/generated/sklearn.datasets.make_swiss_roll.htmll) """ function make_swiss_roll(; n_samples::Int = 100, noise::Float64 = 0.0, random_state::Union{Int,Nothing} = nothing) (features, labels) = datasets.make_swiss_roll( n_samples = n_samples, noise = noise, random_state = random_state) return convert(features, labels) end """ function make_hastie_10_2(; n_samples::Int = 12000, random_state::Union{Int,Nothing} = nothing) Generates data for binary classification used in Hastie et al. 2009, Example 10.2. #Arguments - `n_samples::Int = 100`: The number of samples.. - `random_state::Union{Int, Nothing} = nothing`: Determines random number generation for dataset creation. Pass an int for reproducible output across multiple function calls. See Glossary. Reference: [link](https://scikit-learn.org/stable/modules/generated/sklearn.datasets.make_hastie_10_2.html) """ function make_hastie_10_2(; n_samples::Int = 12000, random_state::Union{Int,Nothing} = nothing) (features, labels) = datasets.make_hastie_10_2( n_samples = n_samples, random_state = random_state) return convert(features, labels) end """ function make_gaussian_quantiles(; mean::Array{<:Union{Number, Nothing}, 1} = [nothing], cov::Float64 = 1, n_samples::Int = 100, n_features::Int = 2, n_classes::Int = 3, shuffle::Bool = true, random_state::Union{Int, Nothing} = nothing) Generate isotropic Gaussian and label samples by quantile. #Arguments - `mean::Union{Array{<:Number, 1}, Nothing} = nothing`: The mean of the multi-dimensional normal distribution. If None then use the origin (0, 0, …). - `cov::Float64 = 1`: The covariance matrix will be this value times the unit matrix. - `n_samples::Int = 100`: The total number of points equally divided among classes. - `n_features::Int = 2`: The number of features for each sample. - `n_classes::Int = 3`: The number of classes. - `shuffle::Bool = true`: Shuffle the samples. - `random_state::Union{Int, Nothing} = nothing`: Determines random number generation for dataset creation. Pass an int for reproducible output across multiple function calls. See Glossary. Reference: [link](https://scikit-learn.org/stable/modules/generated/sklearn.datasets.make_gaussian_quantiles.html) """ function make_gaussian_quantiles(; mean::Union{Array{<:Number, 1}, Nothing} = nothing, cov::Float64 = 1.0, n_samples::Int = 100, n_features::Int = 2, n_classes::Int = 3, shuffle::Bool = true, random_state::Union{Int, Nothing} = nothing) typeof(mean) != Nothing && length(mean) != n_features && throw(DimensionMismatch("length of mean must be equal to n_features.")) (features, labels) = datasets.make_gaussian_quantiles( mean = mean, cov = cov, n_samples = n_samples, n_features = n_features, n_classes = n_classes, shuffle = shuffle, random_state = random_state) return convert(features, labels) end
SyntheticDatasets
https://github.com/ATISLabs/SyntheticDatasets.jl.git
[ "MIT" ]
0.1.1
5aa07104cc57e5aeaaa14891afcac7d0c95f28b7
code
4951
using SyntheticDatasets using DataFrames using Test @testset "SkLearn Generators" begin samples = 20000 features = 20 data = SyntheticDatasets.make_blobs(centers = [-1 1;-0.5 0.75], cluster_std = 0.225, n_samples = 20000, center_box = (-1.5, 1.5)) @test size(data)[1] == samples @test size(data)[2] == 3 samples = 20000 data = SyntheticDatasets.make_moons(n_samples = 20000) @test size(data)[1] == samples @test size(data)[2] == 3 data = SyntheticDatasets.make_s_curve( n_samples = samples, noise = 2.2, random_state = 5) @test size(data)[1] == samples @test size(data)[2] == 4 data = SyntheticDatasets.make_circles(n_samples = samples) @test size(data)[1] == samples @test size(data)[2] == 3 data = SyntheticDatasets.make_regression( n_samples = samples, n_features = features, noise = 2.2, random_state = 5) @test size(data)[1] == samples @test size(data)[2] == features + 1 data = SyntheticDatasets.make_regression( n_samples = samples, n_features = features, n_targets = 2, noise = 2.2, random_state = 5) @test size(data)[1] == samples @test size(data)[2] == features + 2 data = SyntheticDatasets.make_regression( n_samples = samples, n_features = features, n_targets = 3, noise = 2.2, random_state = 5) @test size(data)[1] == samples @test size(data)[2] == features + 3 data = SyntheticDatasets.make_classification( n_samples = samples, n_features = features, n_classes = 1) @test size(data)[1] == samples @test size(data)[2] == features + 1 data = SyntheticDatasets.make_friedman1(n_samples = samples, n_features = features) @test size(data)[1] == samples @test size(data)[2] == features + 1 data = SyntheticDatasets.make_friedman2(n_samples = samples) @test size(data)[1] == samples @test size(data)[2] == 5 data = SyntheticDatasets.make_friedman3(n_samples = samples) @test size(data)[1] == samples @test size(data)[2] == 5 data = SyntheticDatasets.make_low_rank_matrix( n_samples = samples, n_features = features, effective_rank = 10, tail_strength = 0.5, random_state = 5) @test size(data)[1] == samples @test size(data)[2] == features data = SyntheticDatasets.make_swiss_roll( n_samples = samples, noise = 2.2, random_state = 5) @test size(data)[1] == samples @test size(data)[2] == 4 data = SyntheticDatasets.make_hastie_10_2( n_samples = samples, random_state = 5) @test size(data)[1] == samples @test size(data)[2] == 11 data = SyntheticDatasets.make_gaussian_quantiles( n_samples = samples, n_features = features, random_state = 5) @test size(data)[1] == samples @test size(data)[2] == features + 1 @test_throws DimensionMismatch SyntheticDatasets.make_gaussian_quantiles( n_samples = 300, n_features = 4, random_state = 5, mean = [1, 2, 3]) end @testset "Matlab Generators" begin samples = 20000 data = SyntheticDatasets.make_twospirals(n_samples = samples, noise = 2.2) @test size(data)[1] == samples data = SyntheticDatasets.make_halfkernel(n_samples = samples) @test size(data)[1] == samples data = SyntheticDatasets.make_outlier(n_samples = samples) @test size(data)[1] == samples @test size(data)[2] == 3 end
SyntheticDatasets
https://github.com/ATISLabs/SyntheticDatasets.jl.git
[ "MIT" ]
0.1.1
5aa07104cc57e5aeaaa14891afcac7d0c95f28b7
docs
7934
# SyntheticDatasets.jl [![][travis-img]][travis-url] [![][codecov-img]][codecov-url] [![][coverage-img]][coverage-url] The SyntheticDatasets.jl package is a library with functions for generating synthetic artificial datasets. ## Installation The package can be installed with the Julia package manager. From the Julia REPL, type `]` to enter the Pkg REPL mode and run: ``` pkg> add SyntheticDatasets ``` Or, equivalently, via the `Pkg` API: ```julia julia> import Pkg; Pkg.add("SyntheticDatasets") ``` ## Examples A set of pluto notebooks and codes demonstrating the project's current functionality is available in [the examples folder](examples/). Here are a few examples to show the Package capabilities: ```julia using StatsPlots, SyntheticDatasets blobs = SyntheticDatasets.make_blobs( n_samples = 1000, n_features = 2, centers = [-1 1; -0.5 0.5], cluster_std = 0.25, center_box = (-2.0, 2.0), shuffle = true, random_state = nothing); @df blobs scatter(:feature_1, :feature_2, group = :label, title = "Blobs") gauss = SyntheticDatasets.make_gaussian_quantiles( mean = [10,1], cov = 2.0, n_samples = 1000, n_features = 2, n_classes = 3, shuffle = true, random_state = 2); @df gauss scatter(:feature_1, :feature_2, group = :label, title = "Gaussian Quantiles") spirals = SyntheticDatasets.make_twospirals(n_samples = 2000, start_degrees = 90, total_degrees = 570, noise =0.1); @df spirals scatter(:feature_1, :feature_2, group = :label, title = "Two Spirals") kernel = SyntheticDatasets.make_halfkernel( n_samples = 1000, minx = -20, r1 = 20, r2 = 35, noise = 3.0, ratio = 0.6); @df kernel scatter(:feature_1, :feature_2, group = :label, title = "Half Kernel") ``` <p align="center"> <img width="460" height="300" src="https://github.com/ATISLabs/SyntheticDatasets.jl/blob/4b90b37ea57e38c3a7a05f9917912023f8aa5361/examples/subplot.png"> </p> ## Datasets The SyntheticDatasets.jl is a library with functions for generating synthetic artificial datasets. The package has some functions are interfaces to the dataset generator of the [ScikitLearn](https://scikit-learn.org/stable/modules/classes.html#samples-generator). ### ScikitLearn List of package datasets: Dataset | Title | Reference ------------------------|-------------------------------------------------------------------------|-------------------------------------------------- make_blobs | Generate isotropic Gaussian blobs for clustering. | [link](https://scikit-learn.org/stable/modules/generated/sklearn.datasets.make_moons.html) make_moons | Make two interleaving half circles | [link](https://scikit-learn.org/stable/modules/generated/sklearn.datasets.make_blobs.html) make_s_curve | Generate an S curve dataset. | [link](https://scikit-learn.org/stable/modules/generated/sklearn.datasets.make_s_curve.html) make_regression | Generate a random regression problem. | [link](https://scikit-learn.org/stable/modules/generated/sklearn.datasets.make_regression.html) make_classification | Generate a random n-class classification problem. | [link](https://scikit-learn.org/stable/modules/generated/sklearn.datasets.make_classification.html) make_friedman1 | Generate the “Friedman #1” regression problem. | [link](https://scikit-learn.org/stable/modules/generated/sklearn.datasets.make_friedman1.html) make_friedman2 | Generate the “Friedman #2” regression problem. | [link](https://scikit-learn.org/stable/modules/generated/sklearn.datasets.make_friedman2.html) make_friedman3 | Generate the “Friedman #3” regression problem. | [link](https://scikit-learn.org/stable/modules/generated/sklearn.datasets.make_friedman3.html) make_circles | Make a large circle containing a smaller circle in 2d | [link](https://scikit-learn.org/stable/modules/generated/sklearn.datasets.make_circles.html) make_regression | Generate a random regression problem. | [link](https://scikit-learn.org/stable/modules/generated/sklearn.datasets.make_regression.html) make_classification | Generate a random n-class classification problem. | [link](https://scikit-learn.org/stable/modules/generated/sklearn.datasets.make_classification.html) make_low_rank_matrix | Generate a mostly low rank matrix with bell-shaped singular values. | [link](https://scikit-learn.org/stable/modules/generated/sklearn.datasets.make_low_rank_matrix.html) make_swiss_roll | Generate a swiss roll dataset. | [link](https://scikit-learn.org/stable/modules/generated/sklearn.datasets.make_swiss_roll.html) make_hastie_10_2 | Generates data for binary classification used in Hastie et al. |[link](https://scikit-learn.org/stable/modules/generated/sklearn.datasets.make_hastie_10_2.html) make_gaussian_quantiles | Generate isotropic Gaussian and label samples by quantile. | [link](https://scikit-learn.org/stable/modules/generated/sklearn.datasets.make_gaussian_quantiles.html) **Disclaimer**: SyntheticDatasets.jl borrows code and documentation from [scikit-learn](https://scikit-learn.org/stable/modules/classes.html#samples-generator) in the dataset module, but *it is not an official part of that project*. It is licensed under [MIT](LICENSE). ### Other Functions Dataset | Title | Reference -----------------|-------------------------------------------------------------------------|-------------------------------------------------- make_twospirals | Generate two spirals dataset. | [link](https://la.mathworks.com/matlabcentral/fileexchange/41459-6-functions-for-generating-artificial-datasets) make_halfkernel | Generate two half kernel dataset. | [link](https://la.mathworks.com/matlabcentral/fileexchange/41459-6-functions-for-generating-artificial-datasets) make_outlier | Generate outlier dataset. | [link](https://la.mathworks.com/matlabcentral/fileexchange/41459-6-functions-for-generating-artificial-datasets) [travis-img]: https://travis-ci.com/ATISLabs/SyntheticDatasets.jl.svg?branch=master [travis-url]: https://travis-ci.com/ATISLabs/SyntheticDatasets.jl [codecov-img]: https://codecov.io/gh/ATISLabs/SyntheticDatasets.jl/branch/master/graph/badge.svg?token=13TrPsgakO [codecov-url]: https://codecov.io/gh/ATISLabs/SyntheticDatasets.jl [coverage-img]: https://coveralls.io/repos/github/ATISLabs/SyntheticDatasets.jl/badge.svg?branch=master [coverage-url]: https://coveralls.io/github/ATISLabs/SyntheticDatasets.jl?branch=master
SyntheticDatasets
https://github.com/ATISLabs/SyntheticDatasets.jl.git
[ "MIT" ]
0.1.2
523763a2fb599190213f96f2fa860e9295def201
code
658
using RedefStructs using Documenter DocMeta.setdocmeta!(RedefStructs, :DocTestSetup, :(using RedefStructs); recursive=true) makedocs(; modules=[RedefStructs], authors="Federico Stra <[email protected]> and contributors", repo="https://github.com/FedericoStra/RedefStructs.jl/blob/{commit}{path}#{line}", sitename="RedefStructs.jl", format=Documenter.HTML(; prettyurls=get(ENV, "CI", "false") == "true", canonical="https://FedericoStra.github.io/RedefStructs.jl", assets=String[], ), pages=[ "Home" => "index.md", ], ) deploydocs(; repo="github.com/FedericoStra/RedefStructs.jl", )
RedefStructs
https://github.com/FedericoStra/RedefStructs.jl.git
[ "MIT" ]
0.1.2
523763a2fb599190213f96f2fa860e9295def201
code
4451
module RedefStructs export @redef, @redef_print, @kwredef @doc """ @redef [mutable] struct S [<: A] ... end Define a structure in a manner that allows redefinitions. Behind the scenes, this creates a "secret" structure with [`gensym`](https://docs.julialang.org/en/v1/base/base/#Base.gensym) and assigns `S` to its name. See also [`@redef_print`](@ref). # Examples ```jldoctest julia> using RedefStructs julia> @redef struct S s::String end julia> S("Hello").s "Hello" julia> @redef mutable struct S n::Int end julia> S(42).n 42 ``` """ macro redef(struct_def) name = struct_def_name(struct_def) real_name = gensym(name) struct_def = replace!(struct_def, name, real_name) fix_name = :(Base.unwrap_unionall($real_name).name.name = $(QuoteNode(name))) esc(quote $struct_def $fix_name $name = $real_name # this should be `const $name = $real_name` nothing # avoid returning the new struct end) end @doc """ @redef [mutable] struct S [<: A] ... end Define a structure in a manner that allows redefinitions. Behind the scenes, this creates a "secret" structure with [`gensym`](https://docs.julialang.org/en/v1/base/base/#Base.gensym) and defines a specialized method of `Base.show_datatype` which shows `S`. See also [`@redef`](@ref). # Examples ```jldoctest julia> using RedefStructs julia> @redef_print struct S s::String end julia> S("Hello").s "Hello" julia> @redef_print mutable struct S n::Int end julia> S(42).n 42 ``` """ macro redef_print(struct_def) name = struct_def_name(struct_def) real_name = gensym(name) struct_def = replace!(struct_def, name, real_name) fix_print = :(Base.show_datatype(io::Base.IO, ::Base.Type{Base.unwrap_unionall($real_name)}) = Base.print(io, $(QuoteNode(name)))) esc(quote $struct_def $fix_print $name = $real_name # this should be `const $name = $real_name` nothing # avoid returning the new struct end) end @doc """ @kwredef [mutable] struct S [<: A] ... end Define a structure in a manner that allows redefinitions, using `Base.@kwdef`. Behind the scenes, this creates a "secret" structure with [`gensym`](https://docs.julialang.org/en/v1/base/base/#Base.gensym) and assigns `S` to its name. See also [`@redef`](@ref) and `Base.@kwdef`. # Examples ```jldoctest julia> using RedefStructs julia> @kwredef struct S s::String = "<empty>" end julia> S("Hello").s "Hello" julia> @kwredef mutable struct S a::Int = 0 b::Int end julia> S(b=42).a 0 ``` """ macro kwredef(struct_def) name = struct_def_name(struct_def) real_name = gensym(name) struct_def = :(Base.@kwdef $(replace!(struct_def, name, real_name))) fix_name = :(Base.unwrap_unionall($real_name).name.name = $(QuoteNode(name))) esc(quote $struct_def $fix_name $name = $real_name # this should be `const $name = $real_name` nothing # avoid returning the new struct end) end """ struct_def_name(struct_def) Returns the name of the `struct` being defined in a `struct ... end` block. """ function struct_def_name(struct_def) struct_def isa Expr && struct_def.head == :struct || error("expected struct definition") sig = struct_def.args[2] # signature of the struct: `struct <sig> ... end` if sig isa Symbol sig elseif sig.head == :curly sig.args[1] elseif sig.head == :<: # `struct <sig> <: ... ... end` sig = sig.args[1] if sig isa Symbol sig elseif sig.head == :curly sig.args[1] else error("invalid `<:` signature, expected `S <: AbstractType`") end else error("expected signature `S` or `S <: AbstractType`") end end """ replace!(code::Expr, old::Symbol, new::Symbol) Replaces every appearance of `old` in `code` with `new`. Modifies `code` and returns it. """ function replace!(code::Expr, old::Symbol, new::Symbol) code.head = replace!(code.head, old, new) for i in eachindex(code.args) code.args[i] = replace!(code.args[i], old, new) end code end function replace!(code::Symbol, old::Symbol, new::Symbol) code === old ? new : code end function replace!(code, old::Symbol, new::Symbol) code end end # module
RedefStructs
https://github.com/FedericoStra/RedefStructs.jl.git
[ "MIT" ]
0.1.2
523763a2fb599190213f96f2fa860e9295def201
code
784
using RedefStructs using Test @testset "redef" begin @testset "valid" begin abstract type A end @test (@redef struct S end; true) @test (@redef struct S <: A end; true) @test (@redef struct S{T} end; true) @test (@redef struct S{T} <: A end; true) end # @testset "invalid" begin # abstract type A end # @test_throws ErrorException @redef S # @test_throws ErrorException @redef :S # @test_throws ErrorException @redef 1+2 # end end @testset "redef_print" begin abstract type A end @test (@redef_print struct S end; true) @test (@redef_print struct S <: A end; true) @test_broken (@redef_print struct S{T} end; true) @test_broken (@redef_print struct S{T} <: A end; true) end
RedefStructs
https://github.com/FedericoStra/RedefStructs.jl.git
[ "MIT" ]
0.1.2
523763a2fb599190213f96f2fa860e9295def201
docs
1458
# RedefStructs.jl ![Lifecycle](https://img.shields.io/badge/lifecycle-experimental-orange.svg)<!-- ![Lifecycle](https://img.shields.io/badge/lifecycle-maturing-blue.svg) ![Lifecycle](https://img.shields.io/badge/lifecycle-stable-green.svg) ![Lifecycle](https://img.shields.io/badge/lifecycle-retired-orange.svg) ![Lifecycle](https://img.shields.io/badge/lifecycle-archived-red.svg) ![Lifecycle](https://img.shields.io/badge/lifecycle-dormant-blue.svg) --> [![Stable](https://img.shields.io/badge/docs-stable-blue.svg)](https://FedericoStra.github.io/RedefStructs.jl/stable) [![Dev](https://img.shields.io/badge/docs-dev-blue.svg)](https://FedericoStra.github.io/RedefStructs.jl/dev) [![Build Status](https://github.com/FedericoStra/RedefStructs.jl/workflows/CI/badge.svg)](https://github.com/FedericoStra/RedefStructs.jl/actions) [![Code Style: Blue](https://img.shields.io/badge/code%20style-blue-4495d1.svg)](https://github.com/invenia/BlueStyle) [![ColPrac: Contributor's Guide on Collaborative Practices for Community Packages](https://img.shields.io/badge/ColPrac-Contributor's%20Guide-blueviolet)](https://github.com/SciML/ColPrac) This package provides the macro `@redef`, which allows to create `struct`ures which are redefinable. ## Example ```julia julia> using RedefStructs julia> @redef struct S s::String end julia> S("Hello").s "Hello" julia> @redef mutable struct S n::Int end julia> S(42).n 42 ```
RedefStructs
https://github.com/FedericoStra/RedefStructs.jl.git
[ "MIT" ]
0.1.2
523763a2fb599190213f96f2fa860e9295def201
docs
1274
```@meta CurrentModule = RedefStructs ``` # RedefStructs.jl Documentation for [RedefStructs.jl](https://github.com/FedericoStra/RedefStructs.jl). This package provides the macros [`@redef`](@ref), [`@redef_print`](@ref), and [`@kwredef`](@ref) which allow to create `struct`ures which are redefinable. ```@contents Depth = 3 ``` ## Examples Using [`@redef`](@ref): ```jldoctest julia> using RedefStructs julia> @redef struct S s::String end julia> S("Hello").s "Hello" julia> @redef mutable struct S n::Int end julia> S(42).n 42 ``` Using [`@redef_print`](@ref): ```jldoctest julia> using RedefStructs julia> @redef_print struct S s::String end julia> S("Hello").s "Hello" julia> @redef_print mutable struct S n::Int end julia> S(42).n 42 ``` Using [`@redef`](@ref): ```jldoctest julia> using RedefStructs julia> @kwredef struct S s::String = "<empty>" end julia> S("Hello").s "Hello" julia> @kwredef mutable struct S a::Int = 0 b::Int end julia> S(b=42).a 0 ``` ## Library ```@index ``` ### Public ```@autodocs Modules = [RedefStructs] Private = false ``` ### Private ```@autodocs Modules = [RedefStructs] Public = false ```
RedefStructs
https://github.com/FedericoStra/RedefStructs.jl.git
[ "MIT" ]
0.1.0
cc9cbf7252dc1a212d93e0ef510d75e0128dfaff
code
539
using StructuralUnits using Documenter DocMeta.setdocmeta!(StructuralUnits, :DocTestSetup, :(using StructuralUnits); recursive=true) makedocs(; modules=[StructuralUnits], authors="Cole Miller", sitename="StructuralUnits.jl", format=Documenter.HTML(; canonical="https://co1emi11er2.github.io/StructuralUnits.jl", edit_link="main", assets=String[], ), pages=[ "Home" => "index.md", ], ) deploydocs(; repo="github.com/co1emi11er2/StructuralUnits.jl", devbranch="main", )
StructuralUnits
https://github.com/co1emi11er2/StructuralUnits.jl.git
[ "MIT" ]
0.1.0
cc9cbf7252dc1a212d93e0ef510d75e0128dfaff
code
2137
module StructuralUnits using Reexport @reexport using Unitful @reexport using UnitfulLatexify export ft, inch, kip, ksi, ksf, klf, plf, mph, kcf, pcf, ° Unitful.register(StructuralUnits) @unit kip "kip" Kip 1000*u"lbf" false @unit ksi "ksi" KSI 1*u"kip"/(1*u"inch^2") false @unit ksf "ksf" KSF 1*u"kip"/(1*u"ft^2") false @unit klf "klf" KLF 1*u"kip"/(1*u"ft") false @unit plf "plf" PLF 1*u"lbf"/(1*u"ft") false @unit mph "mph" MPH 1*u"mi"/(1*u"hr") false @unit kcf "kcf" KCF 1*u"kip"/(1*u"ft^3") false @unit pcf "pcf" PCF 1*u"lbf"/(1*u"ft^3") false Unitful.preferunits(u"ft") @derived_dimension Area Unitful.𝐋^2 @derived_dimension Volume Unitful.𝐋^3 @derived_dimension Density Unitful.𝐋*Unitful.𝐌*Unitful.𝐓^-2*Unitful.𝐋^-3 @derived_dimension Force Unitful.𝐋*Unitful.𝐌*Unitful.𝐓^-2 @derived_dimension Moment Unitful.𝐋^2*Unitful.𝐌*Unitful.𝐓^-2 @derived_dimension Stress Unitful.𝐋*Unitful.𝐌*Unitful.𝐓^-2/Unitful.𝐋^2 @derived_dimension UDLoad Unitful.𝐋*Unitful.𝐌*Unitful.𝐓^-2/Unitful.𝐋 Unitful.promote_unit(::S, ::T) where {S<:StructuralUnits.AreaUnits, T<:StructuralUnits.AreaUnits} = u"inch^2" Unitful.promote_unit(::S, ::T) where {S<:StructuralUnits.VolumeUnits, T<:StructuralUnits.VolumeUnits} = u"ft^3" Unitful.promote_unit(::S, ::T) where {S<:StructuralUnits.DensityUnits, T<:StructuralUnits.DensityUnits} = u"kcf" Unitful.promote_unit(::S, ::T) where {S<:StructuralUnits.ForceUnits, T<:StructuralUnits.ForceUnits} = u"kip" Unitful.promote_unit(::S, ::T) where {S<:StructuralUnits.MomentUnits, T<:StructuralUnits.MomentUnits} = u"kip*ft" Unitful.promote_unit(::S, ::T) where {S<:StructuralUnits.StressUnits, T<:StructuralUnits.StressUnits} = u"ksi" Unitful.promote_unit(::S, ::T) where {S<:StructuralUnits.UDLoadUnits, T<:StructuralUnits.UDLoadUnits} = u"klf" const ft = u"ft" const inch = u"inch" const kip = u"kip" const ksi = u"ksi" const ksf = u"ksf" const klf = u"klf" const plf = u"plf" const mph = u"mph" const kcf = u"kcf" const pcf = u"pcf" const ° = u"°" const localpromotion = copy(Unitful.promotion) function __init__() Unitful.register(StructuralUnits) merge!(Unitful.promotion, localpromotion) end end
StructuralUnits
https://github.com/co1emi11er2/StructuralUnits.jl.git
[ "MIT" ]
0.1.0
cc9cbf7252dc1a212d93e0ef510d75e0128dfaff
code
174
using StructuralUnits using Test @testset "Unit Conversions " begin include("unit_conversions.jl") end @testset "Unit Promotions " begin include("unit_promotions.jl") end
StructuralUnits
https://github.com/co1emi11er2/StructuralUnits.jl.git
[ "MIT" ]
0.1.0
cc9cbf7252dc1a212d93e0ef510d75e0128dfaff
code
204
@test 1kip == 1000u"lbf" @test 1ksi == 1kip/inch^2 @test 1ksf == 1kip/ft^2 @test 1klf == 1kip/ft @test 1plf == 1u"lbf"/ft @test 1mph == 1*u"mi"/(1*u"hr") @test 1kcf == 1kip/ft^3 @test 1pcf ≈ 1u"lbf"/ft^3
StructuralUnits
https://github.com/co1emi11er2/StructuralUnits.jl.git
[ "MIT" ]
0.1.0
cc9cbf7252dc1a212d93e0ef510d75e0128dfaff
code
437
# Area and Volume Auto Promotion @test 1inch^2 + 0ft^2 === 1inch^2 @test 1.0ft^3 + 0.0inch^3 === 1.0ft^3 # Weight Auto Promotion @test 1.0kip/ft^3 + 0.0kip/inch^3 === 1.0kcf # Force Auto Promotion @test 1.0kip + 0.0u"lbf" === 1.0kip # Moment Auto Promotion @test 1.0kip*ft + 0.0kip*inch === 1.0kip*ft # Stress Auto Promotion @test 1.0ksi + 0.0ksf === 1.0ksi # Linear Weight Auto Promotion @test 1.0kip/ft + 0.0kip/inch === 1.0klf
StructuralUnits
https://github.com/co1emi11er2/StructuralUnits.jl.git
[ "MIT" ]
0.1.0
cc9cbf7252dc1a212d93e0ef510d75e0128dfaff
docs
4372
# StructuralUnits <!-- #[![Stable](https://img.shields.io/badge/docs-stable-blue.svg)](https://co1emi11er2.github.io/StructuralUnits.jl/stable/) --> <!-- [![Dev](https://img.shields.io/badge/docs-dev-blue.svg)](https://co1emi11er2.github.io/StructuralUnits.jl/dev/) --> [![Build Status](https://github.com/co1emi11er2/StructuralUnits.jl/actions/workflows/CI.yml/badge.svg?branch=main)](https://github.com/co1emi11er2/StructuralUnits.jl/actions/workflows/CI.yml?query=branch%3Amain) [![Build Status](https://ci.appveyor.com/api/projects/status/github/co1emi11er2/StructuralUnits.jl?svg=true)](https://ci.appveyor.com/project/co1emi11er2/StructuralUnits-jl) [![Coverage](https://codecov.io/gh/co1emi11er2/StructuralUnits.jl/branch/main/graph/badge.svg)](https://codecov.io/gh/co1emi11er2/StructuralUnits.jl) [![Coverage](https://coveralls.io/repos/github/co1emi11er2/StructuralUnits.jl/badge.svg?branch=main)](https://coveralls.io/github/co1emi11er2/StructuralUnits.jl?branch=main) ## Introduction This is a package for Structural Engineers in the US. It is a small package that extends the [Unitful.jl](https://github.com/PainterQubits/Unitful.jl) package. It exports a few units and changes promotion defaults in the Unitful package. It re-exports [Unitful](https://github.com/PainterQubits/Unitful.jl) and [UnitfulLatexify](https://github.com/gustaphe/UnitfulLatexify.jl), so there is no need to call `Using Unitful`. ## Defined Units Below are a few tables that specify the constants that are exported by the package. These constants can then be used throughout your project. ### Length | Constant/Variable | Unitful Definition | | ---- | ---- | | `ft` | u"ft"| | `inch` | u"inch" | ### Force | Constant/Variable | Unitful Definition | | ---- | ---- | | `kip` | 1000u"lbf" | ### Stress | Constant/Variable | Unitful Definition | | ---- | ---- | | `ksi` | 1\*`kip`/(1\*`inch`^2) | | `ksf` | 1\*`kip`/(1\*`ft`^2) | ### Density | Constant/Variable | Unitful Definition | | ---- | ---- | | `kcf` | 1\*`kip`/(1\*`ft`^3) | | `pcf` | 1\*u"lbf"/(1\*`ft`^3) | ### Linear Weight | Constant/Variable | Unitful Definition | | ---- | ---- | | `klf` | 1\*`kip`/(1\*`ft`) | | `plf` | 1\*u"lbf"/(1\*`ft`) | ### Speed | Constant/Variable | Unitful Definition | | ---- | ---- | | `mph` | 1\*u"mi"/(1\*u"hr") | ### Angle | Constant/Variable | Unitful Definition | | ---- | ---- | | `°` | u"°" | ## Promotion In [Unitful](https://github.com/PainterQubits/Unitful.jl), certain dimensions can automatically promote to a preferred set of units. This package changes those settings to be more in line with prefferences of structural engineers in the US. Note that autopromotion happens mainly with addition or subtraction (not multiplication). Below are a few simple examples of promotion: ### Promotion through addition Based on the StructuralUnits preferences, `ft` is the preferred unit for a length dimension: ```julia julia> 1.0ft + 6.0inch 1.5 ft ``` You can see how adding dimensions with two different units will auto promote to the preferred unit (the preferred unit for Unitful is `m` so this has been changed to `ft` for this package). ### Promotion through multiplication ```julia julia> 1.0ft*6.0inch 6.0 ft inch ``` You can see how multiplying dimensions with different units does not automatically promote the units to the preferred unit for that specific dimension (which in this case would be an area dimension that was derived in this package). You can however promote this manually using the `|>` operator. ```julia julia> 1.0ft*6.0inch |> ft^2 0.5 ft^2 ``` ### Preferred Units for Promotion Below is a list of the preferred units to promote to when auto promotion occurs. | Dimension | Unitful Definition | | ---- | ---- | | Length | `ft`| | Area | `inch`^2 | | Volume | `ft`^3 | | Force | `kip` | | Stress | `ksi` | | Density | `kcf` | | Moment | `kip`*`ft` | | UDLoad | `klf` | ## Contribution This package may be somewhat difficult to contribute too given the fact that it is highly opinionated for its preferred units. This tool will mainly be used internally, so prefferences could change as we start to use the package more. Feel free to view the source code as well as use the package if it fits your needs. The source code is less than 100 lines of code, so I am sure you can use it to create your own units package if needed.
StructuralUnits
https://github.com/co1emi11er2/StructuralUnits.jl.git
[ "MIT" ]
0.1.0
cc9cbf7252dc1a212d93e0ef510d75e0128dfaff
docs
214
```@meta CurrentModule = StructuralUnits ``` # StructuralUnits Documentation for [StructuralUnits](https://github.com/co1emi11er2/StructuralUnits.jl). ```@index ``` ```@autodocs Modules = [StructuralUnits] ```
StructuralUnits
https://github.com/co1emi11er2/StructuralUnits.jl.git
[ "MIT" ]
0.9.7
8df29d512dca8aa40b391e645f9278bab4c09d10
code
371
using Documenter using Enlsip makedocs( sitename = "Enlsip.jl", format = Documenter.HTML(), modules = [Enlsip], pages = [ "Home" => "index.md", "Method" => "method.md", "Usage" => "tutorial.md", "Reference" => "reference.md" ] ) deploydocs( repo = "github.com/UncertainLab/Enlsip.jl.git", devbranch = "main" )
Enlsip
https://github.com/UncertainLab/Enlsip.jl.git
[ "MIT" ]
0.9.7
8df29d512dca8aa40b391e645f9278bab4c09d10
code
212
module Enlsip # Packages using LinearAlgebra, Polynomials, ForwardDiff, Printf # include source files for f in ["structures","cnls_model", "enlsip_functions", "solver"] include("./$f.jl") end end # module
Enlsip
https://github.com/UncertainLab/Enlsip.jl.git
[ "MIT" ]
0.9.7
8df29d512dca8aa40b391e645f9278bab4c09d10
code
19466
export AbstractCnlsModel, CnlsModel export constraints_values, equality_constraints_values, inequality_constraints_values, bounds_constraints_values, total_nb_constraints, nb_equality_constraints, nb_inequality_constraints, nb_lower_bounds, nb_upper_bounds export status, solution, sum_sq_residuals, dict_status_codes #= Structures where the first two fields are the functions evaluating residuals or constraints and the associated jacobian matrix =# abstract type EvaluationFunction end mutable struct ResidualsFunction <: EvaluationFunction reseval jacres_eval nb_reseval::Int nb_jacres_eval::Int end function ResidualsFunction(eval, jac_eval) ResidualsFunction(eval, jac_eval, 0, 0) end # function ResidualsFunction(eval) # num_jac_eval(x::Vector{<:AbstractFloat}) = jac_forward_diff(eval,x) # ResidualsFunction(eval, num_jac_eval,0,0) # end ResidualsFunction(eval) = ResidualsFunction(eval, x::Vector -> ForwardDiff.jacobian(eval, x)) mutable struct ConstraintsFunction <: EvaluationFunction conseval jaccons_eval nb_conseval::Int nb_jaccons_eval::Int end function ConstraintsFunction(eval, jac_eval) ConstraintsFunction(eval, jac_eval, 0, 0) end # function ConstraintsFunction(eval) # num_jac_eval(x::Vector{<:AbstractFloat}) = jac_forward_diff(eval,x) # ConstraintsFunction(eval, num_jac_eval,0,0) # end ConstraintsFunction(eval) = ConstraintsFunction(eval, x::Vector -> ForwardDiff.jacobian(eval, x)) #= Functions to compute in place the residuals, constraints and jacobian matrices of a given EvaluationFunction =# function res_eval!(r::ResidualsFunction, x::Vector{T}, rx::Vector{T}) where {T<:AbstractFloat} rx[:] = r.reseval(x) r.nb_reseval += 1 return end function jacres_eval!(r::ResidualsFunction, x::Vector{T}, J::Matrix{T}) where {T<:AbstractFloat} J[:] = r.jacres_eval(x) r.nb_jacres_eval += 1 return end function cons_eval!(c::ConstraintsFunction, x::Vector{T}, cx::Vector{T}) where {T<:AbstractFloat} cx[:] = c.conseval(x) c.nb_conseval += 1 return end function jaccons_eval!(c::ConstraintsFunction, x::Vector{T}, A::Matrix{T}) where {T<:AbstractFloat} A[:] = c.jaccons_eval(x) c.nb_jaccons_eval += 1 return end # Auxialiry funcion to define EvaluationFunction with numerical jacobian function jac_forward_diff(h_eval, x::Vector{<:AbstractFloat}) δ = sqrt(eps(eltype(x))) hx = h_eval(x) n = size(x,1) m = size(hx,1) Jh = zeros(eltype(hx),(m,n)) for j=1:n δ_j = max(abs(x[j]), 1.0) * δ e_j = [(i == j ? 1.0 : 0.0) for i = 1:n] x_forward = x + δ_j * e_j hx_forward = h_eval(x_forward) Jh[:,j] = (hx_forward - hx) / δ_j end return Jh end #= ExecutionInfo Summarizes information that are given after termination of the algorithm * iterations_detail: List of `DisplayedInfo`, each element of the list contains the details about a given iteration. The list is stored in chronological order (1st element -> 1st iterration, last element -> last_iteration) * nb_function_evaluations : number of residuals and constraints evaluations performed during the execution of the algorithm * nb_jacobian_evaluations : same as above but for Jacobian matrices evaluations * solving_time : time of execution in seconds =# struct ExecutionInfo iterations_detail::Vector{DisplayedInfo} nb_function_evaluations::Int nb_jacobian_evaluations::Int solving_time::Float64 end ExecutionInfo() = ExecutionInfo([DisplayedInfo()], 0, 0, 0.0) """ AbstractCnlsModel Abstract type for [`CnlsModel`](@ref) structure. """ abstract type AbstractCnlsModel{T<:AbstractFloat} end """ CnlsModel{T} where {T<:AbstractFloat} Structure modeling an instance of a constrainted nonlinear least squares problem. This structure contains the following attributes: * `residuals` : function that computes the vector of residuals * `nb_parameters::Int` : number of variables * `nb_residuals::Int` : number of residuals * `stating_point::Vector{T}` : initial solution * `jacobian_residuals` : function that computes the jacobian matrix of the residuals * `eq_constraints` : function that computes the vector of equality constraints * `jacobian_eqcons` : function that computes the jacobian matrix of the equality constraints * `nb_eqcons` : number of equality constraints * `ineq_constraints` : function that computes the vector of inequality constraints * `jacobian_ineqcons` : function that computes the jacobian matrix of the inequality constraints * `nb_ineqcons::Int` : number of inequality constraints * `x_low::Vector{T}` and `x_upp::Vector{T}` : respectively vectors of lower and upper bounds * `status_code::Int` : integer indicating the solving status of the model """ mutable struct CnlsModel{T} <: AbstractCnlsModel{T} residuals nb_parameters::Int nb_residuals::Int starting_point::Vector{T} jacobian_residuals eq_constraints jacobian_eqcons nb_eqcons::Int ineq_constraints jacobian_ineqcons nb_ineqcons::Int x_low::Vector{T} x_upp::Vector{T} constraints_scaling::Bool status_code::Int sol::Vector{T} obj_value::T model_info::ExecutionInfo end function convert_exit_code(code::Int) status_code = 0 if code > 0 status_code = 1 elseif code == -2 || code == -11 status_code = code else status_code = -1 end return status_code end const dict_status_codes = Dict( 0 => :unsolved, 1 => :found_first_order_stationary_point, -1 => :failed, -2 => :maximum_iterations_exceeded, -11 => :time_limit_exceeded ) """ status(model) This functions returns a `Symbol` that gives brief information on the solving status of `model`. If a model has been instantiated but the solver has not been called yet, it will return `:unsolved`. Once the solver has been called and if a first order stationary point satisfying the convergence criteria has been computed, it will return `:found_first_order_stationary_point`. If the algorithm met an abnormall termination criteria, it will return one of the following: * `:failed` : the algorithm encoutered a numerical error that triggered termination * `:maximum_iterations_exceeded` : a solution could not be reached within the maximum number of iterations * `:time_limit_exceeded` : the algorithm stopped because solving time exceeded the time limit """ status(model::CnlsModel) = dict_status_codes[model.status_code] """ solution(model) Once the given `model` has been solved, this function returns the optimal solution, or last solution obtained if no convergence, as a `Vector` of approriate dimension. """ solution(model::CnlsModel) = model.sol """ sum_sq_residuals(model) Once the given `model` has been solved, returns the value of the objective function, i.e. sum of squared residuals functions, computed at the optimal solution. If no convergence, this value is computed at the last solution obtained. """ sum_sq_residuals(model::CnlsModel) = model.obj_value nb_equality_constraints(model::CnlsModel) = model.nb_eqcons nb_inequality_constraints(model::CnlsModel) = model.nb_ineqcons nb_lower_bounds(model::CnlsModel) = count(isfinite, model.x_low) nb_upper_bounds(model::CnlsModel) = count(isfinite, model.x_upp) """ total_nb_constraints(model) Returns the total number of constraints, i.e. equalities, inequalities and bounds, of the given `model`. See also: [`CnlsModel`](@ref). """ total_nb_constraints(model::CnlsModel) = nb_equality_constraints(model) + nb_inequality_constraints(model) + nb_lower_bounds(model) + nb_upper_bounds(model) """ equality_constraints_values(model) Returns the vector of equality constraints values at the solution of `model` (if they are any). """ function equality_constraints_values(model::CnlsModel) sol = solution(model) hx = Vector{eltype(sol)}(undef, nb_equality_constraints(model)) if model.eq_constraints !== nothing hx[:] = model.eq_constraints(sol) end return hx end """ inequality_constraints_values(model) Returns the vector of inequality constraints values at the solution of `model` (if they are any). """ function inequality_constraints_values(model::CnlsModel) sol = solution(model) gx = Vector{eltype(sol)}(undef, nb_inequality_constraints(model)) if model.ineq_constraints !== nothing gx[:] = model.ineq_constraints(sol) end return gx end """ bounds_constraints_values(model) Returns the vector of box constraints values at the solution `xₛ` of `model` (if they are any). If `xₗ` and `xᵤ` are respectively the vectors of lower and upper bounds, it will return `[xₛ-xₗ; xᵤ-xₛ]`. """ function bounds_constraints_values(model::CnlsModel) sol = solution(model) return vcat(sol-model.x_low, model.x_upp-sol) end """ constraints_values(model) Computes values of all the constraints in `model` at the solution. The vector returned is the concatenation of equalities, inequalities and box constraints (in that order). For instance, let `xₛ` be the solution found. If functions `h`, `g` compute equality and inequality constraints and `xₗ, xᵤ` are vectors of lower and lower bounds, it will return `[h(xₛ); g(xₛ); xₛ-xₗ; xᵤ-xₛ]`. If one wants to compute each type of constraints seperately, see [`equality_constraints_values`](@ref), [`inequality_constraints_values`](@ref) and [`bounds_constraints_values`](@ref). """ function constraints_values(model::CnlsModel) sol = solution(model) q, ℓ = model.nb_eqcons, model.nb_ineqcons cx = Vector{eltype(sol)}(undef, q+ℓ+2*length(sol)) if model.nb_eqcons > 0 cx[1:q] = equality_constraints_values(model) end if model.nb_ineqcons > 0 cx[q+1:q+ℓ] = inequality_constraints_values(model) end if nb_lower_bounds(model) + nb_upper_bounds(model) > 0 cx[q+ℓ+1:end] = bounds_constraints_values(model) end return cx end """ model = CnlsModel(residuals, nb_parameters, nb_residuals) Constructor for [`CnlsModel`](@ref). * Positional arguments - `residuals` : function that computes the vector of residuals - `nb_parameters` : number of variables - `nb_residuals` : number of residuals * Keywords arguments : - `stating_point::Vector{T}` : initial solution (default is a vector of zeros of appropriate dimension) - `jacobian_residuals` : function that computes the jacobian matrix of the residuals. If not passed as argument, it is computed numericcaly by forward differences - `eq_constraints` : function that computes the vector of equality constraints - `jacobian_eqcons` : function that computes the jacobian matrix of the equality constraints. If not passed as argument, it is computed numericcaly by forward differences - `nb_eqcons::Int` : number of equality constraints - `ineq_constraints` : function that computes the vector of inequality constraints - `jacobian_ineqcons` : function that computes the jacobian matrix of the inequality constraints. If not passed as argument, it is computed numericcaly by forward differences - `nb_ineqcons::Int` : number of inequality constraints - `x_low::Vector{T}` and `x_upp::Vector{T}` : respectively vectors of lower and upper bounds """ function CnlsModel( residuals=nothing, nb_parameters::Int=0, nb_residuals::Int=0; starting_point::Vector{T}=zeros(nb_parameters), jacobian_residuals=nothing, eq_constraints=nothing, jacobian_eqcons=nothing, nb_eqcons::Int=0, ineq_constraints=nothing, jacobian_ineqcons=nothing, scaling::Bool=false, nb_ineqcons::Int=0, x_low::Vector{T}=fill!(Vector{eltype(starting_point)}(undef,nb_parameters), -Inf), x_upp::Vector{T}=fill!(Vector{eltype(starting_point)}(undef,nb_parameters), Inf)) where {T} # Assertion test on residuals @assert(typeof(residuals) <: Function, "A function evaluating residuals must be provided") @assert(nb_parameters > 0 && nb_residuals > 0, "The number of parameters and number of residuals must be strictly positive") # Assertion tests on constraints @assert(eq_constraints !== nothing || ineq_constraints !== nothing || any(isfinite,x_low) || any(isfinite,x_upp), "There must be at least one constraint") @assert(!(eq_constraints===nothing && nb_eqcons != 0) || !(typeof(eq_constraints <: Function) && nb_eqcons == 0), "Incoherent definition of equality constraints") @assert(!(ineq_constraints===nothing && nb_ineqcons != 0) || !(typeof(ineq_constraints <: Function) && nb_ineqcons == 0), "Incoherent definition of inequality constraints") rx0 = residuals(starting_point) initial_obj_value = dot(rx0,rx0) initial_info = ExecutionInfo() return CnlsModel(residuals, nb_parameters, nb_residuals, starting_point, jacobian_residuals, eq_constraints, jacobian_eqcons, nb_eqcons, ineq_constraints, jacobian_ineqcons, nb_ineqcons, x_low, x_upp, scaling, 0, starting_point, initial_obj_value, initial_info) end function box_constraints(x_low::Vector{T}, x_upp::Vector{T}) where {T<:AbstractFloat} n = size(x_low,1) @assert(n == size(x_upp,1),"Bounds vectors must have same length") no_x_low = all(!isfinite,x_low) no_x_upp = all(!isfinite,x_upp) @assert(!(no_x_low && no_x_upp), "Bounds vectors are assumed to contain at least one finite element") if no_x_low && !no_x_upp cons_w_ubounds(x::Vector{<:AbstractFloat}) = filter(isfinite,x_upp-x) jaccons_w_ubounds(x::Vector{<:AbstractFloat}) = Matrix{eltype(x_upp)}(-I,n,n)[filter(i-> isfinite(x_upp[i]),1:n),:] return cons_w_ubounds, jaccons_w_ubounds elseif !no_x_low && no_x_upp cons_w_lbounds(x::Vector{<:AbstractFloat}) = filter(isfinite, x-x_low) jaccons_w_lbounds(x::Vector{<:AbstractFloat}) = Matrix{eltype(x_low)}(I,n,n)[filter(i-> isfinite(x_low[i]),1:n),:] return cons_w_lbounds, jaccons_w_lbounds else cons_w_bounds(x::Vector{<:AbstractFloat}) = vcat(filter(isfinite, x-x_low), filter(isfinite, x_upp-x)) jaccons_w_bounds(x::Vector{<:AbstractFloat}) = vcat(Matrix{eltype(x_low)}(I,n,n)[filter(i-> isfinite(x_low[i]),1:n),:], Matrix{eltype(x_upp)}(-I,n,n)[filter(i-> isfinite(x_upp[i]),1:n),:]) return cons_w_bounds, jaccons_w_bounds end end # Returns a ConstraintsEvaluation function for problems with bound constraints function instantiate_constraints_w_bounds(eq_constraints, jacobian_eqcons, ineq_constraints, jacobian_ineqcons, x_low, x_upp) bounds_func, jac_bounds_func = box_constraints(x_low, x_upp) # Equality and inequality constraints in the model if eq_constraints !== nothing && ineq_constraints !== nothing cons(x::Vector) = vcat(eq_constraints(x), ineq_constraints(x), bounds_func(x)) # Jacobian provided if jacobian_eqcons !== nothing && jacobian_ineqcons !== nothing jac_cons(x::Vector) = vcat(jacobian_eqcons(x), jacobian_ineqcons(x), jac_bounds_func(x)) constraints_evalfunc = ConstraintsFunction(cons, jac_cons) # Jacobian not provided for inequality constraints elseif jacobian_eqcons !== nothing && jacobian_ineqcons === nothing ad_jac_ineqcons(x::Vector) = vcat(jacobian_eqcons(x), ForwardDiff.jacobian(ineq_constraints, x), jac_bounds_func(x)) constraints_evalfunc = ConstraintsFunction(cons, ad_jac_ineqcons) # Jacobian not provided for equality constraints elseif jacobian_eqcons === nothing && jacobian_ineqcons !== nothing ad_jac_eqcons(x) = vcat(ForwardDiff.jacobian(eq_constraints,x), jacobian_ineqcons(x), jac_bounds_func(x)) constraints_evalfunc = ConstraintsFunction(cons, jac_eqnum) # Jacobian not provided else ad_jac_cons(x::Vector) = vcat(ForwardDiff.jacobian(eq_constraints,x), ForwardDiff.jacobian(ineq_constraints, x), jac_bounds_func(x)) constraints_evalfunc = ConstraintsFunction(cons, ad_jac_cons) end # No inequality constraints elseif eq_constraints !== nothing && ineq_constraints === nothing eq_cons(x::Vector) = vcat(eq_constraints(x), bounds_func(x)) # Jacobian not provided if jacobian_eqcons === nothing jac_eqconsnum(x::Vector) = vcat(ForwardDiff.jacobian(eq_constraints,x), jac_bounds_func(x)) constraints_evalfunc = ConstraintsFunction(eq_cons, jac_eqconsnum) # Jacobian not provided else jac_eqcons(x::Vector) = vcat(jacobian_eq_cons(x), jac_bounds_func(x)) constraints_evalfunc = ConstraintsFunction(eq_cons, jac_eqcons) end # No equality constraints elseif eq_constraints === nothing && ineq_constraints !== nothing ineq_cons(x::Vector) = vcat(ineq_constraints(x), bounds_func(x)) # Jacobian not provided if jacobian_ineqcons === nothing jac_ineqconsnum(x::Vector) = vcat(ForwardDiff.jacobian(ineq_constraints,x), jac_bounds_func(x)) constraints_evalfunc = ConstraintsFunction(ineq_cons, jac_ineqconsnum) # Jacobian provided else jac_ineqcons(x::Vector) = vcat(jacobian_ineqcons(x), jac_bounds_func(x)) constraints_evalfunc = ConstraintsFunction(ineq_cons, jac_ineqcons) end else constraints_evalfunc = ConstraintsFunction(bounds_func, jac_bounds_func) end return constraints_evalfunc end # Returns a ConstraintsEvaluation function for problems without bound constraints function instantiate_constraints_wo_bounds(eq_constraints, jacobian_eqcons, ineq_constraints, jacobian_ineqcons) if eq_constraints !== nothing && ineq_constraints !== nothing cons(x::Vector) = vcat(eq_constraints(x), ineq_constraints(x)) if jacobian_eqcons !== nothing && jacobian_ineqcons !== nothing jac_cons(x::Vector) = vcat(jacobian_eqcons(x), jacobian_ineqcons(x)) constraints_evalfunc = ConstraintsFunction(cons, jac_cons) elseif jacobian_eqcons !== nothing && jacobian_ineqcons === nothing jac_cons_ineqnum(x::Vector) = vcat(jacobian_eqcons(x), ForwardDiff.jacobian(ineq_constraints, x)) constraints_evalfunc = ConstraintsFunction(cons, jac_ineqnum) elseif jacobian_eqcons === nothing && jacobian_ineqcons !== nothing ad_jac_eqcons(x) = vcat(ForwardDiff.jacobian(eq_constraints,x), jacobian_ineqcons(x)) constraints_evalfunc = ConstraintsFunction(cons, jac_eqnum) else ad_jac_cons(x::Vector) = vcat(ForwardDiff.jacobian(eq_constraints,x), ForwardDiff.jacobian(ineq_constraints, x)) constraints_evalfunc = ConstraintsFunction(cons, ad_jac_cons) end elseif eq_constraints !== nothing && ineq_constraints === nothing constraints_evalfunc = (jacobian_eqcons === nothing ? ConstraintsFunction(eq_constraints) : ConstraintsFunction(eq_constraints, jacobian_eqcons)) elseif eq_constraints === nothing && ineq_constraints !== nothing constraints_evalfunc = (jacobian_ineqcons === nothing ? ConstraintsFunction(ineq_constraints) : ConstraintsFunction(ineq_constraints, jacobian_ineqcons)) end return constraints_evalfunc end
Enlsip
https://github.com/UncertainLab/Enlsip.jl.git
[ "MIT" ]
0.9.7
8df29d512dca8aa40b391e645f9278bab4c09d10
code
79878
#= pseudo_rank (diag_T, ε_rank) Computes and returns the rank of a triangular matrix T using its diagonal elements placed in decreasing order according to their absolute value using a certain tolerance `tol` Parameters : * `diag_T` is the diagonal of the Triangular matrix T whose rank is estimated * `ε_rank` is a small positive value used to compute `tol` - `tol = l_diag * ε_rank` where `l_diag` is the length of `diag_T`, i.e. the number of rows of matrix `T`. =# function pseudo_rank(diag_T::Vector{T}, ε_rank::T) where {T} if isempty(diag_T) || abs(diag_T[1]) < ε_rank pseudo_rank = 0 else l_diag = length(diag_T) tol = abs(diag_T[1]) * sqrt(T(l_diag)) * ε_rank r = 1 while r < l_diag && abs(diag_T[r]) > tol r += 1 end pseudo_rank = r - ((r == l_diag && abs(diag_T[r]) > tol) ? 0 : 1) end return pseudo_rank end function new_point!( x::Vector{T}, r::ResidualsFunction, c::ConstraintsFunction, rx::Vector{T}, cx::Vector{T}, J::Matrix{T}, A::Matrix{T}) where {T} # Evaluate residuals and associated jacobian matrix res_eval!(r,x,rx) jacres_eval!(r,x,J) # Evaluate constraints and associated jacobian matrix cons_eval!(c,x,cx) jaccons_eval!(c,x,A) return end #= sub_search_direction(J1,rx,cx,Q1,L11,P1,F_L11,F_J2,n,t,rankA,dimA,dimJ2,code) Equivalent Fortran77 routine : SUBDIR Compute a search direction `p` by solving two triangular systems of equations. First, for `p1`, either `L11*p1 = -P1' * cx` or `R11*p1 = -Q2' * P1' * cx` is solved. Then for `p2`, `R22*p2 = -Q3^T * [J1*p1 + rx]` is solved. `[J1;J2] = J * Q1 * P2` where `J` is the jacobian matrix of residuals. Finally, the search direction is computed by forming : `p = Q1 * [p1 ; P3*p2]` # Parameters * `rx` : residuals vector of size `m` * `cx` : active constraints vector of size `t` * `Q1`, `L11`, `P1` : components of the LQ decomposition of active constraints jacobian matrix `A*P1 = Q1 * [L11 ; 0]` - `Q1` orthogonal `n`x`n` orthogonal matrix - `L11` `t`x`t` lower triangular matrix - `P1` `t`x`t` permutation matrix * `F_L11` : `QRPivoted` object containing infos about QR decomposition of matrix `L11` such that - `L11 * P2 = Q2 * [R11;0]` * `F_J2` : `QRPivoted` object containing infos about QR decomposition of matrix `J2`, last `m-rankA` columns of `J*Q1` - `J2 * P3 = Q3 * [R22;0]` * `J1` first `rankA` columns of matrix `J*Q1` * `n` is the number of parameters * `m` is the number of residuals (size of `rx`) * `t` is the number of constraint in current working set * `rankA` : pseudo-rank of matrix `A` * `dimA` : number of columns of matrix `R11` that should be used when `R11*p1 = -Q2' * P1' * cx` is solved * `dimJ2` : number of columns of matrix `R22` that should be used when `R22*p2 = -Q3^T * [J1*p1 + rx]` is solved * `code` : interger indicating which system to solve to compute `p1` # On return * `p` : vector of size `n`, contains the computed search direction * `b` : vector of size `t`, contains the right handside of the system solved to compute `p1` * `d` : vector of size `m`, contains the right handside of the system solved to compute `p2` =# function sub_search_direction( J1::Matrix{T}, rx::Vector{T}, cx::Vector{T}, F_A::Factorization, F_L11::Factorization, F_J2::Factorization, n::Int, t::Int, rankA::Int, dimA::Int, dimJ2::Int, code::Int) where {T} # Solving without stabilization if code == 1 b = -cx[F_A.p] p1 = LowerTriangular(F_A.R') \ b d_temp = -J1 * p1 - rx d = F_J2.Q' * d_temp δp2 = UpperTriangular(F_J2.R[1:dimJ2, 1:dimJ2]) \ d[1:dimJ2] p2 = [δp2; zeros(T, n - t - dimJ2)][invperm(F_J2.p)] # Solving with stabilization elseif code == -1 b_buff = -cx[F_A.p] b = F_L11.Q' * b_buff δp1 = UpperTriangular(F_L11.R[1:dimA, 1:dimA]) \ b[1:dimA] p1 = ([δp1; zeros(T,t - dimA)][invperm(F_L11.p)])[1:rankA] d_temp = -J1 * p1 - rx d = F_J2.Q' * d_temp δp2 = UpperTriangular(F_J2.R[1:dimJ2, 1:dimJ2]) \ d[1:dimJ2] p2 = [δp2; zeros(T, n - rankA - dimJ2)][invperm(F_J2.p)] end p = F_A.Q * [p1; p2] return p, b, d end #= gn_search_direction(J,rx,cx,Q1,L11,P1,F_L11,rankA,t,ε_rank,current_iter) Equivalent Fortran77 routine : GNSRCH Solves for `y` one of the compound systems : [L11;0] * y = b J * y = -rx or [R11;0] * y = Q2' * B J * y = -rx Then, compute the search direction `p = Q1 * y` If `rankA = t`, the first system is solved, otherwise, the second one is solved. # Parameters * `J` : `m`x`n` jacobian matrix of residuals * `rx` : residuals vector of size `m` * `cx` : active constraints vector of size `t` * `Q1`, `L11`, `P1` : components of the LQ decomposition of active constraints jacobian matrix `A*P1 = Q1 * [L11 ; 0]` - `Q1` orthogonal `n`x`n` orthogonal matrix - `L11` `t`x`t` lower triangular matrix - `P1` `t`x`t` permutation matrix * `F_L11` : `QRPivoted` object containing infos about QR decomposition of matrix `L11` such that - `L11 * P2 = Q2 * [R11;0]` * `rankA` : pseudo-rank of matrix `A` * `ε_rank` : small positive value to compute the pseudo-rank of matrices # On return * `p_gn` : vector of size `n`, contains the computed search direction * `F_J2` : QR decomposition of Matrix `J2` defined in [`sub_search_direction`](@ref) =# function gn_search_direction( J::Matrix{T}, rx::Vector{T}, cx::Vector{T}, F_A::Factorization, F_L11::Factorization, rankA::Int, t::Int, ε_rank::T, current_iter::Iteration) where {T} code = (rankA == t ? 1 : -1) n = size(J,2) JQ1 = J * F_A.Q J1, J2 = JQ1[:, 1:rankA], JQ1[:, rankA+1:end] F_J2 = qr(J2, ColumnNorm()) rankJ2 = pseudo_rank(diag(F_J2.R), ε_rank) p_gn, b_gn, d_gn = sub_search_direction(J1, rx, cx, F_A, F_L11, F_J2, n, t, rankA, rankA, rankJ2, code) current_iter.rankA = rankA current_iter.rankJ2 = rankJ2 current_iter.dimA = rankA current_iter.dimJ2 = rankJ2 current_iter.b_gn = b_gn current_iter.d_gn = d_gn return p_gn, F_J2 end # HESSF # m # Compute in place the (n x n) matrix B = Σ [r_k(x) * G_k] # k=1,m # where G_k is the hessian of residual r_k(x) function hessian_res!( r::ResidualsFunction, x::Vector{T}, rx::Vector{T}, n::Int, m::Int, B::Matrix{T}) where {T} # Data ε1 = eps(T)^(1.0 / 3.0) for k in 1:n, j in 1:k ε_k = max(abs(x[k]), 1.0) * ε1 ε_j = max(abs(x[j]), 1.0) * ε1 e_k = [i == k for i = 1:n] e_j = [i == j for i = 1:n] f1, f2, f3, f4 = zeros(T,m), zeros(T,m), zeros(T,m), zeros(T,m) res_eval!(r,x + ε_j * e_j + ε_k * e_k, f1) res_eval!(r,x - ε_j * e_j + ε_k * e_k, f2) res_eval!(r,x + ε_j * e_j - ε_k * e_k, f3) res_eval!(r,x - ε_j * e_j - ε_k * e_k, f4) # Compute line j of g_k g_kj = (f1 - f2 - f3 + f4) / (4 * ε_j * ε_k) s = dot(g_kj, rx) B[k, j] = s if j != k B[j, k] = s end end end # HESSH # t # Compute in place the (n x n) matrix B = Σ [λ_i * G_k] # k=1 # where G_k is the hessian of residual c_k(x), k in current working set # λ = (λ_1,...,λ_t) are the lagrange multipliers estimates function hessian_cons!( c::ConstraintsFunction, x::Vector{T}, λ::Vector{T}, active::Vector{Int}, n::Int, l::Int, t::Int, B::Matrix{T}) where {T} # Data ε1 = eps(T)^(1 / 3) active_indices = @view active[1:t] for k in 1:n, j in 1:k ε_k = max(abs(x[k]), 1.0) * ε1 ε_j = max(abs(x[j]), 1.0) * ε1 e_k = [i == k for i = 1:n] e_j = [i == j for i = 1:n] f1, f2, f3, f4 = zeros(T,l), zeros(T,l), zeros(T,l), zeros(T,l) cons_eval!(c,x + ε_j * e_j + ε_k * e_k, f1) cons_eval!(c,x - ε_j * e_j + ε_k * e_k, f2) cons_eval!(c,x + ε_j * e_j - ε_k * e_k, f3) cons_eval!(c,x - ε_j * e_j - ε_k * e_k, f4) act_f1 = @view f1[active_indices] act_f2 = @view f2[active_indices] act_f3 = @view f3[active_indices] act_f4 = @view f4[active_indices] # Compute line j of G_k g_kj = (act_f1 - act_f2 - act_f3 + act_f4) / (4.0 * ε_k * ε_j) s = dot(g_kj, λ) B[k, j] = s if k != j B[j, k] = s end end end # NEWTON # Computes the search direction p by minimizing : # T T T T # 0.5*p * (J * J - c_mat + r_mat) * p + (J * r(x)) * p # s.t. # A*p + c(x) = 0 # # # t # c_mat = Σ [λ_i * K_i] # i=1 # where K_i is the hessian of constraint c_i(x), i in current working set # m # r_mat = Σ [r_i(x) * G_i] # i=1 # where G_i is the hessian of residual r_i(x) function newton_search_direction( x::Vector{T}, c::ConstraintsFunction, r::ResidualsFunction, active_cx::Vector{T}, working_set::WorkingSet, λ::Vector{T}, rx::Vector{T}, J::Matrix{T}, F_A::Factorization, F_L11::Factorization, rankA::Int) where {T} error = false # Data (m,n) = size(J) t = length(active_cx) active = working_set.active t, l = working_set.t, working_set.l # Computation of p1, first component of the search direction if t == rankA b = -active_cx[F_A.p] p1 = LowerTriangular(F_A.R') \ b elseif t > rankA b = F_L11.Q' * (-active_cx[F_A.p]) δp1 = UpperTriangular(F_L11.R[1:rankA, 1:rankA]) \ b[1:rankA] p1 = F_L11.P[1:rankA, 1:rankA] * δp1 end if rankA == n return p1 end # Computation of J1, J2 JQ1 = J * F_A.Q J1, J2 = JQ1[:, 1:rankA], JQ1[:, rankA+1:end] # Computation of hessian matrices r_mat, c_mat = zeros(T, n, n), zeros(T, n, n) hessian_res!(r, x, rx, n, m, r_mat) hessian_cons!(c, x, λ, active, n, l, t, c_mat) Γ_mat = r_mat - c_mat E = F_A.Q' * Γ_mat * F_A.Q if t > rankA vect_P2 = F_L11.p E = E[vect_P2,vect_P2] end # Forms the system to compute p2 E21 = E[rankA+1:n, 1:rankA] E22 = E[rankA+1:n, rankA+1:n] W22 = E22 + transpose(J2) * J2 W21 = E21 + transpose(J2) * J1 d = -W21 * p1 - transpose(J2) * rx sW22 = (W22 + W22') * (1/2) if isposdef(sW22) chol_W22 = cholesky(sW22) y = chol_W22.L \ d p2 = chol_W22.U \ y p = F_A.Q * [p1; p2] else p = zeros(T, n) error = true end return p, error end #= first_lagrange_mult_estimate(A,λ,∇fx,cx,scaling_done,diag_scale,F) Equivalent Fortran77 routine : MULEST Compute first order estimate of Lagrange multipliers Solves the system `A' * λ_ls = ∇f(x)` using QR factorisation of `A'` given by : * `A'*P1 = Q1 * [R;0]` Then, computes estimates of lagrage multipliers by forming : `λ = λ_ls - inv(A*A') * cx` # Parameters * `A` : `n`x`t` jacobian matrix of constraints in current working set * `cx` : vector of size `t`, contains evalutations of constraints in current working set * `λ` : vector of size `t`, represent the lagrange multipliers associated to current actives contraints * `∇fx`: vector of size `n`, equals the gradient vector of the objective function * `scaling_done` : Boolean indicating if internal scaling of contraints has been done or not * `diag_scale` : Vector of size `t`, contains the diagonal elements of the scaling matrix if internal scaling is done - The i-th element equals ``\\dfrac{1}{\\|\\nabla c_i(x)\\|}`` for ``i = 1,...,t``, which is the inverse of the length of `A` i-th row - Otherwise, it contains the length of each row in the matrix `A` # On return Modifies in place the vector `λ` with the first order estimate of Lagrange multipliers. =# function first_lagrange_mult_estimate!( A::Matrix{T}, λ::Vector{T}, ∇fx::Vector{T}, cx::Vector{T}, scaling_done::Bool, diag_scale::Vector{T}, F::Factorization, iter::Iteration, ε_rank::T) where {T} (t, n) = size(A) v = zeros(T, t) vnz = zeros(T, t) inv_p = invperm(F.p) prankA = pseudo_rank(diag(F.R), ε_rank) b = F.Q' * ∇fx v[1:prankA] = UpperTriangular(F.R[1:prankA, 1:prankA]) \ b[1:prankA] if prankA < t v[prankA+1:t] = zeros(T, t - prankA) end λ_ls = v[inv_p] # Compute norm of residual iter.grad_res = (n > prankA ? norm(b[prankA+1:n]) : 0.0) # Compute the nonzero first order lagrange multiplier estimate by forming # -1 # λ = λ_ls - (A*A^T) *cx b = -cx[F.p] y = zeros(T, t) # -1 # Compute y =(L11) * b y[1:prankA] = LowerTriangular((F.R')[1:prankA, 1:prankA]) \ b[1:prankA] # -1 # Compute u = R * y u = zeros(T, t) u[1:prankA] = UpperTriangular(F.R[1:prankA, 1:prankA]) \ y[1:prankA] λ[:] = λ_ls + u[inv_p] # Back transform due to row scaling of matrix A if scaling_done λ[:] = λ .* diag_scale end return end # LEAEST # Compute second order least squares estimate of Lagrange multipliers # T T T # Solves the system A * λ = J(x) (r(x) + J(x) * p_gn)) function second_lagrange_mult_estimate!( J::Matrix{T}, F_A::Factorization, λ::Vector{T}, rx::Vector{T}, p_gn::Vector{T}, t::Int, scaling::Bool, diag_scale::Vector{T}) where {T} J1 = (J*F_A.Q)[:, 1:t] b = J1' * (rx + J * p_gn) v = UpperTriangular(F_A.R) \ b λ[:] = v[invperm(F_A.p)] if scaling λ[:] = λ .* diag_scale end return end function minmax_lagrangian_mult( λ::Vector{T}, working_set::WorkingSet, active_C::Constraint) where {T} # Data q,t = working_set.q, working_set.t scaling = active_C.scaling diag_scale = active_C.diag_scale sq_rel = sqrt(eps(eltype(λ))) λ_abs_max = 0.0 sigmin = 1e6 if t > q λ_abs_max = maximum(map(abs,λ)) rows = (scaling ? 1.0 ./ diag_scale : diag_scale) for i = q+1:t λ_i = λ[i] if λ_i*rows[i] <= -sq_rel && λ_i < sigmin sigmin = λ_i end end end return sigmin, λ_abs_max end # SIGNCH # Returns the index of the constraint that shall be deleted from the working set # Returns 0 if no constraint shall be deleted # Obtainted with the lagrange mulitpliers estimates function check_constraint_deletion( q::Int, A::Matrix{T}, λ::Vector{T}, scaling::Bool, diag_scale::Vector{T}, grad_res::T) where {T} t = size(A, 1) δ = 10.0 τ = 0.5 λ_max = (isempty(λ) ? 1.0 : maximum(map(t -> abs(t), λ))) sq_rel = sqrt(eps(eltype(λ))) * λ_max s = 0 if t > q e = sq_rel for i = q+1:t row_i = (scaling ? 1.0 / diag_scale[i] : diag_scale[i]) if row_i * λ[i] <= sq_rel && row_i * λ[i] <= e e = row_i * λ[i] s = i end end if grad_res > -e * δ # grad_res - sq_rel > -e * δ s = 0 end end return s end # EVADD # Move violated constraints to the working set function evaluate_violated_constraints( cx::Vector{T}, W::WorkingSet, index_α_upp::Int) where {T} # Data ε = sqrt(eps(eltype(cx))) δ = 0.1 added = false if W.l > W.t i = 1 while i <= W.l - W.t k = W.inactive[i] if cx[k] < ε || (k == index_α_upp && cx[k] < δ) add_constraint!(W, i) added = true else i += 1 end end end return added end #= Equivalent Fortran77 routine : WRKSET First, an estimate the lagrange multipliers is computed. If there are negative values among the multipliers computed, the constraint associated to the most negative multiplier is deleted from the working set. Then, compute the search direction using Gauss-Newton method. # Parameters * `W` : represents the current working set (see [`WorkingSet`](@ref) for more details). Fields `t`, `active` and `inactive` may be modified when deleting a constraint * `rx` : vector of size `m` containing residuals evaluations * `A` : `l`x`n` jacobian matrix of constraints * `J` = `m`x`n` jacobian matrixe of residuals * `C` : represents constraints in current working set (see [`Constraint`](@ref) for more details) * `∇fx` : vector of size `n`, gradient vector of the objective function * `p_gn` : buffer vector of size `n`, represents the search direction * `iter_k` : Contains infos about the current iteration (see [`Iteration`](@ref)) # On return * `P1`, `L11`, `Q1`, `F_L11` and `F_J2` : QR decompositions used to solve linear systems when computing the search direction in [`sub_search_direction`](@ref) * The fields of `iter_k` related to the computation of the search direction are modified in place =# function update_working_set( W::WorkingSet, rx::Vector{T}, A::Matrix{T}, C::Constraint, ∇fx::Vector{T}, J::Matrix{T}, p_gn::Vector{T}, iter_k::Iteration, ε_rank::T) where {T} λ = Vector{T}(undef, W.t) F_A = qr(C.A', ColumnNorm()) first_lagrange_mult_estimate!(C.A, λ, ∇fx, C.cx, C.scaling, C.diag_scale, F_A, iter_k, ε_rank) s = check_constraint_deletion(W.q, C.A, λ, C.scaling, C.diag_scale, iter_k.grad_res) (m, n) = size(J) # Constraint number s is deleted from the current working set if s != 0 # Save s-th element of cx,λ and row s of A to test for feasible direction cx_s = C.cx[s] A_s = C.A[s, :] λ_s = λ[s] diag_scale_s = C.diag_scale[s] index_s = W.active[s] deleteat!(λ, s) deleteat!(C.cx, s) deleteat!(C.diag_scale, s) remove_constraint!(W, s) iter_k.del = true iter_k.index_del = index_s C.A = C.A[setdiff(1:end, s), :] vect_P1 = F_A.p[:] F_A = qr((C.A)',ColumnNorm()) rankA = pseudo_rank(diag(F_A.R), ε_rank) F_L11 = qr(F_A.R', ColumnNorm()) p_gn[:], F_J2 = gn_search_direction(J, rx, C.cx, F_A, F_L11, rankA, W.t, ε_rank, iter_k) # Test for feasible direction As_p = (rankA <= W.t ? 0.0 : dot(A_s, p_gn)) feasible = (As_p >= -cx_s && As_p > 0) if !feasible insert!(C.cx, s, cx_s) insert!(λ, s, λ_s) insert!(C.diag_scale, s, diag_scale_s) s_inact = findfirst(isequal(index_s), W.inactive) add_constraint!(W, s_inact) iter_k.index_del = 0 iter_k.del = false C.A = (C.scaling ? A[W.active[1:W.t], :] .* C.diag_scale : A[W.active[1:W.t], :]) F_A = qr((C.A)',ColumnNorm()) rankA = pseudo_rank(diag(F_A.R), ε_rank) F_L11 = qr(F_A.R', ColumnNorm()) p_gn[:], F_J2 = gn_search_direction(J, rx, C.cx, F_A, F_L11, rankA, W.t, ε_rank, iter_k) if !(W.t != rankA || iter_k.rankJ2 != min(m, n - rankA)) second_lagrange_mult_estimate!(J, F_A, λ, rx, p_gn, W.t, C.scaling, C.diag_scale) s2 = check_constraint_deletion(W.q, C.A, λ, C.scaling, C.diag_scale, 0.0) if s2 != 0 index_s2 = W.active[s2] deleteat!(λ, s2) deleteat!(C.diag_scale, s2) C.cx = C.cx[setdiff(1:end, s2)] remove_constraint!(W, s2) iter_k.del = true iter_k.index_del = index_s2 C.A = C.A[setdiff(1:end, s2), :] vect_P1 = F_A.p[:] F_A = qr((C.A)',ColumnNorm()) rankA = pseudo_rank(diag(F_A.R), ε_rank) F_L11 = qr(F_A.R', ColumnNorm()) p_gn[:], F_J2 = gn_search_direction(J, rx, C.cx, F_A, F_L11, rankA, W.t, ε_rank, iter_k) end end end # No first order estimate implies deletion of a constraint elseif s == 0 rankA = pseudo_rank(diag(F_A.R), ε_rank) F_L11 = qr(F_A.R', ColumnNorm()) p_gn[:], F_J2 = gn_search_direction(J, rx, C.cx, F_A, F_L11, rankA, W.t, ε_rank, iter_k) if !(W.t != rankA || iter_k.rankJ2 != min(m, n - rankA)) second_lagrange_mult_estimate!(J, F_A, λ, rx, p_gn, W.t, C.scaling, C.diag_scale) s2 = check_constraint_deletion(W.q, C.A, λ, C.scaling, C.diag_scale, 0.0) if s2 != 0 index_s2 = W.active[s2] deleteat!(λ, s2) deleteat!(C.diag_scale, s2) C.cx = C.cx[setdiff(1:end, s2)] remove_constraint!(W, s2) iter_k.del = true iter_k.index_del = index_s2 vect_P1 = F_A.p[:] C.A = C.A[setdiff(1:end, s2), :] F_A = qr((C.A)',ColumnNorm()) rankA = pseudo_rank(diag(F_A.R), ε_rank) F_L11 = qr(F_A.R', ColumnNorm()) p_gn[:], F_J2 = gn_search_direction(J, rx, C.cx, F_A, F_L11, rankA, W.t, ε_rank, iter_k) end end end iter_k.λ = λ return F_A, F_L11, F_J2 end #= init_working_set(cx,K,step,q,l) Equivalent Fortran77 routine : INIALC Compute the first working set by cheking which inequality constraints are strictly positive. Then, initialize the penalty constants. # Parameters * `cx` : vector of size `l`, contains contraints evaluations * `K` : array of vectors, contains infos about penalty constants computed throughout the algorithm * `step` : object of type [`Iteration`](@ref), containts infos about the current iteration, i.e. the first one when this function is called * `q` : number of equality constraints * `l` : total number of constraints # On return * `first_working_set` : [`WorkingSet`](@ref) object, contains infos about the first working set =# function init_working_set(cx::Vector{T}, K::Array{Array{T,1},1}, step::Iteration, q::Int, l::Int) where {T} δ, ϵ, ε_rel = 0.1, 0.01, sqrt(eps(eltype(cx))) # Initialisation des pénalités K[:] = [δ * ones(eltype(cx), l) for i = 1:length(K)] for i = 1:l pos = min(abs(cx[i]) + ϵ, δ) step.w[i] = pos end # Determination du premier ensemble actif active = zeros(typeof(q), l) inactive = zeros(typeof(l), l - q) t = q lmt = 0 # Les contraintes d'égalité sont toujours actives active[1:q] = [i for i = 1:q] for i = q+1:l if cx[i] <= 0.0 t += 1 active[t] = i else lmt += 1 inactive[lmt] = i end end step.t = t first_working_set = WorkingSet(q, t, l, active, inactive) return first_working_set end # PRESUB # Returns dimension when previous descent direction was computed with subspace minimization function subspace_min_previous_step( τ::Vector{T}, ρ::Vector{T}, ρ_prk::T, c1::T, pseudo_rk::Int, previous_dimR::Int, progress::T, predicted_linear_progress::T, prelin_previous_dim::T, previous_α::T) where {T} # Data stepb, pgb1, pgb2, predb, rlenb, c2 = 2e-1, 3e-1, 1e-1, 7e-1, 2.0, 1e2 if ((previous_α < stepb) && (progress <= pgb1 * predicted_linear_progress^2) && (progress <= pgb2 * prelin_previous_dim^2)) # Bad step dim = max(1, previous_dimR - 1) if ((previous_dimR > 1) && (ρ[dim] > c1 * ρ_prk)) return dim end end dim = previous_dimR if previous_dimR < size(τ,1) && (((ρ[dim] > predb * ρ_prk) && (rlenb * τ[dim] < τ[dim+1])) || (c2 * τ[dim] < τ[dim+1])) suggested_dim = dim else i1 = previous_dimR - 1 if i1 <= 0 suggested_dim = pseudo_rk else buff = [i for i = i1:previous_dimR if ρ[i] > predb * ρ_prk] suggested_dim = (isempty(buff) ? pseudo_rk : minimum(buff)) end end return suggested_dim end # PREGN # Returns dimension to use when previous descent direction was computed with Gauss-Newton method function gn_previous_step( τ::Vector{T}, τ_prk::T, mindim::Int, ρ::Vector{T}, ρ_prk::T, pseudo_rank::Int) where {T} # Data τ_max, ρ_min = 2e-1, 5e-1 pm1 = pseudo_rank - 1 if mindim > pm1 suggested_dim = mindim else k = pm1 while (τ[k] >= τ_max * τ_prk || ρ[k] <= ρ_min * ρ_prk) && k > mindim k -= 1 end suggested_dim = (k > mindim ? k : max(mindim, pm1)) end return suggested_dim end # GNDCHK # Decides what method should be used to compute the search direction # This information is told by the value returned by method_code : # 1 if Gauss-Newton search direction is accepted # -1 if subspace inimization is suggested # 2 if the method of Newton is suggested # β_k = sqrt(||b1||^2 + ||d1||^2) is an information used to compute the convergence rate function check_gn_direction( b1nrm::T, d1nrm::T, d1nrm_as_km1::T, dnrm::T, active_c_sum::T, iter_number::Int, rankA::Int, n::Int, m::Int, restart::Bool, constraint_added::Bool, constraint_deleted::Bool, W::WorkingSet, cx::Vector{T}, λ::Vector{T}, iter_km1::Iteration, scaling::Bool, diag_scale::Vector{T}) where {T} # Data δ = 1e-1 c1, c2, c3, c4, c5 = 0.5, 0.1, 4.0, 10.0, 0.05 ε_rel = eps(eltype(λ)) β_k = sqrt(d1nrm^2 + b1nrm^2) method_code = 1 # To accept the Gauss-Newton we must not have used the method of # Newton before and current step must not be a restart step newton_or_restart = iter_km1.code == 2 || restart # If any of the following conditions is satisfied the Gauss-Newton direction is accepted # 1) The first iteration step # 2) estimated convergence factor < c1 # 3) the real progress > c2 * predicted linear progress (provided we are not close to the solution) first_iter = (iter_number == 0) submin_prev_iter = iter_km1.code == -1 add_or_del = (constraint_added || constraint_deleted) convergence_lower_c1 = (β_k < c1 * iter_km1.β) progress_not_close = ((iter_km1.progress > c2 * iter_km1.predicted_reduction) && ((dnrm <= c3 * β_k))) if newton_or_restart || (!first_iter && (submin_prev_iter || !(add_or_del || convergence_lower_c1 || progress_not_close))) # Subspace minimization is suggested if one of the following holds true # 4) There is something left to reduce in subspaces # 5) Addition and/or deletion to/from current working set in the latest step # 6) The nonlinearity is too severe method_code = -1 non_linearity_k = sqrt(d1nrm * d1nrm + active_c_sum) non_linearity_km1 = sqrt(d1nrm_as_km1 * d1nrm_as_km1 + active_c_sum) to_reduce = false if W.q < W.t sqr_ε = sqrt(eps(eltype(λ))) rows = zeros(T, W.t - W.q) for i = W.q+1:W.t rows[i-W.q] = (scaling ? 1.0 / diag_scale[i] : diag_scale[i]) end lagrange_mult_cond = any(>=(-sqr_ε), λ[W.q+1:W.t] .* rows) && any(<(0), λ[W.q+1:W.t]) to_reduce = (to_reduce || lagrange_mult_cond) end if (W.l - W.t > 0) inact_c = [cx[W.inactive[j]] for j = 1:((W.l-W.t))] to_reduce = (to_reduce || any(<(δ), inact_c)) end newton_previously = iter_km1.code == 2 && !constraint_deleted cond4 = active_c_sum > c2 cond5 = (constraint_deleted || constraint_added || to_reduce || (W.t == n && W.t == rankA)) ϵ = max(1e-2, 10.0 * ε_rel) cond6 = !((W.l == W.q) || (rankA <= W.t)) && !((β_k < ϵ * dnrm) || (b1nrm < ϵ && m == n - W.t)) if newton_previously || !(cond4 || cond5 || cond6) cond7 = (iter_km1.α < c5 && non_linearity_km1 < c2 * non_linearity_k) || m == n - W.t cond8 = !(dnrm <= c4 * β_k) if newton_previously || cond7 || cond8 # Method of Newton is the only alternative method_code = 2 end end end return method_code, β_k end # DIMUPP # Determine suitable dimension for solving the system Rx = y # (i.e how many columns of R should be used) # where R is rankR*rankR Upper Triangular # Returns the dimension and a real scalar containing 1.0 when restart is false # or L(previous_dimR-1)/L(previous_dimR) # where L(i) is the length of an estimated search direction computed by using dimension i function determine_solving_dim( previous_dimR::Int, rankR::Int, predicted_linear_progress::T, obj_progress::T, prelin_previous_dim::T, R::UpperTriangular{Float64,Array{T,2}}, y::Vector{T}, previous_α::T, restart::Bool) where {T} # Data c1 = 0.1 newdim = rankR η = 1.0 mindim = 1 if rankR > 0 l_estim_sd, l_estim_righthand = zeros(T,rankR), zeros(T,rankR) l_estim_sd[1] = abs(y[1]) l_estim_righthand[1] = abs(y[1] / R[1, 1]) if rankR > 1 for i = 2:rankR l_estim_sd[i] = y[i] l_estim_righthand[i] = y[i] / R[i, i] l_estim_righthand[i] = norm(l_estim_righthand[i-1:i]) l_estim_sd[i] = norm(l_estim_sd[i-1:i]) end end nrm_estim_sd = l_estim_sd[rankR] nrm_estim_righthand = l_estim_righthand[rankR] # Determine lowest possible dimension dsum = 0.0 psimax = 0.0 for i = 1:rankR dsum += l_estim_sd[i]^2 psi = sqrt(dsum) * abs(R[i, i]) if psi > psimax psimax = psi mindim = i end end k = mindim if !restart if previous_dimR == rankR || previous_dimR <= 0 # Gauss-Newton at previous step suggested_dim = gn_previous_step(l_estim_sd, nrm_estim_sd, mindim, l_estim_righthand, nrm_estim_righthand, rankR) elseif previous_dimR != rankR && previous_dimR > 0 # Subbspace-Minimization at previous step suggested_dim = subspace_min_previous_step(l_estim_sd, l_estim_righthand, nrm_estim_righthand, c1, rankR, previous_dimR, obj_progress, predicted_linear_progress, prelin_previous_dim, previous_α) end newdim = max(mindim, suggested_dim) else newdim = max(0, min(rankR, previous_dimR)) if newdim != 0 k = max(previous_dimR - 1, 1) if l_estim_sd[newdim] != 0 η = l_estim_sd[k] / l_estim_sd[newdim] end end end end return newdim, η end # SUBSPC # Computes the dimensions of the subspaces where minimization should be done function choose_subspace_dimensions( rx_sum::T, rx::Vector{T}, active_cx_sum::T, J1::Matrix{T}, t::Int, rankJ2::Int, rankA::Int, b::Vector{T}, F_L11::Factorization, F_J2::Factorization, previous_iter::Iteration, restart::Bool) where {T} # Data c1, c2, α_low = 0.1, 0.01, 0.2 previous_α = previous_iter.α if rankA <= 0 dimA = 0 previous_dimA = 0 η_A = 1.0 d = -rx elseif rankA > 0 # previous_dimA = abs(previous_iter.rankA) + t - previous_iter.t previous_dimA = abs(previous_iter.dimA) + t - previous_iter.t nrm_b_asprev = norm(b[1:previous_dimA]) nrm_b = norm(b) constraint_progress = dot(previous_iter.cx, previous_iter.cx) - active_cx_sum # Determine Dimension for matrix R11 to be used dimA, η_A = determine_solving_dim(previous_dimA, rankA, nrm_b, constraint_progress, nrm_b_asprev, UpperTriangular(F_L11.R), b, previous_α, restart) # Solve for p1 the system R11*P2*p1 = b # Using dimA columns of R11 # Forms right hand side d = r(x)+J1*p1 δp1 = UpperTriangular(F_L11.R[1:dimA, 1:dimA]) \ b[1:dimA] p1 = F_L11.P[1:rankA, 1:rankA] * [δp1; zeros(T,rankA - dimA)] d = -(rx + J1 * p1) end if rankJ2 > 0 d = F_J2.Q' * d end # previous_dimJ2 = abs(previous_iter.rankJ2) + previous_iter.t - t previous_dimJ2 = abs(previous_iter.dimJ2) + previous_iter.t -t nrm_d_asprev = norm(d[1:previous_dimJ2]) nrm_d = norm(d) residual_progress = dot(previous_iter.rx, previous_iter.rx) - rx_sum dimJ2, η_J2 = determine_solving_dim(previous_dimJ2, rankJ2, nrm_d, residual_progress, nrm_d_asprev, UpperTriangular(F_J2.R), d, previous_α, restart) if !restart && previous_α >= α_low dimA = max(dimA, previous_dimA) dimJ2 = max(dimJ2, previous_dimJ2) end return dimA, dimJ2 end #= search_direction_analys Equivalent Fortran77 routine : ANALYS Check if the latest step was sufficientlt good and eventually recompute the search direction by using either subspace minimization or the method of Newton # On return * `error_code` : integer indicating if there was an error if computations. In current version, errors can come from the method of Newton =# function search_direction_analys( previous_iter::Iteration, current_iter::Iteration, iter_number::Int, x::Vector{T}, c::ConstraintsFunction, r::ResidualsFunction, rx::Vector{T}, cx::Vector{T}, active_C::Constraint, active_cx_sum::T, p_gn::Vector{T}, J::Matrix{T}, working_set::WorkingSet, F_A::Factorization, F_L11::Factorization, F_J2::Factorization) where {T} # Data (m,n) = size(J) rx_sum = dot(rx,rx) active_cx = active_C.cx scaling = active_C.scaling diag_scale = active_C.diag_scale λ = current_iter.λ constraint_added = current_iter.add constraint_deleted = current_iter.del b_gn = current_iter.b_gn nrm_b1_gn = norm(b_gn[1:current_iter.dimA]) rankA = current_iter.rankA d_gn = current_iter.d_gn nrm_d_gn = norm(current_iter.d_gn) nrm_d1_gn = norm(d_gn[1:current_iter.dimJ2]) rankJ2 = current_iter.rankJ2 prev_dimJ2m1 = previous_iter.dimJ2 + previous_iter.t - working_set.t - 1 nrm_d1_asprev = norm(d_gn[1:prev_dimJ2m1]) restart = current_iter.restart #Analys of search direction computed with Gauss-Newton method error_code = 0 method_code, β = check_gn_direction(nrm_b1_gn, nrm_d1_gn, nrm_d1_asprev, nrm_d_gn, active_cx_sum, iter_number, rankA, n, m, restart, constraint_added, constraint_deleted, working_set, cx, λ, previous_iter, scaling, diag_scale) # Gauss-Newton accepted if method_code == 1 dimA = rankA dimJ2 = rankJ2 p, b, d = p_gn, b_gn, d_gn # Subspace minimization to recompute the search direction # using dimA columns of matrix R11 and dimJ2 columns of matrix R22 elseif method_code == -1 JQ1 = J * F_A.Q J1 = JQ1[:, 1:rankA] b = F_L11.Q' * (-active_cx[F_A.p]) dimA, dimJ2 = choose_subspace_dimensions(rx_sum, rx, active_cx_sum, J1, working_set.t, rankJ2, rankA, b, F_L11, F_J2, previous_iter, restart) p, b, d = sub_search_direction(J1, rx, active_cx, F_A, F_L11, F_J2, n, working_set.t, rankA, dimA, dimJ2, method_code) if dimA == rankA && dimJ2 == rankJ2 method_code = 1 end # Search direction computed with the method of Newton elseif method_code == 2 p, newton_error = newton_search_direction(x, c, r, active_cx, working_set, λ, rx, J, F_A, F_L11, rankA) b, d = b_gn, d_gn dimA = -working_set.t dimJ2 = working_set.t - n current_iter.nb_newton_steps += 1 if newton_error error_code = -3 end end # Update of infos about search direction computation current_iter.b_gn = b current_iter.d_gn = d current_iter.dimA = dimA current_iter.dimJ2 = dimJ2 current_iter.code = method_code current_iter.speed = β / previous_iter.β current_iter.β = β current_iter.p = p return error_code end #= Update of the penalty weights in the merit function and steplength computation psi(x,α,p,r,c,w,m,l,t,active,inactive) Compute and return the evaluation of the merit function at ``(x+\\alpha p,w)`` with current working set ``\\mathcal{W}`` and the set of inactive constraints ``\\mathcal{I}`` ``\\psi(x,w) = \\dfrac{1}{2}\\|r(x)\\|^2 + \\dfrac{1}{2}\\sum_{i \\in \\mathcal{W}} w_ic_i(x)^2 + \\dfrac{1}{2} \\sum_{j \\in \\mathcal{I}} w_j\\min(0,c_j(x))^2`` =# function psi( x::Vector, α::T, p::Vector, r::ResidualsFunction, c::ConstraintsFunction, w::Vector, m::Int, l::Int, t::Int, active::Vector{Int}, inactive::Vector{Int}) where {T} rx_new, cx_new = zeros(T, m), zeros(T, l) penalty_constraint_sum = zero(T) #Evaluate residuals and constraints at point x+αp x_new = x + α * p res_eval!(r,x_new,rx_new) cons_eval!(c,x_new,cx_new) # First part of sum with active constraints for i = 1:t j = active[i] penalty_constraint_sum += w[j] * cx_new[j]^2 end # Second part of sum with inactive constraints for i = 1:l-t j = inactive[i] if cx_new[j] < 0.0 penalty_constraint_sum += w[j] * cx_new[j]^2 end end return 0.5 * (dot(rx_new, rx_new) + penalty_constraint_sum) end # ASSORT function assort!( K::Array{Array{T,1},1}, w::Vector{T}, t::Int, active::Vector{Int}) where {T} for i in 1:t, ii in 1:4 k = active[i] if w[k] > K[ii][k] for j = 4:-1:ii+1 K[j][k] = K[j-1][k] end K[ii][k] = w[k] end end return end # EUCMOD # Solve the problem : # # min ||w|| (euclidean norm) # s.t. # w_i ≧ w_old_i # # <y,w> ≧ τ (if ctrl = 2) # # <y,w> = τ (if ctrl = 1) function min_norm_w!( ctrl::Int, w::Vector{T}, w_old::Vector{T}, y::Vector{T}, τ::T, pos_index::Vector{Int}, nb_pos::Int) where {T} w[:] = w_old if nb_pos > 0 y_sum = dot(y, y) y_norm = norm(y) # Scale the vector y if y_norm != 0.0 y /= y_norm end τ_new = τ s = 0.0 n_runch = nb_pos terminated = false ε_rel = eps(eltype(y)) while !terminated τ_new -= s c = (norm(y, Inf) <= ε_rel ? 1.0 : τ_new / y_sum) y_sum, s = 0.0, 0.0 i_stop = n_runch k = 1 while k <= n_runch i = pos_index[k] buff = c * y[k] * y_norm if buff >= w_old[i] w[i] = buff y_sum += y[k]^2 k += 1 else s += w_old[i] * y[k] * y_norm n_runch -= 1 for j = k:n_runch pos_index[j] = pos_index[j+1] y[j] = y[j+1] end end end y_sum *= y_norm * y_norm terminated = (n_runch <= 0) || (ctrl == 2) || (i_stop == n_runch) end end return end # EUCNRM # Update the penalty constants using the euclidean norm function euclidean_norm_weight_update( vA::Vector{T}, cx::Vector{T}, active::Vector{<:Int}, t::Int, μ::T, dimA::Int, previous_w::Vector{T}, K::Array{Array{T,1},1}) where {T} # if no active constraints, previous penalty weights are used w = previous_w[:] if t != 0 # Compute z = [<∇c_i(x),p>^2]_i for i ∈ active z = vA .^ 2 # Compute ztw = z(TR)w_old where w_old holds the 4th lowest weights used so far # for constraints in active set w_old = K[4] ztw = dot(z, w_old[active[1:t]]) pos_index = zeros(Int64, t) if (ztw >= μ) && (dimA < t) # if ztw ≧ μ, no need to change w_old unless t = dimA y = zeros(T, t) # Form vector y and scalar γ (\gamma) # pos_index holds indeces for the y_i > 0 ctrl, nb_pos, γ = 2, 0, 0.0 for i = 1:t k = active[i] y_elem = vA[i] * (vA[i] + cx[k]) if y_elem > 0 nb_pos += 1 pos_index[nb_pos] = k y[nb_pos] = y_elem else γ -= y_elem * w_old[k] end end min_norm_w!(ctrl, w, w_old, y, γ, pos_index, nb_pos) elseif (ztw < μ) && (dimA < t) # Form vector e and scalar τ (\tau) e = zeros(T,t) ctrl, nb_pos, τ = 2, 0, μ for i = 1:t k = active[i] e_elem = -vA[i] * cx[k] if e_elem > 0 nb_pos += 1 pos_index[nb_pos] = k e[nb_pos] = e_elem else τ -= e_elem * w_old[k] end end min_norm_w!(ctrl, w, w_old, e, τ, pos_index, nb_pos) elseif (ztw < μ) && (dimA == t) # Use vector z already formed (z = [<∇c_i(x),p>^2]_i for i ∈ active) # pos_index holds the indeces in active since z elements are > 0 ctrl = 1 pos_index[:] = active[1:t] min_norm_w!(ctrl, w, w_old, z, μ, pos_index, t) end assort!(K, w, t, active) end return w end # MAXNRM # Update the penalty weights corresponding to the # constraints in the current working setb function max_norm_weight_update!( nrm_Ap::T, rmy::T, α_w::T, δ::T, w::Vector{T}, active::Vector{Int}, t::Int, K::Array{Array{T,1},1}) where {T} μ = (abs(α_w - 1.0) <= δ ? 0.0 : rmy / nrm_Ap) i1 = (active[1] != 0 ? active[1] : 1) previous_w = w[i1] ν = max(μ, K[4][1]) for i = 1:t k = active[i] w[k] = ν end if μ > previous_w mu_not_placed = true i = 1 while i <= 4 && mu_not_placed if μ > K[i][1] for j = 4:-1:i+1 K[j][1] = K[j-1][1] end K[i][1] = μ mu_not_placed = false end i += 1 end end return end # WEIGHT # Determine the penalty constants that should be used in the current linesearch # where ψ(α) is approximalety minimized function penalty_weight_update( w_old::Vector{T}, Jp::Vector{T}, Ap::Vector{T}, K::Array{Array{T,1},1}, rx::Vector{T}, cx::Vector{T}, work_set::WorkingSet, dimA::Int, norm_code::Int) where {T} # Data δ = 0.25 active = work_set.active t = work_set.t nrm_Ap = sqrt(dot(Ap, Ap)) nrm_cx = (isempty(cx[active[1:dimA]]) ? 0.0 : max(0,maximum(map(abs,cx[active[1:dimA]])))) nrm_Jp = sqrt(dot(Jp, Jp)) nrm_rx = sqrt(dot(rx,rx)) # Scaling of vectors Jp, Ap, rx and cx if nrm_Jp != 0 Jp = Jp / nrm_Jp end if nrm_Ap != 0 Ap = Ap / nrm_Ap end if nrm_rx != 0 rx = rx / nrm_rx end if nrm_cx != 0 cx = cx / nrm_cx end Jp_rx = dot(Jp, rx) * nrm_Jp * nrm_rx AtwA = 0.0 BtwA = 0.0 if dimA > 0 for i = 1:dimA k = active[i] AtwA += w_old[k] * Ap[i]^2 BtwA += w_old[k] * Ap[i] * cx[k] end end AtwA *= nrm_Ap^2 BtwA *= nrm_Ap * nrm_cx α_w = 1.0 if abs(AtwA + nrm_Jp^2) > eps(eltype(rx)) α_w = (-BtwA - Jp_rx) / (AtwA + nrm_Jp^2) end rmy = (abs(Jp_rx + nrm_Jp^2) / δ) - nrm_Jp^2 if norm_code == 0 w = w_old[:] max_norm_weight_update!(nrm_Ap, rmy, α_w, δ, w, active, t, K) elseif norm_code == 2 w = euclidean_norm_weight_update(Ap*nrm_Ap, cx*nrm_cx, active, t, rmy, dimA, w_old, K) end # T T # Computation of ψ'(0) = [J(x)p] r(x)+ Σ w_i*[∇c_i(x) p]c_i(x) # i ∈ active BtwA = 0.0 AtwA = 0.0 wsum = 0.0 for i = 1:t k = active[i] AtwA += w[k] * Ap[i]^2 BtwA += w[k] * Ap[i] * cx[k] wsum += w[k] end BtwA *= nrm_Ap * nrm_cx AtwA *= nrm_Ap^2 dψ0 = BtwA + Jp_rx return w, dψ0 end # CONCAT # Compute in place the components of vector v used for polynomial minimization function concatenate!(v::Vector{T}, rx::Vector{T}, cx::Vector{T}, w::Vector{T}, m::Int, t::Int, l::Int, active::Vector{<:Int}, inactive::Vector{<:Int}) where {T} v[1:m] = rx[:] if t != 0 for i = 1:t k = active[i] v[m+k] = sqrt(w[k]) * cx[k] end end if l != 0 for j = 1:l-t k = inactive[j] v[m+k] = (cx[k] > 0 ? 0.0 : sqrt(w[k]) * cx[k]) end end return end # LINC2 # Compute in place vectors v0 and v2 so that one dimensional minimization in R^m can be done # Also modifies components of v1 related to constraints function coefficients_linesearch!(v0::Vector{T}, v1::Vector{T}, v2::Vector{T}, α_k::T, rx::Vector{T}, cx::Vector{T}, rx_new::Vector{T}, cx_new::Vector{T}, w::Vector{T}, m::Int, t::Int, l::Int, active::Vector{Int}, inactive::Vector{Int}) where {T} # Compute v0 concatenate!(v0, rx, cx, w, m, t, l, active, inactive) v_buff = zeros(T,m + l) concatenate!(v_buff, rx_new, cx_new, w, m, t, l, active, inactive) # Computation of v2 components v2[:] = ((v_buff - v0) / α_k - v1) / α_k return end # Equivalent Fortran : QUAMIN in dblreduns.f function minimize_quadratic(x1::T, y1::T, x2::T, y2::T, x3::T, y3::T) where {T} d1, d2 = y2 - y1, y3 - y1 s = (x3 - x1)^2 * d1 - (x2 - x1)^2 * d2 q = 2 * ((x2 - x1) * d2 - (x3 - x1) * d1) return x1 - s / q end # Equivalent Fortran : MINRN in dblreduns.f function minrn(x1::T, y1::T, x2::T, y2::T, x3::T, y3::T, α_min::T, α_max::T, p_max::T) where {T} ε = sqrt(eps(typeof(p_max))) / p_max # α not computable # Add an error in this case if abs(x1 - x2) < ε || abs(x3 - x1) < ε || abs(x3 - x2) < ε α, pα = 0.0, 0.0 else # Compute minimum of quadradic passing through y1, y2 and y3 # respectively at points x1, x2 and x3 u = minimize_quadratic(x1, y1, x2, y2, x3, y3) α = clamp(u, α_min, α_max) t1 = (α - x1) * (α - x2) * y3 / ((x3 - x1) * (x3 - x2)) t2 = (α - x3) * (α - x2) * y1 / ((x1 - x3) * (x1 - x2)) t3 = (α - x3) * (α - x2) * y2 / ((x2 - x1) * (x2 - x3)) # Value of the estimation of ψ(α) pα = t1 + t2 + t3 end return α, pα end function parameters_rm( v0::Vector{T}, v1::Vector{T}, v2::Vector{T}, x_min::T, ds::Polynomial{T}, dds::Polynomial{T}) where {T} dds_best = dds(x_min) η, d = 0.1, 1.0 normv2 = dot(v2, v2) h0 = abs(ds(x_min) / dds_best) Dm = abs(6 * dot(v1, v2) + 12 * x_min * normv2) + 24 * h0 * normv2 hm = max(h0, 1) # s'(α) = 0 is solved analytically if dds_best * η < 2 * Dm * hm # If t = α+a1 solves t^3 + b*t + c = O then α solves s'(α) = 0 (a3, a2, a1) = coeffs(ds) / (2 * normv2) b = a2 - (a1^2) / 3 c = a3 - a1 * a2 / 3 + 2 * (a1 / 3)^3 d = (c / 2)^2 + (b / 3)^3 # Two interisting roots if d < 0 α_hat, β_hat = two_roots(b, c, d, a1, x_min) # Only one root is computed else α_hat = one_root(c, d, a1) end # s'(α) = 0 is solved using Newton-Raphson's method else α_hat = newton_raphson(x_min, Dm, ds, dds) end # If only one root computed if d >= 0 β_hat = α_hat end return α_hat, β_hat end function bounds(α_min::T, α_max::T, α::T, s::Polynomial{T}) where {T} α = min(α, α_max) α = max(α, α_min) return α, s(α) end function newton_raphson( x_min::T, Dm::T, ds::Polynomial{T}, dds::Polynomial{T}) where {T} α, newton_iter = x_min, 0 ε, error = 1e-4, 1.0 while error > ε || newton_iter < 3 c = dds(α) h = -ds(α) / c α += h error = (2 * Dm * h^2) / abs(c) newton_iter += 1 end return α end # Equivalent Fortran : ONER in dblreduns.f function one_root(c::T, d::T, a::T) where {T} arg1, arg2 = -c / 2 + sqrt(d), -c / 2 - sqrt(d) return cbrt(arg1) + cbrt(arg2) - a / 3 end # Equivalent Fortran : TWOR in dblreduns.f function two_roots(b::T, c::T, d::T, a::T, x_min::T) where {T} φ = acos(abs(c / 2) / (-b / 3)^(3 / 2)) t = (c <= 0 ? 2 * sqrt(-b / 3) : -2 * sqrt(-b / 3)) # β1 is the global minimizer of s(α). # If d is close to zero the root β1 is stable while β2 and β3 become unstable β1 = t * cos(φ / 3) - a / 3 β2 = t * cos((φ + 2 * π) / 3) - a / 3 β3 = t * cos((φ + 4 * π) / 3) - a / 3 # Sort β1, β2 and β3 so that β1 <= β2 <= β3 β1, β2, β3 = sort([β1, β2, β3]) # β1 or β3 are now the roots of interest α, β = (x_min <= β2 ? (β1, β3) : (β3, β1)) return α, β end # Equivalent Fortran : MINRM in dblreduns.f function minrm( v0::Vector{T}, v1::Vector{T}, v2::Vector{T}, x_min::T, α_min::T, α_max::T) where {T} s = Polynomial([0.5 * dot(v0, v0), dot(v0, v1), dot(v0, v2) + 0.5 * dot(v1, v1), dot(v1, v2), 0.5 * dot(v2, v2)]) ds = derivative(s) dds = derivative(ds) α_hat, β_hat = parameters_rm(v0, v1, v2, x_min, ds, dds) sα, sβ = s(α_hat), s(β_hat) α_old = α_hat α_hat, sα = bounds(α_min, α_max, α_hat, s) if α_old == β_hat β_hat, sβ = α_hat, s(α_hat) else β_hat, sβ = bounds(α_min, α_max, β_hat, s) end return α_hat, sα, β_hat, sβ end # REDC # Returns true if essential reduction in the objective function is likely # Otherwise returns false function check_reduction( ψ_α::T, ψ_k::T, approx_k::T, η::T, diff_psi::T) where {T} # Data δ = 0.2 if ψ_α - approx_k >= η * diff_psi reduction_likely = !((ψ_α - ψ_k < η * diff_psi) && (ψ_k > δ * ψ_α)) else reduction_likely = false end return reduction_likely end # GAC # Halfs the value of u until a Goldstein-Armijo condition is satisfied # or until steplength times search direction is below square root of relative_prevision function goldstein_armijo_step( ψ0::T, dψ0::T, α_min::T, τ::T, p_max::T, x::Vector{T}, α0::T, p::Vector{T}, r::ResidualsFunction, c::ConstraintsFunction, w::Vector{T}, m::Int, l::Int, t::Int, active::Vector{Int}, inactive::Vector{Int}) where {T} u = α0 sqr_ε = sqrt(eps(typeof(u))) exit = (p_max * u < sqr_ε) || (u <= α_min) ψu = psi(x, u, p, r, c, w, m, l, t, active, inactive) while !exit && (ψu > ψ0 + τ * u * dψ0) u *= 0.5 ψu = psi(x, u, p, r, c, w, m, l, t, active, inactive) exit = (p_max * u < sqr_ε) || (u <= α_min) end return u, exit end # LINEC # Linesearch routine for constrained least squares problems # Compute the steplength α (\alpha) for the iteration x_new = x + αp # x current point, p search direction # # α is close to the solution of the problem # min ψ(α) # with α_low <= α <= α_upp # # ψ(α) = 0.5 * (||r(x+αp)||^2 + Σ (w_i * c_i(x+αp)^2) + Σ min(0,w_j * c_j(x+αp))^2) # i j # i correspond to constraints in current working set, j to inactive constraints function linesearch_constrained( x::Vector{T}, α0::T, p::Vector{T}, r::ResidualsFunction, c::ConstraintsFunction, rx::Vector{T}, cx::Vector{T}, JpAp::Vector{T}, w::Vector{T}, work_set::WorkingSet, ψ0::T, dψ0::T, α_low::T, α_upp::T) where {T} # Data m = length(rx) l, t = work_set.l, work_set.t active, inactive = work_set.active, work_set.inactive # LINC1 # Set values of constants and compute α_min, α_max and α_k η = 0.3 # \eta τ = 0.25 # \tau γ = 0.4 # \gamma α_min, α_max = α_low, α_upp α_k = min(α0, α_max) α_km1 = 0.0 ψ_km1 = ψ0 p_max = norm(p, Inf) gac_error = false # LINC2 # Computation of v1 v1 = JpAp if t != 0 for i = 1:t k = active[i] v1[m+k] = sqrt(w[k]) * v1[m+k] end end if l - t != 0 for j = 1:l-t k = inactive[j] v1[m+k] = (cx[k] > 0 ? 0.0 : sqrt(w[k]) * v1[m+k]) end end ψ_k = psi(x, α_k, p, r, c, w, m, l, t, active, inactive) diff_psi = ψ0 - ψ_k x_new = x + α_k * p rx_new, cx_new = zeros(T,m), zeros(T,l) res_eval!(r,x_new,rx_new) cons_eval!(c,x_new,cx_new) v0, v2 = zeros(T,m + l), zeros(m + l) coefficients_linesearch!(v0, v1, v2, α_k, rx, cx, rx_new, cx_new, w, m, t, l, active, inactive) # Set x_min = the best of the points 0 and α0 x_min = (diff_psi >= 0 ? α_k : 0.0) # Minimize in R^m. Use two points 0 and α0 # New suggestion of steplength is α_kp1 (stands for "k+1") # pk is the value of the approximating function at α_kp1 α_kp1, pk, β, pβ = minrm(v0, v1, v2, x_min, α_min, α_max) if α_kp1 != β && pβ < pk && β <= α_k α_kp1 = β pk = pβ end # UPDATE α_km2 = α_km1 ψ_km2 = ψ_km1 α_km1 = α_k ψ_km1 = ψ_k α_k = α_kp1 ψ_k = psi(x, α_k, p, r, c, w, m, l, t, active, inactive) # Test termination condition at α0 if (-diff_psi <= τ * dψ0 * α_km1) || (ψ_km1 < γ * ψ0) # Termination condition satisfied at α0 diff_psi = ψ0 - ψ_k # REDUCE # Check if essential reduction is likely reduction_likely = check_reduction(ψ_km1, ψ_k, pk, η, diff_psi) while reduction_likely # Value of the objective function can most likely be reduced # Minimize in R^n using 3 points : α_km2, α_km1 and α_k # New suggestion of the steplength is α_kp1, pk is its approximated value α_kp1, pk = minrn(α_k, ψ_k, α_km1, ψ_km1, α_km2, ψ_km2, α_min, α_max, p_max) # UPDATE α_km2 = α_km1 ψ_km2 = ψ_km1 α_km1 = α_k ψ_km1 = ψ_k α_k = α_kp1 ψ_k = psi(x, α_k, p, r, c, w, m, l, t, active, inactive) diff_psi = ψ0 - ψ_k reduction_likely = check_reduction(ψ_km1, ψ_k, pk, η, diff_psi) end # Terminate but choose the best point out of α_km1 and α_k if (ψ_km1 - pk >= η * diff_psi) && (ψ_k < ψ_km1) α_km1 = α_k ψ_km1 = ψ_k end # Termination condition not satisfied at α0 else diff_psi = ψ0 - ψ_k # Test termination condition at α1, i.e. α_k if (-diff_psi <= τ * dψ0 * α_k) || (ψ_k < γ * ψ0) # Termination condition satisfied at α1 # Check if α0 is somewhat good if ψ0 <= ψ_km1 x_min = α_k x_new = x + α_k * p res_eval!(r,x_new,rx_new) cons_eval!(c,x_new,cx_new) v0, v2 = zeros(T,m + l), zeros(T,m + l) coefficients_linesearch!(v0, v1, v2, α_k, rx, cx, rx_new, cx_new, w, m, t, l, active, inactive) α_kp1, pk, β, pβ = minrm(v0, v1, v2, x_min, α_min, α_max) if α_kp1 != β && pβ < pk && β <= α_k α_kp1 = β pk = pβ end α_km1 = 0.0 ψ_km1 = ψ0 else # Minimize in R^n. use 3 points : 0, α0 and α1 # New suggestion of the steplength is α_kp1 # pk is the value of the approximating function at α_kp1 α_kp1, pk = minrn(α_k, ψ_k, α_km1, ψ_km1, α_km2, ψ_km2, α_min, α_max, p_max) end diff = ψ0 - ψ_k # UPDATE α_km2 = α_km1 ψ_km2 = ψ_km1 α_km1 = α_k ψ_km1 = ψ_k α_k = α_kp1 ψ_k = psi(x, α_k, p, r, c, w, m, l, t, active, inactive) # Check if essential reduction is likely reduction_likely = check_reduction(ψ_km1, ψ_k, pk, η, diff_psi) while reduction_likely # Value of the objective function can most likely be reduced # Minimize in R^n using 3 points : α_km2, α_km1 and α_k # New suggestion of the steplength is α_kp1, pk its approximated value α_kp1, pk = minrn(α_k, ψ_k, α_km1, ψ_km1, α_km2, ψ_km2, α_min, α_max, p_max) # UPDATE α_km2 = α_km1 ψ_km2 = ψ_km1 α_km1 = α_k ψ_km1 = ψ_k α_k = α_kp1 ψ_k = psi(x, α_k, p, r, c, w, m, l, t, active, inactive) reduction_likely = check_reduction(ψ_km1, ψ_k, pk, η, diff_psi) end # Terminate but choose the best point out of α_km1 and α_k if (ψ_km1 - pk >= η * diff_psi) && (ψ_k < ψ_km1) α_km1 = α_k ψ_km1 = ψ_k end else # Take a pure Goldstein-Armijo step α_km1, gac_error = goldstein_armijo_step(ψ0, dψ0, α_min, τ, p_max, x, α_k, p, r, c, w, m, l, t, active, inactive) end end α = α_km1 return α, gac_error end # UPBND # Determine the upper bound of the steplength function upper_bound_steplength( A::Matrix{T}, cx::Vector{T}, p::Vector{T}, work_set::WorkingSet, index_del::Int) where {T} # Data inactive = work_set.inactive t = work_set.t l = work_set.l α_upper = Inf index_α_upp = 0 if norm(inactive, Inf) > 0 for i = 1:l-t j = inactive[i] if j != index_del ∇cjTp = dot(A[j, :], p) α_j = -cx[j] / ∇cjTp if cx[j] > 0 && ∇cjTp < 0 && α_j < α_upper α_upper = α_j index_α_upp = j end end end end α_upper = min(3.0, α_upper) return α_upper, index_α_upp end #= compute_steplength Equivalent Fortran77 routine : STPLNG Update the penalty weights and compute the steplength using the merit function [`psi`](@ref) If search direction computed with method of Newton, an undamped step is taken, i.e. ``\\alpha =1`` # On return * `α` : the computed steplength * `w` : vector of size `l`, containts the computed penalty constants =# function compute_steplength( iter::Iteration, previous_iter::Iteration, x::Vector{T}, r::ResidualsFunction, rx::Vector{T}, J::Matrix{T}, c::ConstraintsFunction, cx::Vector{T}, A::Matrix{T}, active_constraint::Constraint, work_set::WorkingSet, K::Array{Array{T,1},1}, weight_code::Int) where {T} # Data c1 = 1e-3 (m,_) = size(J) p = iter.p dimA = iter.dimA rankJ2 = iter.rankJ2 method_code = iter.code ind_constraint_del = iter.index_del previous_α = previous_iter.α prev_rankJ2 = previous_iter.rankJ2 w_old = previous_iter.w Jp = J * p Ap = A * p JpAp = vcat(Jp, Ap) active_Ap = (active_constraint.A) * p active_index = work_set.active[1:work_set.t] if active_constraint.scaling active_Ap = active_Ap ./ active_constraint.diag_scale end Ψ_error = 0 if method_code != 2 # Compute penalty weights and derivative of ψ at α = 0 w, dψ0 = penalty_weight_update(w_old, Jp, active_Ap, K, rx, cx, work_set, dimA, weight_code) # # Compute ψ(0) = 0.5 * [||r(x)||^2 + Σ (w_i*c_i(x)^2)] # i ∈ active ψ0 = 0.5 * (dot(rx, rx) + dot(w[active_index], cx[active_index] .^ 2)) # check is p is a descent direction if dψ0 >= 0 α = 1.0 Ψ_error = -1 iter.index_α_upp = 0 else # Determine upper bound of the steplength α_upp, index_α_upp = upper_bound_steplength(A, cx, p, work_set, ind_constraint_del) α_low = α_upp / 3000.0 # Determine a first guess of the steplength magfy = (rankJ2 < prev_rankJ2 ? 6.0 : 3.0) α0 = min(1.0, magfy * previous_α, α_upp) # Compute the steplength α, gac_error = linesearch_constrained(x, α0, p, r, c, rx, cx, JpAp, w, work_set, ψ0, dψ0, α_low, α_upp) if gac_error ψ_k = psi(x,α,p,r,c,w,m,work_set.l,work_set.t,work_set.active,work_set.inactive) Ψ_error = check_derivatives(dψ0,ψ0,ψ_k,x,α,p,r,c,w,work_set,m) end # Compute the predicted linear progress and actual progress uppbound = min(1.0, α_upp) atwa = dot(w[active_index], active_Ap .^ 2) iter.predicted_reduction = uppbound * (-2.0 * dot(Jp, rx) - uppbound * dot(Jp, Jp) + (2.0 - uppbound^2) * atwa) # Computation of new point and actual progress # Evaluate residuals and constraints at the new point rx_new = zeros(T,m) cx_new = zeros(T,work_set.l) x_new = x + α * p res_eval!(r,x_new,rx_new) cons_eval!(c,x_new,cx_new) whsum = dot(w[active_index], cx_new[active_index] .^ 2) iter.progress = 2 * ψ0 - dot(rx_new, rx_new) - whsum iter.index_α_upp = (index_α_upp != 0 && abs(α - α_upp) > 0.1 ? 0 : index_α_upp) end else # Take an undamped step w = w_old α_upp = 3.0 iter.index_α_upp = 0 α = 1.0 end return α, w, Ψ_error end function check_derivatives( dψ0::T, ψ0::T, ψ_k::T, x_old::Vector{T}, α::T, p::Vector{T}, r::ResidualsFunction, c::ConstraintsFunction, w::Vector{T}, work_set::WorkingSet, m::Int) where {T} # Data l,t = work_set.l, work_set.t active, inactive = work_set.active,work_set.inactive ctrl = -1 ψ_mα = psi(x_old,-α,p,r,c,w,m,l,t,active,inactive) dψ_forward = (ψ_k - ψ0) / α dψ_backward = (ψ0 - ψ_mα) / α dψ_central = (ψ_k - ψ_mα) / (2*α) max_diff = maximum(map(abs,[dψ_forward-dψ_central , dψ_forward - dψ_backward, dψ_backward - dψ_central])) inconsistency = abs(dψ_forward-dψ0) > max_diff && abs(dψ_central-dψ0) > max_diff exit = (inconsistency ? -1 : 0) return exit end function evaluation_restart!(iter::Iteration, error_code::Int) iter.restart = (error_code < 0) end #= check_termination_criteria(iter::Iteration,prev_iter::Iteration,W::WorkingSet,active_C::Constraint,x,cx,rx_sum,∇fx,max_iter,nb_iter,ε_abs,ε_rel,ε_x,ε_c,error_code) Equivalent Fortran77 routine : `TERCRI` This functions checks if any of the termination criteria are satisfied ``\\varepsilon_c,\\varepsilon_x,\\varepsilon_{rel}`` and ``\\varepsilon_{abs}`` are small positive values to test convergence. There are convergence criteria (conditions 1 to 7) and abnormal termination criteria (conditions 8 to 12) 1. ``\\|c(x_k)\\| < \\varepsilon_c`` for constraints in the working set and all inactive constraints must be strictly positive 2. ``\\|A_k^T \\lambda_k - \\nabla f(x_k)\\| < \\sqrt{\\varepsilon_{rel}}*(1 + \\|\\nabla f(x_k)\\|)`` 3. ``\\underset{i}{\\min}\\ \\lambda_k^{(i)} \\geq \\varepsilon_{rel}*\\underset{i}{\\max}\\ |\\lambda_k^{(i)}|`` - or ``\\underset{i}{\\min}\\ \\lambda_k^{(i)} \\geq \\varepsilon_{rel}*(1+\\|r(x_k)\\|^2)`` if there is only one inequality 4. ``\\|d_1\\|^2 \\leq \\varepsilon_x * \\|x_k\\|`` 5. ``\\|r(x_k)\\|^2 \\leq \\varepsilon_{abs}^2`` 6. ``\\|x_k-x_{k-1}\\| < \\varepsilon_x * \\|x_k\\|`` 7. ``\\dfrac{\\sqrt{\\varepsilon_{rel}}}{\\|p_k\\|} > 0.25`` 8. number of iterations exceeds `MAX_ITER` 9. Convergence to a non feasible point 10. Second order derivatives not allowed by the user (TODO : not implemented yet) 11. Newton step fails or too many Newton steps done 12. The latest direction is not a descent direction to the merit function (TODO : not implemented yet) Concitions 1 to 3 are necessary conditions. This functions returns `exit_code`, an integer containing infos about the termination of the algorithm * `0` if no termination criterion is satisfied * `10000` if criterion 4 satisfied * `2000` if criterion 5 satisfied * `300` if criterion 6 satisfied * `40` if criterion 7 satisfied * `-2` if criterion 8 satisfied * `-5` if criterion 11 satisfied * `-9` if the search direction is computed with Newton method at least five times * `-10` if not possible to satisfy the constraints * `-11` if time limit exceeded If multiple convergence criteria are satisfied, their corresponding values are added into `exit_code`. `exit_code != 0` means the termination of the algorithm =# function check_termination_criteria( iter::Iteration, prev_iter::Iteration, W::WorkingSet, active_C::Constraint, x::Vector{T}, cx::Vector{T}, rx_sum::T, ∇fx::Vector{T}, max_iter::Int, nb_iter::Int, ε_abs::T, ε_rel::T, ε_x::T, ε_c::T, error_code::Int, Δ_time::T, σ_min::T, λ_abs_max::T, Ψ_error::Int) where {T} exit_code = 0 rel_tol = eps(T) alfnoi = rel_tol / (norm(iter.p) + rel_tol) # Preliminary conditions preliminary_cond = !(iter.restart || (iter.code == -1 && alfnoi <= 0.25)) if preliminary_cond # Check necessary conditions necessary_crit = (!iter.del) && (norm(active_C.cx) < ε_c) && (iter.grad_res < sqrt(ε_rel) * (1 + norm(∇fx))) if W.l - W.t > 0 inactive_index = W.inactive[1:(W.l-W.t)] inactive_cx = cx[inactive_index] necessary_crit = necessary_crit && (all(>(0), inactive_cx)) end if W.t > W.q if W.t == 1 factor = 1 + rx_sum elseif W.t > 1 factor = λ_abs_max end necessary_crit = necessary_crit && (σ_min >= ε_rel * factor) end if necessary_crit # Check the sufficient conditions d1 = @view iter.d_gn[1:iter.dimJ2] x_diff = norm(prev_iter.x - x) # Criterion 4 if dot(d1, d1) <= rx_sum * ε_rel^2 exit_code += 10000 end # Criterion 5 if rx_sum <= ε_abs^2 exit_code += 2000 end # Criterion 6 if x_diff < ε_x * norm(x) exit_code += 300 end # Criterion 7 if alfnoi > 0.25 exit_code += 40 end end end if exit_code == 0 # Check abnormal termination criteria x_diff = norm(prev_iter.x - iter.x) Atcx_nrm = norm(transpose(active_C.A) * active_C.cx) active_penalty_sum = (W.t == 0 ? 0.0 : dot(iter.w[W.active[1:W.t]], iter.w[W.active[1:W.t]])) # Criterion 9 if nb_iter >= max_iter exit_code = -2 # Criterion 12 elseif error_code == -3 exit_code = -5 # Too many Newton steps elseif iter.nb_newton_steps > 5 exit_code = -9 elseif Ψ_error == -1 exit_code = -6 # test if impossible to satisfy the constraints elseif x_diff <= 10.0 * ε_x && Atcx_nrm <= 10.0 * ε_c && active_penalty_sum >= 1.0 exit_code = -10 # time limit elseif Δ_time > 0 exit_code = -11 end # TODO : implement critera 10-11 end return exit_code end #= Functions to print details about execution of the algorithm =# function print_header(model::CnlsModel, io::IO=stdout) print(io,"\n\n") println(io, '*'^64) println(io, "*",' '^62,"*") println(io, "*"," "^23,"Enlsip.jl v0.9.7"," "^23,"*") println(io, "*",' '^62,"*") println(io, "* This is the Julia version of the ENLSIP algorithm, initially *") println(io, "* conceived and developed in Fortran77 by Per Lindstrom and *") println(io, "* Per Ake Wedin from the Institute of Information Processing *") println(io, "* (University of Umea, Sweden). *") println(io, "*",' '^62,"*") println(io, '*'^64) println(io, "\nCharacteristics of the model\n") println(io, "Number of parameters.................: ", @sprintf("%5i", model.nb_parameters)) println(io, "Number of residuals..................: ", @sprintf("%5i", model.nb_residuals)) println(io, "Number of equality constraints.......: ", @sprintf("%5i", model.nb_eqcons)) println(io, "Number of inequality constraints.....: ", @sprintf("%5i", model.nb_ineqcons)) println(io, "Number of lower bounds...............: ", @sprintf("%5i", count(isfinite, model.x_low))) println(io, "Number of upper bounds...............: ", @sprintf("%5i", count(isfinite, model.x_upp))) println(io, "Constraints internal scaling.........: $(model.constraints_scaling)\n") end function print_initialized_model(model::CnlsModel, io::IO=stdout) print_header(model, io) println(io, "Model has been initialized.\n\nMethod solve! can be called to execute Enlsip.") end function print_iter(k::Int, iter_data::DisplayedInfo; io::IO=stdout) @printf(io, "%4d %.7e %.2e %.2e %.2e %.3e\n", k, iter_data.objective, iter_data.sqr_nrm_act_cons, iter_data.nrm_p, iter_data.α, iter_data.reduction) end function final_print(model::CnlsModel, exec_info::ExecutionInfo, io::IO=stdout) @printf(io, "\nNumber of iterations...................: %4d", length(exec_info.iterations_detail)) @printf(io, "\n\nSquare sum of residuals................: %.7e", sum_sq_residuals(model)) @printf(io, "\n\nNumber of function evaluations.........: %4d", exec_info.nb_function_evaluations) @printf(io, "\nNumber of Jacobian matrix evaluations..: %4d", exec_info.nb_jacobian_evaluations) @printf(io, "\n\nSolving time (seconds).................: %.3f\n", exec_info.solving_time) println(io, "Termination status.....................: $(status(model))\n\n") end function print_diagnosis(model::CnlsModel, io::IO=stdout) exec_info = model.model_info print_header(model, io) println(io, "\nIteration steps information\n") println(io, "iter objective ||active_constraints||² ||p|| α reduction") for (k, detail_iter_k) in enumerate(exec_info.iterations_detail) print_iter(k, detail_iter_k) end final_print(model, exec_info, io) end ##### Enlsip solver ##### #= enlsip(x0,r,c,n,m,q,l;scaling = false,weight_code = 2,MAX_ITER = 100,ε_abs = 1e-10,ε_rel = 1e-3,ε_x = 1e-3,ε_c = 1e-3) Main function for ENLSIP solver. Must be called with the following arguments: * `x0::Vector{Foat64}` is the departure point * `r` is a function to evaluate residuals values and jacobian * `c` is a function of type to evaluate constraints values and jacobian * `n::Int` is the number of parameters * `m::Int` is the number of residuals * `q::Int` is the number of equality constraints * `l::Int` is the total number of constraints (equalities and inequalities) The following arguments are optionnal and have default values: * `scaling::Bool` - boolean indicating if internal scaling of constraints value and jacobian must be done or not - `false` by default * `weight_code::Int` is an int representing the method used to compute penality weights at each iteration - `1` represents maximum norm method - `2` (default value) represents euclidean norm method * `MAX_ITER::Int` - int defining the maximum number of iterations - equals `100` by default * `ε_abs`, `ε_rel`, `ε_x` and `ε_c` - small AsbtractFloat positive scalars - default are the recommended one by the authors, i.e. - `ε_x = 1e-3` - `ε_c = 1e-4` - `ε_rel = 1e-5` - `ε_abs = ε_rank 1e-10` =# function enlsip(x0::Vector{T}, r::ResidualsFunction, c::ConstraintsFunction, n::Int, m::Int, q::Int, l::Int; scaling::Bool=false, weight_code::Int=2, MAX_ITER::Int=100, TIME_LIMIT::T=1000., ε_abs::T=eps(T), ε_rel::T=√ε_abs, ε_x::T=ε_rel, ε_c::T=ε_rel, ε_rank::T=ε_rel, ) where {T} enlsip_info = ExecutionInfo() start_time = time() nb_iteration = 0 # Vector of penalty constants K = [zeros(T, l) for i = 1:4] # Evaluate residuals, constraints and jacobian matrices at starting point rx, cx = zeros(T,m), zeros(T,l) J, A = zeros(T,m, n), zeros(T,l, n) new_point!(x0, r, c, rx, cx, J, A) # First Iteration x_opt = x0 f_opt = dot(rx, rx) first_iter = Iteration(x0, zeros(T,n), rx, cx, l, 1.0, 0, zeros(T,l), zeros(T,l), 0, 0, 0, 0, zeros(T,n), zeros(T,n), 0.0, 0.0, 0.0, 0.0, 0.0, false, true, false, false, 0, 1, 0) # Initialization of the working set working_set = init_working_set(cx, K, first_iter, q, l) first_iter.t = working_set.t active_C = Constraint(cx[working_set.active[1:working_set.t]], A[working_set.active[1:working_set.t], :], scaling, zeros(T,working_set.t)) # Gradient of the objective function ∇fx = transpose(J) * rx p_gn = zeros(T, n) # Estimation of the Lagrange multipliers # Computation of the Gauss-Newton search direction evaluate_scaling!(active_C) F_A, F_L11, F_J2 = update_working_set(working_set, rx, A, active_C, ∇fx, J, p_gn, first_iter, ε_rank) rx_sum = dot(rx, rx) active_cx_sum = dot(cx[working_set.active[1:working_set.t]], cx[working_set.active[1:working_set.t]]) first_iter.t = working_set.t previous_iter = copy(first_iter) # Analys of the lastly computed search direction error_code = search_direction_analys(previous_iter, first_iter, nb_iteration, x0, c, r, rx, cx, active_C, active_cx_sum, p_gn, J, working_set, F_A, F_L11, F_J2) # Computation of penalty constants and steplentgh α, w, Ψ_error = compute_steplength(first_iter, previous_iter, x0, r, rx, J, c, cx, A, active_C, working_set, K, weight_code) first_iter.α = α first_iter.w = w x = x0 + α * first_iter.p # Evaluate residuals, constraints and compute jacobians at new point new_point!(x, r, c, rx, cx, J, A) ∇fx = transpose(J) * rx rx_sum = dot(rx, rx) # Check for termination criterias at new point evaluation_restart!(first_iter, error_code) σ_min, λ_abs_max = minmax_lagrangian_mult(first_iter.λ, working_set, active_C) Δ_time = (time()-start_time) - TIME_LIMIT exit_code = check_termination_criteria(first_iter, previous_iter, working_set, active_C, x, cx, rx_sum, ∇fx, MAX_ITER, nb_iteration, ε_abs, ε_rel, ε_x, ε_c, error_code, Δ_time, σ_min, λ_abs_max, Ψ_error) # Initialization of the list of collected information to be printed list_iter_detail = Vector{DisplayedInfo}(undef, 0) first_iter_detail = DisplayedInfo(f_opt, active_cx_sum, norm(first_iter.p), first_iter.α, first_iter.progress) push!(list_iter_detail, first_iter_detail) # Check for violated constraints and add it to the working set first_iter.add = evaluate_violated_constraints(cx, working_set, first_iter.index_α_upp) active_C.cx = cx[working_set.active[1:working_set.t]] active_C.A = A[working_set.active[1:working_set.t], :] #= Rearrangement of iterations data storage The iteration that just terminated is stored as previous iteration The current `iter` can be used for the next iteration =# previous_iter = copy(first_iter) first_iter.x = x first_iter.rx = rx first_iter.cx = cx f_opt = dot(rx, rx) nb_iteration += 1 iter = copy(first_iter) iter.first = false iter.add = false iter.del = false # Main loop for next iterations while exit_code == 0 # println( "\nIter $nb_iteration\n") p_gn = zeros(T,n) # Estimation of the Lagrange multipliers # Computation of the Gauss-Newton search direction evaluate_scaling!(active_C) F_A, F_L11, F_J2 = update_working_set(working_set, rx, A, active_C, ∇fx, J, p_gn, iter, ε_rank) active_cx_sum = dot(cx[working_set.active[1:working_set.t]], cx[working_set.active[1:working_set.t]]) iter.t = working_set.t # Analys of the lastly computed search direction error_code = search_direction_analys(previous_iter, iter, nb_iteration, x, c, r, rx, cx, active_C, active_cx_sum, p_gn, J, working_set,F_A, F_L11, F_J2) # Computation of penalty constants and steplentgh α, w, Ψ_error = compute_steplength(iter, previous_iter, x, r, rx, J, c, cx, A, active_C, working_set, K, weight_code) iter.α = α iter.w = w x = x + α * iter.p # Evaluate residuals, constraints and compute jacobians at new point new_point!(x, r, c, rx, cx, J, A) rx_sum = dot(rx, rx) ∇fx = transpose(J) * rx # Check for termination criterias at new point evaluation_restart!(iter, error_code) σ_min, λ_abs_max = minmax_lagrangian_mult(iter.λ, working_set, active_C) Δ_time = (time()-start_time) - TIME_LIMIT exit_code = check_termination_criteria(iter, previous_iter, working_set, active_C, iter.x, cx, rx_sum, ∇fx, MAX_ITER, nb_iteration, ε_abs, ε_rel, ε_x, ε_c, error_code, Δ_time, σ_min, λ_abs_max, Ψ_error) # Another step is required if (exit_code == 0) # Print collected informations about current iteration # Push current iteration data to the list of collected information to be printed current_iter_detail = DisplayedInfo(f_opt, active_cx_sum, norm(iter.p), iter.α, iter.progress) push!(list_iter_detail, current_iter_detail) # Check for violated constraints and add it to the working set iter.add = evaluate_violated_constraints(cx, working_set, iter.index_α_upp) active_C.cx = cx[working_set.active[1:working_set.t]] active_C.A = A[working_set.active[1:working_set.t], :] # Update iteration data field nb_iteration += 1 previous_iter = copy(iter) iter.x = x iter.rx = rx iter.cx = cx iter.del = false iter.add = false f_opt = dot(rx, rx) else # Algorithm has terminated x_opt = x f_opt = dot(rx,rx) # Execution information stored in a `ExecutionInfo` data structure solving_time = time() - start_time func_ev = r.nb_reseval + c.nb_conseval jac_ev = r.nb_jacres_eval + c.nb_jaccons_eval enlsip_info = ExecutionInfo(list_iter_detail, func_ev, jac_ev, solving_time) end end return exit_code, x_opt, f_opt, enlsip_info end
Enlsip
https://github.com/UncertainLab/Enlsip.jl.git
[ "MIT" ]
0.9.7
8df29d512dca8aa40b391e645f9278bab4c09d10
code
3903
export solve!, print_cnls_model """ solve!(model{T}) Once a [`CnlsModel`](@ref) has been instantiated, this function solves the optimzation problem associated by using the method implemented in the `Enlsip` solver. Options: * `silent::Bool` - Set to `false` if one wants the algorithm to print details about the iterations and termination of the solver - Default is `true`, i.e. by default, there is no output. If one wants to print those information afert solving, the [`print_cnls_model`](@ref) method can be called * `max_iter::Int` - Maximum number of iterations allowed - Default is `100` * `scaling::Bool` - Set to `true` if one wants the algorithm to work with a constraints jacobian matrix whose rows are scaled (i.e. all constraints gradients vectors are scaled) - Default is `false` * `time_limit::T` - Maximum elapsed time (i.e. wall time) - Default is `1000` Tolerances: * `abs_tol::T` - Absolute tolerance for small residuals - Default is `eps(T)` * `rel_tol::T` - Relative tolerance used to measure first order criticality and consistency - Default is `sqrt(eps(T))` * `c_tol::T` - Tolerance used to measure feasability of the constraints - Default is `sqrt(eps(T))` * `x_tol::T` - Tolerance used to measure the distance between two consecutive iterates - Default is `sqrt(eps(T))` """ function solve!(model::CnlsModel{T}; silent::Bool=true, max_iter::Int=100, scaling::Bool=false, time_limit::T=1e3, abs_tol::T=eps(T), rel_tol::T=√abs_tol, c_tol::T=rel_tol, x_tol::T=rel_tol) where {T} # Internal scaling model.constraints_scaling = scaling # Evaluation functions residuals_evalfunc = (model.jacobian_residuals === nothing ? ResidualsFunction(model.residuals) : ResidualsFunction(model.residuals, model.jacobian_residuals)) if all(!isfinite,vcat(model.x_low, model.x_upp)) constraints_evalfunc = instantiate_constraints_wo_bounds(model.eq_constraints, model.jacobian_eqcons, model.ineq_constraints, model.jacobian_ineqcons) else constraints_evalfunc = instantiate_constraints_w_bounds(model.eq_constraints, model.jacobian_eqcons, model.ineq_constraints, model.jacobian_ineqcons, model.x_low, model.x_upp) end nb_constraints = total_nb_constraints(model) # Call the ENLSIP solver exit_code, x_opt, f_opt, enlsip_info = enlsip(model.starting_point, residuals_evalfunc, constraints_evalfunc, model.nb_parameters, model.nb_residuals, model.nb_eqcons, nb_constraints; scaling=scaling, MAX_ITER=max_iter, TIME_LIMIT=time_limit, ε_rel = rel_tol, ε_x = x_tol, ε_c = c_tol, ε_rank=√eps(T)) # Update of solution related fields in model model.model_info = enlsip_info model.status_code = convert_exit_code(exit_code) model.sol = x_opt model.obj_value = f_opt !silent && print_diagnosis(model) return end """ print_cnls_model(model,io) One can call this function to print information about an instance `model` (see [`CnlsModel`](@ref)). If `model` has just been instantiated but not solved, it will print general information about the model, such as the dimensions of the residuals, parameters and constraints. After calling the [`solve!`](@ref) method, the output will be enhanced with details about the iterations performed during the execution of the algorithm. The following info are also printed: * number of iterations * total number of function and Jacobian matrix evaluations for both residuals and contraints * solving time in seconds * value of the objective function found by the algorithm * termination status (see [`status`](@ref)) """ function print_cnls_model(model::CnlsModel, io::IO=stdout) model_status = status(model) if model_status == :unsolved print_initialized_model(model, io) else print_diagnosis(model, io) end end
Enlsip
https://github.com/UncertainLab/Enlsip.jl.git
[ "MIT" ]
0.9.7
8df29d512dca8aa40b391e645f9278bab4c09d10
code
7327
#= AbstractIteration{T<:AbstractFloat} Abstract type for later types defined to store data about an iteration of the Enlsip algorithm =# abstract type AbstractIteration{T<:AbstractFloat} end #= Iteration{T} <: AbstractIteration Summarizes the useful informations about an iteration of the Enlsip algorithm * `x` : Departure point of the iteration * `p` : Descent direction * `rx` : vector of size `m`, contains value of residuals at `x` * `cx` : vector of size `l`, contains value of constraints at `x` * `t` : Number of constraints in current working set (ie constraints considered active) * `α` : Value of steplength * `λ` : Vector of size `t`, containts Lagrange multipliers estimates * `rankA` : pseudo rank of matrix `A`, jacobian of active constraints * `rankJ2` : pseudo rank of matrix `J2`, block extracted from `J`, jacobian of residuals * `b_gn` : right handside of the linear system solved to compute first part of `p` * `d_gn` : right handside of the linear system solved to compute second part of `p` * `predicted_reduction` : predicted linear progress * `progress` : reduction in the objective function * `β` : scalar used to estimate convergence factor * `restart` : indicate if current iteration is a restart step or no * `first` : indicate if current iteration is the first one or no * `add` : indicate if a constraint has been added to the working set * `del` : indicate if a constraint has been deleted from the working set * `index_del` : index of the constraint that has been deleted from working set (`0` if no deletion) * `code` : Its value caracterizes the method used to compute the search direction `p` - `1` represents Gauss-Newton method - `-1` represents Subspace minimization - `2` represents Newton method * `nb_newton_steps` : number of search direction computed using the method of Newton =# mutable struct Iteration{T} <: AbstractIteration{T} x::Vector{T} p::Vector{T} rx::Vector{T} cx::Vector{T} t::Int α::T index_α_upp::Int λ::Vector{T} w::Vector{T} rankA::Int rankJ2::Int dimA::Int dimJ2::Int b_gn::Vector{T} d_gn::Vector{T} predicted_reduction::T progress::T grad_res::T speed::T β::T restart::Bool first::Bool add::Bool del::Bool index_del::Int code::Int nb_newton_steps::Int end Base.copy(s::Iteration) = Iteration(s.x, s.p, s.rx, s.cx, s.t, s.α, s.index_α_upp, s.λ, s.w, s.rankA, s.rankJ2, s.dimA, s.dimJ2, s.b_gn, s.d_gn, s.predicted_reduction, s.progress, s.grad_res, s.speed, s.β, s.restart, s.first, s.add, s.del, s.index_del, s.code, s.nb_newton_steps) #= DisplayedInfo{T} Contains the specific data on an iteration of Enlsip that are to be displayed in the execution details * objective : value of the objective function, i.e. sum of squared residuals * sqr_nrm_act_cons : sum of squared active constraints * nrm_p : norm of the search direction * α : value of steplength * reduction : reduction of the objective function at the end of the iteration =# struct DisplayedInfo{T} <: AbstractIteration{T} objective::T sqr_nrm_act_cons::T nrm_p::T α::T reduction::T end DisplayedInfo() = DisplayedInfo(0.0, 0.0, 0.0, 0.0, 0.0) #= Constraint Struct used to represent the active constraints Fields are the useful informations about active constraints at a point x : * `cx` : Vector of size t, contains values of constraints in current working set * `A` : Matrix of size `t` x `t`, jacobian matrix of constraints in current working set * `scaling` : Boolean indicating if internal scaling of `cx` and `A` is done * `diag_scale` : Vector of size `t`, contains the diagonal elements of the scaling matrix if internal scaling is done - The i-th element equals ``\\dfrac{1}{\\|\\nabla c_i(x)\\|}`` for ``i = 1,...,t``, which is the inverse of the length of `A` i-th row - Otherwise, it contains the length of each row in the matrix `A` =# mutable struct Constraint{T<:AbstractFloat} cx::Vector{T} A::Matrix{T} scaling::Bool diag_scale::Vector{T} end # EVSCAL # Scale jacobian matrix of active constraints A and active constraints evaluation vector cx if so indicated (ie if scale different from 0) by forming vectors : # diag*A and diag*cx # where diag is an array of dimension whose i-th element equals either ||∇c_i(x)|| or (1/||∇c_i(x)|) depending on wether scaling is done or not. # The vectors are formed by modifying in place matrix A and vector cx function evaluate_scaling!(C::Constraint) t = size(C.A, 1) ε_rel = eps(eltype(C.cx)) C.diag_scale = zeros(t) for i = 1:t row_i = norm(C.A[i, :]) C.diag_scale[i] = row_i if C.scaling if abs(row_i) < ε_rel row_i = 1.0 end C.A[i, :] /= row_i C.cx[i] /= row_i C.diag_scale[i] = 1.0 / row_i end end return end #= WorkingSet In ENLSIP, the working-set is a prediction of the set of active constraints at the solution It is updated at every iteration thanks to a Lagrangian multipliers estimation Fields of this structure summarize infos about the qualification of the constraints, i.e. : * `q` : number of equality constraints * `t` : number of constraints in current working set (all equalities and some inequalities considered to be active at the solution) * `l` : total number of constraints (i.e. equalities and inequalities) * active : - `Vector` of size `l` - first `t` elements are indeces of constraints in working set sorted in increasing order, other elements equal `0` * inactive : - `Vector` of size `l-q` - first `l-t` elements are indeces of constraints not in working set sorted in increasing order, other elements equal `0` =# mutable struct WorkingSet q::Int t::Int l::Int active::Vector{Int} inactive::Vector{Int} end #= Constructot for WorkingSet q : Number of equality constraints l : Number of inequality constraints Initial acticve set contains all equality constraints indices Initial inactive set contains all inequality constraints indices =# function WorkingSet(q::Int, l::Int) active = zeros(Int, l) inactive = zeros(Int, l-q) active[1:q] = [i for i=1:q] inactive[:] = [i for i=q+1:l] return WorkingSet(q, q, l, active, inactive) end # Equivalent Fortran : DELETE in dblreduns.f # Moves the active constraint number s to the inactive set function remove_constraint!(W::WorkingSet, s::Int) l, t = W.l, W.t # Ajout de la contrainte à l'ensemble inactif W.inactive[l-t+1] = W.active[s] sort!(@view W.inactive[1:l-t+1]) # Réorganisation de l'ensemble actif for i = s:t-1 W.active[i] = W.active[i+1] end W.active[t] = 0 W.t -= 1 return end # Equivalent Fortran : ADDIT in dblreduns.f # Add the inactive constraint number s to the active set function add_constraint!(W::WorkingSet, s::Int) l, t = W.l, W.t # s-th inactive constraint moved from inactive to active set W.active[t+1] = W.inactive[s] sort!(@view W.active[1:t+1]) # Inactive set reorganized for i = s:l-t-1 W.inactive[i] = W.inactive[i+1] end W.inactive[l-t] = 0 W.t += 1 return end
Enlsip
https://github.com/UncertainLab/Enlsip.jl.git
[ "MIT" ]
0.9.7
8df29d512dca8aa40b391e645f9278bab4c09d10
code
236
using Enlsip using Test include("internal/working_set.jl") include("internal/constraints.jl") include("problems/HS65.jl") include("problems/osborne2.jl") include("problems/chained_rosenbrock.jl") include("problems/chained_wood.jl")
Enlsip
https://github.com/UncertainLab/Enlsip.jl.git
[ "MIT" ]
0.9.7
8df29d512dca8aa40b391e645f9278bab4c09d10
code
1009
@testset "ConstraintsFunction structure" begin c(x::Vector) = [3x[1]^3 + 2x[2] - 5 + sin(x[1]-x[2]*sin(x[1]+x[2])), 4x[4] - x[3]*exp(x[3]-x[4]) - 3] x = zeros(4) c_func = Enlsip.ConstraintsFunction(c) @test c_func.nb_conseval == 0 && c_func.nb_jaccons_eval == 0 A = Matrix{Float64}(undef, 2,4) Enlsip.jaccons_eval!(c_func, x,A) @test c_func.nb_conseval == 0 && c_func.nb_jaccons_eval == 1 x_low = [-1.0, -Inf, -2.0, -Inf] x_upp = [Inf, Inf, 5.0, 10.0] f_bounds, jac_f_bounds = Enlsip.box_constraints(x_low, x_upp) @test Inf ∉ abs.(f_bounds(x)) @test eltype(jac_f_bounds(x)) <: AbstractFloat && all(isfinite, jac_f_bounds(x)) h_func = Enlsip.instantiate_constraints_w_bounds(c, nothing, nothing, nothing, x_low, x_upp) hx = Vector{Float64}(undef, 6) Ah = Matrix{Float64}(undef, 6, 4) Enlsip.cons_eval!(h_func, x, hx) Enlsip.jaccons_eval!(h_func, x, Ah) @test hx ≈ h_func.conseval(x) @test Ah ≈ h_func.jaccons_eval(x) end
Enlsip
https://github.com/UncertainLab/Enlsip.jl.git
[ "MIT" ]
0.9.7
8df29d512dca8aa40b391e645f9278bab4c09d10
code
1385
# Unitary tests for non exported functions in Enlsip.jl @testset "Working set structure tests" begin # Test with 5 equality constraints and 5 inequality constraints q1, l1 = 5, 10 wrkset1 = Enlsip.WorkingSet(q1, l1) # Initialization of the working set @test length(wrkset1.active) == l1 && length(wrkset1.inactive) == l1 - q1 @test wrkset1.t == q1 a1, d1 = 7, 10 Enlsip.add_constraint!(wrkset1, a1 - wrkset1.t) Enlsip.add_constraint!(wrkset1, d1- wrkset1.t) Enlsip.remove_constraint!(wrkset1, 7) @test a1 ∈ wrkset1.active && a1 ∉ wrkset1.inactive @test d1 ∉ wrkset1.active && d1 ∈ wrkset1.inactive @test wrkset1.t == q1 + 1 @test count(!=(0), wrkset1.active) + count(!=(0), wrkset1.inactive) == l1 # Test with no equality constraints and 8 inequality constraints q2, l2 = 0, 8 wrkset2 = Enlsip.WorkingSet(q2,l2) @test wrkset2.active == zeros(l2) && wrkset2.inactive == [i for i ∈ 1:l2] # Make constraints 1, 4, 5 and 8 active Enlsip.add_constraint!(wrkset2, 1) Enlsip.add_constraint!(wrkset2, 4-wrkset2.t) Enlsip.add_constraint!(wrkset2, 5-wrkset2.t) Enlsip.add_constraint!(wrkset2, 8-wrkset2.t) lmt = wrkset2.l - wrkset2.t @test wrkset2.t == 4 && lmt == 4 @test all(∈(wrkset2.active[1:wrkset2.t]), [1,4,5,8]) @test all(∈(wrkset2.inactive[1:lmt]), [2,3,6,7]) end
Enlsip
https://github.com/UncertainLab/Enlsip.jl.git
[ "MIT" ]
0.9.7
8df29d512dca8aa40b391e645f9278bab4c09d10
code
1452
@testset "Problem 65 from Hock Schittkowski collection" begin n = 3 m = 3 nb_eq = 0 nb_constraints = 7 r(x::Vector) = [x[1] - x[2]; (x[1]+x[2]-10.0) / 3.0; x[3]-5.0] jac_r(x::Vector) = [1. -1. 0; 1/3 1/3 0.; 0. 0. 1.] c(x::Vector) = [48.0 - x[1]^2-x[2]^2-x[3]^2] jac_c(x::Vector) = [ -2x[1] -2x[2] -2x[3]] x_l = [-4.5, -4.5, -5.0] x_u = [4.5, 4.5, 5.0] x0 = [-5.0, 5.0, 0.0] hs65_model = Enlsip.CnlsModel(r, n, m ;jacobian_residuals=jac_r, starting_point=x0, ineq_constraints = c, jacobian_ineqcons=jac_c, nb_ineqcons = 1, x_low=x_l, x_upp=x_u) solve!(hs65_model) @test size(x0,1) == hs65_model.nb_parameters @test r(x0) ≈ hs65_model.residuals(x0) @test jac_r(x0) ≈ hs65_model.jacobian_residuals(x0) @test vcat(c(x0),x0-x_l,x_u-x0) ≈ vcat(hs65_model.ineq_constraints(x0), x0-hs65_model.x_low, hs65_model.x_upp-x0) @test nb_constraints == total_nb_constraints(hs65_model) @test status(hs65_model) in values(dict_status_codes) @test typeof(solution(hs65_model)) <: Vector && size(solution(hs65_model),1) == n @test typeof(sum_sq_residuals(hs65_model)) <: Number && isfinite(sum_sq_residuals(hs65_model)) @test length(Enlsip.constraints_values(hs65_model)) == Enlsip.total_nb_constraints(hs65_model) @test Enlsip.constraints_values(hs65_model) ≈ [c(Enlsip.solution(hs65_model)); Enlsip.solution(hs65_model)-x_l; x_u-Enlsip.solution(hs65_model)] end
Enlsip
https://github.com/UncertainLab/Enlsip.jl.git
[ "MIT" ]
0.9.7
8df29d512dca8aa40b391e645f9278bab4c09d10
code
2242
@testset "Problem Chained Rosenbrock" begin n = 1000 m = 2(n-1) nb_eq = n-2 nb_constraints = n-2 function r(x::Vector) n = length(x) m = 2(n-1) rx = Vector{eltype(x)}(undef,m) rx[1:n-1] = [10(x[i]^2 - x[i+1]) for i=1:n-1] rx[n:m] = [x[k-n+1] - 1 for k=n:m] return rx end # Constraints function c(x::Vector) n = length(x) cx = [3x[k+1]^3 + 2x[k+2] - 5 + sin(x[k+1]-x[k+2])*sin(x[k+1]+x[k+2]) + 4x[k+1] - x[k]*exp(x[k]-x[k+1]) - 3 for k=1:n-2] return cx end function jac_res(x::Vector) n = size(x,1) m = 2(n-1) J = zeros(eltype(x), (m,n)) for i=1:n-1 J[i,i] = 20x[i] J[i,i+1] = -10 end for i=n:m J[i,i-n+1] = 1 end return J end function jac_cons(x::Vector) n = size(x,1) A = zeros(eltype(x), (n-2,n)) for k=1:n-2 A[k,k] = -(x[k]+1) * exp(x[k]-x[k+1]) A[k,k+1] = 9x[k+1]^2 + cos(x[k+1]-x[k+2])*sin(x[k+1]+x[k+2]) + sin(x[k+1]-x[k+2])*cos(x[k+1]+x[k+2]) + 4 + x[k]*exp(x[k]-x[k+1]) A[k,k+2] = 2 - cos(x[k+1]-x[k+2])*sin(x[k+1]+x[k+2]) + sin(x[k+1]-x[k+2])*cos(x[k+1]+x[k+2]) end return A end x0 = [(mod(i,2) == 1 ? -1.2 : 1.0) for i=1:n] Crmodel = CnlsModel(r,n,m; starting_point=x0, jacobian_residuals = jac_res, eq_constraints=c, jacobian_eqcons=jac_cons, nb_eqcons=nb_eq) solve!(Crmodel) @test size(x0,1) == Crmodel.nb_parameters @test r(x0) ≈ Crmodel.residuals(x0) @test jac_res(x0) ≈ Crmodel.jacobian_residuals(x0) @test c(x0) ≈ Crmodel.eq_constraints(x0) @test Crmodel.ineq_constraints === nothing @test all(!isfinite, Crmodel.x_low) && all(!isfinite, Crmodel.x_upp) @test nb_constraints == total_nb_constraints(Crmodel) @test status(Crmodel) in values(dict_status_codes) @test typeof(solution(Crmodel)) <: Vector && size(solution(Crmodel),1) == n @test typeof(sum_sq_residuals(Crmodel)) <: Number && isfinite(sum_sq_residuals(Crmodel)) # Time limit solve!(Crmodel; time_limit=-1.0) @test status(Crmodel) == dict_status_codes[-11] end
Enlsip
https://github.com/UncertainLab/Enlsip.jl.git
[ "MIT" ]
0.9.7
8df29d512dca8aa40b391e645f9278bab4c09d10
code
1082
@testset "ChainedWood problem for local Newton method" begin # Dimensions n = 20 # 1000 20, needs to be ≥ 8 m = 6 * (div(n,2)-1) nb_eq = n-7 nb_constraints = nb_eq # Residuals function r(x::Vector) n = length(x) N = div(n,2) - 1 s = √(10) rx1 = [10(x[2i-1]^2 - x[2i]) for i=1:N] rx2 = [x[2i-1] - 1 for i=1:N] rx3 = [3s*(x[2i+1]^2 - x[2i+2]) for i=1:N] rx4 = [x[2i+1]-1 for i=1:N] rx5 = [s*(x[2i] + x[2i+2] - 2) for i=1:N] rx6 = [(x[2i] - x[2i+2])*(1/s) for i=1:N] return [rx1;rx2;rx3;rx4;rx5;rx6] end # Constraints function c(x::Vector) n = length(x) cx = [(2+5x[k+5]^2)*x[k+5] + 1 + sum(x[i]*(1+x[i]) for i=max(k-5,1):k+1) for k=1:n-7] return cx end x0 = [(mod(i,2) == 1 ? -2. : 1.) for i=1:n] CW_model = CnlsModel(r,n,m; starting_point=x0, eq_constraints=c, nb_eqcons=nb_eq) solve!(CW_model; rel_tol=1e-5, x_tol = 1e-3, c_tol=1e-6) @test status(CW_model) in values(dict_status_codes) end
Enlsip
https://github.com/UncertainLab/Enlsip.jl.git
[ "MIT" ]
0.9.7
8df29d512dca8aa40b391e645f9278bab4c09d10
code
2776
@testset "Osborne 2: Box constrained problem" begin n = 11 m = 65 nb_eq = 0 nb_constraints = 22 # DataPoints dataset = [1 0.0 1.366; 2 0.1 1.191; 3 0.2 1.112; 4 0.3 1.013; 5 0.4 0.991; 6 0.5 0.885; 7 0.6 0.831; 8 0.7 0.847; 9 0.8 0.786; 10 0.9 0.725; 11 1.0 0.746; 12 1.1 0.679; 13 1.2 0.608; 14 1.3 0.655; 15 1.4 0.616; 16 1.5 0.606; 17 1.6 0.602; 18 1.7 0.626; 19 1.8 0.651; 20 1.9 0.724; 21 2.0 0.649; 22 2.1 0.649; 23 2.2 0.694; 24 2.3 0.644; 25 2.4 0.624; 26 2.5 0.661; 27 2.6 0.612; 28 2.7 0.558; 29 2.8 0.533; 30 2.9 0.495; 31 3.0 0.500; 32 3.1 0.423; 33 3.2 0.395; 34 3.3 0.375; 35 3.4 0.538; 36 3.5 0.522; 37 3.6 0.506; 38 3.7 0.490; 39 3.8 0.478; 40 3.9 0.467; 41 4.0 0.457; 42 4.1 0.457; 43 4.2 0.457; 44 4.3 0.457; 45 4.4 0.457; 46 4.5 0.457; 47 4.6 0.457; 48 4.7 0.457; 49 4.8 0.457; 50 4.9 0.457; 51 5.0 0.457; 52 5.1 0.431; 53 5.2 0.431; 54 5.3 0.424; 55 5.4 0.420; 56 5.5 0.414; 57 5.6 0.411; 58 5.7 0.406; 59 5.8 0.406; 60 5.9 0.406; 61 6.0 0.406; 62 6.1 0.406; 63 6.2 0.406; 64 6.3 0.406; 65 6.4 0.406] t = dataset[1:m,2] y = dataset[1:m,3] function r_k(x::Vector, t::T, y::T) where {T} rx = x[1]*exp(-x[5]*t) + x[2]*exp(-x[6]*(t-x[9])^2) + x[3]*exp(-x[7]*(t-x[10])^2) + x[4]*exp(-x[8]*(t-x[11])^2) return y - rx end r(x::Vector) = [r_k(x,t[k],y[k]) for k=1:m] low_bounds = [1.31, 0.4314, 0.6336, 0.5, 0.5, 0.6, 1.0, 4.0, 2.0, 4.5689, 5.0] upp_bounds = [1.4, 0.8, 1.0, 1.0, 1.0, 3.0, 5.0, 7.0, 2.5, 5.0, 6.0] # Saved starting point x0 = [1.3344098963722457 0.5572842161127423 0.6757364753061974 0.8291980513226953 0.9233565833014519 0.9588470511477797 1.9610314699563896 4.055321823656234 2.048625993866472 4.60296578920499 5.95212572157736] osborne2_model = Enlsip.CnlsModel(r,n,m; starting_point = x0, x_low = low_bounds, x_upp = upp_bounds) solve!(osborne2_model) bounds_values = Enlsip.constraints_values(osborne2_model) @test nb_upper_bounds(osborne2_model) == length(upp_bounds) && nb_lower_bounds(osborne2_model) == length(low_bounds) @test total_nb_constraints(osborne2_model) == nb_constraints @test osborne2_model.jacobian_residuals === nothing @test nb_equality_constraints(osborne2_model) == 0 && osborne2_model.eq_constraints === nothing @test nb_inequality_constraints(osborne2_model) == 0 && osborne2_model.ineq_constraints === nothing @test length(bounds_values) == length(low_bounds) + length(upp_bounds) end
Enlsip
https://github.com/UncertainLab/Enlsip.jl.git
[ "MIT" ]
0.9.7
8df29d512dca8aa40b391e645f9278bab4c09d10
docs
4529
# Enlsip.jl [![](https://img.shields.io/badge/docs-stable-green.svg)](https://uncertainlab.github.io/Enlsip.jl/stable/) [![](https://img.shields.io/badge/docs-dev-blue.svg)](https://uncertainlab.github.io/Enlsip.jl/dev/) Package `Enlsip.jl` is the Julia version of ENLSIP, an open source algorithm originally written in Fortran77 and designed to solve nonlinear least-squares problems subject to nonlinear constraints. The optimization method implemented in ENLSIP is described in > Per Lindström and Per-Åke Wedin, *Gauss Newton based algorithms for constrained nonlinear least squares problems*. > Technical Report S-901 87, Institute of Information processing, University of Umeå, Sweden, 1988. The source code of the Fortran77 library is available at [https://plato.asu.edu/sub/nonlsq.html](https://plato.asu.edu/sub/nonlsq.html). Problems that can be solved using `Enlsip.jl` are modeled as follows: ```math \begin{aligned} \min_{x \in \mathbb{R}^n} \quad & \dfrac{1}{2} \|r(x)\|^2 \\ \text{s.t.} \quad & c_i(x) = 0, \quad i \in \mathcal{E} \\ & c_i(x) \geq 0, \quad i \in \mathcal{I}, \\ & l_i \leq x_i \leq u_i, \quad i \in \{1,\ldots,n\}, \end{aligned} ``` where: * the residuals $r_i:\mathbb{R}^n\rightarrow\mathbb{R}$ and the constraints $c_i:\mathbb{R}^n\rightarrow\mathbb{R}$ are assumed to be $\mathcal{C}^2$ functions; * norm $\|\|\cdot\|\|$ denotes the Euclidean norm; * $l$ and $u$ are respectively vectors of lower and upper bounds. In the formulation above, bound constraints are written seperately but they are treated as classical inequality constraints in the method implemented in ENLSIP. ## How to install To add Enlsip, use Julia's package manager by typing the following command inside the REPL: ```julia using Pkg Pkg.add("Enlsip") ``` ## How to Use Solving a problem with Enlsip is organized in two steps. First, you need to create a model of your problem with the `CnlsModel` structure. ### Creating a model An object of type `CnlsModel` can be created using a constructor, whose arguments are the following: * `residuals` : function that computes the vector of residuals * `nb_parameters` : number of variables * `nb_residuals` : number of residuals * `stating_point` : initial solution * `jacobian_residuals` : function that computes the jacobian matrix of the residuals. If not passed as argument, it is computed numericcaly by forward differences * `eq_constraints` : function that computes the vector of equality constraints * `jacobian_eqcons` : function that computes the jacobian matrix of the equality constraints. If not passed as argument, it is computed numericcaly by forward differences * `nb_eqcons` : number of equality constraints * `ineq_constraints` : function that computes the vector of inequality constraints * `jacobian_ineqcons` : function that computes the jacobian matrix of the inequality constraints. If not passed as argument, it is computed numericcaly by forward differences * `nb_ineqcons` : number of inequality constraints * `x_low` and `x_upp` : respectively vectors of lower and upper bounds ### Solving a model Then, once your model is instantiated, you can call the `solve!` function to solve your problem. ### Example with problem 65 from Hock Schittkowski collection[^HS80] ```julia # Import Enlsip using Enlsip # Dimensions of the problem n = 3 # number of parameters m = 3 # number of residuals # Residuals and jacobian matrix associated r(x::Vector) = [x[1] - x[2]; (x[1]+x[2]-10.0) / 3.0; x[3]-5.0] jac_r(x::Vector) = [1. -1. 0; 1/3 1/3 0.; 0. 0. 1.] # Constraints (one nonlinear inequality and box constraints) c(x::Vector) = [48.0 - x[1]^2-x[2]^2-x[3]^2] jac_c(x::Vector) = [ -2x[1] -2x[2] -2x[3]] x_l = [-4.5, -4.5, -5.0] x_u = [4.5, 4.5, 5.0] # Starting point x0 = [-5.0, 5.0, 0.0] # Instantiate a model associated with the problem hs65_model = Enlsip.CnlsModel(r, n, m ;jacobian_residuals=jac_r, starting_point=x0, ineq_constraints = c, jacobian_ineqcons=jac_c, nb_ineqcons = 1, x_low=x_l, x_upp=x_u) # Call of the `solve!` function Enlsip.solve!(hs65_model) # Print solution and objective value println("Algorithm termination status: ", Enlsip.status(hs65_model)) println("Optimal solution: ", Enlsip.solution(hs65_model)) println("Optimal objective value: ", Enlsip.sum_sq_residuals(hs65_model)) ``` [^HS80]: W. Hock and K. Schittkowski. *Test Examples for Nonlinear Programming Codes*, volume 187 of Lecture Notes in Economics and Mathematical Systems. Springer, second edition, 1980.
Enlsip
https://github.com/UncertainLab/Enlsip.jl.git
[ "MIT" ]
0.9.7
8df29d512dca8aa40b391e645f9278bab4c09d10
docs
2252
# [Enlsip.jl documentation](@id Home) ## Introduction Package `Enlsip.jl` is the Julia version of an eponymous Fortran77 library (ENLSIP standing for Easy Nonlinear Least Squares Inequalities Program) designed to solve nonlinear least-squares problems under nonlinear constraints. The optimization method implemented in `Enlsip.jl` was conceived in the early 1980s by two Swedish authors named Per Lindström and Per Åke Wedin [^LW88]. It is designed for solve nonlinear least-squares problems subject to (s.t.) nonlinear constraints, which can be modeled as the following optimization problem: ```math \begin{aligned} \min_{x \in \mathbb{R}^n} \quad & \dfrac{1}{2} \|r(x)\|^2 \\ \text{s.t.} \quad & c_i(x) = 0, \quad i \in \mathcal{E} \\ & c_i(x) \geq 0, \quad i \in \mathcal{I}, \\ \end{aligned} ``` where: * the residuals $r_i:\mathbb{R}^n\rightarrow\mathbb{R}$ and the constraints $c_i:\mathbb{R}^n\rightarrow\mathbb{R}$ are assumed to be $\mathcal{C}^2$ functions; * norm $\|\cdot\|$ denotes the Euclidean norm. Note that box constraints are modeled as general inequality constraints. ## How to install To add Enlsip, use Julia's package manager by typing the following command inside the REPL: ```julia using Pkg Pkg.add("Enlsip") ``` ## How to use Using `Enlsip.jl` to solve optimization problems consists in, first, instantiating a model and then call the solver on it. Details and examples with problems from the literature can be found in the [Usage](@ref) page. ## Description of the algorithm `Enlsip.jl` incorporates an iterative method computing a first order critical point of the problem. A brief description of the method and the stopping criteria is given in [Method](@ref). ## Bug reports and contributions As this package is a conversion from Fortran77 to Julia, there might be some bugs that we did not encountered yet, so if you think you found one, you can open an [issue](https://github.com/UncertainLab/Enlsip.jl/issues) to report it. Issues can also be opened to discuss about eventual suggestions of improvement. [^LW88]: P. Lindström and P.Å. Wedin, *Gauss-Newton based algorithms for constrained nonlinear least squares problems* , Institute of Information processing, University of Umeå Sweden, 1988.
Enlsip
https://github.com/UncertainLab/Enlsip.jl.git
[ "MIT" ]
0.9.7
8df29d512dca8aa40b391e645f9278bab4c09d10
docs
6503
# [Method](@id Method) In this section, a brief description of the method implemented in `Enlsip.jl` is given. We recall that the problem to solve is of the form: ```math \begin{aligned} \min_{x \in \mathbb{R}^n} \quad & \dfrac{1}{2} \|r(x)\|^2 \\ \text{s.t.} \quad & c_i(x) = 0, \quad i \in \mathcal{E} \\ & c_i(x) \geq 0, \quad i \in \mathcal{I}, \\ \end{aligned} ``` with: * the residuals $r_i:\mathbb{R}^n\rightarrow\mathbb{R}$ and the constraints $c_i:\mathbb{R}^n\rightarrow\mathbb{R}$ assumed to be $\mathcal{C}^2$ functions; * norm $\|\cdot\|$ denotes the Euclidean norm. We introduce the Lagrangian associated to the problem: ```math L(x,\lambda) = \dfrac{1}{2} \|r(x)\|^2 - \sum_{i \in \mathcal{E} \cup \mathcal{I}} \lambda_i c_i(x), ``` where $\lambda = \left(\lambda_i\right)_{i\in \mathcal{E} \cup \mathcal{I}}$ denotes the vector of Lagrange multipliers. ## Conduct of the algorithm Starting from a point $x_0$, the algorithm builds a sequence $(x_k)_k$ converging to a first order critical point of the problem. At a given iteration $k$, a search direction $p_k\in\mathbb{R}^n$ and a steplength $\alpha_k\in[0,1]$ are computed such that the next step is $x_{k+1}:=x_k+\alpha_kp_k$. An estimate $\lambda_{k}\in\mathbb{R}^{|\mathcal{E}| + |\mathcal{I}|}$ of the vector of Lagrange multipliers is then computed and convergence is tested. ### Search direction The search direction is the solution of a subproblem derived from an approximation of the original problem. First, the residuals are linearized in a small neighborhood of current point $x_k$: $$r(x_k+p)\approx J_kp+r_k,$$ where $J_k$ denotes the Jacobian matrix of the residuals function evaluated at $x_k$ and $r_k:=r(x_k)$ . The resulting objective function of the subproblem corresponds to the Gauss-Newton approximation. The constraints of the subproblem are formed after a subset of the constraints of the original problem. It contains all the equality constraints but only the inequality constraints that are believed to be satisfied with equality at the solution. This subset, often denoted as the working set in the literature, is updated at every iteration and can be seen as a guess of the optimal active set. For more details on the active set strategy implemented in `Enlsip.jl`, see chapters 5 and 6 of *Practical Optimization*[^GMW82]. Noting $\hat{c}_k$ the vector of constraints in the working set evaluated at $x_k$ and $\hat{A}_k$ its Jacobian matrix, the subproblem is then given by: ```math \begin{aligned} \min_{p \in \mathbb{R}^n} \quad & \dfrac{1}{2} \|J_kp+r_k\|^2 \\ \text{s.t.} \quad & \hat{A}_kp + \hat{c}_k= 0. \end{aligned} ``` The subproblem is then solved by a null-space type method. ### Steplength The steplength aims to maintain feasibility of all of the constraints and to reduce the value of the objective function. In `Enlsip.jl`, this process involves an $\ell_2$-type merit function: $$\psi_2(x, \mu_k) = \dfrac{1}{2} \|r(x)\|^2 + \mu_k \sum_{i\in\mathcal{E}} c_i(x)^2+ \mu_k \sum_{i\in\mathcal{I}} \min(0,c_i(x))^2,$$ where the scalar $\mu_k > 0$ is a penalty parameter updated at every iteration. Steplength computation is performed by applying a linesearch method on function $\psi_2$. This consists in minimizing the merit function along the direction from $x_k$ to $x_k+p_k$ , i.e. finding $\alpha_k\in[0,1]$ such that $$\alpha_k \in \arg\min_{\alpha \in [0,1]} \psi_2(x_k+\alpha_kp_k, \mu_k).$$ The authors of the Fortran77 version of ENLSIP developed a linesearch method in which an approximate, but acceptable, minimizer of the merit function is computed[^LW84]. ### Lagrange multipliers estimate Components of $\lambda_k$ associated to the inequality constraints not in the working set are fixed to zero. The remaining multipliers, associated to the constraints in the working set, are estimated by the minimum norm solution of the KKT system obtained after cancelling the Lagrange multipliers corresponding to inactive inequality constraints (under strict complementarity). This results into computing the vector $\hat{\lambda}_k^{LS}$ such that: ```math \hat{\lambda}_k^{LS} \in \arg\min_v \|\hat{A}_k^T v - J_k^Tr_k\|^2. ``` Since this process does not depend from the computation of the search direction, the method implemented in `Enlsip.jl` can be qualified as a primal method. ## [Stopping criteria](@id Stopping) Termination criteria implemented in `Enlsip.jl` follow the conventions presented in chapter 8 of *Practical Optimization*[^GMW82]. From the Lagrange multipliers estimates $\lambda_k$, we define: * scalar $\sigma_{min}$: smallest Lagrange multiplier estimate corresponding to an inequality constraint in the working set; * scalar $\lambda_{max}$: Lagrange multiplier estimate of largest absolute value (among multipliers associated with equality and inequality constraints). The small positive constants `c_tol`, `rel_tol`, `x_tol` and `abs_tol` are user-specified tolerances. Default values used in `Enlsip.jl` are given in the [Usage](@ref) page (see function [`solve!`](@ref)). To qualify as a candidate solution, current iterate must first meet the following necessary conditions: * *Strict Complementarity*: Lagrange multipliers estimates of inequality constraints in the working set are stricly positive; * *Primal feasability*: $\|\hat{c}_k\| \leq$ `c_tol` and values of the inequality constraints not in the working set are strictly positive at $x_k$; * *First order criticality*: $\|\nabla_x L(x_k,\lambda_k)\| \leq$ `√rel_tol` $* \left(1+\|J^T_kr_k\|\right)$; * *Consistency*: $\sigma_{min} \geq$ `rel_tol`$* \lambda_{max}$. If all criteria above are satisfied, the algorithm stops if one of the following conditions is met: * *Small distance between the last two setps*: $\|x_{k+1}-x_k\|<$ `x_tol` $ *\|x_k\|$; * *Small residuals*: $\|r_k\|^2 \leq$ `abs_tol`. ### Convergence To our knowledge, there is no formal proof of convergence of the method described above, though local convergence with a linear rate is to be expected from the Gauss-Newton paradigm, provided that the initial point is close enough to the solution. Numerical tests confirmed that the efficiency of the method is influenced by the initial point. [^GMW82]: P.E. Gill, W. Murray and M.H. Wright, *Practical Optimization*, Academic Press, San Diego, CA, USA, 1982. [^LW84]: P. Lindström and P.Å. Wedin, *A new linesearch algorithm for nonlinear least squares problems*, Mathematical Programming, vol. 29(3), pages 268-296, 1984.
Enlsip
https://github.com/UncertainLab/Enlsip.jl.git
[ "MIT" ]
0.9.7
8df29d512dca8aa40b391e645f9278bab4c09d10
docs
116
# [Reference](@id Reference) ## Index ```@index Pages = ["reference.md"] ``` ```@autodocs Modules = [Enlsip] ```
Enlsip
https://github.com/UncertainLab/Enlsip.jl.git
[ "MIT" ]
0.9.7
8df29d512dca8aa40b391e645f9278bab4c09d10
docs
12343
# [Usage](@id Usage) ```@meta CurrentModule = Enlsip ``` ```@setup tutorial using Enlsip, JuMP, Ipopt ``` This section provides details on how to instantiate and solve a constrained least-squares problem with `Enlsip.jl` As a reminder from [Home](@ref), problems to solve are of the following form: ```math \begin{aligned} \min_{x \in \mathbb{R}^n} \quad & \dfrac{1}{2} \|r(x)\|^2 \\ \text{s.t.} \quad & c_i(x) = 0, \quad i \in \mathcal{E} \\ & c_i(x) \geq 0, \quad i \in \mathcal{I}, \\ \end{aligned} ``` with: * the residuals $r_i:\mathbb{R}^n\rightarrow\mathbb{R}$ and the constraints $c_i:\mathbb{R}^n\rightarrow\mathbb{R}$ assumed to be $\mathcal{C}^2$ functions; * norm $\|\cdot\|$ denoting the Euclidean norm. Note that with this formulation, bounds constraints are not distinguished from general inequality constraints. Though, for ease of use, they can be provided directly as vectors of lower and/or upper bounds (see [Instantiate](@ref)). It should be borne in mind, however, that the method implemented in `Enlsip.jl` has been conceived for nonlinear problems, as there is no other assumption made about the nature of the residuals and constraints functions, apart from being two-time continuously differentiable. The algorithm can still be used to solve linear least squares subject to linear constraints but it will not be as effective as other software where those aspects are taken into account in the design of the optimization method. ## [Instantiate a model](@id Instantiate) Solving a problem with Enlsip is organized in two steps. First, a model of type [`CnlsModel`](@ref) must be instantiated. The `CnlsModel` constructor requires the evaluation functions of residuals, constraints, their associated jacobian matrices and dimensions of the problem. Although the package enables one to create linear unconstrained least squares, it is recommended to use it on problems with nonlinear residuals and general constraints. The three following positional arguments are mandatory to create a model: * `residuals` : function that computes the vector of residuals * `nb_parameters` : number of variables * `nb_residuals` : number of residuals The following keyword arguments are optional and deal with constraints and Jacobian matrices. If the Jacobian matrix functions are not provided, they are computed numerically by forward differences using automatic differenciation[^Backend]. [^Backend]: `ForwardDiff.jl` [https://juliadiff.org/ForwardDiff.jl/stable/](https://juliadiff.org/ForwardDiff.jl/stable/) Argument | Details :---------------------|:---------------------------------------------- `starting_point` | initial solution (can be an infeasbile point) `jacobian_residuals` | function computing the Jacobian matrix of the residuals `eq_constraints` | function computing the equality constraints `jacobian_eqcons` | function computing the Jacobian matrix of the equality constraints `nb_eqcons` | number of equality constraints `ineq_constraints` | function computing the inequality constraints `jacobian_ineqcons` | function computing the Jacobian matrix of the inequality constraints `nb_ineqcons` | number of inequality constraints `x_low` | vector of lower bounds `x_upp` | vector of upper bounds It is assumed that the the different functions passed as arguments of the `CnlsModel` constructor are called `f(x)`, where `x` is a vector of `nb_parameters` elements and `f` is one of the functions `residuals`, `eq_constraints`, `jacobian_eqcons` etc. ## [Solving](@id Solving a model) Then, the `Enlsip` solver can be used by calling the [`solve!`](@ref) function on an instantiated model. One can pass keywords arguments to modify some options of the algorithm or adjust the tolerances. For the expression of the termination criteria, see [Method](@ref) page ([Stopping](@ref)). ```@docs Enlsip.solve! ``` Diagnosis of the conduct of the algorithm can be printed by either setting the `silent` keyword argument of the function [`solve!`](@ref) to `false` or by calling [`print_cnls_model`](@ref) after solving. Here are some details on how to read and understand the different columns of the output: Column | Description :------------------------------|:---------------------------------------------- `iter` | iteration number `objective` | value of the sum of squared residuals (i.e. objective function) at current point $\vert\vert$ `active_constraints` $\vert\vert^2$ | value of the sum of squared active constraints at current point $\vert\vert$ `p` $\vert\vert$ | norm of the search direction computed at current iteration $\alpha$ | value of the steplength computed at current iteration `reduction` | reduction in the objective function performed after moving to the next iterate One can get additional info about termination of the algorithm by calling one of the following functions: Name | :----------------------------| [`solution`](@ref) | [`status`](@ref) | [`constraints_values`](@ref) | [`sum_sq_residuals`](@ref) | ```@docs Enlsip.solution ``` ```@docs Enlsip.status ``` ```@docs Enlsip.constraints_values ``` ```@docs Enlsip.sum_sq_residuals ``` ## [Examples](@id Examples) ### Problem 65 from Hock and Schittkowski collection[^HS80] We show how to implement and solve the following problem: ```math \begin{aligned} \min_{x_1, x_2, x_3} \quad & (x_1-x_2)^2 + \dfrac{(x_1+x_2-10)^2}{9}+(x_3-5)^2 \\ \text{s.t.} \quad & 48-x_1^2-x_2^2-x_3^2 \geq 0\\ & -4.5\leq x_i \leq 4.5, \quad i=1,2\\ & -5 \leq x_3 \leq 5. \end{aligned}. ``` The expected optimal solution is $(3.650461821, 3.65046168, 4.6204170507)$. Associated value of objective function equals $0.9535288567$. First, we provide the dimensions of the problems. ```@example tutorial # Dimensions of the problem n = 3 # number of parameters m = 3 # number of residuals nothing # hide ``` Then, we define the functions required to compute the residuals, constraints, their respective jacobian matrices and a starting point. In this example, we use the starting point given in the reference[^HS80], i.e. $(-5, 5, 0)$ ```@example tutorial # Residuals and Jacobian matrix associated r(x::Vector) = [x[1] - x[2]; (x[1]+x[2]-10.0) / 3.0; x[3]-5.0] jac_r(x::Vector) = [1. -1. 0; 1/3 1/3 0.; 0. 0. 1.] # Constraints (one nonlinear inequality and box constraints) c(x::Vector) = [48.0 - x[1]^2-x[2]^2-x[3]^2] # evaluation function for the equality constraint jac_c(x::Vector) = [ -2x[1] -2x[2] -2x[3]] # Jacobian matrix of the equality constraint x_l = [-4.5, -4.5, -5.0] # lower bounds x_u = [4.5, 4.5, 5.0] # upper bounds # Starting point x0 = [-5.0, 5.0, 0.0] nothing # hide ``` A `CnlsModel` can now be instantiated. ```@example tutorial # Instantiate a model associated with the problem hs65_model = Enlsip.CnlsModel(r, n, m ;starting_point=x0, ineq_constraints = c, nb_ineqcons = 1, x_low=x_l, x_upp=x_u, jacobian_residuals=jac_r, jacobian_ineqcons=jac_c) nothing # hide ``` Finally, the `solve!` function can be called on our model. In this example, keyword arguments remain to default values. ```@example tutorial Enlsip.solve!(hs65_model) ``` Once `Enlsip` solver has been executed on our problem, a summary of the conduct of the algorithm can be printed by calling [`print_cnls_model`](@ref). ```@example tutorial Enlsip.print_cnls_model(hs65_model) ``` If one just wants to know about termination of the algorithm, calling [`status`](@ref) will tell if the problem has been successfully solved or not. ```@example tutorial Enlsip.status(hs65_model) ``` Then, calling [`solution`](@ref) and [`sum_sq_residuals`](@ref) will respectively return the optimal solution obtained and the value of objective function at that point. ```@example tutorial hs65_solution = Enlsip.solution(hs65_model) ``` ```@example tutorial hs65_objective = Enlsip.sum_sq_residuals(hs65_model) ``` The solution obtained is relatively close to the expected optimal solution, although it differs from more than the tolerance used. ```@example tutorial maximum(abs.(hs65_solution - [3.650461821, 3.65046168, 4.6204170507])) < sqrt(eps(Float64)) ``` However, the difference between the objective value obtained with `Enlsip` and the expected one does not exceed the default tolerance. ```@example tutorial abs(hs65_objective - 0.9535288567) < sqrt(eps(Float64)) ``` [^HS80]: W. Hock and K. Schittkowski. *Test Examples for Nonlinear Programming Codes*, volume 187 of Lecture Notes in Economics and Mathematical Systems. Springer, second edition, 1980. ### Chained Rosenbrock problem[^LV99] [^LV99]: L. Lukšan and J. Vlček. *Sparse and Partially Separable Test Problems for Unconstrained and Equality Constrained Optimization*. Technical report 767, 1999. We now consider the following problem: ```math \begin{aligned} \min_{x} \quad & \sum_{i=1}^{n-1} 100(x_i^2-x_{i+1})^2 + (x_i-1)^2 \\ \text{s.t.} \quad & 3x_{k+1}^3 + 2x_{k+2}+\sin(x_{k+1}-x_{k+2})\sin(x_{k+1}+x_{k+2})+4x_{k+1} - x_k\exp(x_k-x_{k+1}) - 8 = 0 \\ & k=1,\ldots, n-2, \end{aligned} ``` for a given natural number $n\geq 3$. In this example, we use $n=1000$. Though analytic Jacobians are easy to define, they will be passed as arguments in the model instantiation, so to let the algorithm use automatic differentiation. ```@example tutorial # Dimensions n = 1000 # Number of variables m = 2(n-1) # Number of residuals nb_eq = n-2 # Number of equality constraints # Residuals function r(x::Vector) n = length(x) m = 2(n-1) rx = Vector{eltype(x)}(undef,m) rx[1:n-1] = [10(x[i]^2 - x[i+1]) for i=1:n-1] rx[n:m] = [x[k-n+1] - 1 for k=n:m] return rx end # Constraints function c(x::Vector) n = length(x) cx = [3x[k+1]^3 + 2x[k+2] - 5 + sin(x[k+1]-x[k+2])*sin(x[k+1]+x[k+2]) + 4x[k+1] - x[k]*exp(x[k]-x[k+1]) - 3 for k=1:n-2] return cx end x0 = [(mod(i,2) == 1 ? -1.2 : 1.0) for i=1:n] # Starting point # Instantiation of the model cr_enlsip = CnlsModel(r,n,m; starting_point=x0, eq_constraints=c, nb_eqcons=nb_eq) # Solving Enlsip.solve!(cr_enlsip) # Show solving status Enlsip.status(cr_enlsip) ``` To give an insight on how the performance of the algorithm scales when dimensions increase, we give a table of the solving time obtained with different values of parameter `n`. For comparison purposes, the calculation times obtained with the Julia version of the [IPOPT](https://github.com/jump-dev/Ipopt.jl) general solver for nonlinear programming [^WB06] are also indicated. Both solvers were used with their respective default tolerances. With the same starting point, both solvers reach similar local solutions despite different stopping criteria. We show the modeling of the problem with [JuMP](https://jump.dev/JuMP.jl/stable/) and its solving with `IPOPT` for `n=1000`. ```@example tutorial cr_ipopt = Model(Ipopt.Optimizer); set_silent(cr_ipopt) @variable(cr_ipopt, x[i=1:n], start = x0[i]) for k=1:n-2 @NLconstraint(cr_ipopt, 3x[k+1]^3 + 2x[k+2] - 5 + sin(x[k+1]-x[k+2])*sin(x[k+1]+x[k+2]) + 4x[k+1] - x[k]*exp(x[k]-x[k+1]) - 3 == 0) end @NLobjective(cr_ipopt, Min, sum(100(x[i]^2 - x[i+1])^2 + (x[i]-1)^2 for i=1:n-1)) optimize!(cr_ipopt) termination_status(cr_ipopt) ``` The two solvers reach similar solutions. ```@example tutorial Enlsip.sum_sq_residuals(cr_enlsip) ≈ objective_value(cr_ipopt) ``` ```@example tutorial Enlsip.solution(cr_enlsip) ≈ value.(cr_ipopt[:x]) ``` The benchmark[^BT] of the solving times (in seconds) for `Enlsip.jl` and `Ipopt.jl` is given in the following table: Value of `n` | `Enlsip.jl` | `IPOPT` :-------------|:------------|-----------: `10` | `3.616e-4` | `2.703e-3` `100` | `3.322e-2` | `4.759e-3` `1000` | `2.325e0` | `2.520e-2` `5000` | `3.172e2` | `1.490e-1` [^BT]: The values shown in the table were obtained using the `@btime` macro from the [BenchmarkTools.jl](https://juliaci.github.io/BenchmarkTools.jl/stable/) package. [^WB06]: A. Wächter and L. Biegler, *On the implementation of an interior-point filter line-search algorithm for large-scale nonlinear programming*, Mathematical Programming, vol. 106(1), pages 25-57, 2006.
Enlsip
https://github.com/UncertainLab/Enlsip.jl.git
[ "MIT" ]
0.4.9
e592c828aabfbc829a55af6edbac589681bdf856
code
2077
module LocalSearchSolvers using Base.Threads using CompositionalNetworks using ConstraintDomains using Constraints using Dictionaries using Distributed using JSON using Lazy # Exports internal export constraint!, variable!, objective!, add!, add_var_to_cons!, add_value! export delete_value!, delete_var_from_cons!, domain, variable, constraint, objective export length_var, length_cons, constriction, draw, describe, get_variable export get_variables, get_constraint, get_constraints, get_objective, get_objectives export get_cons_from_var, get_vars_from_cons, get_domain, get_name, solution # export for CBLS.jl export _set_domain!, is_sat, max_domains_size, get_value, update_domain!, has_solution export set_option!, get_option, sense, sense! # Exports Model export model # Exports error/predicate/objective functions export o_dist_extrema, o_mincut # Exports Solver export solver, solve!, specialize, specialize!, Options, get_values, best_values export best_value, time_info, status # Include utils include("utils.jl") # Include model related files include("variable.jl") include("constraint.jl") include("objective.jl") include("model.jl") # Include solver state and pool of configurations related files include("configuration.jl") include("pool.jl") include("fluct.jl") include("state.jl") # Include strategies include("strategies/move.jl") include("strategies/neighbor.jl") include("strategies/objective.jl") include("strategies/parallel.jl") include("strategies/perturbation.jl") include("strategies/portfolio.jl") include("strategies/tabu.jl") # precede restart.jl include("strategies/restart.jl") include("strategies/selection.jl") include("strategies/solution.jl") include("strategies/termination.jl") include("strategy.jl") # meta strategy methods and structures # Include solvers include("options.jl") include("time_stamps.jl") include("solver.jl") include("solvers/sub.jl") include("solvers/meta.jl") include("solvers/lead.jl") include("solvers/main.jl") # Include usual objectives include("objectives/extrema.jl") include("objectives/cut.jl") end
LocalSearchSolvers
https://github.com/JuliaConstraints/LocalSearchSolvers.jl.git
[ "MIT" ]
0.4.9
e592c828aabfbc829a55af6edbac589681bdf856
code
773
mutable struct Configuration{T} solution::Bool value::Float64 values::Dictionary{Int, T} end is_solution(c) = c.solution get_value(c) = c.value get_error(c) = is_solution(c) ? 0.0 : get_value(c) get_values(c) = c.values get_value(c, x) = get_values(c)[x] set_value!(c, val) = c.value = val set_values!(c, values) = c.values = values set_sat!(c, b) = c.solution = b compute_cost(m, config::Configuration) = compute_cost(m, get_values(config)) compute_cost!(m, config::Configuration) = set_value!(config, compute_cost(m, config)) function Configuration(m::_Model, X) values = draw(m) val = compute_costs(m, values, X) sol = val ≈ 0.0 opt = sol && !is_sat(m) return Configuration(sol, opt ? compute_objective(m, values) : val, values) end
LocalSearchSolvers
https://github.com/JuliaConstraints/LocalSearchSolvers.jl.git
[ "MIT" ]
0.4.9
e592c828aabfbc829a55af6edbac589681bdf856
code
1238
""" Constraint{F <: Function} Structure to store an error function and the variables it constrains. """ struct Constraint{F <: Function} <: FunctionContainer f::F vars::Vector{Int} end function Constraint(F, c::Constraint{F2}) where {F2 <: Function} return Constraint{F}(c.f, c.vars) end """ _get_vars(c::Constraint) Returns the variables constrained by `c`. """ _get_vars(c::Constraint) = c.vars """ _add!(c::Constraint, x) Add the variable of indice `x` to `c`. """ _add!(c::Constraint, x) = push!(c.vars, x) """ _delete!(c::Constraint, x::Int) Delete `x` from `c`. """ _delete!(c::Constraint, x) = deleteat!(c.vars, findfirst(y -> y == x, c.vars)) """ _length(c::Constraint) Return the number of constrained variables by `c`. """ _length(c::Constraint) = length(c.vars) """ var::Int ∈ c::Constraint """ Base.in(var::Int, c::Constraint) = var ∈ c.vars """ constraint(f, vars) DOCSTRING """ function constraint(f, vars) b1 = hasmethod(f, NTuple{1, Any}, (:X,)) b2 = hasmethod(f, NTuple{1, Any}, (:do_not_use_this_kwarg_name,)) g = f if !b1 || b2 g = (x; X = nothing) -> f(x) end return Constraint(g, collect(Int == Int32 ? map(Int, vars) : vars)) end
LocalSearchSolvers
https://github.com/JuliaConstraints/LocalSearchSolvers.jl.git
[ "MIT" ]
0.4.9
e592c828aabfbc829a55af6edbac589681bdf856
code
594
struct Fluct cons::Dictionary{Int, Float64} vars::Dictionary{Int, Float64} Fluct(cons, vars) = new(zeros(cons), zeros(vars)) end function reset!(fluct) zeros! = d -> foreach(k -> set!(d, k, 0.0), keys(d)) zeros!(fluct.cons) zeros!(fluct.vars) end function copy_to!(fluct, cons, vars) foreach(k -> set!(fluct.cons, k, cons[k]), keys(cons)) foreach(k -> set!(fluct.vars, k, vars[k]), keys(vars)) end function copy_from!(fluct, cons, vars) foreach(k -> set!(cons, k, fluct.cons[k]), keys(cons)) foreach(k -> set!(vars, k, fluct.vars[k]), keys(vars)) end
LocalSearchSolvers
https://github.com/JuliaConstraints/LocalSearchSolvers.jl.git
[ "MIT" ]
0.4.9
e592c828aabfbc829a55af6edbac589681bdf856
code
14142
""" _Model{V <: Variable{<:AbstractDomain},C <: Constraint{<:Function},O <: Objective{<:Function}} A struct to model a problem as a set of variables, domains, constraints, and objectives. ``` struct _Model{V <: Variable{<:AbstractDomain},C <: Constraint{<:Function},O <: Objective{<:Function}} variables::Dictionary{Int,V} constraints::Dictionary{Int,C} objectives::Dictionary{Int,O} # counter to add new variables: vars, cons, objs max_vars::Ref{Int} max_cons::Ref{Int} max_objs::Ref{Int} # Bool to indicate if the _Model instance has been specialized (relatively to types) specialized::Ref{Bool} # Symbol to indicate the kind of model for specialized methods such as pretty printing kind::Symbol end ``` """ struct _Model{V <: Variable{<:AbstractDomain}, C <: Constraint{<:Function}, O <: Objective{<:Function}}# <: MOI.ModelLike variables::Dictionary{Int, V} constraints::Dictionary{Int, C} objectives::Dictionary{Int, O} # counter to add new variables: vars, cons, objs max_vars::Ref{Int} # TODO: UInt ? max_cons::Ref{Int} max_objs::Ref{Int} # Sense (min = 1, max = -1) sense::Ref{Int} # Bool to indicate if the _Model instance has been specialized (relatively to types) specialized::Ref{Bool} # Symbol to indicate the kind of model for specialized methods such as pretty printing kind::Symbol # Best known bound best_bound::Union{Nothing, Float64} # Time of construction (seconds) since epoch time_stamp::Float64 end """ model() Construct a _Model, empty by default. It is recommended to add the constraints, variables, and objectives from an empty _Model. The following keyword arguments are available, - `vars=Dictionary{Int,Variable}()`: collection of variables - `cons=Dictionary{Int,Constraint}()`: collection of constraints - `objs=Dictionary{Int,Objective}()`: collection of objectives - `kind=:generic`: the kind of problem modeled (useful for specialized methods such as pretty printing) """ function model(; vars = Dictionary{Int, Variable}(), cons = Dictionary{Int, Constraint}(), objs = Dictionary{Int, Objective}(), kind = :generic, best_bound = nothing ) max_vars = Ref(zero(Int)) max_cons = Ref(zero(Int)) max_objs = Ref(zero(Int)) sense = Ref(one(Int)) # minimization specialized = Ref(false) _Model(vars, cons, objs, max_vars, max_cons, max_objs, sense, specialized, kind, best_bound, time()) end """ _max_vars(m::M) where M <: Union{Model, AbstractSolver} Access the maximum variable id that has been attributed to `m`. """ _max_vars(m::_Model) = m.max_vars.x """ _max_cons(m::M) where M <: Union{Model, AbstractSolver} Access the maximum constraint id that has been attributed to `m`. """ _max_cons(m::_Model) = m.max_cons.x """ _max_objs(m::M) where M <: Union{Model, AbstractSolver} Access the maximum objective id that has been attributed to `m`. """ _max_objs(m::_Model) = m.max_objs.x _best_bound(m::_Model) = m.best_bound """ _inc_vars!(m::M) where M <: Union{Model, AbstractSolver} Increment the maximum variable id that has been attributed to `m`. """ _inc_vars!(m::_Model) = m.max_vars.x += 1 """ _inc_vars!(m::M) where M <: Union{Model, AbstractSolver} Increment the maximum constraint id that has been attributed to `m`. """ _inc_cons!(m::_Model) = m.max_cons.x += 1 """ _inc_vars!(m::M) where M <: Union{Model, AbstractSolver} Increment the maximum objective id that has been attributed to `m`. """ _inc_objs!(m::_Model) = m.max_objs.x += 1 """ get_variables(m::M) where M <: Union{Model, AbstractSolver} Access the variables of `m`. """ get_variables(m::_Model) = m.variables """ get_constraints(m::M) where M <: Union{Model, AbstractSolver} Access the constraints of `m`. """ get_constraints(m::_Model) = m.constraints """ get_objectives(m::M) where M <: Union{Model, AbstractSolver} Access the objectives of `m`. """ get_objectives(m::_Model) = m.objectives """ get_kind(m::M) where M <: Union{Model, AbstractSolver} Access the kind of `m`, such as `:sudoku` or `:generic` (default). """ get_kind(m::_Model) = m.kind """ get_variable(m::M, x) where M <: Union{Model, AbstractSolver} Access the variable `x`. """ get_variable(m::_Model, x) = get_variables(m)[x] """ get_constraint(m::M, c) where M <: Union{Model, AbstractSolver} Access the constraint `c`. """ get_constraint(m::_Model, c) = get_constraints(m)[c] """ get_objective(m::M, o) where M <: Union{Model, AbstractSolver} Access the objective `o`. """ get_objective(m::_Model, o) = get_objectives(m)[o] """ get_domain(m::M, x) where M <: Union{Model, AbstractSolver} Access the domain of variable `x`. """ get_domain(m::_Model, x) = get_domain(get_variable(m, x)) """ get_name(m::M, x) where M <: Union{Model, AbstractSolver} Access the name of variable `x`. """ get_name(::_Model, x) = "x$x" """ get_cons_from_var(m::M, x) where M <: Union{Model, AbstractSolver} Access the constraints restricting variable `x`. """ get_cons_from_var(m::_Model, x) = _get_constraints(get_variable(m, x)) """ get_vars_from_cons(m::M, c) where M <: Union{Model, AbstractSolver} Access the variables restricted by constraint `c`. """ get_vars_from_cons(m::_Model, c) = _get_vars(get_constraint(m, c)) """ get_time_stamp(m::M) where M <: Union{Model, AbstractSolver} Access the time (since epoch) when the model was created. This time stamp is for internal performance measurement. """ get_time_stamp(m::_Model) = m.time_stamp """ length_var(m::M, x) where M <: Union{Model, AbstractSolver} Return the domain length of variable `x`. """ length_var(m::_Model, x) = length(get_variable(m, x)) """ length_cons(m::M, c) where M <: Union{Model, AbstractSolver} Return the length of constraint `c`. """ length_cons(m::_Model, c) = _length(get_constraint(m, c)) """ length_objs(m::M) where M <: Union{Model, AbstractSolver} Return the number of objectives in `m`. """ length_objs(m::_Model) = length(get_objectives(m)) """ length_vars(m::M) where M <: Union{Model, AbstractSolver} Return the number of variables in `m`. """ length_vars(m::_Model) = length(get_variables(m)) """ length_cons(m::M) where M <: Union{Model, AbstractSolver} Return the number of constraints in `m`. """ length_cons(m::_Model) = length(get_constraints(m)) """ draw(m::M, x) where M <: Union{Model, AbstractSolver} Draw a random value of `x` domain. """ draw(m::_Model, x) = rand(get_variable(m, x)) draw(m::_Model, x, n) = rand(get_variable(m, x), n) """ constriction(m::M, x) where M <: Union{Model, AbstractSolver} Return the constriction of variable `x`. """ constriction(m::_Model, x) = _constriction(get_variable(m, x)) """ delete_value(m::M, x, val) where M <: Union{Model, AbstractSolver} Delete `val` from `x` domain. """ delete_value!(m::_Model, x, val) = delete!(get_variable(m, x), val) """ delete_var_from_cons(m::M, c, x) where M <: Union{Model, AbstractSolver} Delete `x` from the constraint `c` list of restricted variables. """ delete_var_from_cons!(m::_Model, c, x) = _delete!(get_constraint(m, c), x) """ add_value!(m::M, x, val) where M <: Union{Model, AbstractSolver} Add `val` to `x` domain. """ add_value!(m::_Model, x, val) = add!(get_variable(m, x), val) """ add_var_to_cons!(m::M, c, x) where M <: Union{Model, AbstractSolver} Add `x` to the constraint `c` list of restricted variables. """ add_var_to_cons!(m::_Model, c, x) = _add!(get_constraint(m, c), x) """ add!(m::M, x) where M <: Union{Model, AbstractSolver} add!(m::M, c) where M <: Union{Model, AbstractSolver} add!(m::M, o) where M <: Union{Model, AbstractSolver} Add a variable `x`, a constraint `c`, or an objective `o` to `m`. """ function add!(m::_Model, x::Variable) _inc_vars!(m) insert!(get_variables(m), _max_vars(m), x) end function add!(m::_Model, c::Constraint) _inc_cons!(m) insert!(get_constraints(m), _max_cons(m), c) foreach(x -> _add_to_constraint!(m.variables[x], _max_cons(m)), c.vars) end function add!(m::_Model, o::Objective) _inc_objs!(m) insert!(get_objectives(m), _max_objs(m), o) end """ variable!(m::M, d) where M <: Union{Model, AbstractSolver} Add a variable with domain `d` to `m`. """ function variable!(m::_Model, d = domain()) add!(m, variable(d)) return _max_vars(m) end """ constraint!(m::M, func, vars) where M <: Union{Model, AbstractSolver} Add a constraint with an error function `func` defined over variables `vars`. """ function constraint!(m::_Model, func, vars::V) where {V <: AbstractVector{<:Number}} add!(m, constraint(func, vars)) return _max_cons(m) end """ objective!(m::M, func) where M <: Union{Model, AbstractSolver} Add an objective evaluated by `func`. """ function objective!(m::_Model, func) add!(m, objective(func, "o" * string(_max_objs(m) + 1))) end """ describe(m::M) where M <: Union{Model, AbstractSolver} Describe the model. """ function describe(m::_Model) # TODO: rewrite _describe objectives = "" if Dictionaries.length(m.objectives) == 0 objectives = "Constraint Satisfaction Program (CSP)" else objectives = "Constraint Optimization Program (COP) with Objective(s)\n" objectives *= mapreduce( o -> "\t\t" * o.name * "\n", *, get_objectives(m); init = "")[1:(end - 1)] end variables = mapreduce( x -> "\t\tx$(x[1]): " * string(get_domain(x[2])) * "\n", *, pairs(m.variables); init = "" )[1:(end - 1)] constraints = mapreduce(c -> "\t\tc$(c[1]): " * string(c[2].vars) * "\n", *, pairs(m.constraints); init = "")[1:(end - 1)] str = """ _Model description $objectives Variables: $(length(m.variables)) $variables Constraints: $(length(m.constraints)) $constraints """ return str end """ is_sat(m::M) where M <: Union{Model, AbstractSolver} Return `true` if `m` is a satisfaction model. """ is_sat(m::_Model) = length_objs(m) == 0 """ is_specialized(m::M) where M <: Union{Model, AbstractSolver} Return `true` if the model is already specialized. """ function is_specialized(m::_Model) return m.specialized.x end """ specialize(m::M) where M <: Union{Model, AbstractSolver} Specialize the structure of a model to avoid dynamic type attribution at runtime. """ function specialize(m::_Model) vars_types = Set{Type}() cons_types = Set{Type}() objs_types = Set{Type}() foreach(x -> push!(vars_types, typeof(x.domain)), get_variables(m)) foreach(c -> push!(cons_types, typeof(c.f)), get_constraints(m)) foreach(o -> push!(objs_types, typeof(o.f)), get_objectives(m)) vars_union = _to_union(vars_types) cons_union = _to_union(cons_types) objs_union = _to_union(objs_types) vars = similar(get_variables(m), Variable{vars_union}) cons = similar(get_constraints(m), Constraint{cons_union}) objs = similar(get_objectives(m), Objective{objs_union}) foreach(x -> vars[x] = Variable(vars_union, get_variable(m, x)), keys(vars)) foreach(c -> cons[c] = Constraint(cons_union, get_constraint(m, c)), keys(cons)) foreach(o -> objs[o] = Objective(objs_union, get_objective(m, o)), keys(objs)) max_vars = Ref(_max_vars(m)) max_cons = Ref(_max_cons(m)) max_objs = Ref(_max_objs(m)) specialized = Ref(true) _Model(vars, cons, objs, max_vars, max_cons, max_objs, m.sense, specialized, get_kind(m), _best_bound(m), get_time_stamp(m)) end """ _is_empty(m::Model) DOCSTRING """ function _is_empty(m::_Model) return length_objs(m) + length_vars(m) == 0 end """ _set_domain!(m::Model, x, values) DOCSTRING # Arguments: - `m`: DESCRIPTION - `x`: DESCRIPTION - `values`: DESCRIPTION """ function _set_domain!(m::_Model, x, values) d = domain(values) m.variables[x] = Variable(d, get_cons_from_var(m, x)) end function _set_domain!(m::_Model, x, a::Tuple, b::Tuple) d = domain(a, b) m.variables[x] = Variable(d, get_cons_from_var(m, x)) end # function _set_domain!(m::_Model, x,r::R) where {R <: AbstractRange} # d = domain(r) # m.variables[x] = Variable(d, get_cons_from_var(m, x)) # end function _set_domain!(m::_Model, x, d::D) where {D <: AbstractDomain} m.variables[x] = Variable(d, get_cons_from_var(m, x)) end """ domain_size(m::Model, x) = begin DOCSTRING """ domain_size(m::_Model, x) = domain_size(get_variable(m, x)) """ max_domains_size(m::Model, vars) = begin DOCSTRING """ max_domains_size(m::_Model, vars) = maximum(map(x -> domain_size(m, x), vars)) """ empty!(m::Model) DOCSTRING """ function Base.empty!(m::_Model) empty!(m.variables) empty!(m.constraints) empty!(m.objectives) m.max_vars[] = 0 m.max_cons[] = 0 m.max_objs[] = 0 m.specialized[] = false end # Non modificating cost and objective computations draw(m::_Model) = map(rand, get_variables(m)) compute_cost(c::Constraint, values, X) = apply(c, map(x -> values[x], c.vars), X) function compute_costs(m, values, X) return sum(c -> compute_cost(c, values, X), get_constraints(m); init = 0.0) end function compute_costs(m, values, cons, X) return sum(c -> compute_cost(c, values, X), view(get_constraints(m), cons); init = 0.0) end compute_objective(m, values; objective = 1) = apply(get_objective(m, objective), values) function update_domain!(m, x, d) if isempty(get_variable(m, x)) old_d = get_variable(m, x).domain _set_domain!(m, x, d.domain) else old_d = get_variable(m, x).domain are_continuous = typeof(d) <: ContinuousDomain && typeof(old_d) <: ContinuousDomain new_d = if are_continuous intersect_domains(old_d, d) else intersect_domains(convert(RangeDomain, old_d), convert(RangeDomain, d)) end _set_domain!(m, x, new_d) end end sense(m::_Model) = m.sense[] sense!(m::_Model, ::Val{:min}) = m.sense[] = 1 sense!(m::_Model, ::Val{:max}) = m.sense[] = -1
LocalSearchSolvers
https://github.com/JuliaConstraints/LocalSearchSolvers.jl.git
[ "MIT" ]
0.4.9
e592c828aabfbc829a55af6edbac589681bdf856
code
681
""" Objective{F <: Function} A structure to handle objectives in a solver. ``` struct Objective{F <: Function} name::String f::F end ```` """ struct Objective{F <: Function} <: FunctionContainer name::String f::F end """ Objective(F, o::Objective{F2}) where {F2 <: Function} Constructor used in specializing a solver. Should never be called externally. """ function Objective(F, o::Objective{F2}) where {F2 <: Function} return Objective{F}(o.name, o.f) end """ objective(func, name) Construct an objective with a function `func` that should be applied to a collection of variables. """ function objective(func, name) Objective(name, func) end
LocalSearchSolvers
https://github.com/JuliaConstraints/LocalSearchSolvers.jl.git
[ "MIT" ]
0.4.9
e592c828aabfbc829a55af6edbac589681bdf856
code
6697
const print_levels = Dict( :silent => 0, :minimal => 1, :partial => 2, :verbose => 3 ) """ Options() # Arguments: - `dynamic::Bool`: is the model dynamic? - `iteration::Union{Int, Float64}`: limit on the number of iterations - `print_level::Symbol`: verbosity to choose among `:silent`, `:minimal`, `:partial`, `:verbose` - `solutions::Int`: number of solutions to return - `specialize::Bool`: should the types of the model be specialized or not. Usually yes for static problems. For dynamic in depends if the user intend to introduce new types. The specialized model is about 10% faster. - `tabu_time::Int`: DESCRIPTION - `tabu_local::Int`: DESCRIPTION - `tabu_delta::Float64`: DESCRIPTION - `threads::Int`: Number of threads to use - `time_limit::Float64`: time limit in seconds - `function Options(; dynamic = false, iteration = 10000, print_level = :minimal, solutions = 1, specialize = !dynamic, tabu_time = 0, tabu_local = 0, tabu_delta = 0.0, threads = typemax(0), time_limit = Inf) ```julia # Setting options in JuMP syntax: print_level, time_limit, iteration model = Model(CBLS.Optimizer) set_optimizer_attribute(model, "iteration", 100) set_optimizer_attribute(model, "print_level", :verbose) set_time_limit_sec(model, 5.0) ``` """ mutable struct Options dynamic::Bool info_path::String iteration::Tuple{Bool, Union{Int, Float64}} print_level::Symbol process_threads_map::Dict{Int, Int} solutions::Int specialize::Bool tabu_time::Int tabu_local::Int tabu_delta::Float64 time_limit::Tuple{Bool, Float64} # seconds function Options(; dynamic = false, info_path = "", iteration = (false, 100), print_level = :minimal, process_threads_map = Dict{Int, Int}(1 => typemax(0)), solutions = 1, specialize = !dynamic, tabu_time = 0, tabu_local = 0, tabu_delta = 0.0, time_limit = (false, 1.0) # seconds ) ds_str = "The model types are specialized to the starting domains, constraints," * " and objectives types. Dynamic elements that add a new type will raise an error!" dynamic && specialize && @warn ds_str notds_str = "The solver types are not specialized in a static model context," * " which is sub-optimal." !dynamic && !specialize && @info notds_str itertime_str = "Both iteration and time limits are disabled. " * "Optimization runs will run infinitely." new_iteration = if iteration isa Tuple{Bool, Union{Int, Float64}} iteration else iteration = (false, iteration) end new_time_limit = if time_limit isa Tuple{Bool, Float64} time_limit else time_limit = (false, time_limit) end new_iteration[2] == Inf && new_time_limit[2] == Inf && @warn itertime_str new( dynamic, info_path, new_iteration, print_level, process_threads_map, solutions, specialize, tabu_time, tabu_local, tabu_delta, new_time_limit ) end end """ _verbose(settings, str) Temporary logging function. #TODO: use better log instead (LoggingExtra.jl) """ function _verbose(options, str) pl = options.print_level print_levels[pl] ≥ 3 && (@info str) end """ _dynamic(options) = begin DOCSTRING """ _dynamic(options) = options.dynamic """ _dynamic!(options, dynamic) = begin DOCSTRING """ _dynamic!(options, dynamic) = options.dynamic = dynamic """ _info_path(options, path) DOCSTRING """ _info_path(options) = options.info_path """ _info_path!(options, iterations) = begin DOCSTRING """ _info_path!(options, path) = options.info_path = path """ _iteration(options) = begin DOCSTRING """ _iteration(options) = options.iteration """ _iteration!(options, iterations) = begin DOCSTRING """ _iteration!(options, iterations) = options.iteration = iterations function _iteration!(options, iterations::Union{Int, Float64}) options.iteration = (false, iterations) end """ _print_level(options) = begin DOCSTRING """ _print_level(options) = options.print_level """ _print_level!(options, level) = begin DOCSTRING """ _print_level!(options, level) = options.print_level = level """ _process_threads_map(options) TBW """ _process_threads_map(options) = options.process_threads_map """ _process_threads_map!(options, ptm) TBW """ _process_threads_map!(options, ptm::AbstractDict) = options.process_threads_map = ptm function _process_threads_map!(options, ptm::AbstractVector) return _process_threads_map!(options, Dict(enumerate(ptm))) end """ _solutions(options) = begin DOCSTRING """ _solutions(options) = options.solutions """ _solutions!(options, solutions) = begin DOCSTRING """ _solutions!(options, solutions) = options.solutions = solutions """ _specialize(options) = begin DOCSTRING """ _specialize(options) = options.specialize """ _specialize!(options, specialize) = begin DOCSTRING """ _specialize!(options, specialize) = options.specialize = specialize """ _tabu_time(options) = begin DOCSTRING """ _tabu_time(options) = options.tabu_time """ _tabu_time!(options, time) = begin DOCSTRING """ _tabu_time!(options, time) = options.tabu_time = time """ _tabu_local(options) = begin DOCSTRING """ _tabu_local(options) = options.tabu_local """ _tabu_local!(options, time) = begin DOCSTRING """ _tabu_local!(options, time) = options.tabu_local = time """ _tabu_delta(options) = begin DOCSTRING """ _tabu_delta(options) = options.tabu_delta """ _tabu_delta!(options, time) = begin DOCSTRING """ _tabu_delta!(options, time) = options.tabu_delta = time """ _threads(options) = begin DOCSTRING """ _threads(options, p = 1) = get!(options.process_threads_map, p, typemax(0)) """ _threads!(options, threads) = begin DOCSTRING """ _threads!(options, threads, p = 1) = push!(options.process_threads_map, p => threads) """ _time_limit(options) DOCSTRING """ _time_limit(options) = options.time_limit """ _time_limit!(options, time::Time) = begin DOCSTRING """ _time_limit!(options, time::Tuple{Bool, Float64}) = options.time_limit = time _time_limit!(options, time::Float64) = options.time_limit = (false, time) function set_option!(options, name, value) eval(Symbol("_" * name * "!"))(options, value) end function get_option(options, name, args...) eval(Symbol("_" * name))(options, args...) end
LocalSearchSolvers
https://github.com/JuliaConstraints/LocalSearchSolvers.jl.git
[ "MIT" ]
0.4.9
e592c828aabfbc829a55af6edbac589681bdf856
code
919
abstract type AbstractPool end struct EmptyPool end @enum PoolStatus empty_pool=0 halfway_pool unsat_pool mixed_pool full_pool mutable struct _Pool{T} <: AbstractPool best::Int configurations::Vector{Configuration{T}} status::PoolStatus value::Float64 end const Pool = Union{EmptyPool, _Pool} pool() = EmptyPool() function pool(config::Configuration) best = 1 configs = [deepcopy(config)] status = full_pool value = get_value(config) return _Pool(best, configs, status, value) end function pool!(s) has_solution(s) || _draw!(s) s.pool = pool(s.state.configuration) end is_empty(::EmptyPool) = true is_empty(pool) = isempty(pool.configurations) best_config(pool) = pool.configurations[pool.best] best_value(pool) = pool.value best_values(pool) = get_values(best_config(pool)) has_solution(::EmptyPool) = false has_solution(pool::_Pool) = is_solution(best_config(pool))
LocalSearchSolvers
https://github.com/JuliaConstraints/LocalSearchSolvers.jl.git
[ "MIT" ]
0.4.9
e592c828aabfbc829a55af6edbac589681bdf856
code
15096
""" AbstractSolver Abstract type to encapsulate the different solver types such as `Solver` or `_SubSolver`. """ abstract type AbstractSolver end # Dummy method to (not) add a TimeStamps to a solver add_time!(::AbstractSolver, i) = nothing function solver(ms, id, role; pool = pool(), strats = MetaStrategy(ms)) mlid = make_id(meta_id(ms), id, Val(role)) return solver(mlid, ms.model, ms.options, pool, ms.rc_report, ms.rc_sol, ms.rc_stop, strats, Val(role)) end # Forwards from model field @forward AbstractSolver.model add! @forward AbstractSolver.model add_value! @forward AbstractSolver.model add_var_to_cons! @forward AbstractSolver.model constraint! @forward AbstractSolver.model constriction @forward AbstractSolver.model delete_value! @forward AbstractSolver.model delete_var_from_cons! @forward AbstractSolver.model describe @forward AbstractSolver.model domain_size @forward AbstractSolver.model draw @forward AbstractSolver.model get_cons_from_var @forward AbstractSolver.model get_constraint @forward AbstractSolver.model get_constraints @forward AbstractSolver.model get_domain @forward AbstractSolver.model get_name @forward AbstractSolver.model get_objective @forward AbstractSolver.model get_objectives @forward AbstractSolver.model get_variable @forward AbstractSolver.model get_variables @forward AbstractSolver.model get_vars_from_cons @forward AbstractSolver.model is_sat @forward AbstractSolver.model is_specialized @forward AbstractSolver.model length_cons @forward AbstractSolver.model length_objs @forward AbstractSolver.model length_var @forward AbstractSolver.model length_vars @forward AbstractSolver.model max_domains_size @forward AbstractSolver.model objective! @forward AbstractSolver.model sense @forward AbstractSolver.model sense! @forward AbstractSolver.model state @forward AbstractSolver.model update_domain! @forward AbstractSolver.model variable! @forward AbstractSolver.model _best_bound @forward AbstractSolver.model _inc_cons! @forward AbstractSolver.model _is_empty @forward AbstractSolver.model _max_cons @forward AbstractSolver.model _set_domain! # Forwards from state field @forward AbstractSolver.state get_error @forward AbstractSolver.state get_value @forward AbstractSolver.state get_values @forward AbstractSolver.state set_error! @forward AbstractSolver.state set_value! @forward AbstractSolver.state _best @forward AbstractSolver.state _best! @forward AbstractSolver.state _cons_cost @forward AbstractSolver.state _cons_cost! @forward AbstractSolver.state _cons_costs @forward AbstractSolver.state _cons_costs! @forward AbstractSolver.state _inc_last_improvement! @forward AbstractSolver.state _last_improvement @forward AbstractSolver.state _optimizing @forward AbstractSolver.state _optimizing! @forward AbstractSolver.state _satisfying! @forward AbstractSolver.state _set! @forward AbstractSolver.state _solution @forward AbstractSolver.state _swap_value! @forward AbstractSolver.state _reset_last_improvement! @forward AbstractSolver.state _value @forward AbstractSolver.state _value! @forward AbstractSolver.state _values @forward AbstractSolver.state _values! @forward AbstractSolver.state _var_cost @forward AbstractSolver.state _var_cost! @forward AbstractSolver.state _vars_costs @forward AbstractSolver.state _vars_costs! # Forward from options @forward AbstractSolver.options get_option @forward AbstractSolver.options set_option! @forward AbstractSolver.options _verbose # Forwards from pool (of solutions) @forward AbstractSolver.pool best_config @forward AbstractSolver.pool best_value @forward AbstractSolver.pool best_values @forward AbstractSolver.pool has_solution # Forwards from strategies @forward AbstractSolver.strategies check_restart! @forward AbstractSolver.strategies decay_tabu! @forward AbstractSolver.strategies decrease_tabu! @forward AbstractSolver.strategies delete_tabu! @forward AbstractSolver.strategies empty_tabu! @forward AbstractSolver.strategies insert_tabu! @forward AbstractSolver.strategies length_tabu @forward AbstractSolver.strategies tabu_list """ specialize!(solver) Replace the model of `solver` by one with specialized types (variables, constraints, objectives). """ specialize!(s) = s.model = specialize(s.model) """ _draw!(s) Draw a random (re-)starting configuration. """ function _draw!(s) foreach(x -> _set!(s, x, draw(s, x)), keys(get_variables(s))) end """ _compute_cost!(s, ind, c) Compute the cost of constraint `c` with index `ind`. """ function _compute_cost!(s, ind, c) old_cost = _cons_cost(s, ind) new_cost = compute_cost(c, _values(s), s.state.icn_computations) _cons_cost!(s, ind, new_cost) foreach(x -> _var_cost!(s, x, _var_cost(s, x) + new_cost - old_cost), c.vars) end """ _compute_costs!(s; cons_lst::Indices{Int} = Indices{Int}()) Compute the cost of constraints `c` in `cons_lst`. If `cons_lst` is empty, compute the cost for all the constraints in `s`. """ function _compute_costs!(s; cons_lst = Indices{Int}()) if isempty(cons_lst) foreach(((id, c),) -> _compute_cost!(s, id, c), pairs(get_constraints(s))) else foreach( ((id, c),) -> _compute_cost!(s, id, c), pairs(view(get_constraints(s), cons_lst)) ) end set_error!(s, sum(_cons_costs(s))) end """ _compute_objective!(s, o::Objective) _compute_objective!(s, o = 1) Compute the objective `o`'s value. """ function _compute_objective!(s, o::Objective) val = sense(s) * apply(o, _values(s).values) set_value!(s, val) if is_empty(s.pool) || val < best_value(s) s.pool = pool(s.state.configuration) end end _compute_objective!(s, o = 1) = _compute_objective!(s, get_objective(s, o)) """ _compute!(s; o::Int = 1, cons_lst = Indices{Int}()) Compute the objective `o`'s value if `s` is satisfied and return the current `error`. # Arguments: - `s`: a solver - `o`: targeted objective - `cons_lst`: list of targeted constraints, if empty compute for the whole set """ function _compute!(s; o::Int = 1, cons_lst = Indices{Int}()) _compute_costs!(s; cons_lst) if get_error(s) == 0.0 _optimizing(s) && _compute_objective!(s, o) is_sat(s) && (s.pool = pool(s.state.configuration)) return true end return false end """ _neighbours(s, x, dim = 0) DOCSTRING # Arguments: - `s`: DESCRIPTION - `x`: DESCRIPTION - `dim`: DESCRIPTION """ function _neighbours(s, x, dim = 0) if dim == 0 is_discrete = typeof(get_variable(s, x).domain) <: ContinuousDomain return is_discrete ? map(_ -> draw(s, x), 1:(length_vars(s) * length_cons(s))) : get_domain(s, x) else neighbours = Set{Int}() foreach( c -> foreach( y -> begin b = _value(s, x) ∈ get_variable(s, y) && _value(s, y) ∈ get_variable(s, x) b && push!(neighbours, y) end, get_vars_from_cons(s, c)), get_cons_from_var(s, x) ) return delete!(neighbours, x) end end state!(s) = s.state = state(s) function _init!(s, ::Val{:global}) if !is_specialized(s) && get_option(s, "specialize") specialize!(s) set_option!(s, "specialize", true) end put!(s.rc_stop, nothing) foreach(i -> put!(s.rc_report, nothing), setdiff(workers(), [1])) end function _init!(s, ::Val{:meta}) t = min(get_option(s, "threads"), Threads.nthreads()) foreach(id -> push!(s.subs, solver(s, id - 1, :sub)), 2:t) return nothing end function _init!(s, ::Val{:remote}) for w in setdiff(workers(), [1]) ls = remotecall(solver, w, s, w, :lead) remote_do(set_option!, w, fetch(ls), "print_level", :silent) t = min(get_option(s, "threads", w), remotecall_fetch(Threads.nthreads, w)) remote_do(set_option!, w, fetch(ls), "threads", t) push!(s.remotes, w => ls) end end function _init!(s, ::Val{:local}) get_option(s, "tabu_time") == 0 && set_option!(s, "tabu_time", length_vars(s) ÷ 2) # 10? get_option(s, "tabu_local") == 0 && set_option!(s, "tabu_local", get_option(s, "tabu_time") ÷ 2) get_option(s, "tabu_delta") == 0 && set_option!( s, "tabu_delta", get_option(s, "tabu_time") - get_option(s, "tabu_local")) # 20-30 state!(s) pool!(s) return has_solution(s) end _init!(s, role::Symbol) = _init!(s, Val(role)) """ _restart!(s, k = 10) Restart a solver. """ function _restart!(s, k = 10) _verbose(s, "\n============== RESTART!!!!================\n") _draw!(s) empty_tabu!(s) δ = ((k - 1) * get_option(s, "tabu_delta")) + get_option(s, "tabu_time") / k set_option!(s, "tabu_delta", δ) (_compute!(s) && !is_sat(s)) ? _optimizing!(s) : _satisfying!(s) end """ _check_restart(s) Check if a restart of `s` is necessary. If `s` has subsolvers, this check is independent for all of them. """ function _check_restart(s) a = _last_improvement(s) > length_vars(s) b = check_restart!(s; tabu_length = length_tabu(s)) return a || b end """ _select_worse(s::S) where S <: Union{_State, AbstractSolver} Within the non-tabu variables, select the one with the worse error . """ function _select_worse(s) nontabu = setdiff(keys(_vars_costs(s)), keys(tabu_list(s))) return _find_rand_argmax(view(_vars_costs(s), nontabu)) end """ _move!(s, x::Int, dim::Int = 0) Perform an improving move in `x` neighbourhood if possible. # Arguments: - `s`: a solver of type S <: AbstractSolver - `x`: selected variable id - `dim`: describe the dimension of the considered neighbourhood """ function _move!(s, x::Int, dim::Int = 0) best_values = [begin old_v = _value(s, x) end] best_swap = [x] tabu = true # unless proved otherwise, this variable is now tabu best_cost = old_cost = get_error(s) copy_to!(s.state.fluct, _cons_costs(s), _vars_costs(s)) for v in _neighbours(s, x, dim) dim == 0 && v == old_v && continue dim == 0 ? _value!(s, x, v) : _swap_value!(s, x, v) _verbose(s, "Compute costs: selected var(s) x_$x " * (dim == 0 ? "= $v" : "⇆ x_$v")) cons_x_v = union(get_cons_from_var(s, x), dim == 0 ? [] : get_cons_from_var(s, v)) _compute!(s, cons_lst = cons_x_v) cost = get_error(s) if cost < best_cost _verbose(s, "cost = $cost < $best_cost") tabu = false best_cost = cost dim == 0 ? best_values = [v] : best_swap = [v] elseif cost == best_cost _verbose(s, "cost = best_cost = $cost") push!(dim == 0 ? best_values : best_swap, v) end if cost == 0 && is_sat(s) s.pool == pool(s.state.configuration) return best_values, best_swap, tabu end copy_from!(s.state.fluct, _cons_costs(s), _vars_costs(s)) set_error!(s, old_cost) # swap/change back the value of x (and y/) dim == 0 ? _value!(s, x, old_v) : _swap_value!(s, x, v) end return best_values, best_swap, tabu end """ _step!(s) Iterate a step of the solver run. """ function _step!(s) # select worst variables x = _select_worse(s) _verbose(s, "Selected x = $x") # Local move (change the value of the selected variable) best_values, best_swap, tabu = _move!(s, x) # _compute!(s) # If local move is bad (tabu), then try permutation if tabu _, best_swap, tabu = _move!(s, x, 1) _compute!(s) else # compute the costs changes from best local move _compute!(s; cons_lst = get_cons_from_var(s, x)) end # decay tabu list decay_tabu!(s) # update tabu list with either worst or selected variable insert_tabu!(s, x, tabu ? :tabu : :pick) _verbose(s, "Tabu list: $(tabu_list(s))") # Inc last improvement if tabu tabu ? _inc_last_improvement!(s) : _reset_last_improvement!(s) # Select the best move (value or swap) if x ∈ best_swap _value!(s, x, rand(best_values)) _verbose(s, "best_values: $best_values") else _swap_value!(s, x, rand(best_swap)) _verbose(s, "best_swap : $best_swap") end # Compute costs and possibly evaluate objective functions # return true if a solution for sat is found if _compute!(s) !is_sat(s) ? _optimizing!(s) : return true end # Restart if necessary _check_restart(s) && _restart!(s) return false # no satisfying configuration or optimizing end """ _check_subs(s) Check if any subsolver of a main solver `s`, for - *Satisfaction*, has a solution, then return it, resume the run otherwise - *Optimization*, has a better solution, then assign it to its internal state """ _check_subs(::AbstractSolver) = 0 # Dummy method """ stop_while_loop() Check the stop conditions of the `solve!` while inner loop. """ stop_while_loop(::AbstractSolver) = nothing """ solve_while_loop!(s, ) Search the space of configurations. """ function solve_while_loop!(s, stop, sat, iter, st) while stop_while_loop(s, stop, iter, st) iter += 1 _verbose( s, "\n\tLoop $(iter) ($(_optimizing(s) ? "optimization" : "satisfaction"))") _step!(s) && sat && break _verbose(s, "vals: $(length(_values(s)) > 0 ? _values(s) : nothing)") best_sub = _check_subs(s) if best_sub > 0 bs = s.subs[best_sub] s.pool = deepcopy(bs.pool) sat && break end end end """ remote_dispatch!(solver) Starts the `LeadSolver`s attached to the `MainSolver`. """ remote_dispatch!(::AbstractSolver) = nothing # dummy method """ solve_for_loop!(solver, stop, sat, iter) First loop in the solving process that starts `LeadSolver`s from the `MainSolver`, and `_SubSolver`s from each `MetaSolver`. """ solve_for_loop!(s, stop, sat, iter, st) = solve_while_loop!(s, stop, sat, iter, st) function update_pool!(s, pool) is_empty(pool) && return nothing if is_sat(s) || best_value(s) > best_value(pool) s.pool = deepcopy(pool) end end """ remote_stop!!(solver) Fetch the pool of solutions from `LeadSolvers` and merge it into the `MainSolver`. """ remote_stop!(::AbstractSolver) = nothing """ post_process(s::MainSolver) Launch a series of tasks to round-up a solving run, for instance, export a run's info. """ post_process(::AbstractSolver) = nothing function solve!(s, stop = Atomic{Bool}(false)) start_time = time() add_time!(s, 1) # only used by MainSolver iter = 0 # only used by MainSolver sat = is_sat(s) _init!(s) && (sat ? (iter = typemax(0)) : _optimizing!(s)) add_time!(s, 2) # only used by MainSolver solve_for_loop!(s, stop, sat, iter, start_time) add_time!(s, 5) # only used by MainSolver remote_stop!(s) add_time!(s, 6) # only used by MainSolver post_process(s) # only used by MainSolver end """ solution(s) Return the only/best known solution of a satisfaction/optimization model. """ solution(s) = has_solution(s) ? best_values(s) : _values(s)
LocalSearchSolvers
https://github.com/JuliaConstraints/LocalSearchSolvers.jl.git
[ "MIT" ]
0.4.9
e592c828aabfbc829a55af6edbac589681bdf856
code
4623
abstract type AbstractState end struct EmptyState <: AbstractState end """ GeneralState{T <: Number} A mutable structure to store the general state of a solver. All methods applied to `GeneralState` are forwarded to `S <: AbstractSolver`. ``` mutable struct GeneralState{T <: Number} <: AbstractState configuration::Configuration{T} cons_costs::Dictionary{Int, Float64} last_improvement::Int tabu::Dictionary{Int, Int} vars_costs::Dictionary{Int, Float64} end ``` """ mutable struct _State{T} <: AbstractState configuration::Configuration{T} cons_costs::Dictionary{Int, Float64} fluct::Fluct icn_computations::Matrix{Float64} optimizing::Bool last_improvement::Int vars_costs::Dictionary{Int, Float64} end @forward _State.configuration get_values, get_error, get_value, compute_cost!, set_values! @forward _State.configuration set_value!, set_sat! const State = Union{EmptyState, _State} state() = EmptyState() function state(m::_Model, pool = pool(); opt = false) X = Matrix{Float64}(undef, m.max_vars[], CompositionalNetworks.max_icn_length()) lc, lv = length_cons(m) > 0, length_vars(m) > 0 config = Configuration(m, X) cons = lc ? zeros(Float64, get_constraints(m)) : Dictionary{Int, Float64}() last_improvement = 0 vars = lv ? zeros(Float64, get_variables(m)) : Dictionary{Int, Float64}() fluct = Fluct(cons, vars) return _State(config, cons, fluct, X, opt, last_improvement, vars) end """ _cons_costs(s::S) where S <: Union{_State, AbstractSolver} Access the constraints costs. """ _cons_costs(s::_State) = s.cons_costs """ _vars_costs(s::S) where S <: Union{_State, AbstractSolver} Access the variables costs. """ _vars_costs(s::_State) = s.vars_costs """ _vars_costs(s::S) where S <: Union{_State, AbstractSolver} Access the variables costs. """ _values(s::_State) = get_values(s) """ _optimizing(s::S) where S <: Union{_State, AbstractSolver} Check if `s` is in an optimizing state. """ _optimizing(s::_State) = s.optimizing """ _cons_costs!(s::S, costs) where S <: Union{_State, AbstractSolver} Set the constraints costs. """ _cons_costs!(s::_State, costs) = s.cons_costs = costs """ _vars_costs!(s::S, costs) where S <: Union{_State, AbstractSolver} Set the variables costs. """ _vars_costs!(s::_State, costs) = s.vars_costs = costs """ _values!(s::S, values) where S <: Union{_State, AbstractSolver} Set the variables values. """ _values!(s::_State{T}, values) where {T <: Number} = set_values!(s, values) """ _optimizing!(s::S) where S <: Union{_State, AbstractSolver} Set the solver `optimizing` status to `true`. """ _optimizing!(s::_State) = s.optimizing = true """ _satisfying!(s::S) where S <: Union{_State, AbstractSolver} Set the solver `optimizing` status to `false`. """ _satisfying!(s::_State) = s.optimizing = false """ _cons_cost(s::S, c) where S <: Union{_State, AbstractSolver} Return the cost of constraint `c`. """ _cons_cost(s::_State, c) = get!(_cons_costs(s), c, 0.0) """ _var_cost(s::S, x) where S <: Union{_State, AbstractSolver} Return the cost of variable `x`. """ _var_cost(s::_State, x) = get!(_vars_costs(s), x, 0.0) """ _value(s::S, x) where S <: Union{_State, AbstractSolver} Return the value of variable `x`. """ _value(s::_State, x) = _values(s)[x] """ _cons_cost!(s::S, c, cost) where S <: Union{_State, AbstractSolver} Set the `cost` of constraint `c`. """ _cons_cost!(s::_State, c, cost) = _cons_costs(s)[c] = cost """ _var_cost!(s::S, x, cost) where S <: Union{_State, AbstractSolver} Set the `cost` of variable `x`. """ _var_cost!(s::_State, x, cost) = _vars_costs(s)[x] = cost """ _value!(s::S, x, val) where S <: Union{_State, AbstractSolver} Set the value of variable `x` to `val`. """ _value!(s::_State, x, val) = _values(s)[x] = val """ _set!(s::S, x, val) where S <: Union{_State, AbstractSolver} Set the value of variable `x` to `val`. """ _set!(s::_State, x, val) = set!(_values(s), x, val) """ _set!(s::S, x, y) where S <: Union{_State, AbstractSolver} Swap the values of variables `x` and `y`. """ function _swap_value!(s::_State, x, y) aux = _value(s, x) _value!(s, x, _value(s, y)) _value!(s, y, aux) end _last_improvement(s::_State) = s.last_improvement _inc_last_improvement!(s::_State) = s.last_improvement += 1 _reset_last_improvement!(s::_State) = s.last_improvement = 0 has_solution(s::_State) = is_solution(s.configuration) function set_error!(s::_State, err) sat = err ≈ 0.0 set_sat!(s, sat) !sat && set_value!(s, err) end get_error(::EmptyState) = Inf
LocalSearchSolvers
https://github.com/JuliaConstraints/LocalSearchSolvers.jl.git
[ "MIT" ]
0.4.9
e592c828aabfbc829a55af6edbac589681bdf856
code
625
struct MetaStrategy{RS <: RestartStrategy, TS <: TabuStrategy} restart::RS tabu::TS end function MetaStrategy(model; tenure = min(length_vars(model) ÷ 2, 10), tabu = tabu(tenure, tenure ÷ 2), # restart = restart(tabu, Val(:universal)), restart = restart(tabu, Val(:random); rp = 0.05) ) return MetaStrategy(restart, tabu) end # forwards from RestartStrategy @forward MetaStrategy.restart check_restart! # forwards from TabuStrategy @forward MetaStrategy.tabu decrease_tabu!, delete_tabu!, decay_tabu! @forward MetaStrategy.tabu length_tabu, insert_tabu!, empty_tabu!, tabu_list
LocalSearchSolvers
https://github.com/JuliaConstraints/LocalSearchSolvers.jl.git
[ "MIT" ]
0.4.9
e592c828aabfbc829a55af6edbac589681bdf856
code
1808
mutable struct TimeStamps # seconds ts0::Float64 # model construction start ts1::Float64 # ts1 ≤ _init! ts2::Float64 # _init! ≤ ts2 ≤ @threads ts3::Float64 # @threads ≤ ts3 ≤ remote_start ts4::Float64 # remote_start ≤ ts4 ≤ main_run ts5::Float64 # main_run ≤ ts5 ≤ remote_stop ts6::Float64 # remote_stop ≤ ts6 end function TimeStamps(ts::Float64 = zero(Float64)) t = zero(Float64) return TimeStamps(ts, t, t, t, t, t, t) end TimeStamps(model::_Model) = TimeStamps(get_time_stamp(model)) add_time!(stamps, ts, ::Val{1}) = stamps.ts1 = ts add_time!(stamps, ts, ::Val{2}) = stamps.ts2 = ts add_time!(stamps, ts, ::Val{3}) = stamps.ts3 = ts add_time!(stamps, ts, ::Val{4}) = stamps.ts4 = ts add_time!(stamps, ts, ::Val{5}) = stamps.ts5 = ts add_time!(stamps, ts, ::Val{6}) = stamps.ts6 = ts add_time!(stamps, i) = add_time!(stamps, time(), Val(i)) get_time(stamps, ::Val{0}) = stamps.ts1 get_time(stamps, ::Val{1}) = stamps.ts1 get_time(stamps, ::Val{2}) = stamps.ts2 get_time(stamps, ::Val{3}) = stamps.ts3 get_time(stamps, ::Val{4}) = stamps.ts4 get_time(stamps, ::Val{5}) = stamps.ts5 get_time(stamps, ::Val{6}) = stamps.ts6 get_time(stamps, i) = get_time(stamps, Val(i)) function time_info(stamps) info = Dict([ :model => get_time(stamps, 1) - get_time(stamps, 0), :init => get_time(stamps, 2) - get_time(stamps, 1), :threads_start => get_time(stamps, 3) - get_time(stamps, 2), :remote_start => get_time(stamps, 4) - get_time(stamps, 3), :local_run => get_time(stamps, 5) - get_time(stamps, 4), :remote_stop => get_time(stamps, 6) - get_time(stamps, 5), :total_run => get_time(stamps, 6) - get_time(stamps, 1), :model_and_run => get_time(stamps, 6) - get_time(stamps, 0) ]) return info end
LocalSearchSolvers
https://github.com/JuliaConstraints/LocalSearchSolvers.jl.git
[ "MIT" ]
0.4.9
e592c828aabfbc829a55af6edbac589681bdf856
code
818
""" _to_union(datatype) Make a minimal `Union` type from a collection of data types. """ _to_union(datatype) = Union{(isa(datatype, Type) ? [datatype] : datatype)...} """ _find_rand_argmax(d::DictionaryView) Compute `argmax` of `d` and select one element randomly. """ function _find_rand_argmax(d::DictionaryView) max = -Inf argmax = Vector{Int}() for (k, v) in pairs(d) if v > max max = v argmax = [k] elseif v == max push!(argmax, k) end end return rand(argmax) end abstract type FunctionContainer end apply(fc::FC) where {FC <: FunctionContainer} = fc.f apply(fc::FC, x, X) where {FC <: FunctionContainer} = convert(Float64, apply(fc)(x; X)) apply(fc::FC, x) where {FC <: FunctionContainer} = convert(Float64, apply(fc)(x))
LocalSearchSolvers
https://github.com/JuliaConstraints/LocalSearchSolvers.jl.git
[ "MIT" ]
0.4.9
e592c828aabfbc829a55af6edbac589681bdf856
code
2409
""" Variable{D <: AbstractDomain} A structure containing the necessary information for a solver's variables: `name`, `domain`, and `constraints` it belongs. ``` struct Variable{D <: AbstractDomain} domain::D constraints::Indices{Int} end ``` """ mutable struct Variable{D <: AbstractDomain} domain::D constraints::Indices{Int} end function Variable(D, x::Variable{D2}) where {D2 <: AbstractDomain} return Variable{D}(x.domain, x.constraints) end # Methods: lazy forwarding from ConstraintDomains.domain.jl @forward Variable.domain Base.length, Base.rand, Base.delete!, Base.isempty # @forward Variable.domain get_domain, domain_size add!(x::Variable, value) = ConstraintDomains.add!(x.domain, value) get_domain(x::Variable) = ConstraintDomains.get_domain(x.domain) domain_size(x::Variable) = ConstraintDomains.domain_size(x.domain) """ _get_constraints(x::Variable) Access the list of `constraints` of `x`. """ _get_constraints(x::Variable) = x.constraints """ _add_to_constraint!(x::Variable, id) Add a constraint `id` to the list of constraints of `x`. """ _add_to_constraint!(x::Variable, id) = set!(_get_constraints(x), id) """ _delete_from_constraint!(x::Variable, id) Delete a constraint `id` from the list of constraints of `x`. """ _delete_from_constraint!(x::Variable, id) = delete!(x.constraints, id) """ _constriction(x::Variable) Return the `cosntriction` of `x`, i.e. the number of constraints restricting `x`. """ _constriction(x::Variable) = length(x.constraints) """ x::Variable ∈ constraint value ∈ x::Variable Check if a variable `x` is restricted by a `constraint::Int`, or if a `value` belongs to the domain of `x`. """ Base.in(x::Variable, constraint) = constraint ∈ x.constraints Base.in(value, x::Variable) = value ∈ x.domain """ variable(values::AbstractVector{T}, name::AbstractString; domain = :set) where T <: Number variable(domain::AbstractDomain, name::AbstractString) where D <: AbstractDomain Construct a variable with discrete domain. See the `domain` method for other options. ```julia d = domain([1,2,3,4], types = :indices) x1 = variable(d, "x1") x2 = variable([-89,56,28], "x2", domain = :indices) ``` """ variable() = Variable(domain(), Indices{Int}()) variable(domain::D) where {D <: AbstractDomain} = Variable(domain, Indices{Int}()) variable(vals) = isempty(vals) ? variable() : variable(domain(vals))
LocalSearchSolvers
https://github.com/JuliaConstraints/LocalSearchSolvers.jl.git
[ "MIT" ]
0.4.9
e592c828aabfbc829a55af6edbac589681bdf856
code
469
""" o_mincut(graph, values; interdiction = 0) Compute the capacity of a cut (determined by the state of the solver) with a possible `interdiction` on the highest capacited links. """ function o_mincut(graph, values; interdiction = 0) capacity = Vector{Float64}() n = size(graph, 1) for i in 1:n, j in 1:n (values[i] < values[n + 1] < values[j]) && push!(capacity, graph[i, j]) end return sum(sort!(capacity)[1:(end - interdiction)]) end
LocalSearchSolvers
https://github.com/JuliaConstraints/LocalSearchSolvers.jl.git
[ "MIT" ]
0.4.9
e592c828aabfbc829a55af6edbac589681bdf856
code
205
""" dist_extrema(values::T...) where {T <: Number} Computes the distance between extrema in an ordered set. """ function o_dist_extrema(values) m, M = extrema(values) return Float64(M - m) end
LocalSearchSolvers
https://github.com/JuliaConstraints/LocalSearchSolvers.jl.git
[ "MIT" ]
0.4.9
e592c828aabfbc829a55af6edbac589681bdf856
code
1047
""" LeadSolver <: MetaSolver Solver managed remotely by a MainSolver. Can manage its own set of local sub solvers. """ mutable struct LeadSolver <: MetaSolver meta_local_id::Tuple{Int, Int} model::_Model options::Options pool::Pool rc_report::RemoteChannel rc_sol::RemoteChannel rc_stop::RemoteChannel state::State strategies::MetaStrategy subs::Vector{_SubSolver} end function solver( mlid, model, options, pool, rc_report, rc_sol, rc_stop, strats, ::Val{:lead}) l_options = deepcopy(options) set_option!(l_options, "print_level", :silent) ss = Vector{_SubSolver}() return LeadSolver( mlid, model, l_options, pool, rc_report, rc_sol, rc_stop, state(), strats, ss) end function _init!(s::LeadSolver) _init!(s, :meta) _init!(s, :local) end stop_while_loop(s::LeadSolver, ::Atomic{Bool}, ::Int, ::Float64) = isready(s.rc_stop) function remote_stop!(s::LeadSolver) isready(s.rc_stop) && take!(s.rc_stop) put!(s.rc_sol, s.pool) take!(s.rc_report) end
LocalSearchSolvers
https://github.com/JuliaConstraints/LocalSearchSolvers.jl.git
[ "MIT" ]
0.4.9
e592c828aabfbc829a55af6edbac589681bdf856
code
4102
""" MainSolver <: AbstractSolver Main solver. Handle the solving of a model, and optional multithreaded and/or distributed subsolvers. # Arguments: - `model::Model`: A formal description of the targeted problem - `state::_State`: An internal state to store the info necessary to a solving run - `options::Options`: User options for this solver - `subs::Vector{_SubSolver}`: Optional subsolvers """ mutable struct MainSolver <: MetaSolver meta_local_id::Tuple{Int, Int} model::_Model options::Options pool::Pool rc_report::RemoteChannel rc_sol::RemoteChannel rc_stop::RemoteChannel remotes::Dict{Int, Future} state::State status::Symbol strategies::MetaStrategy subs::Vector{_SubSolver} time_stamps::TimeStamps end make_id(::Int, id, ::Val{:lead}) = (id, 0) function solver(model = model(); options = Options(), pool = pool(), strategies = MetaStrategy(model) ) mlid = (1, 0) rc_report = RemoteChannel(() -> Channel{Nothing}(length(workers()))) rc_sol = RemoteChannel(() -> Channel{Pool}(length(workers()))) rc_stop = RemoteChannel(() -> Channel{Nothing}(1)) remotes = Dict{Int, Future}() subs = Vector{_SubSolver}() ts = TimeStamps(model) return MainSolver(mlid, model, options, pool, rc_report, rc_sol, rc_stop, remotes, state(), :not_called, strategies, subs, ts) end # Forwards from TimeStamps @forward MainSolver.time_stamps add_time!, time_info, get_time """ empty!(s::Solver) """ function Base.empty!(s::MainSolver) empty!(s.model) s.state = state() empty!(s.subs) # TODO: empty remote solvers end """ status(solver) Return the status of a MainSolver. """ status(s::MainSolver) = s.status function _init!(s::MainSolver) _init!(s, :global) _init!(s, :remote) _init!(s, :meta) _init!(s, :local) end function stop_while_loop(s::MainSolver, ::Atomic{Bool}, iter, start_time) @debug "debug stop" iter (time()-start_time) if !isready(s.rc_stop) s.status = :solution_limit return false end iter_sat = get_option(s, "iteration")[1] && has_solution(s) iter_limit = iter > get_option(s, "iteration")[2] if (iter_sat && iter_limit) || iter_limit s.status = :iteration_limit return false end time_sat = get_option(s, "time_limit")[1] && has_solution(s) time_limit = time() - start_time > get_option(s, "time_limit")[2] if (time_sat && time_limit) || time_limit s.status = :time_limit return false end return true end function remote_dispatch!(s::MainSolver) for (w, ls) in s.remotes remote_do(solve!, w, fetch(ls)) end end function post_process(s::MainSolver) path = get_option(s, "info_path") sat = is_sat(s) if s.status == :not_called s.status = :solution_limit end if !isempty(path) info = Dict( :solution => has_solution(s) ? collect(best_values(s)) : nothing, :time => time_info(s), :type => sat ? "Satisfaction" : "Optimization" ) !sat && has_solution(s) && push!(info, :value => best_value(s)) write(path, JSON.json(info)) end end function remote_stop!(s::MainSolver) isready(s.rc_stop) && take!(s.rc_stop) sat = is_sat(s) @info "Remote stop: report main pool" best_values(s.pool) has_solution(s) s.rc_report s.rc_sol s.rc_stop length(s.remotes) if !sat || !has_solution(s) @warn "debugging remote stop" nworkers() length(s.remotes) while isready(s.rc_report) || isready(s.rc_sol) wait(s.rc_sol) t = take!(s.rc_sol) @info "Remote stop: report remote pool" best_values(t) length(s.remotes) update_pool!(s, t) if sat && has_solution(t) empty!(s.rc_report) break end @info "mark 1" isready(s.rc_report) && take!(s.rc_report) @info "mark 2" end end @info "Remote stop: report best pool" best_values(s.pool) length(s.remotes) end
LocalSearchSolvers
https://github.com/JuliaConstraints/LocalSearchSolvers.jl.git
[ "MIT" ]
0.4.9
e592c828aabfbc829a55af6edbac589681bdf856
code
1182
""" Abstract type to encapsulate all solver types that manages other solvers. """ abstract type MetaSolver <: AbstractSolver end meta_id(s) = s.meta_local_id[1] make_id(meta, id, ::Val{:sub}) = (meta, id) function _check_subs(s::MetaSolver) if is_sat(s) for (id, ss) in enumerate(s.subs) has_solution(ss) && return id end else for (id, ss) in enumerate(s.subs) bs = is_empty(s.pool) ? nothing : best_value(s) bss = is_empty(ss.pool) ? nothing : best_value(ss) isnothing(bs) && (isnothing(bss) ? continue : return id) isnothing(bss) ? continue : (bss < bs && return id) end end return 0 end function solve_for_loop!(s::MetaSolver, stop, sat, iter, st) @threads for id in 1:min(nthreads(), get_option(s, "threads")) if id == 1 add_time!(s, 3) # only used by MainSolver remote_dispatch!(s) # only used by MainSolver add_time!(s, 4) # only used by MainSolver solve_while_loop!(s, stop, sat, iter, st) atomic_or!(stop, true) else solve!(s.subs[id - 1], stop) end end end
LocalSearchSolvers
https://github.com/JuliaConstraints/LocalSearchSolvers.jl.git
[ "MIT" ]
0.4.9
e592c828aabfbc829a55af6edbac589681bdf856
code
951
""" _SubSolver <: AbstractSolver An internal solver type called by MetaSolver when multithreading is enabled. # Arguments: - `id::Int`: subsolver id for debugging - `model::Model`: a ref to the model of the main solver - `state::_State`: a `deepcopy` of the main solver that evolves independently - `options::Options`: a ref to the options of the main solver """ mutable struct _SubSolver <: AbstractSolver meta_local_id::Tuple{Int, Int} model::_Model options::Options pool::Pool state::State strategies::MetaStrategy end function solver(mlid, model, options, pool, ::RemoteChannel, ::RemoteChannel, ::RemoteChannel, strats, ::Val{:sub}) sub_options = deepcopy(options) set_option!(sub_options, "print_level", :silent) return _SubSolver(mlid, model, sub_options, pool, state(), strats) end _init!(s::_SubSolver) = _init!(s, :local) stop_while_loop(::_SubSolver, stop, ::Int, ::Float64) = !(stop[])
LocalSearchSolvers
https://github.com/JuliaConstraints/LocalSearchSolvers.jl.git
[ "MIT" ]
0.4.9
e592c828aabfbc829a55af6edbac589681bdf856
code
1979
abstract type RestartStrategy end # Random restart struct RandomRestart <: RestartStrategy reset_percentage::Float64 end function restart(::Any, ::Val{:random}; rp = 0.05) return RandomRestart(rp) end function check_restart!(rs::RandomRestart; tabu_length = nothing) return rand() ≤ rs.reset_percentage end # Tabu restart mutable struct TabuRestart <: RestartStrategy index::Int tenure::Int limit::Int reset_percentage::Float64 end function restart(strategy, ::Val{:tabu}; rp = 1.0, index = 1) limit = tenure(strategy, :tabu) - tenure(strategy, :pick) return TabuRestart(index, tenure(strategy, :tabu), limit, rp) end function check_restart!(rs::TabuRestart; tabu_length) a = rs.index * (tabu_length + rs.limit - rs.tenure) b = (rs.index + 1) * rs.limit # a = tabu_length + rs.limit - rs.tenure # b = rs.limit if rand() ≤ a / b rs.index += 1 return true end return false end # Restart sequences mutable struct RestartSequence{F <: Function} <: RestartStrategy index::Int current::Int last_restart::Int next::F RestartSequence(seq) = new{typeof(seq)}(1, seq(1), 1, seq) end current(r) = r.current function next!(r) r.index += 1 r.current = r.next(r.index) r.last_restart = 1 return r.current end inc_last!(rs) = rs.last_restart += 1 function check_restart!(rs::RestartSequence; tabu_length = nothing) proceed = rs.current > rs.last_restart proceed ? inc_last!(rs) : next!(rs) return !proceed end ## Universal restart sequence function oeis(n, b, ::Val{:A082850}) m = log(b, n + 1) return isinteger(m) ? Int(m) : oeis(n - (b^floor(m) - 1), :A082850) end oeis(n, b, ::Val{:A182105}) = b^(oeis(n, :A082850) - 1) oeis(n, ref::Symbol, b = 2) = oeis(n, b, Val(ref)) restart(::Any, ::Val{:universal}) = RestartSequence(n -> oeis(n, :A182105)) # Generic restart constructor restart(tabu, strategy::Symbol) = restart(tabu, Val(strategy))
LocalSearchSolvers
https://github.com/JuliaConstraints/LocalSearchSolvers.jl.git
[ "MIT" ]
0.4.9
e592c828aabfbc829a55af6edbac589681bdf856
code
2398
abstract type TabuStrategy end struct NoTabu <: TabuStrategy end struct KeenTabu <: TabuStrategy tabu_tenure::Int tabu_list::Dictionary{Int, Int} end struct WeakTabu <: TabuStrategy tabu_tenure::Int pick_tenure::Int tabu_list::Dictionary{Int, Int} end tabu() = NoTabu() function tabu(tabu_tenure) tabu_list = Dictionary{Int, Int}() return KeenTabu(tabu_tenure, tabu_list) end function tabu(tabu_tenure, pick_tenure) tabu_list = Dictionary{Int, Int}() return WeakTabu(tabu_tenure, pick_tenure, tabu_list) end tenure(strategy, ::Val{:tabu}) = strategy.tabu_tenure tenure(strategy::WeakTabu, ::Val{:pick}) = strategy.pick_tenure tenure(::TabuStrategy, ::Val{:pick}) = zero(Int) tenure(::NoTabu, ::Val{:tabu}) = zero(Int) tenure(strategy, field) = tenure(strategy, Val(field)) """ _tabu(s::S) where S <: Union{_State, AbstractSolver} Access the list of tabu variables. """ tabu_list(ts) = ts.tabu_list """ _tabu(s::S, x) where S <: Union{_State, AbstractSolver} Return the tabu value of variable `x`. """ tabu_value(ts, x) = tabu_list(ts)[x] """ _decrease_tabu!(s::S, x) where S <: Union{_State, AbstractSolver} Decrement the tabu value of variable `x`. """ decrease_tabu!(ts, x) = tabu_list(ts)[x] -= 1 """ _delete_tabu!(s::S, x) where S <: Union{_State, AbstractSolver} Delete the tabu entry of variable `x`. """ delete_tabu!(ts, x) = delete!(tabu_list(ts), x) """ _empty_tabu!(s::S) where S <: Union{_State, AbstractSolver} Empty the tabu list. """ empty_tabu!(ts) = Dictionaries.empty!(tabu_list(ts)) """ _length_tabu!(s::S) where S <: Union{_State, AbstractSolver} Return the length of the tabu list. """ length_tabu(ts) = length(tabu_list(ts)) """ _insert_tabu!(s::S, x, tabu_time) where S <: Union{_State, AbstractSolver} Insert the bariable `x` as tabu for `tabu_time`. """ insert_tabu!(ts, x, ::Val{:tabu}) = insert!(tabu_list(ts), x, max(1, tenure(ts, :tabu))) insert_tabu!(ts::KeenTabu, x, kind::Symbol) = insert_tabu!(ts, x, Val(kind)) insert_tabu!(ts::WeakTabu, x, kind) = insert!(tabu_list(ts), x, max(1, tenure(ts, kind))) insert_tabu!(ts, x, kind) = nothing """ _decay_tabu!(s::S) where S <: Union{_State, AbstractSolver} Decay the tabu list. """ function decay_tabu!(ts) foreach( ((x, tabu),) -> tabu == 1 ? delete_tabu!(ts, x) : decrease_tabu!(ts, x), pairs(tabu_list(ts)) ) end
LocalSearchSolvers
https://github.com/JuliaConstraints/LocalSearchSolvers.jl.git
[ "MIT" ]
0.4.9
e592c828aabfbc829a55af6edbac589681bdf856
code
882
@testset "Aqua.jl" begin import Aqua import LocalSearchSolvers # TODO: Fix the broken tests and remove the `broken = true` flag Aqua.test_all( LocalSearchSolvers; ambiguities = (broken = true,), deps_compat = false, piracies = (broken = false,), unbound_args = (broken = false) ) @testset "Ambiguities: LocalSearchSolvers" begin # Aqua.test_ambiguities(LocalSearchSolvers;) end @testset "Piracies: LocalSearchSolvers" begin Aqua.test_piracies(LocalSearchSolvers;) end @testset "Dependencies compatibility (no extras)" begin Aqua.test_deps_compat( LocalSearchSolvers; check_extras = false # ignore = [:Random] ) end @testset "Unbound type parameters" begin # Aqua.test_unbound_args(LocalSearchSolvers;) end end
LocalSearchSolvers
https://github.com/JuliaConstraints/LocalSearchSolvers.jl.git
[ "MIT" ]
0.4.9
e592c828aabfbc829a55af6edbac589681bdf856
code
59
@testset "TestItemRunner" begin @run_package_tests end
LocalSearchSolvers
https://github.com/JuliaConstraints/LocalSearchSolvers.jl.git
[ "MIT" ]
0.4.9
e592c828aabfbc829a55af6edbac589681bdf856
code
2682
d1 = domain([4, 3, 2, 1]) d2 = domain(1:4) domains = Dictionary(1:2, [d1, d2]) @testset "Internals: Domains" begin for d in domains # constructors and ∈ for x in [1, 2, 3, 4] @test x ∈ d end # length @test length(d) == 4 # draw and ∈ @test rand(d) ∈ d end # add! ConstraintDomains.add!(d1, 5) @test 5 ∈ d1 # delete! delete!(d1, 5) @test 5 ∉ d1 end x1 = variable([4, 3, 2, 1]) x2 = variable(d2) x3 = variable() # TODO: tailored test for free variable vars = Dictionary(1:2, [x1, x2]) @testset "Internals: variables" begin for x in vars # add and delete from constraint LS._add_to_constraint!(x, 1) LS._add_to_constraint!(x, 2) LS._delete_from_constraint!(x, 2) @test x ∈ 1 @test x ∉ 2 @test LS._constriction(x) == 1 @test length(x) == 4 for y in [1, 2, 3, 4] @test y ∈ x end @test rand(x) ∈ x end add!(x1, 5) @test 5 ∈ x1 delete!(x1, 5) @test 5 ∉ x1 end values = [1, 2, 3] inds = [1, 2] err = (x; X) -> error_f(USUAL_CONSTRAINTS[:all_different])(x) c1 = constraint(err, inds) c2 = constraint(err, inds) cons = Dictionary(1:2, [c1, c2]) @testset "Internals: constraints" begin for c in cons LS._add!(c, 3) @test 3 ∈ c LS._delete!(c, 3) @test 3 ∉ c @test LS._length(c) == 2 c.f(values; X = Matrix{Float64}(undef, 3, CompositionalNetworks.max_icn_length())) end end o1 = objective(sum, "Objective 1: sum") o2 = objective(prod, "Objective 2: product") objs = Dictionary(1:2, [o1, o2]) @testset "Internals: objectives" begin for o in objs @test o.f(values) == 6 end end m = model() # LocalSearchSolvers.describe(m) x1 = variable([4, 3, 2, 1]) x2 = variable(d2) vars = Dictionary(1:2, [x1, x2]) values = [1, 2, 3] inds = [1, 2] c1 = constraint(err, inds) c2 = constraint(err, inds) cons = Dictionary(1:2, [c1, c2]) o1 = objective(sum, "Objective 1: sum") o2 = objective(prod, "Objective 2: product") objs = Dictionary(1:2, [o1, o2]) @testset "Internals: model" begin for x in vars add!(m, x) end variable!(m, d1) for c in cons add!(m, c) end constraint!(m, err, [1, 2]) for o in objs add!(m, o) end objective!(m, max) length_var(m, 1) length_cons(m, 1) constriction(m, 1) draw(m, 1) get_objective(m, 1) delete_value!(m, 1, 1) add_value!(m, 1, 1) delete_var_from_cons!(m, 1, 1) add_var_to_cons!(m, 1, 1) # describe(m) end ## Test Solver s1 = solver() LS.get_error(LS.EmptyState())
LocalSearchSolvers
https://github.com/JuliaConstraints/LocalSearchSolvers.jl.git
[ "MIT" ]
0.4.9
e592c828aabfbc829a55af6edbac589681bdf856
code
6303
function mincut(graph; source, sink, interdiction = 0) m = model(; kind = :cut) n = size(graph, 1) d = domain(0:n) separator = n + 1 # value that separate the two sides of the cut # Add variables: foreach(_ -> variable!(m, d), 0:n) # Extract error function from usual_constraint e1 = (x; X) -> error_f(USUAL_CONSTRAINTS[:ordered])(x) e2 = (x; X) -> error_f(USUAL_CONSTRAINTS[:all_different])(x) # Add constraint constraint!(m, e1, [source, separator, sink]) constraint!(m, e2, 1:(n + 1)) # Add objective objective!(m, (x...) -> o_mincut(graph, x...; interdiction)) return m end function golomb(n, L = n^2) m = model(; kind = :golomb) # Add variables d = domain(0:L) foreach(_ -> variable!(m, d), 1:n) # Extract error function from usual_constraint e1 = (x; X) -> error_f(USUAL_CONSTRAINTS[:all_different])(x) e2 = (x; X) -> error_f(USUAL_CONSTRAINTS[:all_equal])(x; val = 0) e3 = (x; X) -> error_f(USUAL_CONSTRAINTS[:dist_different])(x) # # Add constraints constraint!(m, e1, 1:n) constraint!(m, e2, 1:1) for i in 1:(n - 1), j in (i + 1):n, k in i:(n - 1), l in (k + 1):n (i, j) < (k, l) || continue constraint!(m, e3, [i, j, k, l]) end # Add objective objective!(m, o_dist_extrema) return m end function sudoku(n; start = nothing) N = n^2 d = domain(1:N) m = model(; kind = :sudoku) # Add variables if isnothing(start) foreach(_ -> variable!(m, d), 1:(N^2)) else foreach(((x, v),) -> variable!(m, 1 ≤ v ≤ N ? domain(v) : d), pairs(start)) end e = (x; X) -> error_f(USUAL_CONSTRAINTS[:all_different])(x) # Add constraints: line, columns; blocks foreach(i -> constraint!(m, e, (i * N + 1):((i + 1) * N)), 0:(N - 1)) foreach(i -> constraint!(m, e, [j * N + i for j in 0:(N - 1)]), 1:N) for i in 0:(n - 1) for j in 0:(n - 1) vars = Vector{Int}() for k in 1:n for l in 0:(n - 1) push!(vars, (j * n + l) * N + i * n + k) end end constraint!(m, e, vars) end end return m end @testset "Raw solver: internals" begin models = [ sudoku(2) ] for m in models # @info describe(m) options = Options( print_level = :verbose, time_limit = Inf, iteration = Inf, info_path = "info.json", process_threads_map = Dict{Int, Int}( [2 => 2, 3 => 1] )) s = solver(m; options) for x in keys(get_variables(s)) @test get_name(s, x) == "x$x" for c in get_cons_from_var(s, x) @test x ∈ get_vars_from_cons(s, c) end @test constriction(s, x) == 3 @test draw(s, x) ∈ get_domain(s, x) end for c in keys(get_constraints(s)) @test length_cons(s, c) == 4 end for x in keys(get_variables(s)) add_var_to_cons!(s, 3, x) delete_var_from_cons!(s, 3, x) @test length_var(s, x) == 4 end for c in keys(get_constraints(s)) add_var_to_cons!(s, c, 17) @test length_cons(s, c) == 5 @test 17 ∈ get_constraint(s, c) delete_var_from_cons!(s, c, 17) @test length_cons(s, c) == 4 end solve!(s) solution(s) # TODO: temp patch for coverage, make it nice for x in keys(LocalSearchSolvers.tabu_list(s)) LocalSearchSolvers.tabu_value(s, x) end # LocalSearchSolvers._values!(s, Dictionary{Int,Int}()) # display(solution(s)) @info time_info(s) rm("info.json") end end @testset "Raw solver: sudoku" begin sudoku_instance = collect(Iterators.flatten([9 3 0 0 0 0 0 4 0 0 0 0 0 4 2 0 9 0 8 0 0 1 9 6 7 0 0 0 0 0 4 7 0 0 0 0 0 2 0 0 0 0 0 6 0 0 0 0 0 2 3 0 0 0 0 0 8 5 3 1 0 0 2 0 9 0 2 8 0 0 0 0 0 7 0 0 0 0 0 5 3])) s = solver(sudoku(3; start = sudoku_instance); options = Options(print_level = :minimal, iteration = Inf, time_limit = 10)) display(Dictionary(1:length(sudoku_instance), sudoku_instance)) solve!(s) display(solution(s)) display(s.time_stamps) end @testset "Raw solver: golomb" begin s = solver(golomb(5); options = Options(print_level = :minimal, iteration = 1000)) solve!(s) @info "Results golomb!" @info "Values: $(get_values(s))" @info "Sol (val): $(best_value(s))" @info "Sol (vals): $(!isnothing(best_value(s)) ? best_values(s) : nothing)" end @testset "Raw solver: mincut" begin graph = zeros(5, 5) graph[1, 2] = 1.0 graph[1, 3] = 2.0 graph[1, 4] = 3.0 graph[2, 5] = 1.0 graph[3, 5] = 2.0 graph[4, 5] = 3.0 s = solver( mincut(graph, source = 1, sink = 5), options = Options(print_level = :minimal)) solve!(s) @info "Results mincut!" @info "Values: $(get_values(s))" @info "Sol (val): $(best_value(s))" @info "Sol (vals): $(!isnothing(best_value(s)) ? best_values(s) : nothing)" s = solver(mincut(graph, source = 1, sink = 5, interdiction = 1), options = Options(print_level = :minimal)) solve!(s) @info "Results 1-mincut!" @info "Values: $(get_values(s))" @info "Sol (val): $(best_value(s))" @info "Sol (vals): $(!isnothing(best_value(s)) ? best_values(s) : nothing)" s = solver(mincut(graph, source = 1, sink = 5, interdiction = 2); options = Options(print_level = :minimal, time_limit = 15, iteration = Inf)) # @info describe(s) solve!(s) @info "Results 2-mincut!" @info "Values: $(get_values(s))" @info "Sol (val): $(best_value(s))" @info "Sol (vals): $(!isnothing(best_value(s)) ? best_values(s) : nothing)" @info time_info(s) end
LocalSearchSolvers
https://github.com/JuliaConstraints/LocalSearchSolvers.jl.git
[ "MIT" ]
0.4.9
e592c828aabfbc829a55af6edbac589681bdf856
code
394
using Distributed import ConstraintDomains import CompositionalNetworks @everywhere using Constraints using Dictionaries @everywhere using LocalSearchSolvers using Test using TestItemRunner using TestItems const LS = LocalSearchSolvers @testset "LocalSearchSolvers.jl" begin include("Aqua.jl") include("TestItemRunner.jl") include("internal.jl") include("raw_solver.jl") end
LocalSearchSolvers
https://github.com/JuliaConstraints/LocalSearchSolvers.jl.git
[ "MIT" ]
0.4.9
e592c828aabfbc829a55af6edbac589681bdf856
docs
5469
# LocalSearchSolvers [![Docs](https://img.shields.io/badge/docs-dev-blue.svg)](https://JuliaConstraints.github.io/LocalSearchSolvers.jl/dev) [![Docs](https://img.shields.io/badge/docs-stable-blue.svg)](https://JuliaConstraints.github.io/LocalSearchSolvers.jl/stable) [![Build Status](https://github.com/JuliaConstraints/LocalSearchSolvers.jl/workflows/CI/badge.svg)](https://github.com/JuliaConstraints/LocalSearchSolvers.jl/actions) [![codecov](https://codecov.io/gh/JuliaConstraints/LocalSearchSolvers.jl/branch/main/graph/badge.svg?token=4T0VEWISUA)](https://codecov.io/gh/JuliaConstraints/LocalSearchSolvers.jl) [![Code Style: Blue](https://img.shields.io/badge/code%20style-blue-4495d1.svg)](https://github.com/invenia/BlueStyle) # Constraint-Based Local Search Framework The **LocalSearchSolvers.jl** framework proposes sets of technical components of Constraint-Based Local Search (CBLS) solvers and combine them in various ways. Make your own CBLS solver! A higher-level *JuMP* interface is available as [CBLS.jl](https://github.com/JuliaConstraints/CBLS.jl) and is the recommended way to use this package. A set of examples is available within [ConstraintModels.jl](https://github.com/JuliaConstraints/ConstraintModels.jl). ![](img/sudoku3x3.png) ### Dependencies This package makes use of several dependencies from the JuliaConstraints GitHub org: - [ConstraintDomains.jl](https://github.com/JuliaConstraints/ConstraintDomains.jl): a domains back-end package for all JuliaConstraints front packages - [Constraints.jl](https://github.com/JuliaConstraints/Constraints.jl): a constraints back-end package for all JuliaConstraints front packages - [CompositionalNetworks.jl](https://github.com/JuliaConstraints/CompositionalNetworks.jl): a module to learn error functions automatically given a *concept* - [Garamon.jl](https://github.com/JuliaConstraints/Garamon.jl) (incoming): geometrical constraints It also relies on great packages from the julialang ecosystem, among others, - [ModernGraphs.jl](https://github.com/Humans-of-Julia/ModernGraphs.jl) (incoming): a dynamic multilayer framework for complex graphs which allows a fine exploration of entangled neighborhoods ### Related packages - [JuMP.jl](https://github.com/jump-dev/JuMP.jl): a rich interface for optimization solvers - [CBLS.jl](https://github.com/JuliaConstraints/CBLS.jl): the actual interface with JuMP for `LocalSearchSolvers.jl` - [ConstraintModels.jl](https://github.com/JuliaConstraints/ConstraintModels.jl): a dataset of models for Constraint Programming - [COPInstances.jl](https://github.com/JuliaConstraints/COPInstances.jl) (incoming): a package to store, download, and generate combinatorial optimization instances ### Features Wanted features list: - **Strategies** - [ ] *Move*: local move, permutation between `n` variables - [ ] *Neighbor*: simple or multiplexed neighborhood, dimension/depth - [ ] *Objective(s)*: single/multiple objectives, Pareto, etc. - [ ] *Parallel*: distributed and multi-threaded, HPC clusters - [ ] *Perturbation*: dynamic, restart, pool of solutions - [ ] *Portfolio*: portfolio of solvers, partition in sub-problems - [ ] *Restart* - [x] restart sequence - [ ] partial/probabilistic restart (in coordination with perturbation strategies) - [ ] *Selection* of variables: roulette selection, multi-variables, meta-variables (cf subproblem) - [ ] *Solution(s)*: management of pool, best versus diverse - [x] *Tabu* - [x] No Tabu - [x] Weak-tabu - [x] Keen-tabu - [ ] *Termination*: when, why, how, interactive, results storage (remote) - **Featured strategies** - [ ] Adaptive search - [ ] Extremal optimization - **Others** - [ ] Resolution of problems - [x] SATisfaction - [x] OPTimisation (single-objective) - [ ] OPTimisation (multiple-objective) - [ ] Dynamic problems - [ ] Domains - [x] Discrete domains (any type of numbers) - [x] Continuous domains - [ ] Arbitrary Objects such as physical ones - [ ] Domain Specific Languages (DSL) - [x] Straight Julia `:raw` - [x] JuMP*ish* | MathOptInterface.jl - [ ] MiniZinc - [ ] OR-tools ? - [ ] Learning settings (To be incorporated in [MetaStrategist.jl](https://github.com/JuliaConstraints/MetaStrategist.jl)) - [x] Compositional Networks (error functions, cost functions) - [ ] Reinforcement learning for above mentioned learning features - [ ] Automatic benchmarking and learning from all the possible parameter combination (instance, model, solver, size, restart, hardware, etc.) ### Contributing Contributions to this package are more than welcome and can be arbitrarily, and not exhaustively, split as follows: - All features mentioned above - Adding new constraints and symmetries - Adding new problems and instances - Adding new ICNs to learn error of existing constraints - Creating other compositional networks which target other kind of constraints - Just making stuff better, faster, user-friendlier, etc. #### Contact Do not hesitate to contact me (@azzaare) or other members of JuliaConstraints on GitHub (file an issue), the julialang [Discourse](https://discourse.julialang.org) forum, the julialang [Slack](https://julialang.org/slack/) workspace, the julialang [Zulip](https://julialang.zulipchat.com/) server (*Constraint Programming* stream), or the Humans of Julia [Humans-of-Julia](https://humansofjulia.org/) discord server(*julia-constraint* channel).
LocalSearchSolvers
https://github.com/JuliaConstraints/LocalSearchSolvers.jl.git
[ "MIT" ]
0.1.7
79e541dc38e1b13ceb024af4fb5f87a10bfbea85
code
339
push!(LOAD_PATH, "../src/") using BellDiagonalQudits using Documenter makedocs( sitename="BellDiagonalQudits.jl", modules=[BellDiagonalQudits], pages=[ "Home" => "index.md", "Manual" => "manual.md", "Library" => "library.md" ]) deploydocs(; repo="github.com/kungfugo/BellDiagonalQudits.jl" )
BellDiagonalQudits
https://github.com/kungfugo/BellDiagonalQudits.jl.git
[ "MIT" ]
0.1.7
79e541dc38e1b13ceb024af4fb5f87a10bfbea85
code
1763
module BellDiagonalQudits using LinearAlgebra: eigvals, I, Hermitian, tr, dot, normalize, Diagonal, norm, svd using QuantumInformation: proj, ket, bra, ketbra, max_entangled, ⊗, reshuffle, norm_trace, ppt, fidelity using Distributions: Uniform, Normal using Permutations: Permutation using LazySets: VPolytope, HPolytope, tohrep, tovrep, vertices_list, ∈ using Polyhedra using Optim using AbstractAlgebra: inv, residue_ring, ZZ export CoordState, StandardBasis, DensityState, BoundedCoordEW, AnalysisSpecification, ClassConflictException, AnalysedCoordState, uniform_bell_sampler, create_random_coordstates, create_standard_indexbasis, create_densitystate, create_bipartite_weyloperator_basis, create_alt_indexbasis, create_altbellstate, create_kernel_polytope, extend_vpolytope_by_densitystates, create_random_bounded_ews, get_bounded_coordew, generate_symmetries, get_symcoords, analyse_coordstate, sym_analyse_coordstate, classify_analyzed_states!, concurrence_qp_gendiagonal_check, create_dictionary_from_basis, create_standard_mub, tovrep, FIMAX_routine, P1_P2_routine, DEJMPS_routine, BBPSSW_routine, iterative_FIMAX_protocol, iterative_P1_P2_protocol, iterative_DEJMPS_protocol, iterative_BBPSSW_protocol, efficiency include("structs.jl") include("Utils/utils.jl") include("BellStates/bellStates.jl") include("Parameterization/parameterization.jl") include("Optimization/optimization.jl") include("EntanglementWitnesses/eWitnesses.jl") include("Symmetries/symmetries.jl") include("EntanglementChecks/concurrence.jl") include("EntanglementChecks/mub.jl") include("EntanglementChecks/entanglementChecks.jl") include("SeparableStates/separableStates.jl") include("Distillation/stabilizerDistillation.jl") end
BellDiagonalQudits
https://github.com/kungfugo/BellDiagonalQudits.jl.git
[ "MIT" ]
0.1.7
79e541dc38e1b13ceb024af4fb5f87a10bfbea85
code
4588
""" Represents a Bell basis related to Weyl operators. - basis: Array with elements containing Bell basis density matrices, Weyl- and flat indices. """ struct StandardBasis basis::Array{Tuple{Int64,Tuple{Int64,Int64},Array{Complex{Float64},2}},1} end; """ Represents a Bell diagonal state in Bell basis. - coords: Coordinates in Bell basis. - eClass: Entanglement class of the represented state. """ mutable struct CoordState coords::Array{Float64,1} eClass::String end; """ Represents a Bell diagonal state. - coords: Coordinates in Bell basis. - densityMatrix: Hermitian density matrix in computational basis. - eClass: Entanglement class of the represented state. """ mutable struct DensityState coords::Array{Float64,1} densityMatrix::Hermitian{Complex{Float64},Array{Complex{Float64},2}} eClass::String end; """ Represents an operator to detect Bell diagonal entangled states. - coords: Coordinates in Bell basis - operatorMatrix: Hermitian matrix representing the linear operator in computational basis. """ mutable struct EntanglementWitness coords::Array{Float64,1} operatorMatrix::Hermitian{Complex{Float64},Array{Complex{Float64},2}} end; """ Represents an entanglement witness ``W`` with extrema and extremizers to detect entangled Bell diagonal states. - coords: Coordinates in Bell basis. - upperBound: Upper bound of ``tr W \\rho`` satisfied by all separable states ``\\rho``. Violation detects entanglement. - lowerBound: Lower bound of ``tr W \\rho`` satisfied by all separable states ``\\rho``. Violation detects entanglement. - maximizingDensityMatrix: Density matrix of separable state ``\\rho`` in computational basis, maximizing ``tr W \\rho``. - minimizingDensityMatrix: Density matrix of separable state ``\\rho`` in computational basis. minimizing ``tr W \\rho``. - checkedIterations: Number of iterations used in the optimization of bounds. """ mutable struct BoundedEW coords::Array{Float64,1} upperBound::Float64 lowerBound::Float64 maximizingDensityMatrix::Hermitian{Complex{Float64},Array{Complex{Float64},2}} minimizingDensityMatrix::Hermitian{Complex{Float64},Array{Complex{Float64},2}} checkedIterations::Int64 end; """ Represents an entanglement witness ``W`` with extrema to detect entangled Bell diagonal states. - coords: Coordinates in Bell basis. - upperBound: Upper bound of ``tr W \\rho`` satisfied by all separable states ``\\rho``. Violation detects entanglement. - lowerBound: Lower bound of ``tr W \\rho`` satisfied by all separable states ``\\rho``. Violation detects entanglement. - checkedIterations: Number of iterations used in the optimization of bounds. """ mutable struct BoundedCoordEW coords::Array{Float64,1} upperBound::Float64 lowerBound::Float64 checkedIterations::Int64 end; """ Specification which entanglement checks to use. - kernel_check - spinrep_check - ppt_check - realignment_check - concurrence_qp_check - mub_check - numeric_ew_check - useSymmetries """ mutable struct AnalysisSpecification kernel_check::Bool spinrep_check::Bool ppt_check::Bool realignment_check::Bool concurrence_qp_check::Bool mub_check::Bool numeric_ew_check::Bool useSymmetries::Bool end """ Representing an entanglement analyzed Bell diagonal state. - coordState: The analyzed `CoordState` - kernel: `true` if kernel check successful, else `false`. `missing` if entanglement check not applied. - spinrep: `true` if spinrep check successful, else `false`. `missing` if entanglement check not applied. - ppt: `true` if ppt check successful, else `false`. `missing` if entanglement check not applied. - realign: `true` if realignment check successful, else `false`. `missing` if entanglement check not applied. - concurrence: `true` if concurrence check successful, else `false`. `missing` if entanglement check not applied. - mub: `true` if mub check successful, else `false`. `missing` if entanglement check not applied. - numericEW: `true` if numericEW check successful, else `false`. `missing` if entanglement check not applied. """ mutable struct AnalysedCoordState coordState::CoordState kernel::Union{Missing,Bool} spinrep::Union{Missing,Bool} ppt::Union{Missing,Bool} realign::Union{Missing,Bool} concurrence::Union{Missing,Bool} mub::Union{Missing,Bool} numericEW::Union{Missing,Bool} end; """ Exception for conflicts in analysis results. - state: The `AnalysedCoordState` for which a conflict occurs. """ struct ClassConflictException <: Exception state::AnalysedCoordState end;
BellDiagonalQudits
https://github.com/kungfugo/BellDiagonalQudits.jl.git
[ "MIT" ]
0.1.7
79e541dc38e1b13ceb024af4fb5f87a10bfbea85
code
11864
""" uniform_bell_sampler(n, d, object=:magicSimplex, precision=10) Create array of `n` uniformly distributed ``d^2`` Bell diagonal states represented as `CoordState` rounded to `precision` digits. Use `object=:enclosurePolytope` to create CoordStates in the enclosure polytope, having all ``coords \\leq 1/d``. """ function uniform_bell_sampler(n, d, object=:magicSimplex, precision=10) productParams = Array{CoordState}(undef, 0) nFound = 0 while nFound < n u = zeros(d^2 + 1) u[2:(d^2)] = sort(vec(rand(Uniform(0, 1), 1, (d^2 - 1)))) u[d^2+1] = 1 coords = round.(diff(u), digits=precision) if object != :enclosurePolytope || all(x -> x <= 1 / d, coords) push!(productParams, CoordState(coords, "UNKNOWN")) nFound += 1 end end return productParams end """ create_random_coordstates(nSamples, d, object=:magicSimplex, precision=10, roundToSteps::Int=0, nTriesMax=10000000) Return an array of `nSamples` `` d^2 `` dimensional CoordStates. Use the `object` to specify the coordinate ranges to [0,1] for 'magicSimplex' or [0, 1/d] for 'enclosurePolytope'. If `roundToSteps` > 0, round the coordinates to the vertices that divide the range in `roundToSteps`` equally sized sections. Be aware that the resulting distribution of points is generally not uniform. """ function create_random_coordstates(nSamples, d, object=:magicSimplex, precision=10, roundToSteps::Int=0)::Array{CoordState} productParams = Array{CoordState}(undef, 0) nFound = 0 if object != :enclosurePolytope while (nFound < nSamples) # only parameters which build a convex sum relevant c = vec(rand(Uniform(0, 1), 1, (d^2 - 1))) # If wanted, move random point to nearest step-point if roundToSteps > 0 c = round.(roundToSteps * c) / roundToSteps end c = round.(c, digits=precision) if sum(c) <= 1 push!(c, round(1 - sum(c), digits=precision)) paramState = CoordState(c, "UNKNOWN") push!(productParams, paramState) nFound += 1 end end else while (nFound < nSamples) c = vec(rand(Uniform(0, 1 / d), 1, (d^2 - 1))) if roundToSteps > 0 c = round.(roundToSteps * d * c) / (roundToSteps * d) end c = round.(c, digits=precision) if (1 - 1 / d) <= sum(c) <= 1 push!(c, round(1 - sum(c), digits=precision)) paramState = CoordState(c, "UNKNOWN") push!(productParams, paramState) nFound += 1 end end end return productParams end """ create_bipartite_maxentangled(d) Return maximally entangled pure state of a bipartite system of dimension ``d^2``. """ function create_bipartite_maxentangled(d) return proj(max_entangled(d * d)) end """ weyloperator(d, k, l) Return the ``(d,d)``- dimensional matrix representation of Weyl operator ``W_{k,l}``. """ function weyloperator(d, k, l) weylKetBra = zeros(Complex{Float64}, d, d) for j in (0:d-1) weylKetBra = weylKetBra + exp((2 / d * π * im) * j * k) * ketbra(j + 1, mod(j + l, d) + 1, d, d) end return weylKetBra end """ get_intertwiner(d, k, l) Return the tensor product ``W_{k,l} \\otimes \\mathbb{1}_d``. """ function get_intertwiner(d, k, l) w = weyloperator(d, k, l) Id = I(d) return w ⊗ Id end """ weyltrf(d, ρ, k, l) Apply the ``(k,l)``-th Weyl transformation of dimension `d` to the density matrix `ρ`. Return ``W_{k,l} \\rho W_{k,l}^\\dagger``. """ function weyltrf(d, ρ, k, l) @assert size(ρ)[1] == d * d && size(ρ)[2] == d * d W = get_intertwiner(d, k, l) ρTrf = W * ρ * W' return ρTrf end """ create_basis_state_operators(d, bellStateOperator, precision) Use maximally entangled Bell state `bellStateOperator` of dimension `d` to create Bell basis and return with corresponding flat and Weyl indices. """ function create_basis_state_operators(d, bellStateOperator, precision) mIt = Iterators.product(fill(0:(d-1), 2)...) basisStates = Array{ Tuple{ Int, Tuple{Int,Int}, Array{Complex{Float64},2} }, 1}(undef, 0) for (index, value) in enumerate(mIt) k = value[1] l = value[2] #Weyl transformation to basis states P_kl = Hermitian(round.(weyltrf(d, bellStateOperator, k, l), digits=precision)) push!(basisStates, (index, value, P_kl)) end return basisStates end """ create_standard_indexbasis(d, precision) Return indexed Bell basis for `d` dimensions as `StandardBasis` rounded to `precision` digits. """ function create_standard_indexbasis(d, precision)::StandardBasis maxEntangled = create_bipartite_maxentangled(d) standardBasis = StandardBasis(create_basis_state_operators(d, maxEntangled, precision)) return standardBasis end """ create_densitystate(coordState::CoordState, standardBasis::StandardBasis) Return `DensityState`` containing the density matrix in computational basis based on `coordState` coordinates in Bell `standardBasis`. """ function create_densitystate(coordState::CoordState, standardBasis::StandardBasis)::DensityState basisOps = map(x -> x[3], standardBasis.basis) densityState = DensityState( coordState.coords, Hermitian(generic_vectorproduct(coordState.coords, basisOps)), coordState.eClass ) return densityState end """ create_weyloperator_basis(d) Return vector of length ``d^2``, containing the Weyl operator basis for the ``(d,d)`` dimensionalmatrix space. """ function create_weyloperator_basis(d)::Vector{Array{Complex{Float64},2}} weylOperatorBasis = [] for i in (0:(d-1)) for j in (0:(d-1)) push!(weylOperatorBasis, weyloperator(d, i, j)) end end return weylOperatorBasis end """ create_bipartite_weyloperator_basis(d) Return vector of length ``d^4``, containing the product basis of two Weyl operator bases as basis for the ``(d^2,d^2)`` matrix space. """ function create_bipartite_weyloperator_basis(d)::Vector{Array{Complex{Float64},2}} weylOperatorBasis = create_weyloperator_basis(d) bipartiteWeylOperatorBasis = [] for k in weylOperatorBasis for l in weylOperatorBasis push!(bipartiteWeylOperatorBasis, k ⊗ l) end end return bipartiteWeylOperatorBasis end """ create_dimelement_sublattices(d) Return all sublattices with `d` elements represented as vector of tuples in the ``d^2`` elements discrete phase space induced by Weyl operators. """ function create_dimelement_sublattices(d) propDivs = get_properdivisors(d) allLattices = Array{Array{Tuple{Int,Int},1},1}(undef, 0) allPoints = Iterators.product(fill(0:(d-1), 2)...) for point in allPoints px = point[1] py = point[2] # Get horizontal line through point sSubLattice = Array{Tuple{Int,Int},1}(undef, 0) for s in (0:(d-1)) sPoint = ((px + s) % d, py) push!(sSubLattice, sPoint) end push!(allLattices, sSubLattice) # Get vertical and diagonal lines through point for k in (0:(d-1)) kSubLattice = Array{Tuple{Int,Int},1}(undef, 0) for s in (0:(d-1)) ksPoint = ((px + k * s) % d, (py + s) % d) push!(kSubLattice, ksPoint) end push!(allLattices, kSubLattice) end # Get sublattices including point for b in propDivs for x in (0:b-1) xbSubLattice = Array{Tuple{Int,Int},1}(undef, 0) for u in (0:(d/b-1)) for v in (0:(b-1)) xuvbPoint = ((px + u * b + x * b) % d, (py + v * d / b) % d) push!(xbSubLattice, xuvbPoint) end end push!(allLattices, xbSubLattice) end end end # remove duplicates allLattices = unique(sort.(allLattices)) return allLattices end """ create_index_sublattice_state(standardBasis::StandardBasis, subLattice) Return collection of `standardBasis` elements contributing to the state corresponding to the `sublattice`, coordinates in Bell basis and density matrix in computational basis. """ function create_index_sublattice_state(standardBasis::StandardBasis, subLattice) lengthSub = length(subLattice) subBasisStates = Array{ Tuple{ Int, Array{Complex{Float64},2} }, 1}(undef, 0) #Go through all points and select for each the index and basis state for point in subLattice # find basis state that belongs to the given element of the sublattice foundIndex = findfirst(x -> x[2] == point, standardBasis.basis) push!(subBasisStates, (foundIndex, standardBasis.basis[foundIndex][3])) end indices = Array{Int,1}(undef, 0) subLatticeState = zeros(Complex{Float64}, size(standardBasis.basis[1][3])) # Collect indices and add basis state for state in subBasisStates push!(indices, state[1]) subLatticeState = subLatticeState + state[2] end #Get corresponding coordinates coordinates = map_indices_to_normcoords(indices, length(standardBasis.basis)) # Collection of indices of basis elements which are equally mixed indexSubLatticeState = [indices, coordinates, 1 / lengthSub * subLatticeState] return indexSubLatticeState end """ altbell_creatingoperator(d, k, l, α) Return the ``(d,d)``- dimensional matrix representation of an alternative operator that is used to create Bell states ``V_{k,l}``. ``V_{k,l} ⊗ Id Ω_00`` creates ``1/√d * ∑ω^(ks)*α_(s,l) ket{s-l} ⊗ ket{s}`` """ function altbell_creatingoperator(d, k, l, α::Matrix{Complex{Float64}}) operatorKetBra = zeros(Complex{Float64}, d, d) @assert size(α) == (d, d) #Normalize α = map(x -> x / abs(x), α) for j in (0:d-1) operatorKetBra = operatorKetBra + ( exp((2 / d * π * im) * (j + l) * k) * α[mod(j + l, d)+1, l+1] * ketbra(j + 1, mod(j + l, d) + 1, d, d) ) end return operatorKetBra end """ create_altbellstate(state(d,k,l,α, returnDensity) Return an alternative Bell state in the computational basis. Return denisty matrix unless returnDensity=false, in which case return state vector. """ function create_altbellstate(d, k, l, α::Matrix{Complex{Float64}}, returnDensity::Bool=true) V_kl = altbell_creatingoperator(d, k, l, α) IV_kl = V_kl ⊗ I(d) me = max_entangled(d * d) if returnDensity return (proj(IV_kl * me)) else return (IV_kl * me) end end """ create_alt_indexbasis(d, l, α, precision) Return alternative indexed Bell basis for `d` dimensions as `StandardBasis` rounded to `precision` digits. Elements of secondary index `l` are replaced by alternative Bell state defined by `d`-element vector of phases `α`. """ function create_alt_indexbasis(d, α::Matrix{Complex{Float64}}, precision)::StandardBasis altIndexbasis = create_standard_indexbasis(d, precision) for (k, l) in Iterators.product(fill(0:(d-1), 2)...) #Weyl transformation to basis states P_alt_kl = rounddigits(Hermitian(create_altbellstate(d, k, l, α)), precision) #Find corresponding standard basis element elIndex = findfirst(x -> x[2] == (k, l), altIndexbasis.basis) #Replace element altIndexbasis.basis[elIndex] = (elIndex, (k, l), P_alt_kl) end return (altIndexbasis) end
BellDiagonalQudits
https://github.com/kungfugo/BellDiagonalQudits.jl.git
[ "MIT" ]
0.1.7
79e541dc38e1b13ceb024af4fb5f87a10bfbea85
code
24759
""" canonic_eigenbasis_weylprime(d, E) Create array of eigenvectors-eigenvalue tuples for Weyl operator indexed by tuple `E` in dimension `d`. """ function canonic_eigenbasis_weylprime(d, E::Tuple{Int,Int}) (a, b) = E ES = [] if d == 2 for n in 0:1 if (a, b) == (0, 0) λ = 0 ev_n = (modket(n, 2), λ) elseif b == 0 λ = n ev_n = (modket(n * b, 2), λ) else λ = n + 1 / 2 * (mod(a * b, 2)) ev_n = (1 / sqrt(2) * (modket(0, 2) + exp(2 / d * π * im*λ) * modket(1, 2)), λ) end push!(ES, ev_n) end else R, = residue_ring(ZZ, d) for λ in 0:(d-1) if (a, b) == (0, 0) ev_λ = (modket(λ, d), 0) elseif b == 0 inv_a = Int(inv(R(a)).data) ev_λ = (modket(λ * inv_a, d), λ) else inv_b = Int(inv(R(b)).data) if d == 2 inv_2 = 0 else > inv_2 = Int(inv(R(2)).data) end ev = 1 / sqrt(d) * modket(0, d) for j in 1:(d-1) Γ_λj = Int(R(j * inv_b * λ - j * inv_b * (j * inv_b - 1) * inv_2 * a * b).data) ev += 1 / sqrt(d) * exp(2 / d * π * im * Γ_λj) * modket(j, d) end ev_λ = (ev, λ) end push!(ES, ev_λ) end end return (ES) end """ create_canonic_enconding(g, d) Return unitary matrix as encoding for generating stabilizer element `g` in demension`d`. """ function create_canonic_enconding(g::Vector{Tuple{Int,Int}}, d) @assert length(g) == 2 (i_1, j_1) = g[1] (i_2, j_2) = g[2] ES1 = canonic_eigenbasis_weylprime(d, g[1]) ES2 = canonic_eigenbasis_weylprime(d, g[2]) if d == 2 u = [] for b in 0:1 λ = mod(b + 1 / 2 * mod(i_1 * j_1 + i_2 * j_2, 2), 2) for k1 in 0:1 (k1_v, k1_λ1) = (ES1[k1+1][1], ES1[k1+1][2]) for k2 in 0:1 (k2_v, k2_λ2) = (ES2[k2+1][1], ES2[k2+1][2]) if (mod(k1_λ1 + k2_λ2, 2) == mod(λ, 2)) u_bk = k1_v ⊗ k2_v push!(u, u_bk) end end end end else u = [] for b in 0:(d-1) for k1 in 0:(d-1) (k1_v, k1_b) = (ES1[k1+1][1], ES1[k1+1][2]) for k2 in 0:(d-1) (k2_v, k2_b) = (ES2[k2+1][1], ES2[k2+1][2]) if (mod(k1_b + k2_b, d) == b) u_bk = k1_v ⊗ k2_v push!(u, u_bk) end end end end end @assert length(u) == d^2 U = stack(u) return (U) end #Optional function create_X_set_from_encodings(U, V) X_set = [] for m in 0:d-1 X_m = complex(zeros(d, d)) for a in 0:(d-1), b in 0:(d-1) ma_index = findfirst(modket(m, d) ⊗ modket(a, d) .== 1) mb_index = findfirst(modket(m, d) ⊗ modket(b, d) .== 1) u_ma = U[:, ma_index] v_mb = V[:, mb_index] X_m += u_ma' * v_mb * modket(a, d) * modbra(b, d) end push!(X_set, X_m) end return (X_set) end """ get_s_for_generator(g, E) Return s-value of error element `E`` for stabilzer generator `g` in dimension `d`. """ function get_s_for_generator(g::Vector{Tuple{Int,Int}}, E::Vector{Tuple{Int,Int}}, d) @assert length(g) == length(E) s = 0 for n in eachindex(g) s += g[n][2] * E[n][1] - g[n][1] * E[n][2] end return (mod(s, d)) end """ get_erroroperator_from_errorelement(E, d) Return error operator in computational basis from error element `E` in dimension `d`. """ function get_erroroperator_from_errorelement(E::Vector{Tuple{Int,Int}}, d) e = first(E) w = weyloperator(d, e[1], e[2]) for el in E[2:lastindex(E)] w = w ⊗ weyloperator(d, el[1], el[2]) end return (w) end """ get_erroraction_from_encoding(U, W, bVec, sVec, d ) Create error action operator for an error `W` in encoding `U` for measurment outcomes `bVec` and `sVec` in dimension `d`. """ function get_erroraction_from_encoding(U, W, bVec, sVec, d) @assert size(U) == size(W) @assert length(bVec) == length(sVec) == 1 b = bVec[1] s = sVec[1] Y = U' * W * U T = complex(zeros(d, d)) for k in 0:(d-1), l in 0:(d-1) Tkl = (modbra(b + s, d) ⊗ modbra(k, d)) * Y * (modket(b, d) ⊗ modket(l, d)) T += Tkl * (modket(k, d) ⊗ modbra(l, d)) end return T end """ get_s_dict_for_generators(gVec, n, d) Create Dict containing the s-values for each error element (keys) for stabilizer generating elements `gVec` for `n`-copies in dimension `d`. """ function get_s_dict_for_generators(gVec::Vector{Vector{Tuple{Int,Int}}}, n, d) @assert n == 2 @assert length(gVec) == 1 dict = Dict() for i1 in 0:(d-1), j1 in 0:(d-1), i2 in 0:(d-1), j2 in 0:(d-1) E = [(i1, j1), (i2, j2)] sVec = Int[] for g in gVec s = get_s_for_generator(g, E, d) push!(sVec, s) end dict[E] = sVec end return (dict) end """ get_codespace_errorops_for_meas(U, gVec, aVec, bVec) For given encoding `U` of a stabilizer with generating elements `gVec` and measurement outcomes `aVec` and `bVec`, return Dict of error elements (keys) and error action operators (values). """ function get_codespace_errorops_for_meas(U, gVec::Vector{Vector{Tuple{Int,Int}}}, aVec::Vector{Int}, bVec::Vector{Int}, n, d) @assert length(aVec) == length(bVec) == 1 @assert n == 2 sVec = map(x -> mod(x, d), aVec - bVec) s_dict = get_s_dict_for_generators(gVec, n, d) codespace_errorops_dict = filter(x -> x[2] == sVec, s_dict) for errorkey in keys(codespace_errorops_dict) W_errorop = get_erroroperator_from_errorelement(errorkey, d) cs_errorop = get_erroraction_from_encoding(U, W_errorop, bVec, sVec, d) codespace_errorops_dict[errorkey] = cs_errorop end return (codespace_errorops_dict) end """ get_stdbasis_probabilities(ρ, stdBasis, precision) Return probability of measuring a Bell `stdBasis` state for `ρ` in `precision`. """ function get_stdbasis_probabilities(ρ, stdBasis, precision=10) basis = stdBasis.basis probs = map(x -> (x[1], x[2], (tr(ρ * x[3]) |> real |> (y -> rounddigits(y, precision)))), basis) return (probs) end """ get_prob_for_E(ρ, E, stdBasis) Return probability of measurment of `stdBasis` corresponding to error element `E` in state `ρ`. """ function get_prob_for_E(ρ, E::Vector{Tuple{Int,Int}}, stdbasis) stdbasisProbs = get_stdbasis_probabilities(ρ, stdbasis, 10) pE = 1 for Em in E pEm = real(first(filter(x -> x[2] == Em, stdbasisProbs))[3]) pE *= pEm end return (pE) end """ get_s_errorkeys(gVec, sVec, n, d) Return all errors with `sValue` for `n`-cope stabilizer generators `gVec` in `d` dimenions. """ function get_s_errorkeys(gVec, sVec, n, d) @assert n == 2 sDict = get_s_dict_for_generators(gVec, n, d) ES = keys(filter(x -> x[2] == sVec, sDict)) return (ES) end """ get_prob_for_errorkeys(ρ, errorKeys, n, stdBasis) Get total error probability for `n`-copy `errorKeys` defined by `stdBasis` in `rho`. """ function get_prob_for_errorkeys(ρ, errorKeys, n, stdbasis) @assert n == 2 pS = 0 for E in errorKeys pE = get_prob_for_E(ρ, E, stdbasis) pS += pE end return (pS) end """ get_abelian_subgroup_generators(d, n) Return all generators of abelian subgroups for the `n`-copy weyl-Heisenberg group in `d` dimensions. """ function get_abelian_subgroup_generators(d, n) @assert n == 2 @assert d ∈ (2, 3) potentialGenerators = Vector{Tuple{Int,Int}}[] generators = Vector{Tuple{Int,Int}}[] for i1 in 0:(d-1), j1 in 0:(d-1), i2 in 0:(d-1), j2 in 0:(d-1) if (i1, j1, i2, j2) !== (0, 0, 0, 0) E = [(i1, j1), (i2, j2)] push!(potentialGenerators, E) end end while !isempty(potentialGenerators) g = first(potentialGenerators) push!(generators, g) gg = add_errorkeys(g, g, d, n) filter!(x -> x != g, potentialGenerators) filter!(x -> x != gg, potentialGenerators) end return (generators) end """ get_coset_partition(gVec, n, d) Return coset partition of error elements defined by stabilizer generating elements `gVec` of `n`-copies in `d` dimensions. """ function get_coset_partition(gVec, n, d) @assert n == 2 @assert d ∈ (2, 3) @assert length(gVec) == 1 @assert gVec[1] !== [(0, 0), (0, 0)] g = gVec[1] gg = add_errorkeys(g, g, d, n) errorKeys = Vector{Tuple{Int,Int}}[] for i1 in 0:(d-1), j1 in 0:(d-1), i2 in 0:(d-1), j2 in 0:(d-1) if (i1, j1, i2, j2) !== (0, 0, 0, 0) E = [(i1, j1), (i2, j2)] push!(errorKeys, E) end end cosets = Vector{Vector{Tuple{Int,Int}}}[] while !isempty(errorKeys) coset = Vector{Tuple{Int,Int}}[] E = first(errorKeys) push!(coset, E) for x in 1:(d-1) E = add_errorkeys(E, g, d, n) push!(coset, E) end push!(cosets, coset) filter!(x -> !(x ∈ coset), errorKeys) end return (cosets) end """ get_cosets_prob_s(ρ, gVec, n, d, stdbasis) Return vector of tuples containing the cosets defined by stabilizer generating elements `gVec` for `n`-copies in`d` dimensions together with its s-value and probabilies in the `stdbasis`. """ function get_cosets_prob_s(ρ, gVec, n, d, stdbasis) s_dict = get_s_dict_for_generators(gVec, n, d) cosets = get_coset_partition(gVec, n, d) cosetsProbS = map(c -> (c, s_dict[c[1]], get_prob_for_errorkeys(ρ, c, n, stdbasis)), cosets) return (cosetsProbS) end """ get_s_prob_dict(ρ, gVec, n, d, stdbasis) Return Dict of `stdbasis` probabilities (values) for each s-value (keys) in `n`-copy state `rho` of subsystem dimension `d`. """ function get_s_prob_dict(ρ, gVec, n, d, stdbasis) s_dict = get_s_dict_for_generators(gVec, n, d) s_values = unique(values(s_dict)) s_prob_dict = Dict() for sVec in s_values ES = get_s_errorkeys(gVec, sVec, n, d) PS = get_prob_for_errorkeys(ρ, ES, n, stdbasis) s_prob_dict[sVec] = PS end return (s_prob_dict) end """ get_s_normalized_coset_probs(ρ, gVec, n, d, stdbasis) Return array of tuples containing the cosets and s-values defined by generating `n`-copy stabilizer elements `gVec` and the coset probabilitiies, normalized coset probabilites and the s-value probabilies for the `stdbasis` in `d` dimensions. """ function get_s_normalized_coset_probs(ρ, gVec, n, d, stdbasis) cosetProbS = get_cosets_prob_s(ρ, gVec, n, d, stdbasis) sProbDict = get_s_prob_dict(ρ, gVec, n, d, stdbasis) #remove zero probability sVecs filter!(x -> x[2] > 0, sProbDict) filter!(x -> x[2] ∈ keys(sProbDict), cosetProbS) normCosetProbs = map(x -> (x[1], x[2], x[3], x[3] / sProbDict[x[2]], sProbDict[x[2]]), cosetProbS) return (sort(normCosetProbs, by=(x -> -x[4]))) end """ get_max_fidelity_stabilizer_coset(ρ, n, d, stdbasis) Returns stabilizer generator, coset of maximal normalized probability and corresponding s-value, coset probabily and s-value probabily for `n`-copy input state `ρ` in `d` dimensions with respect to `stdbasis`. """ function get_max_fidelity_stabilizer_coset(ρ, n, d, stdbasis) allGens = get_abelian_subgroup_generators(d, n) maxFidelityStabCosets = map( g -> (g, first(get_s_normalized_coset_probs(ρ, [g], n, d, stdbasis))), allGens ) opt = sort(maxFidelityStabCosets, by=(x -> -x[2][4])) |> first return (opt[1], opt[2][1], opt[2][2], opt[2][4], opt[2][5]) end """ stabilizer_routine((ρ, gVec, aVec, bVec, Uenc, n, d, stdbasis) Return output state and probability of success for one iteration of the stabilizer distillation routine. The routine is defined by the input state `ρ`, the stabilizer generating element `gVec`, the measurement outcomes `aVec` and `bVec`, the encoding operator `Uenc`, the number of copies `n`, the dimension of the subsystems `d` and the standard Bell bases `stdbasis`. """ function stabilizer_routine(ρ, gVec, aVec, bVec, Uenc, n, d, stdbasis::StandardBasis) @assert length(stdbasis.basis) == d^2 @assert size(ρ) == (d^2, d^2) @assert n == 2 @assert length(gVec) == length(aVec) == length(bVec) == 1 sVec = aVec - bVec ES = get_s_errorkeys(gVec, sVec, n, d) PS = get_prob_for_errorkeys(ρ, ES, n, stdbasis) if rounddigits(PS, 10) == 0 return (ρ) end TES = get_codespace_errorops_for_meas(Uenc, gVec, aVec, bVec, n, d) P00 = stdbasis.basis[1][3] ρ_out = complex(zeros(d^2, d^2)) for E in ES pE = get_prob_for_E(ρ, E, stdbasis) TE = TES[E] ρ_out += pE * ( (TE ⊗ I(d)) * P00 * (TE ⊗ I(d))' ) end ρ_out = 1 / PS * ρ_out #Normalization return (ρ_out, PS) end """ FIMAX_routine(ρ, n, d, stdbasis) Applies one iteration of FIMAX routine to the `n`-copy input state `'rho` in `d` dimensions. Returns the output state and the probabilies of success with respect to the `stdbasis`. """ function FIMAX_routine(ρ, n, d, stdbasis::StandardBasis) @assert n == 2 @assert d ∈ (2, 3) maxFidelityStabilizerCoset = get_max_fidelity_stabilizer_coset(ρ, n, d, stdbasis) (g, cosetRep, sVec, successProb) = (x -> (x[1], x[2][1], x[3], x[5]))(maxFidelityStabilizerCoset) aVec = sVec bVec = aVec - sVec U_canonic = create_canonic_enconding(g, d) cosetRepOp = get_erroroperator_from_errorelement(cosetRep, d) cosetRepCodespaceErrorOp = get_erroraction_from_encoding(U_canonic, cosetRepOp, bVec, sVec, d) ρ_out_raw = stabilizer_routine(ρ, [g], aVec, bVec, U_canonic, n, d, stdbasis)[1] #Correction operation correctionOp = cosetRepCodespaceErrorOp' ρ_out = (correctionOp ⊗ I(d)) * ρ_out_raw * (correctionOp ⊗ I(d))' return (ρ_out, real(successProb)) end """ P1_routine(ρ, n, d, stdbasis) Applies one iteration of P1 routine to the `n`-copy input state `'rho` in `d` dimensions. Returns the output state and the probabilies of success with respect to the `stdbasis`. """ function P1_routine(ρ, n, d, stdbasis::StandardBasis) g = [(1, 0), (mod(-1, d), 0)] gVec = [g] aVec = [0] bVec = [0] U = create_canonic_enconding(g, d) (ρ, succProb) = stabilizer_routine(ρ, gVec, aVec, bVec, U, n, d, stdbasis) return (ρ, real(succProb)) end """ P2_routine(ρ, n, d, stdbasis) Applies one iteration of P2 routine to the `n`-copy input state `'rho` in `d` dimensions. Returns the output state and the probabilies of success with respect to the `stdbasis`. """ function P2_routine(ρ, n, d, stdbasis::StandardBasis) g = [(1, 0), (mod(-1, d), 0)] gVec = [g] aVec = [0] bVec = [0] U = create_canonic_enconding(g, d) bFT = (FT_OP(d) ⊗ conj(FT_OP(d))) ρ = bFT * ρ * bFT' (ρ, succProb) = stabilizer_routine(ρ, gVec, aVec, bVec, U, n, d, stdbasis) ρ = bFT * ρ * bFT' return (ρ, real(succProb)) end """ P1_P2_routine(ρ, n, d, stdbasis) Applies one iteration of P1_P2 routine to the `n`-copy input state `'rho` in `d` dimensions. Returns the output state and the probabilies of success with respect to the `stdbasis`. """ function P1_P2_routine(ρ, n, d, stdbasis::StandardBasis) basisDict = create_dictionary_from_basis(stdbasis) bellCoords = belldiagonal_projection(stdbasis, ρ).coords Z_indices = map(i -> basisDict[1][i], [(k, 0) for k in 0:(d-1)]) X_indices = map(i -> basisDict[1][i], [(0, k) for k in 0:(d-1)]) Z_error_sum = sum(bellCoords[Z_indices]) X_error_sum = sum(bellCoords[X_indices]) if Z_error_sum > X_error_sum (ρ, succProb) = P2_routine(ρ, n, d, stdbasis) else (ρ, succProb) = P1_routine(ρ, n, d, stdbasis) end return (ρ, real(succProb)) end """ BBPSSW_routine(ρ, n, d, stdbasis) Applies one iteration of BBPSSW routine to the `n`-copy input state `'rho` in `d` dimensions. Returns the output state and the probabilies of success with respect to the `stdbasis`. """ function BBPSSW_routine(ρ, n, d, stdbasis::StandardBasis) @assert n == 2 basisDict = create_dictionary_from_basis(stdbasis) densityState = belldiagonal_projection(stdbasis, ρ) coords = densityState.coords depol_coords = depolarize_coords(coords) bellCoords(k, l) = depol_coords[basisDict[1][(k, l)]] newCoords = zeros(d^2) for x in 0:(d-1), y in 0:(d-1) i = basisDict[1][(x, y)] a_xy = 0.0 for k in 0:(d-1) a_xy += bellCoords(k, y) * bellCoords(mod(x - k, d), y) end newCoords[i] = a_xy end succProb = sum(newCoords) if succProb == 0.0 throw("successProb is zero") end normNowCoords = newCoords / succProb ρ_new = create_densitystate(CoordState(normNowCoords, "UNKNOWN"), stdbasis).densityMatrix return (ρ_new, real(succProb)) end """ DEJMPS_routine(ρ, n, d, stdbasis) Applies one iteration of DEJMPS routine to the `n`-copy input state `'rho` in `d` dimensions. Returns the output state and the probabilies of success with respect to the `stdbasis`. """ function DEJMPS_routine(ρ, n, d, stdbasis::StandardBasis) g = [(1, 0), (d - 1, 0)] gVec = [g] aVec = [0] bVec = [0] U = create_canonic_enconding(g, d) bFT = (FT_OP(d) ⊗ conj(FT_OP(d))) (ρ, succProb) = stabilizer_routine(ρ, gVec, aVec, bVec, U, n, d, stdbasis) ρ = bFT * ρ * bFT' return (ρ, real(succProb)) end """ iterative_specific_stabilizer_protocol(ρ, targetFid, gVec, aVec, bVec, U, n, d, stdBasis, maxIts) Applies iterations of the stabilizer routine to the `n`-copy input state `'rho` in `d` dimensions for stabilizer generating elements `gVec`, encoding `U` and measurement outcomes `aVec` and`bVec`. Iterates until `targetFid` or maximal number of iterations `maxIts` is reached. Returns `distillable=true` if `targetFid` could be reached and fidelities and success probabilies with respect to the `stdbasis` for each iteration. """ function iterative_specific_stabilizer_protocol(ρ, targetFid, gVec, aVec, bVec, U, n, d, stdbasis::StandardBasis, maxIts=100) P_00 = stdbasis.basis[1][3] isPpt = isppt(ρ, d, 10) F_00 = fidelity(ρ, P_00) i = 0 iterations = [i] fidelities = [F_00] successProbs = [0.0] while (F_00 <= targetFid) && !isPpt && (i < maxIts) i += 1 (ρ, succProb) = stabilizer_routine(ρ, gVec, aVec, bVec, U, n, d, stdbasis) isPpt = isppt(ρ, d, 10) F_00 = fidelity(ρ, P_00) push!(iterations, i) push!(fidelities, F_00) push!(successProbs, succProb) end distillable = false if F_00 > targetFid && i < maxIts distillable = true elseif isPpt || i >= maxIts distillable = false end return (distillable, iterations, fidelities, successProbs) end """ iterative_FIMAX_protocol(ρ, targetFid, n, d, stdBasis, maxIts) Applies iterations of the FIMAX routine to the `n`-copy input state `ρ` in `d` dimensions. Iterates until `targetFid` or maximal number of iterations `maxIts` is reached. Returns `distillable=true` if `targetFid` could be reached and fidelities and success probabilies with respect to the `stdbasis` for each iteration. """ function iterative_FIMAX_protocol(ρ, targetFid, n, d, stdbasis, maxIts=100) P_00 = stdbasis.basis[1][3] isPpt = isppt(ρ, d, 10) F_00 = fidelity(ρ, P_00) i = 0 iterations = [i] fidelities = [F_00] successProbs = [0.0] while (F_00 <= targetFid) && !isPpt && (i < maxIts) i += 1 (ρ, succProb) = FIMAX_routine(ρ, n, d, stdbasis) isPpt = isppt(ρ, d, 10) F_00 = fidelity(ρ, P_00) push!(iterations, i) push!(fidelities, F_00) push!(successProbs, succProb) end distillable = false if F_00 > targetFid && i < maxIts distillable = true elseif isPpt || i >= maxIts distillable = false end return (distillable, iterations, fidelities, successProbs) end """ iterative_P1_P2_protocol(ρ, targetFid, n, d, stdBasis, maxIts) Applies iterations of the P1_P2 routine to the `n`-copy input state `ρ` in `d` dimensions. Iterates until `targetFid` or maximal number of iterations `maxIts` is reached. Returns `distillable=true` if `targetFid` could be reached and fidelities and success probabilies with respect to the `stdbasis` for each iteration. """ function iterative_P1_P2_protocol(ρ, targetFid, n, d, stdbasis, maxIts=100) P_00 = stdbasis.basis[1][3] isPpt = isppt(ρ, d, 10) F_00 = fidelity(ρ, P_00) i = 0 iterations = [i] fidelities = [F_00] successProbs = [0.0] while (F_00 <= targetFid) && !isPpt && (i < maxIts) i += 1 (ρ, succProb) = P1_P2_routine(ρ, n, d, stdbasis) isPpt = isppt(ρ, d, 10) F_00 = fidelity(ρ, P_00) push!(iterations, i) push!(fidelities, F_00) push!(successProbs, succProb) end distillable = false if F_00 > targetFid && i < maxIts distillable = true elseif isPpt || i >= maxIts distillable = false end return (distillable, iterations, fidelities, successProbs) end """ iterative_BBPSSW_protocol(ρ, targetFid, n, d, stdBasis, maxIts) Applies iterations of the BBPSSW routine to the `n`-copy input state `ρ` in `d` dimensions. Iterates until `targetFid` or maximal number of iterations `maxIts` is reached. Returns `distillable=true` if `targetFid` could be reached and fidelities and success probabilies with respect to the `stdbasis` for each iteration. """ function iterative_BBPSSW_protocol(ρ, targetFid, n, d, stdbasis, maxIts=100) P_00 = stdbasis.basis[1][3] isPpt = isppt(ρ, d, 10) F_00 = fidelity(ρ, P_00) i = 0 iterations = [i] fidelities = [F_00] successProbs = [0.0] while (F_00 <= targetFid) && !isPpt && (i < maxIts) i += 1 (ρ, succProb) = BBPSSW_routine(ρ, n, d, stdbasis) isPpt = isppt(ρ, d, 10) F_00 = fidelity(ρ, P_00) push!(iterations, i) push!(fidelities, F_00) push!(successProbs, succProb) end distillable = false if F_00 > targetFid && i < maxIts distillable = true elseif isPpt || i >= maxIts distillable = false end return (distillable, iterations, fidelities, successProbs) end """ iterative_DEJMPS_protocol(ρ, targetFid, n, d, stdBasis, maxIts) Applies iterations of the DEJMPS routine to the `n`-copy input state `ρ` in `d` dimensions. Iterates until `targetFid` or maximal number of iterations `maxIts` is reached. Returns `distillable=true` if `targetFid` could be reached and fidelities and success probabilies with respect to the `stdbasis` for each iteration. """ function iterative_DEJMPS_protocol(ρ, targetFid, n, d, stdbasis, maxIts=100) P_00 = stdbasis.basis[1][3] isPpt = isppt(ρ, d, 10) F_00 = fidelity(ρ, P_00) i = 0 iterations = [i] fidelities = [F_00] successProbs = [0.0] while (F_00 <= targetFid) && !isPpt && (i < maxIts) i += 1 (ρ, succProb) = DEJMPS_routine(ρ, n, d, stdbasis) isPpt = isppt(ρ, d, 10) F_00 = fidelity(ρ, P_00) push!(iterations, i) push!(fidelities, F_00) push!(successProbs, succProb) end distillable = false if F_00 > targetFid && i < maxIts distillable = true elseif isPpt || i >= maxIts distillable = false end return (distillable, iterations, fidelities, successProbs) end """ efficiency(distillable, iterations, successProbs, n) Returns efficiency of `n`-copy distillation protocol with `iterations` iterations of success probabilities `successProbs`. """ function efficiency(distillable, iterations, successProbs, n) if !distillable return (0.0) else nIts = length(iterations[2:end]) totalProb = prod(successProbs[2:end]) if length(nIts) == 0 eff = 0.0 else eff = 1 / n^nIts * totalProb end return (eff) end end
BellDiagonalQudits
https://github.com/kungfugo/BellDiagonalQudits.jl.git
[ "MIT" ]
0.1.7
79e541dc38e1b13ceb024af4fb5f87a10bfbea85
code
2722
""" get_concurrence_qp(coords, d, dictionaries) Return quasi-pure approximation of the concurrence for a Bell diagonal state represented by coordinates `coords` with respect to a `StandardBasis` and corresponding `dictionaries` in `d` dimensions. """ function get_concurrence_qp(coords, d, dictionaries)::Float64 S = Float64[] D = length(coords) dict = dictionaries[2] revDict = dictionaries[1] (maxCoord, maxIndex) = findmax(coords) (n, m) = dict[maxIndex] for i in 1:D (k, l) = dict[i] push!( S, sqrt( max( 0, d / (2 * (d - 1)) * coords[i] * ( (1 - 2 / d) * maxCoord * δ(i, maxIndex) + 1 / d^2 * coords[revDict[( mod(2 * n - k, d), mod(2 * m - l, d) )]] ) ) ) ) end maxS = findmax(S)[1] cQP = maxS - (sum(S) - maxS) if cQP > 0 return cQP else return 0 end end """ createProjectorOperator(d) Return concurrence related operator in arbitrary dimension `d`. """ function createProjectorOperator(d) A = proj(0 * ket(1, d^4)) for j in 1:d for i in 1:(j-1) for l in 1:d for k in 1:(l-1) A += proj( ket(i, d) ⊗ ket(k, d) ⊗ ket(j, d) ⊗ ket(l, d) - ket(j, d) ⊗ ket(k, d) ⊗ ket(i, d) ⊗ ket(l, d) - ket(i, d) ⊗ ket(l, d) ⊗ ket(j, d) ⊗ ket(k, d) + ket(j, d) ⊗ ket(l, d) ⊗ ket(i, d) ⊗ ket(k, d) ) end end end end return 4 * A end """ get_concurrence_qp_gendiagonal(coords, d, basisStates) Return quasi-pure approximation of the concurrence for a `d`-dimensional Bell diagonal state represented by coordinates `coords` with respect to a set of `basisStates`. """ function get_concurrence_qp_gendiagonal(coords, d, basisStates::Array{Vector{ComplexF64}}) maxIndex = findmax(coords)[2] A = createProjectorOperator(d) Ω_max = basisStates[maxIndex] Χ = A * (Ω_max ⊗ Ω_max) Χ = Χ / norm(Χ) T = complex(zeros(d^2, d^2)) for i in 1:d^2, j in 1:d^2 μ_i = coords[i] μ_j = coords[j] T[i, j] = sqrt(μ_i * μ_j) * (basisStates[i]' ⊗ basisStates[j]') * Χ end sV = svd(T).S maxSv = findmax(sV)[1] concurrence_qp = max(0, 2 * maxSv - sum(sV)) return (concurrence_qp) end
BellDiagonalQudits
https://github.com/kungfugo/BellDiagonalQudits.jl.git
[ "MIT" ]
0.1.7
79e541dc38e1b13ceb024af4fb5f87a10bfbea85
code
18126
""" kernel_check(coordState::CoordState, kernelPolytope::Union{HPolytope{Float64,Array{Float64,1}},VPolytope{Float64,Array{Float64,1}}}) Return `true` if the Euclidean coordinates of the `coordState`` are contained in the `kernelPolytope` represented in V- or H-representation. """ function kernel_check(coordState::CoordState, kernelPolytope::Union{HPolytope{Float64,Array{Float64,1}},VPolytope{Float64,Array{Float64,1}}})::Bool if coordState.coords ∈ kernelPolytope return true else return false end end """ ppt_check(coordState::CoordState, standardBasis::StandardBasis, precision=10) Return `true`` if the `coordState` defined via the `standardBasis` has positive partial transposition in the given `precision`. """ function ppt_check(coordState::CoordState, standardBasis::StandardBasis, precision=10)::Bool densityState = create_densitystate(coordState, standardBasis) ρ = densityState.densityMatrix d = Int(sqrt(size(ρ, 1))) return isppt(ρ, d, precision) end """ realignment_check(coordState::CoordState, standardBasis::StandardBasis, precision=10) Return `true`` if the realigned `coordState` defined via the `standardBasis` has trace norm ``> 1`` in the given `precision`. """ function realignment_check(coordState::CoordState, standardBasis::StandardBasis, precision=10)::Bool densityState = create_densitystate(coordState, standardBasis) ρ = densityState.densityMatrix r_ρ = reshuffle(ρ) return (round(norm_trace(r_ρ), digits=precision) > 1) end """ numeric_ew_check(coordState::CoordState, boundedEWs::Array{BoundedCoordEW}, relUncertainity::Float64) Return `true` if any entanglement witness of `boundedEWs` detects the density matrix `ρ` as entangled. An entanglement witness ``E`` of `boundedEWs` detects `ρ`, if the scalar product ``\\rho``.`coords` ``\\cdot E``.`coords` is not in [`lowerBound`, `upperBound`]. If a `relUncertainity` is given, the violation relative to `upperBound-lowerBound` needs to exceed `relUncertainity`` to detect entanglement. """ function numeric_ew_check(coordState::CoordState, boundedEWs::Array{BoundedCoordEW}, relUncertainity=0.0)::Bool anyEntanglementFound = false for boundedEW in boundedEWs intervalLength = boundedEW.upperBound - boundedEW.lowerBound tolerance = intervalLength * relUncertainity anyEntanglementFound = !( (boundedEW.lowerBound - tolerance) <= dot(coordState.coords, boundedEW.coords) <= (boundedEW.upperBound + tolerance) ) # If one EW witnesses entanglement, we can stop if anyEntanglementFound == true break end end return anyEntanglementFound end """ concurrence_qp_check(coordState::CoordState, d, dictionaries, precision=10) Return `true` if the quasi-pure concurrence (see `concurrence.jl`) is positive for a `coordState` and given basis `dictionaries` in the given `precision`. """ function concurrence_qp_check(coordState::CoordState, d, dictionaries, precision=10)::Bool coords = coordState.coords if round(get_concurrence_qp(coords, d, dictionaries), digits=precision) > 0 return true else return false end end """ concurrence_qp_gendiagonal_check(coordState, d, basisStates, precision=10) Return `true` if the quasi-pure concurrence (see `concurrence.jl`) is positive for a `coordState` and given basis states `basisStates` in the given `precision`. """ function concurrence_qp_gendiagonal_check(coordState::CoordState, d, basisStates::Array{Vector{ComplexF64}}, precision=10)::Bool coords = coordState.coords if round(get_concurrence_qp_gendiagonal(coords, d, basisStates), digits=precision) > 0 return true else return false end end """ mub_check(coordState::CoordState, d, stdBasis::StandardBasis, mubSet::Vector{Vector{Vector{ComplexF64}}}) Return `true` if the sum of mutual predictibilities for a `mubSet` (see `mub.jl`) of dimension `d` exceeds ``2`` for a `coordState` and given `standardBasis`. """ function mub_check(coordState::CoordState, d, stdBasis::StandardBasis, mubSet::Vector{Vector{Vector{ComplexF64}}})::Bool ρ = create_densitystate(coordState, stdBasis).densityMatrix if calculate_mub_correlation(d, mubSet, ρ) > 2 return true else return false end end """ spinrep_check(coordState::CoordState, stdBasis::StandardBasis, bipartiteWeylBasis::Vector{Array{Complex{Float64},2}}, precision=10) Return `true` and detects a `coordState` for a `standardBasis` as separbale, if its coefficiencts in the `bipartiteWeylBasis` have 1-norm smaller than ``2`` in given `precision`. """ function spinrep_check(coordState::CoordState, stdBasis::StandardBasis, bipartiteWeylBasis::Vector{Array{Complex{Float64},2}}, precision=10) ρ = create_densitystate(coordState, stdBasis).densityMatrix spinRepCoefficients = map(x -> tr(ρ * x'), bipartiteWeylBasis) absCoeffs = map(x -> real(sqrt(x' * x)), spinRepCoefficients) return (round(sum(absCoeffs), digits=precision) <= 2) end """ analyse_coordstate( d, coordState::CoordState, anaSpec::AnalysisSpecification, stdBasis::StandardBasis=missing, kernelPolytope::Union{HPolytope{Float64,Array{Float64,1}},VPolytope{Float64,Array{Float64,1}},Missing}=missing, bipartiteWeylBasis::Union{Vector{Array{Complex{Float64},2}},Missing}=missing, dictionaries::Union{Any,Missing}=missing, mubSet::Union{Vector{Vector{Vector{ComplexF64}}},Missing}=missing, boundedEWs::Union{Array{BoundedCoordEW},Missing}=missing, precision=10, relUncertainity=0.0 ) Return an `AnalysedCoordState` for a `coordState` in `d` dimensions based on the given `anaSpec` and corresponding analysis objects. If an entanglement check should not be carried out or if an analysis object in not passed as variable, the corresponding property in `anaSpec` needs to be `false`. In this case, return the corresponding property of the `AnalysedCoordState` as `missing`. """ function analyse_coordstate( d, coordState::CoordState, anaSpec::AnalysisSpecification, stdBasis::StandardBasis=missing, kernelPolytope::Union{HPolytope{Float64,Array{Float64,1}},VPolytope{Float64,Array{Float64,1}},Missing}=missing, bipartiteWeylBasis::Union{Vector{Array{Complex{Float64},2}},Missing}=missing, dictionaries::Union{Any,Missing}=missing, mubSet::Union{Vector{Vector{Vector{ComplexF64}}},Missing}=missing, boundedEWs::Union{Array{BoundedCoordEW},Missing}=missing, precision=10, relUncertainity=0.0 )::AnalysedCoordState anaCoordState = AnalysedCoordState( coordState, missing, missing, missing, missing, missing, missing, missing ) # Kernel check if anaSpec.kernel_check && !ismissing(kernelPolytope) anaCoordState.kernel = kernel_check(coordState, kernelPolytope) end # Spinrep check if anaSpec.spinrep_check && !ismissing(stdBasis) && !ismissing(bipartiteWeylBasis) anaCoordState.spinrep = spinrep_check(coordState, stdBasis, bipartiteWeylBasis, precision) end # PPT check if anaSpec.ppt_check && !ismissing(stdBasis) anaCoordState.ppt = ppt_check(coordState, stdBasis, precision) end # Realign check if anaSpec.realignment_check && !ismissing(stdBasis) anaCoordState.realign = realignment_check(coordState, stdBasis, precision) end # Concurrence QP check if anaSpec.concurrence_qp_check && !ismissing(dictionaries) anaCoordState.concurrence = concurrence_qp_check(coordState, d, dictionaries, precision) end # Mub check if anaSpec.mub_check && !ismissing(stdBasis) && !ismissing(mubSet) anaCoordState.mub = mub_check(coordState, d, stdBasis, mubSet) end # numericEW check if anaSpec.numeric_ew_check && !ismissing(boundedEWs) anaCoordState.numericEW = numeric_ew_check(coordState, boundedEWs, relUncertainity) end return anaCoordState end """ sym_analyse_coordstate( d, coordState::CoordState, symmetries::Array{Permutation}, anaSpec::AnalysisSpecification, stdBasis::StandardBasis=missing, kernelPolytope::Union{HPolytope{Float64,Array{Float64,1}},VPolytope{Float64,Array{Float64,1}},Missing}=missing, bipartiteWeylBasis::Union{Vector{Array{Complex{Float64},2}},Missing}=missing, dictionaries::Union{Any,Missing}=missing, mubSet::Union{Vector{Vector{Vector{ComplexF64}}},Missing}=missing, boundedCoordEWs::Union{Array{BoundedCoordEW},Missing}=missing, precision=10, relUncertainity=0.0 ) Return an `AnalysedCoordState` for a `coordState` in `d` dimensions based on the given `anaSpec` and corresponding analysis objects and symmetry analysis. If an entanglement check should not be carried out or if an analysis object in not passed as variable, the corresponding property in `anaSpec` needs to be `false`. In this case, return the corresponding property of the `AnalysedCoordState` as `missing`. """ function sym_analyse_coordstate( d, coordState::CoordState, symmetries::Array{Permutation}, anaSpec::AnalysisSpecification, stdBasis::StandardBasis=missing, kernelPolytope::Union{HPolytope{Float64,Array{Float64,1}},VPolytope{Float64,Array{Float64,1}},Missing}=missing, bipartiteWeylBasis::Union{Vector{Array{Complex{Float64},2}},Missing}=missing, dictionaries::Union{Any,Missing}=missing, mubSet::Union{Vector{Vector{Vector{ComplexF64}}},Missing}=missing, boundedCoordEWs::Union{Array{BoundedCoordEW},Missing}=missing, precision=10, relUncertainity=0.0 )::AnalysedCoordState if !anaSpec.useSymmetries throw("useSymmetries not specified in analysis specification") end copyAnaSpec = deepcopy(anaSpec) kernelCheckPassed = false spinrepCheckPassed = false pptCheckPassed = false realignmentCheckPassed = false concurrenceQpCheckPassed = false mubCheckPassed = false numericEwCheckPassed = false groupKernel = missing groupSpinrep = missing groupPpt = missing groupRealign = missing groupConcurrence = missing groupMub = missing groupNumericEw = missing # Create all symmetric states # Avoid duplicates if length(coordState.coords) == length(unique(coordState.coords)) symCoordStates = unique(map( x -> CoordState(x, coordState.eClass), get_symcoords(coordState.coords, symmetries) )) else symCoordStates = map( x -> CoordState(x, coordState.eClass), get_symcoords(coordState.coords, symmetries) ) end # Analyse all symmetric states for symCoordState in symCoordStates analysedSymCoordState = analyse_coordstate( d, symCoordState, copyAnaSpec, stdBasis, kernelPolytope, bipartiteWeylBasis, dictionaries, mubSet, boundedCoordEWs, precision, relUncertainity ) # Update copyAnaSpecs for sym group: Skip analysis for other group states if check was successful for state # Kernel check implies sep in kernel which is preserved ==> Keep searching if enabled and missing if copyAnaSpec.kernel_check kernelCheckPassed = !ismissing(analysedSymCoordState.kernel) if kernelCheckPassed groupKernel = analysedSymCoordState.kernel end copyAnaSpec.kernel_check = !kernelCheckPassed end # Spinrep check implies SEP ==> Keep searching if enabled and (false or missing) if copyAnaSpec.spinrep_check spinrepCheckDone = !ismissing(analysedSymCoordState.spinrep) spinrepCheckPassed = !ismissing(analysedSymCoordState.spinrep) && analysedSymCoordState.spinrep if spinrepCheckPassed groupSpinrep = true elseif spinrepCheckDone groupSpinrep = false end copyAnaSpec.spinrep_check = !spinrepCheckPassed end # Ppt check determines PPT/NPT which is preserved under symmetry ==> Keep searching if enabled and missing if copyAnaSpec.ppt_check pptCheckPassed = !ismissing(analysedSymCoordState.ppt) if pptCheckPassed groupPpt = analysedSymCoordState.ppt end copyAnaSpec.ppt_check = !pptCheckPassed end # Realignment check implies entanglement which is preserved under symmetry ==> Keep searching if enabled and (false or missing) if copyAnaSpec.realignment_check realignmentCheckDone = !ismissing(analysedSymCoordState.realign) realignmentCheckPassed = !ismissing(analysedSymCoordState.realign) && analysedSymCoordState.realign if realignmentCheckPassed groupRealign = true elseif realignmentCheckDone groupRealign = false end copyAnaSpec.realignment_check = !realignmentCheckPassed end # Concurrence check implies entanglement which is preserved under symmetry ==> Keep searching if enabled and (false or missing) if copyAnaSpec.concurrence_qp_check concurrenceQpCheckDone = !ismissing(analysedSymCoordState.concurrence) concurrenceQpCheckPassed = !ismissing(analysedSymCoordState.concurrence) && analysedSymCoordState.concurrence if concurrenceQpCheckPassed groupConcurrence = true elseif concurrenceQpCheckDone groupConcurrence = false end copyAnaSpec.concurrence_qp_check = !concurrenceQpCheckPassed end # Mub check implies entanglement which is preserved under symmetry ==> Keep searching if enabled and (false or missing) if copyAnaSpec.mub_check mubCheckDone = !ismissing(analysedSymCoordState.mub) mubCheckPassed = !ismissing(analysedSymCoordState.mub) && analysedSymCoordState.mub if mubCheckPassed groupMub = true elseif mubCheckDone groupMub = false end copyAnaSpec.mub_check = !mubCheckPassed end # EW check implies entanglement which is preserved under symmetry ==> Keep searching if enabled and (false or missing) if copyAnaSpec.numeric_ew_check numericEwCheckDone = !ismissing(analysedSymCoordState.numericEW) numericEwCheckPassed = !ismissing(analysedSymCoordState.numericEW) && analysedSymCoordState.numericEW if numericEwCheckPassed groupNumericEw = true elseif numericEwCheckDone groupNumericEw = false end copyAnaSpec.numeric_ew_check = !numericEwCheckPassed end allDetermined = !any([ copyAnaSpec.kernel_check, copyAnaSpec.spinrep_check, copyAnaSpec.ppt_check, copyAnaSpec.realignment_check, copyAnaSpec.concurrence_qp_check, copyAnaSpec.mub_check, copyAnaSpec.numeric_ew_check ]) if allDetermined break end end anaSymCoordState = AnalysedCoordState( coordState, groupKernel, groupSpinrep, groupPpt, groupRealign, groupConcurrence, groupMub, groupNumericEw ) return anaSymCoordState end """ classify_entanglement(analysedCoordState) Return entanglement class of `analysedCoordState`. Entanglement class can be "UNKNWON", "PPT_UNKNOWN" for PPT states that can be separable or entangled, "SEP" for separable states, "BOUND" for PPT/bound entangled states or "NPT" for NPT/free entangled states. """ function classify_entanglement(analysedCoordState) class = "UNKNOWN" if (!ismissing(analysedCoordState.ppt)) && !analysedCoordState.ppt #npt class = "NPT" elseif (!ismissing(analysedCoordState.kernel) && analysedCoordState.kernel) || (!ismissing(analysedCoordState.spinrep) && analysedCoordState.spinrep) #separable class = "SEP" elseif ( !ismissing(analysedCoordState.ppt) && analysedCoordState.ppt && !( (!ismissing(analysedCoordState.kernel) && analysedCoordState.kernel) || (!ismissing(analysedCoordState.spinrep) && analysedCoordState.spinrep) ) ) ##ppt not sep class = "PPT_UNKNOWN" if !ismissing(analysedCoordState.realign) if analysedCoordState.realign class = "BOUND" end end if !ismissing(analysedCoordState.concurrence) if analysedCoordState.concurrence class = "BOUND" end end if !ismissing(analysedCoordState.mub) if analysedCoordState.mub class = "BOUND" end end if !ismissing(analysedCoordState.numericEW) if analysedCoordState.numericEW class = "BOUND" end end end return class end """ classify_analyzed_states!(anaCoordStates::Array{AnalysedCoordState}) Set entanglement class for array of `analysedCoordStates`. """ function classify_analyzed_states!(analysedCoordStates::Array{AnalysedCoordState}) for anaCoordState in analysedCoordStates derivedClass = classify_entanglement(anaCoordState) if derivedClass != "UNKNOWN" if anaCoordState.coordState.eClass == "UNKNOWN" anaCoordState.coordState.eClass = derivedClass else if anaCoordState.coordState.eClass != derivedClass throw(ClassConflictException(anaCoordState)) end end end end return analysedCoordStates end
BellDiagonalQudits
https://github.com/kungfugo/BellDiagonalQudits.jl.git
[ "MIT" ]
0.1.7
79e541dc38e1b13ceb024af4fb5f87a10bfbea85
code
3952
""" create_standard_mub(d) Return vector of mutually unbiased bases for dimensions `d` three or four. """ function create_standard_mub(d)::Vector{Vector{Vector{ComplexF64}}} mubSet = Vector{Vector{ComplexF64}}[] if d == 3 #There are 4 mutually unbiased Bases. mubSet = Vector{Vector{ComplexF64}}[] w = exp(2 // 3 * π * im) B1 = [ ket(1, 3), ket(2, 3), ket(3, 3) ] B2 = [ 1 / sqrt(3) * (ket(1, 3) + ket(2, 3) + ket(3, 3)), 1 / sqrt(3) * (ket(1, 3) + w * ket(2, 3) + w^2 * ket(3, 3)), 1 / sqrt(3) * (ket(1, 3) + w^2 * ket(2, 3) + w * ket(3, 3)) ] B3 = [ 1 / sqrt(3) * (ket(1, 3) + w * ket(2, 3) + w * ket(3, 3)), 1 / sqrt(3) * (ket(1, 3) + w^2 * ket(2, 3) + ket(3, 3)), 1 / sqrt(3) * (ket(1, 3) + ket(2, 3) + w^2 * ket(3, 3)) ] B4 = [ 1 / sqrt(3) * (ket(1, 3) + w^2 * ket(2, 3) + w^2 * ket(3, 3)), 1 / sqrt(3) * (ket(1, 3) + ket(2, 3) + w * ket(3, 3)), 1 / sqrt(3) * (ket(1, 3) + w * ket(2, 3) + ket(3, 3)) ] push!(mubSet, B1) push!(mubSet, B2) push!(mubSet, B3) push!(mubSet, B4) elseif d == 4 B1 = [ ket(1, 4), ket(2, 4), ket(3, 4), ket(4, 4) ] B2 = [ 1 / 2 * (ket(1, 4) + ket(2, 4) + ket(3, 4) + ket(4, 4)), 1 / 2 * (ket(1, 4) + ket(2, 4) - ket(3, 4) - ket(4, 4)), 1 / 2 * (ket(1, 4) - ket(2, 4) - ket(3, 4) + ket(4, 4)), 1 / 2 * (ket(1, 4) - ket(2, 4) + ket(3, 4) - ket(4, 4)) ] B3 = [ 1 / 2 * (ket(1, 4) - im * ket(2, 4) - im * ket(3, 4) - ket(4, 4)), 1 / 2 * (ket(1, 4) - im * ket(2, 4) + im * ket(3, 4) + ket(4, 4)), 1 / 2 * (ket(1, 4) + im * ket(2, 4) + im * ket(3, 4) - ket(4, 4)), 1 / 2 * (ket(1, 4) + im * ket(2, 4) - im * ket(3, 4) + ket(4, 4)) ] B4 = [ 1 / 2 * (ket(1, 4) - ket(2, 4) - im * ket(3, 4) - im * ket(4, 4)), 1 / 2 * (ket(1, 4) - ket(2, 4) + im * ket(3, 4) + im * ket(4, 4)), 1 / 2 * (ket(1, 4) + ket(2, 4) + im * ket(3, 4) - im * ket(4, 4)), 1 / 2 * (ket(1, 4) + ket(2, 4) - im * ket(3, 4) + im * ket(4, 4)) ] B5 = [ 1 / 2 * (ket(1, 4) - im * ket(2, 4) - ket(3, 4) - im * ket(4, 4)), 1 / 2 * (ket(1, 4) - im * ket(2, 4) + ket(3, 4) + im * ket(4, 4)), 1 / 2 * (ket(1, 4) + im * ket(2, 4) + ket(3, 4) - im * ket(4, 4)), 1 / 2 * (ket(1, 4) + im * ket(2, 4) - ket(3, 4) + im * ket(4, 4)) ] push!(mubSet, B1) push!(mubSet, B2) push!(mubSet, B3) push!(mubSet, B4) push!(mubSet, B5) else throw("Only d=3 and d=4 are supported") end return (mubSet) end """ calculate_mub_correlation(d, mubSet::Vector{Vector{Vector{ComplexF64}}}, ρ, s=-1) Based on complete set of mutually unbiased bases `mubSet`, return sum of mutual predictibilities, shifted by `s`, for density matrix `ρ` in `d` dimensions. """ function calculate_mub_correlation(d, mubSet::Vector{Vector{Vector{ComplexF64}}}, ρ, s=-1) if s == -1 if d == 3 s = 2 elseif d == 4 s = 3 else s = 0 end end C = 0 for k in 1:length(mubSet) B = mubSet[k] if k == 1 for i = 1:d C += tr( Hermitian(proj( B[i] ⊗ B[mod((i - 1) + s, d)+1] ) * ρ) ) end else for i = 1:d C += tr( Hermitian(proj( B[i] ⊗ conj(B[i]) ) * ρ) ) end end end return (C) end
BellDiagonalQudits
https://github.com/kungfugo/BellDiagonalQudits.jl.git
[ "MIT" ]
0.1.7
79e541dc38e1b13ceb024af4fb5f87a10bfbea85
code
6159
""" create_random_witnesses(standardBasis::StandardBasis, n) Return array of `n` uniformly distributed random `EntanglementWitness` represented in Bell basis `standardBasis`. """ function create_random_witnesses(standardBasis::StandardBasis, n)::Array{EntanglementWitness} basisOps = map(x -> x[3], standardBasis.basis) D = length(basisOps) randomParams = rand(Uniform(-1, 1), n, D) wits = Array{EntanglementWitness}(undef, 0) for i in 1:n push!(wits, EntanglementWitness(randomParams[i, :], Hermitian(generic_vectorproduct(randomParams[i, :], basisOps)))) end return wits end """ create_halfspheric_witnesses(standardBasis::StandardBasis, n) Return array of `n` uniformly distributed random `EntanglementWitness` on unit sphere represented in Bell basis `standardBasis`. """ function create_halfspheric_witnesses(standardBasis::StandardBasis, n)::Array{EntanglementWitness} basisOps = map(x -> x[3], standardBasis.basis) D = length(basisOps) randomParams = Vector{Float64}[] for i in 1:n randomVector = normalize(rand(Normal(), D)) if randomVector[1] < 0 randomVector[1] = -randomVector[1] end push!(randomParams, randomVector) end wits = Array{EntanglementWitness}(undef, 0) for i in 1:n push!(wits, EntanglementWitness(randomParams[i], Hermitian(generic_vectorproduct(randomParams[i], basisOps)))) end return wits end """ get_direct_functions_for_wit_traceoptimization(wit::EntanglementWitness, d) Return the function and its negative that calculates ``tr \\rho`` `wit.coords`, the trace of the given witness `wit` multiplied by a parameterized seperable state ``\\rho`` in `d` dimensions. """ function get_direct_functions_for_wit_traceoptimization(wit::EntanglementWitness, d) function getTrace(λ, witOpM, d) λ1 = λ[1:(2*(d-1))] λ2 = λ[(2*(d-1)+1):end] U1 = get_comppar_unitary_from_parvector(λ1, d) U2 = get_comppar_unitary_from_parvector(λ2, d) U = U1 ⊗ U2 b = proj(ket(1, d^2)) t = real(tr(witOpM * U * b * U')) return t end function opt_f(x) return getTrace(x, wit.operatorMatrix, d) end function opt_negf(x) return -getTrace(x, wit.operatorMatrix, d) end return (opt_f, opt_negf) end """ get_witness_extrema(d, wit::EntanglementWitness, iterations, method, useConstrainedOpt=false) Return optimization (see optimization.jl) results for lower and upper bound of `d` dimensional EntanglementWitness `wit` using `iterations` runs and Optim.jl optimization method `method`. """ function get_witness_extrema( d, wit::EntanglementWitness, iterations, method, useConstrainedOpt=false )::Vector{Tuple{Float64,Vector{Float64}}} optFuncs = get_direct_functions_for_wit_traceoptimization(wit, d) optRes = direct_optimization( optFuncs[1], optFuncs[2], method, d, iterations, useConstrainedOpt ) return optRes end """ get_bounded_ew(d, wit::EntanglementWitness, iterations, method=Optim.NelderMead, useConstrainedOpt=false) Return BoundedEW in `d` dimensions based on EntanglementWitness `wit` and `iterations` optimization runs of lower and upper bound for separable states. """ function get_bounded_ew( d, wit::EntanglementWitness, iterations, method=Optim.NelderMead, useConstrainedOpt=false )::BoundedEW witExtremizer = get_witness_extrema( d, wit, iterations, method, useConstrainedOpt ) b = proj(ket(1, d^2)) totalMin = witExtremizer[1][1] totalMax = witExtremizer[2][1] minimizingParams = witExtremizer[1][2] minimizingParams1 = minimizingParams[1:(2*(d-1))] minimizingParams2 = minimizingParams[(2*(d-1)+1):end] minimizingU1 = get_comppar_unitary_from_parvector(minimizingParams1, d) minimizingU2 = get_comppar_unitary_from_parvector(minimizingParams2, d) minimizingU = minimizingU1 ⊗ minimizingU2 minimizingDensityMatrix = Hermitian(minimizingU * b * minimizingU') maximizingParams = witExtremizer[2][2] maximizingParams1 = maximizingParams[1:(2*(d-1))] maximizingParams2 = maximizingParams[(2*(d-1)+1):end] maximizingU1 = get_comppar_unitary_from_parvector(maximizingParams1, d) maximizingU2 = get_comppar_unitary_from_parvector(maximizingParams2, d) maximizingU = maximizingU1 ⊗ maximizingU2 maximizingDensityMatrix = Hermitian(maximizingU * b * maximizingU') return BoundedEW( wit.coords, totalMax, totalMin, maximizingDensityMatrix, minimizingDensityMatrix, iterations) end """ create_random_bounded_ews( d, standardBasis::StandardBasis, n, sphericalOnly::Bool, iterations::Integer, method=Optim.NelderMead, useConstrainedOpt=false ) Return array of `n` `BoundedEW` with ``d^2`` `standardBasis` coordinates uniformly distributed in [-1, 1] if `sphericalOnly` is false or uniformly distributed on unit sphere otherwise. Use `iterations` runs to improve optimizatio with Optim.jl optimization method `method`. """ function create_random_bounded_ews( d, standardBasis::StandardBasis, n, sphericalOnly::Bool, iterations::Integer, method=Optim.NelderMead, useConstrainedOpt=false )::Array{BoundedEW} if (length(standardBasis.basis) != d^2) throw("Dimension and basis do not match") end if (sphericalOnly) witnessCreator = create_halfspheric_witnesses else witnessCreator = create_random_witnesses end randWits = witnessCreator(standardBasis, n) boundedEWs = map(x -> get_bounded_ew(d, x, iterations, method, useConstrainedOpt), randWits) return boundedEWs end """ get_bounded_coordew(bEw::BoundedEW)::BoundedCoordEW Map BoundedEW `bEw` to corresponding `BoundedCoordEW`. """ function get_bounded_coordew(bEw::BoundedEW)::BoundedCoordEW return BoundedCoordEW(bEw.coords, bEw.upperBound, bEw.lowerBound, bEw.checkedIterations) end
BellDiagonalQudits
https://github.com/kungfugo/BellDiagonalQudits.jl.git
[ "MIT" ]
0.1.7
79e541dc38e1b13ceb024af4fb5f87a10bfbea85
code
2445
""" direct_optimization(f, negf, method, d, iterations, constrainedOpt=false) Return total (minimum, minimizer) and (maximum, maximizer) of `iterations` optimization runs of function `f` and its negative `negf` over the set of separale states using Optim.jl optimization mehtod `method`. Optim.jl is used for optimazation based on `parameterization.jl`, so `f` and `negf` are defined for ``2(d-1)`` parameters. Supported methods include `NelderMead`, `LBFGS` and `NewtonTrustRegion`. """ function direct_optimization(f, negf, method, d, iterations, constrainedOpt=false) lHalf = d - 1 lMax = (2(d - 1)) lowerBoundParam = zeros(2 * (d - 1)) upperBoundParam = zeros(2 * (d - 1)) for k in 1:lHalf upperBoundParam[k] = π / 2 end for k in (lHalf+1):lMax upperBoundParam[k] = 2 * π end combinedLowerBounds = [lowerBoundParam; lowerBoundParam] combinedUpperBounds = [upperBoundParam; upperBoundParam] detMaxima = Float64[] detMinima = Float64[] detMaximizers = [] detMinimizers = [] for it in 1:iterations x_init_random = zeros(length(combinedUpperBounds)) for i in eachindex(x_init_random) x_init_random[i] = rand(Uniform(combinedLowerBounds[i], combinedUpperBounds[i])) end if (!constrainedOpt) detOptmin = optimize(f, x_init_random, method()) detOptmax = optimize(negf, x_init_random, method()) detMin = Optim.minimum(detOptmin) detMax = -Optim.minimum(detOptmax) else detOptmin = optimize(f, combinedLowerBounds, combinedUpperBounds, x_init_random, Fminbox(method())) detOptmax = optimize(negf, combinedLowerBounds, combinedUpperBounds, x_init_random, Fminbox(method())) detMin = Optim.minimum(detOptmin) detMax = -Optim.minimum(detOptmax) end push!(detMaxima, detMax) push!(detMinima, detMin) push!(detMaximizers, detOptmax.minimizer) push!(detMinimizers, detOptmin.minimizer) end # Get total extrema of runs minimizerIndex = findmin(detMinima) maximizerIndex = findmax(detMaxima) totalMin = minimizerIndex[1] totalMax = maximizerIndex[1] totalMinimizer = detMinimizers[minimizerIndex[2]] totalMaximizer = detMaximizers[maximizerIndex[2]] return [ (totalMin, totalMinimizer), (totalMax, totalMaximizer) ] end
BellDiagonalQudits
https://github.com/kungfugo/BellDiagonalQudits.jl.git
[ "MIT" ]
0.1.7
79e541dc38e1b13ceb024af4fb5f87a10bfbea85
code
1908
""" create_red_parmatrix_from_parvector(x, d) Return parameter matrix for pure state parameterization from parameter vector `x` of length ``2(d-1)``. """ function create_red_parmatrix_from_parvector(x, d) if length(x) != (2 * (d - 1)) throw("Param vector and dimension mismatch") end λ = zeros(d, d) k = 0 #fill first row with first elements of x for n in 2:d k = k + 1 λ[1, n] = x[k] end # fill first column with second half elements of x for n in 2:d k = k + 1 λ[n, 1] = x[k] end return λ end """ create_comppar_unitary(λ, d) Return `d` dimensional prameterized unitary matrix from parameter matrix `λ`. """ function create_comppar_unitary(λ, d) # create onb P = Array{ Array{Complex{Float64},2}, 1}(undef, 0) for i in (1:d) b_i = proj(ket(i, d)) push!(P, b_i) end σ = Array{Array{Complex{Float64},2},2}(undef, d, d) # define factor 1 for global phases R = I(d) for l in 1:d R = R * exp(im * P[l] * λ[l, l]) end # define factor 2 for rotations and relative phases L = I(d) for m in (1:d-1) for n in (m+1:d) σ[m, n] = -im * ketbra(m, n, d, d) + im * ketbra(n, m, d, d) L = L * exp(im * P[n] * λ[n, m]) * exp(im * σ[m, n] * λ[m, n]) end end U_C = L * R return U_C end """ get_comppar_unitary_from_parvector(x, d) Return parameterized unitatry matrix U of dimension `d` and rank 1 from parameter vector `x` with ``2(d-1)`` elements. Using the first basis state of the computational basis with density matrix ``e_1``, any pure state ``\\rho`` can be generated as ``\\rho = U e_1 U^\\dagger``. """ function get_comppar_unitary_from_parvector(x, d) λ = create_red_parmatrix_from_parvector(x, d) U = create_comppar_unitary(λ, d) return U end
BellDiagonalQudits
https://github.com/kungfugo/BellDiagonalQudits.jl.git
[ "MIT" ]
0.1.7
79e541dc38e1b13ceb024af4fb5f87a10bfbea85
code
2236
""" create_kernel_vertexstates(d, standardBasis::StandardBasis) Return array containing collections of corresponding `standardBasis` indices, coordinates and density matrices for all `d` element sublattices in discrete phase space. """ function create_kernel_vertexstates(d, standardBasis::StandardBasis) allSubLattices = create_dimelement_sublattices(d) vertexStates = map(x -> create_index_sublattice_state(standardBasis, x), allSubLattices) return vertexStates end """ create_kernel_hpolytope(vertexCoordinates) Return LazySets.HPolytope representation of polytope defined by `vertexCoordinates`. """ function create_kernel_hpolytope(vertexCoordinates) #Create polytope in vertex representation vPt = VPolytope(vertexCoordinates) #Convert to H-representation return tohrep(vPt) end """ create_kernel_polytope(d, standardBasis::StandardBasis) Return LazySets.HPolytope representation of the kernel polytope for dimension `d` and Bell basis `standardBasis`. """ function create_kernel_polytope(d, standardBasis::StandardBasis) # Create kernel vertex states vertexStates = create_kernel_vertexstates(d, standardBasis) # Get coordinates vertexCoords = map(x -> x[2], vertexStates) # Create kernel polytope return create_kernel_hpolytope(vertexCoords) end """ extend_vpolytope_by_densitystates( sepPolytope::VPolytope{Float64,Array{Float64,1}}, sepDensityStates::Array{DensityState}, precision::Integer ) Return an extended Lazysets.VPolytope representation of polytope of separable states based on given polytope `sepPolytope` and new separable `sepDensityStates` as new vertices. """ function extend_vpolytope_by_densitystates( sepPolytope::VPolytope{Float64,Array{Float64,1}}, sepDensityStates::Array{DensityState}, precision::Integer )::VPolytope{Float64,Array{Float64,1}} existingVertices = vertices_list(sepPolytope) newVertices = unique(map(x -> rounddigits(abs.(x.coords), precision), sepDensityStates)) combinedVertices = [existingVertices; newVertices] uniqueVertices = unique(map(x -> rounddigits(abs.(x), precision), combinedVertices)) return VPolytope(uniqueVertices) end
BellDiagonalQudits
https://github.com/kungfugo/BellDiagonalQudits.jl.git
[ "MIT" ]
0.1.7
79e541dc38e1b13ceb024af4fb5f87a10bfbea85
code
4697
""" get_permutation_from_translation(translation::Tuple{Int,Int}, stdBasis::StandardBasis, d) Return `Permutations.Permutation` of translation for ``d^2`` dimensional vector of coordinates in Bell basis `standardBasis`. """ function get_permutation_from_translation(translation::Tuple{Int,Int}, stdBasis::StandardBasis, d) myDicts = create_dictionary_from_basis(stdBasis) dict = myDicts[1] #keys are tuples reverseDict = myDicts[2] #keys are indices D = length(myDicts[1]) t = collect(translation) perm = zeros(D) for i in 1:D oldCoords = collect(reverseDict[i]) newCoords = mod.(oldCoords + t, d) permIndex = dict[Tuple(newCoords)] perm[i] = permIndex end return Permutation(perm) end """ get_permutation_from_momentuminversion(stdBasis::StandardBasis, d) Return `Permutations.Permutation` of momentum inversion for ``d^2`` dimensional vector of coordinates in Bell basis `standardBasis`. """ function get_permutation_from_momentuminversion(stdBasis::StandardBasis, d) #load dictionary myDicts = create_dictionary_from_basis(stdBasis) dict = myDicts[1] #keys are tuples reverseDict = myDicts[2] #keys are indices D = length(myDicts[1]) perm = zeros(D) for i in 1:D oldCoords = collect(reverseDict[i]) newCoords = mod.([-oldCoords[1], oldCoords[2]], d) permIndex = dict[Tuple(newCoords)] perm[i] = permIndex end return Permutation(perm) end """ get_permutation_from_quarterrotation(stdBasis::StandardBasis, d) Return `Permutations.Permutation` of qurater rotation for ``d^2`` dimensional vector of coordinates in Bell basis `standardBasis`. """ function get_permutation_from_quarterrotation(stdBasis::StandardBasis, d) #load dictionary myDicts = create_dictionary_from_basis(stdBasis) dict = myDicts[1] #keys are tuples reverseDict = myDicts[2] #keys are indices D = length(myDicts[1]) perm = zeros(D) for i in 1:D oldCoords = collect(reverseDict[i]) newCoords = mod.([oldCoords[2], -oldCoords[1]], d) permIndex = dict[Tuple(newCoords)] perm[i] = permIndex end return Permutation(perm) end """ get_permutation_from_verticalshear(stdBasis::StandardBasis, d) Return `Permutations.Permutation`` of vertical shear for ``d^2`` dimensional vector of coordinates in Bell basis`standardBasis`. """ function get_permutation_from_verticalshear(stdBasis::StandardBasis, d) #load dictionary myDicts = create_dictionary_from_basis(stdBasis) dict = myDicts[1] #keys are tuples reverseDict = myDicts[2] #keys are indices D = length(myDicts[1]) perm = zeros(D) for i in 1:D oldCoords = collect(reverseDict[i]) newCoords = mod.([oldCoords[1] + oldCoords[2], oldCoords[2]], d) permIndex = dict[Tuple(newCoords)] perm[i] = permIndex end return Permutation(perm) end """ generate_symmetries(stdBasis::StandardBasis, d, orderLimit=0) Return array of `Permutations.Permutation` of all symmetries up to order `orderLimit` in `d` dimensions generated by the generators represented in `standardBasis`. """ function generate_symmetries(stdBasis::StandardBasis, d, orderLimit=0)::Array{Permutation} allSymmetries = Permutation[] #Get all translations for i in 0:(d-1) for j in 0:(d-1) push!(allSymmetries, get_permutation_from_translation((i, j), stdBasis, d)) end end generators = ( get_permutation_from_quarterrotation(stdBasis, d), get_permutation_from_momentuminversion(stdBasis, d), get_permutation_from_verticalshear(stdBasis, d) ) findNew = true order = 1 while findNew foundSims = Permutation[] for x in generators generatedSyms = map(s -> s * x, allSymmetries) newSyms = filter(e -> !(e in allSymmetries), generatedSyms) append!(foundSims, newSyms) end if length(foundSims) > 0 append!(allSymmetries, foundSims) end order += 1 findNew = (length(foundSims) > 0 && (orderLimit >= order || orderLimit == 0)) unique!(allSymmetries) end return allSymmetries end """ get_symcoords(coords::Array{Float64,1}, symPermutations::Array{Permutation}) Return array containing all symmetric Bell coordinates of given symmetries `symPermutations` applied to Bell coordinates `coords`. """ function get_symcoords(coords::Array{Float64,1}, symPermutations::Array{Permutation}) symCoords = map(x -> Matrix(x) * coords, symPermutations) return symCoords end
BellDiagonalQudits
https://github.com/kungfugo/BellDiagonalQudits.jl.git
[ "MIT" ]
0.1.7
79e541dc38e1b13ceb024af4fb5f87a10bfbea85
code
5252
""" ispsd(M, precision) Return `true` if the smallest eingenvalue of matrix `M` rounded to precision `precision` is not negative. """ function ispsd(M, precision) isPSD = false realEigvals = real.(eigvals(M)) if round(minimum(realEigvals), digits=precision) >= 0 isPSD = true end return isPSD end """ generic_vectorproduct(A,B) For any vectors of equal length, return ``\\sum_i A[i]B[i]``, the sum of all products of elements with the same index. """ function generic_vectorproduct(A, B) @assert length(A) == length(B) d = length(A) Res = 0 * (A[1] * B[1]) for i in (1:d) Res = Res + A[i] * B[i] end return Res end """ rounddigits(A, precision) Return `A` with all elemets rounded up to `precision` digits. """ function rounddigits(A, precision) (x -> round(x, digits=precision)).(A) end """ isPPTP(ρ, d, precision) Return `true` if the partial transposition of the Hermitian matrix based on the upper triangular of `ρ` is positive semi-definite in `precision`. """ function isppt(ρ, d, precision) M = Hermitian(ρ) minEigvalPT = real(ppt(M, [d, d], 2)) return round(minEigvalPT, digits=precision) >= 0 end """ create_dictionary_from_basis(stdBasis) Return vector containing a dictionary and it's inverse, relating the ``d^2`` flat indices to the double indices of `stdBasis`. """ function create_dictionary_from_basis(stdBasis::StandardBasis) basisDict = Dict() for i in stdBasis.basis basisDict[i[2]] = i[1] end reverseDict = Dict() for i in stdBasis.basis reverseDict[i[1]] = i[2] end return [basisDict, reverseDict] end """ δ(n,m) Return 1 if `n`==`m` """ function δ(n, m)::Int8 if n == m return 1 else return 0 end end """ δ_mod(n,m,x) Return 1 if `n` and `m` are congruent modulo `x`. """ function δ_mod(n, m, x)::Int8 if mod(n, x) == mod(m, x) return 1 else return 0 end end """ map_indices_to_normcoords(indices, D) Return `D` element normalized coordinate vector with equal nonzero values at given `indices`. """ function map_indices_to_normcoords(indices, D) c = zeros(D) for i in indices c[i] = 1 / length(indices) end return c end """ get_properdivisors(k:Int) Return vector of proper divisors of `k`. """ function get_properdivisors(k::Int) divisors = Array{Int,1}(undef, 0) for j in (2:floor(sqrt(k))) if k % j == 0 push!(divisors, j) if j != sqrt(k) push!(divisors, k / j) end end end return divisors end """ FT_OP(d) Returns the `d`-dimensional Fourier gate. """ function FT_OP(d) F = complex(zeros(d, d)) for i in 0:(d-1), j in (0:d-1) F += 1 / sqrt(d) * exp(2 * pi * im / d * j * i) * ketbra(i + 1, j + 1, d) end return (F) end """ GXOR_OP_ADD(d) Returns the `d`-dimensional generalization of the GXOR gate acting as |i>k|j> => |i>|i+j>. """ function GXOR_OP_ADD(d) GXOR = complex(zeros(d^2, d^2)) for i in 0:(d-1), m in 0:(d-1), j in 0:(d-1), n in 0:(d-1) GXOR += δ(i, j) * δ(m, mod(j + n, d)) * (modket(i, d) ⊗ modket(m, d)) * (modbra(j, d) ⊗ modbra(n, d)) end return (GXOR) end """ GXOR_OP_SUB(d) Returns the `d`-dimensional generalization of the GXOR gate acting as |i>k|j> => |i>|i-j>. """ function GXOR_OP_SUB(d) GXOR = complex(zeros(d^2, d^2)) for i in 0:(d-1), m in 0:(d-1), j in 0:(d-1), n in 0:(d-1) GXOR += δ(i, j) * δ(m, mod(j - n, d)) * (modket(i, d) ⊗ modket(m, d)) * (modbra(j, d) ⊗ modbra(n, d)) end return (GXOR) end """ depolarize_coords(coords) Return depolarized elements of a coord probability vector. Leaves the first element invariant. Remaining elements are replaced by their average value. """ function depolarize_coords(coords) l = length(coords) newCoords = [coords[1]; (sum(coords[2:end]) / (l - 1)) * ones(l - 1)] return (newCoords) end """ belldiagonal_projection(stdbasis, ρ) Projects any density matrix to the set of Bell-diagonal densitystates of corresponding dimension as defined by the `stdbasis`. """ function belldiagonal_projection(stdBasis::StandardBasis, ρ, eClass="UNKNOWN", precision::Integer=10)::DensityState coords = Float64[] for basisOp in stdBasis.basis push!(coords, real(round(tr(basisOp[3] * ρ), digits=precision))) end projState = create_densitystate(CoordState(coords, eClass), stdBasis) return projState end """ add_errorkeys(x,y,d,n) Adds two error elements mod d. """ function add_errorkeys(x, y, d, n) @assert n == 2 ((x_i1, x_j1), (x_i2, x_j2)) = (x[1], x[2]) ((y_i1, y_j1), (y_i2, y_j2)) = (y[1], y[2]) z_i1 = mod((x_i1 + y_i1), d) z_j1 = mod((x_j1 + y_j1), d) z_i2 = mod((x_i2 + y_i2), d) z_j2 = mod((x_j2 + y_j2), d) return ( [(z_i1, z_j1), (z_i2, z_j2)] ) end """ modket(k,d) Return the `k`th ket vector modulo `d`. """ function modket(k, d) return (ket(mod(k, d) + 1, d)) end """ modbra(k,d) Return the `k`th bra vector modulo `d`. """ function modbra(k, d) return (bra(mod(k, d) + 1, d)) end
BellDiagonalQudits
https://github.com/kungfugo/BellDiagonalQudits.jl.git
[ "MIT" ]
0.1.7
79e541dc38e1b13ceb024af4fb5f87a10bfbea85
code
7839
using BellDiagonalQudits using Test using LazySets: tovrep, vertices_list using LinearAlgebra: Diagonal, I testStandardBasis2 = create_standard_indexbasis(2, 10) testStandardBasis3 = create_standard_indexbasis(3, 10) testAltBasisStates3 = Vector{ComplexF64}[] for (k, l) in Iterators.product(fill(0:(2), 2)...) #Weyl transformation to basis states state_alt_kl = create_altbellstate(3, k, l, complex(ones(3, 3)), false) push!(testAltBasisStates3, state_alt_kl) end testStandardBasis4 = create_standard_indexbasis(4, 10) testStandardKernel3 = create_kernel_polytope(3, testStandardBasis3) testStandardKernel4 = create_kernel_polytope(4, testStandardBasis4) testExtKernel3 = extend_vpolytope_by_densitystates(tovrep(testStandardKernel3), [create_densitystate(CoordState(1 / 9 * ones(9), "SEP"), testStandardBasis3)], 10) testBipartiteWeylBasis3 = create_bipartite_weyloperator_basis(3) testDictionaries3 = create_dictionary_from_basis(testStandardBasis3) testMub3 = create_standard_mub(3) testMub4 = create_standard_mub(4) testRandomCoordWits = map(x -> get_bounded_coordew(x), create_random_bounded_ews(3, testStandardBasis3, 2, true, 20)) testSyms3 = generate_symmetries(testStandardBasis3, 3) testAnaSpec = AnalysisSpecification(true, true, true, true, true, true, true, false) testAnaSpecSym = AnalysisSpecification(true, true, true, true, true, true, true, true) testDistillationState2 = create_densitystate(CoordState([0.6, 0.4 / 3, 0.4 / 3, 0.4 / 3], "UNKNOWN"), testStandardBasis2).densityMatrix testDistillationState3 = create_densitystate(CoordState([0.5, 0.5 / 8, 0.5 / 8, 0.5 / 8, 0.5 / 8, 0.5 / 8, 0.5 / 8, 0.5 / 8, 0.5 / 8], "UNKNOWN"), testStandardBasis3).densityMatrix @testset "BellDiagonalQudits.jl" begin # BellDiagonalQudits/src/BellStates @test length(uniform_bell_sampler(10, 3)) == 10 @test length(uniform_bell_sampler(10, 3, :enclosurePolytope)) == 10 @test length(create_random_coordstates(10, 3, :magicSimplex)) == 10 @test length(create_random_coordstates(10, 3, :magicSimplex, 10, 5)) == 10 @test length(create_standard_indexbasis(4, 10).basis) == 16 @test length(create_alt_indexbasis(3, complex(ones(3, 3)), 10).basis) == 9 @test testDictionaries3[1][2, 1] == 6 @test create_densitystate(CoordState(1 / 9 * ones(9), "UNKNOWN"), testStandardBasis3).coords ≈ 1 / 9 * ones(9) @test length(create_bipartite_weyloperator_basis(3)) == 81 # BellDiagonalQudits/src/EntanglementWitness @test length(testRandomCoordWits) == 2 # BellDiagonalQudits/src/SeparableStates @test length(vertices_list(tovrep(testStandardKernel3))) == 12 @test length(vertices_list(tovrep(testStandardKernel4))) == 24 @test length(vertices_list(testExtKernel3)) == 13 # BellDiagonalQudits/src/Symmetries @test length(testSyms3) == 432 @test get_symcoords( [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0], generate_symmetries(testStandardBasis3, 3)[1:2] ) == [ [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0], [7.0, 8.0, 9.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0] ] # BellDiagonalQudits/src/EntanglementChecks @test length(testMub4) == 5 @test all( map( i -> getfield( analyse_coordstate( 3, CoordState(1 / 9 * ones(9), "UNKNOWN"), testAnaSpec, testStandardBasis3, testStandardKernel3, testBipartiteWeylBasis3, testDictionaries3, testMub3, testRandomCoordWits ), i ) == getfield( AnalysedCoordState( CoordState(1 / 9 * ones(9), "UNKNOWN"), true, true, true, false, false, false, false ), i), propertynames( AnalysedCoordState( CoordState(1 / 9 * ones(9), "UNKNOWN"), true, true, true, false, false, false, false ) )[2:8] ) ) @test all( map( i -> getfield( sym_analyse_coordstate( 3, CoordState(1 / 9 * ones(9), "UNKNOWN"), testSyms3[1:10], testAnaSpecSym, testStandardBasis3, testStandardKernel3, testBipartiteWeylBasis3, testDictionaries3, testMub3, testRandomCoordWits ), i ) == getfield( AnalysedCoordState( CoordState(1 / 9 * ones(9), "UNKNOWN"), true, true, true, false, false, false, false ), i), propertynames( AnalysedCoordState( CoordState(1 / 9 * ones(9), "UNKNOWN"), true, true, true, false, false, false, false ) )[2:8] ) ) @test map( x -> x.coordState.eClass, classify_analyzed_states!([ AnalysedCoordState( CoordState(ones(9), "UNKNOWN"), true, true, true, false, false, false, false ), AnalysedCoordState( CoordState(ones(9), "UNKNOWN"), false, false, true, false, false, false, false ), AnalysedCoordState( CoordState(ones(9), "UNKNOWN"), false, false, true, true, false, false, false ), AnalysedCoordState( CoordState(ones(9), "UNKNOWN"), false, false, false, true, false, false, false )]) ) == ["SEP", "PPT_UNKNOWN", "BOUND", "NPT"] @test concurrence_qp_gendiagonal_check( CoordState([0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0], "UNKNOWN"), 3, testAltBasisStates3 ) #BellDiagonalQudits/src/Distillation @test FIMAX_routine(testDistillationState2, 2, 2, testStandardBasis2)[2] > 0 @test FIMAX_routine(testDistillationState3, 2, 3, testStandardBasis3)[2] > 0 @test P1_P2_routine(testDistillationState3, 2, 3, testStandardBasis3)[2] > 0 @test DEJMPS_routine(testDistillationState3, 2, 3, testStandardBasis3)[2] > 0 @test BBPSSW_routine(testDistillationState3, 2, 3, testStandardBasis3)[2] > 0 @test iterative_FIMAX_protocol(testDistillationState2, 0.9, 2, 2, testStandardBasis2, 100)[1] @test iterative_FIMAX_protocol(testDistillationState3, 0.9, 2, 3, testStandardBasis3, 100)[1] @test iterative_P1_P2_protocol(testDistillationState3, 0.9, 2, 3, testStandardBasis3, 100)[1] @test iterative_DEJMPS_protocol(testDistillationState3, 0.9, 2, 3, testStandardBasis3, 100)[1] @test iterative_BBPSSW_protocol(testDistillationState3, 0.9, 2, 3, testStandardBasis3, 100)[1] @test efficiency(true, [1, 2, 3], [0.5, 0.7, 0.9], 2) > 0 end
BellDiagonalQudits
https://github.com/kungfugo/BellDiagonalQudits.jl.git
[ "MIT" ]
0.1.7
79e541dc38e1b13ceb024af4fb5f87a10bfbea85
docs
5202
# Contributor Covenant Code of Conduct ## Our Pledge We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community. ## Our Standards Examples of behavior that contributes to a positive environment for our community include: * Demonstrating empathy and kindness toward other people * Being respectful of differing opinions, viewpoints, and experiences * Giving and gracefully accepting constructive feedback * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience * Focusing on what is best not just for us as individuals, but for the overall community Examples of unacceptable behavior include: * The use of sexualized language or imagery, and sexual attention or advances of any kind * Trolling, insulting or derogatory comments, and personal or political attacks * Public or private harassment * Publishing others' private information, such as a physical or email address, without their explicit permission * Other conduct which could reasonably be considered inappropriate in a professional setting ## Enforcement Responsibilities Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful. Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate. ## Scope This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at . All complaints will be reviewed and investigated promptly and fairly. All community leaders are obligated to respect the privacy and security of the reporter of any incident. ## Enforcement Guidelines Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct: ### 1. Correction **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community. **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested. ### 2. Warning **Community Impact**: A violation through a single incident or series of actions. **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban. ### 3. Temporary Ban **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior. **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban. ### 4. Permanent Ban **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals. **Consequence**: A permanent ban from any sort of public interaction within the community. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0, available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity). [homepage]: https://www.contributor-covenant.org For answers to common questions about this code of conduct, see the FAQ at https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
BellDiagonalQudits
https://github.com/kungfugo/BellDiagonalQudits.jl.git
[ "MIT" ]
0.1.7
79e541dc38e1b13ceb024af4fb5f87a10bfbea85
docs
3524
[![CI][ci-img]][ci-url] [![codecov][cov-img]][cov-url] [![][docs-dev-img]][docs-dev-url] [![DOI](https://zenodo.org/badge/506929284.svg)](https://zenodo.org/badge/latestdoi/506929284) [![DOI](https://joss.theoj.org/papers/10.21105/joss.04924/status.svg)](https://doi.org/10.21105/joss.04924) [ci-img]: https://github.com/kungfugo/BellDiagonalQudits.jl/actions/workflows/CI.yml/badge.svg [ci-url]: https://github.com/kungfugo/BellDiagonalQudits.jl/actions/workflows/CI.yml [cov-img]: http://codecov.io/github/kungfugo/BellDiagonalQudits.jl/coverage.svg [cov-url]: https://codecov.io/github/kungfugo/BellDiagonalQudits.jl [docs-dev-img]: https://img.shields.io/badge/docs-dev-blue.svg [docs-dev-url]: https://kungfugo.github.io/BellDiagonalQudits.jl/dev/ # BellDiagonalQudits.jl _Generate and analyze Bell diagonal Qudits with Julia_ A package for generation and entanglement classification of Bell diagonal quantum states. Bell diagonal states are generated as mixtures maximally entangled Bell states, which are related by Weyl transformations. The special propterties of these states, e.g. symmetries, allow efficient methods to be leveraged for the detection of entanglement, including its generally hard to detect form of PPT/bound entanglement. This package provides methods to sample states, to numerically generate entanglement witnesses and to apply and extend further criteria to detect entanglement or separability in general dimension. For a precise description of implemented methods and related research results see [1], [2], [3] and the references therein. ## Package Features - Create mixtures of maximally entangled Bell states based on Weyl transformations in any dimension - Classify Bell diagonal states as separable, PPT/bound entangled or NPT/free entangled - Generate numerical entanglement witnesses for Bell diagonal states - Generate entanglement conserving symmetries and use them for entanglement classification ## Installation BellDiagonalQudits can be installed using the Julia package manager. From the Julia REPL, type `]` to enter the Pkg REPL mode and run ``` pkg> add BellDiagonalQudits ``` The package can be loaded via ```julia julia> using BellDiagonalQudits ``` ## Documentation Documentation is available at [https://kungfugo.github.io/BellDiagonalQudits.jl/dev/](https://kungfugo.github.io/BellDiagonalQudits.jl/dev/) ## References [1] Popp, C., Hiesmayr, B.C., _Almost complete solution for the NP-hard separability problem of Bell diagonal qutrits_, Sci Rep 12, 12472 (2022), [https://doi.org/10.1038/s41598-022-16225-z](https://doi.org/10.1038/s41598-022-16225-z) [2] Baumgartner, B., Hiesmayr, B.C., Narrenhofer, H. _A special simplex in the state space for entangled qudits_, J. Phys. A Math. Theor. 40, 7919 (2007), [https://doi.org/10.1088/1751-8113/40/28/s03] (https://doi.org/10.1088/1751-8113/40/28/s03) [3] Popp, C., Hiesmayr, B.C., _Bound Entanglement of Bell Diagonal Pairs of Qutrits and Ququarts: A Comparison_, arXiv (2022), [https://arxiv.org/abs/2209.15267] (https://arxiv.org/abs/2209.15267) ## Contributions Any contribution to BellDiagonalQudits.jl is welcome in the following ways: * Reporting bugs and suggestions in the issues section of the project's Github. * Modifying the code or documentation with a pull request. To contribute to the package, fork the repository on GitHub, clone it and make modifications on a new branch. Once your changes are made, push them on your fork and create the Pull Request on the main repository.
BellDiagonalQudits
https://github.com/kungfugo/BellDiagonalQudits.jl.git
[ "MIT" ]
0.1.7
79e541dc38e1b13ceb024af4fb5f87a10bfbea85
docs
2216
# BellDiagonalQudits.jl _Generate and analyze Bell diagonal Qudits with Julia_ A package for generation and entanglement classification of Bell diagonal quantum states. Bell diagonal states are generated as mixtures maximally entangled Bell states, which are related by Weyl transformations. The special propterties of these states, e.g. symmetries, allow efficient methods to be leveraged for the detection of entanglement, including its generally hard to detect form of PPT/bound entanglement. This package provides methods to sample states, to numerically generate entanglement witnesses and to apply and extend further criteria to detect entanglement or separability in general dimension. Furthermore, it provides methods for entanglement distillation. For a precise description of implemented methods and related research results see [1] and [2] and the references therein. ## Package Features - Create mixtures of maximally entangled Bell states based on Weyl transformations in any dimension - Classify Bell diagonal states as separable, PPT/bound entangled or NPT/free entangled - Generate numerical entanglement witnesses for Bell diagonal states - Generate entanglement conserving symmetries and use them for entanglement classification - Execute recurrence-based entanglement distillation protocols. ## References [1] Popp, C., Hiesmayr, B.C., _Almost complete solution for the NP-hard separability problem of Bell diagonal qutrits_, Sci Rep 12, 12472 (2022), [https://doi.org/10.1038/s41598-022-16225-z](https://doi.org/10.1038/s41598-022-16225-z) [2] Baumgartner, B., Hiesmayr, B.C., Narrenhofer, H. _A special simplex in the state space for entangled qudits_, J. Phys. A Math. Theor. 40, 7919 (2007), [https://doi.org/10.1088/1751-8113/40/28/s03] (https://doi.org/10.1088/1751-8113/40/28/s03) [3] Popp, C., Hiesmayr, B.C., _Bound Entanglement of Bell Diagonal Pairs of Qutrits and Ququarts: A Comparison_, arXiv (2022), [https://arxiv.org/abs/2209.15267] (https://arxiv.org/abs/2209.15267) [4] Popp, C., Sutter, T.C., Hiesmayr, B.C., _A Novel Stabilizer-based Entanglement Distillation Protocol for Qudits_, arXiv (2024), [https://arxiv.org/abs/2408.02383] (https://arxiv.org/abs/2408.02383)
BellDiagonalQudits
https://github.com/kungfugo/BellDiagonalQudits.jl.git
[ "MIT" ]
0.1.7
79e541dc38e1b13ceb024af4fb5f87a10bfbea85
docs
180
# Library ```@index ``` ## Public ```@autodocs Modules = [BellDiagonalQudits] Private = false ``` ## Internal ```@autodocs Modules = [BellDiagonalQudits] Public = false ```
BellDiagonalQudits
https://github.com/kungfugo/BellDiagonalQudits.jl.git
[ "MIT" ]
0.1.7
79e541dc38e1b13ceb024af4fb5f87a10bfbea85
docs
8044
# Manual This manual shows how to use the package by using it to sample a set of uniformly distributed Bell diagonal states and to analyse their entanglement properties. Here, we apply criteria for separability and entanglement to determine the entanglement class of generated bipartite qutrits, i.e. `d=3`. In this system, bound entangled states, i.e. entangled states with positive partial transposition (PPT) that cannot be used for entanglement distillation, exist. The entanglement classes are labeled "SEP" for separability, "BOUND" for bound entanglement, "FREE" for entanglement with negative partial transposition (i.e. distillable) and "PPT_UNKNOWN" for PPT states that could not be classified as entangled or separable. ## Package installation BellDiagonalQudits can be installed using the Julia package manager. From the Julia REPL, type `]` to enter the Pkg REPL mode and run ``` pkg> add BellDiagonalQudits ``` The package can be loaded via ```julia julia> using BellDiagonalQudits ``` ## State generation Create a basis of maximally entangled bipartite Bell states in `d^2` dimensions. Each Bell basis state is created by applying a certain Weyl transformation to the maximally entangled state. Sample Bell diagonal random mixed states of those Bell states, represented by their `d^2` coordinates (mixing probabilities) in the Bell basis. \ **Bell basis generation** Create a Bell basis `myBasis` by applying each of the `d^2` Weyl transformations `W_{k,l} \\otimes \\mathbb{1}_d` to the maximally entangled state.`myBasis.basis` contains the enumerated Bell states in computational basis together with the indices of the corresponding Weyl transformation. `myBasisDict` contains the dictionaries to relate the enumerated `d^2` Bell basis states to the double indices `(k,l)` of the corresponding Weyl transformation. ```julia d = 3 myBasis = create_standard_indexbasis(d,10) myBasisDict = create_dictionary_from_basis(myBasis) ``` \ **State sampling** Create uniformly distributed random representations of quantum states by specifying the coordinates of the state in the created Bell basis. The coordinates represent the mixing probabilities of the Bell basis states. Here, we create only states with Bell coordinates within the "enclosure polytope", which is defined by the limitation of all coordinates (mixing probabilities) to be smaller than or equal to `1/d`. This subset is known to contain all (but not only) states with positive partial transposition (PPT), which can be separable or bound entangled. ```julia myCoordStates = uniform_bell_sampler(100, d, :enclosurePolytope) ``` Create `DensityState`s including the density matrix of each state in the computational basis, created by mixing the Bell states of `myBasis` according to the `coords` of `myCoordStates`. ```julia myDensityStates = map(x->create_densitystate(x, myBasis), myCoordStates) ``` ## Analysis prerequisites Now create the analysis objects required for the entanglement classification using several criteria for entanglement or separability. \ **Separable kernel polytope** The kernel polytope is known to contain only Bell coordinates that represent separable states. It is defined as the convex hull of vertices related to special separable states called "subgroup states". The related `kernel check` tests if the Bell coordinates of a given unclassified state are contained in this convex hull and thus indicates separability. ```julia mySepKernel = create_kernel_polytope(d, myBasis) ``` If additional separable states `newSepDensityStates` are known, the kernel polytope can be exteded to a larger convex hull in order to improve the kernel check for separability. For a (trivial) example, consider the separable, maximally mixed state having all Bell states mixed equally with probability `1/d^2`. First,specify the coordinates in the Bell basis and set the `eClass` of the corresponding `CoordState` to "SEP". Then, calculate the density matrix and create the `DensityState`. Finally, extend the kernel polytope `mySepKernel` by the array containing this separable state. ```julia maxMixedCoordState = CoordState(1/d^2*ones(d^2), "SEP") maxMixedDensityState = create_densitystate(maxMixedCoordState, myBasis) newSepDensityStates = [maxMixedDensityState] myExtendedKernel = extend_vpolytope_by_densitystates(tovrep(mySepKernel), newSepDensityStates, 10) ``` \ **Weyl operator basis** Use the Weyl operators to construct a basis of the space of `(d^2,d^2)` matrices. This object is used for the `spinrep check` indicating separability according to the representation of the density matrix of a given state in this basis. ```julia myWeylOperatorBasis = create_bipartite_weyloperator_basis(d) ``` \ **Mutually unbiased bases (MUBs)** Create the a set of mutually unbiased bases (MUBs) constructed with the Weyl operators and represented in the computational basis. ```julia myMub = create_standard_mub(d) ``` \ **Symmetries** Generate entanglement class conserving symmetries represented as permutations of state coordinates in the Bell basis. Given a classified state, the orbit, i.e. the set of states that are generated by applying all symmetries to the classified state, is known to be of the same entanglement class. The symmetries can be used to improve the entanglement classification. ```julia mySyms = generate_symmetries(myBasis, d) ``` \ **Entanglement witnesses** Generate `n` numerical entanglement witnesses by numerical optimization over the set of separable states. Here, the entanglement witnesses are represented by their coordinates in the Bell basis, an upper, and a lower bound. For all separable states, the inner product of the state and witness coordinates obeys these bounds. A violation of the inner product of an unknown state and the witness thus indicates entanglement. Use `iterations` runs to improve the determined upper and lower bounds. Other optimization methods than the default `NelderMead` can be used. ```julia n = 2 myOptimizedEWs = create_random_bounded_ews( d, myBasis, n, true, 20 ) ``` ```julia myOptimizedCoodEWs = map(x->get_bounded_coordew(x), myOptimizedEWs) ``` ## Entanglement classification **Analysis specification** Specify, which entanglement checks to use. See properties of type `AnalysisSpecification`. In this case we check separability with the kernel and spinrep check and test for entanglement using the ppt, realignment, concurrence_qp and numeric_ew check. ```julia myAnaSpec = AnalysisSpecification( true, true, true, true, true, false, true, false ) ``` \ **Apply analysis to all generated states** If `useSymmetries == false` in the analysis specification `myAnaSpec` use `analyse_coordstate`, else use `sym_analyse_coordstate` to leverage the symmetries `mySyms` for improved classification. ```julia f(x) = analyse_coordstate( d, x, myAnaSpec, myBasis, mySepKernel, myWeylOperatorBasis, myBasisDict, missing, myOptimizedCoodEWs ) myAnalysedCoordStates = map(x->f(x), myCoordStates) ``` Finally use analysis results to set `CoordState.eClass` to assign the entanglement class to the states. ```julia classify_analyzed_states!(myAnalysedCoordStates) ``` Identify e.g. bound entangled states as ```julia myBoundStates = filter(x->x.coordState.eClass == "BOUND", myAnalysedCoordStates) ``` ## Entanglement distillation Create and distill a Bell-diagonal state with the FIMAX protocol. First, create a test state. ```julia d=3 testBDS = create_densitystate(CoordState([0.5, 0.5 / 8, 0.5 / 8, 0.5 / 8, 0.5 / 8, 0.5 / 8, 0.5 / 8, 0.5 / 8, 0.5 / 8], "UNKNOWN"), myBasis).densityMatrix ``` To execute one iteration of the FIMAX routine, run: ```julia FIMAX_routine_results = FIMAX_routine(testBDS, 2, d, myBasis) ``` To iterate this procedure until a target fidelity of 0.99 with the maximally entangled state is achieved, execute: ```julia FIMAX_protocol_results = iterative_FIMAX_protocol(testBDS, 0.99, 2, d, testStandardBasis3, 100) ```
BellDiagonalQudits
https://github.com/kungfugo/BellDiagonalQudits.jl.git
[ "MIT" ]
0.1.7
79e541dc38e1b13ceb024af4fb5f87a10bfbea85
docs
5509
--- title: "BellDiagonalQudits: A package for entanglement analyses of mixed maximally entangled qudits" tags: - Julia - quantum information - quantum physics - entanglement - separability problem - Bell states authors: - name: Christopher Popp orcid: 0000-0002-2352-3731 affiliation: 1 affiliations: - name: Faculty of Physics, University of Vienna, Währingerstrasse 17, 1090, Vienna Austria index: 1 date: 15 December 2022 bibliography: paper.bib --- # Summary In the field of quantum information and technology, entanglement in quantum systems called qudits is regarded as resource for quantum-based or quantum-assisted information processing tasks. It allows new ways of information processing like quantum computation or quantum teleportation and provides possibilities for speedups in a variety of algorithms with applications like search or optimization. Despite its theoretical and practical relevance, there is no general method to determine whether a given quantum state is entangled or not due to a special and hard to detect form of entanglement called bound entanglement. Bipartite Bell states are maximally entangled states of two qudits and are of high relevance for application in quantum technologies. Mixtures of those states can be entangled, including its bound form, or separable. Leveraging their special properties, Bell states can be numerically generated and analyzed for their entanglement properties by various methods implemented in this Julia package. # Statement of need `BellDiagonalQudits` is an Quantum Information-affiliated Julia package for generation and entanglement analyses of mixed maximally entangled bipartite qudits in general dimension. The API for `BellDiagonalQudits` provides an user-friendly interface to generate representations of Bell diagonal quantum states and to analyze their entanglement properties with various general or specialized criteria to detect entanglement or separability. Leveraging geometric properties of a certain class of mixed Bell states that are related by Weyl transformations, `BellDiagonalQudits` combines known analytical results by @baumgartner and numerical methods for quantum state representation and analysis. It leverages and depends on the Julia package `QuantumInformation`, the convex sets of `LazySets` [@lazysets] and the optimization methods of `Optim` [@optim]. `BellDiagonalQudits` was designed to be used by researchers in quantum science and quantum information theory. It has already been used in multiple scientific publications, e.g. in @PoppACS and @PoppBoundEntComparison in the context of entanglement classification and detection of bipartite qudits in dimension three and four. The combination of efficient state generation via random sampling or deterministic procedures and implementation of both frequently used and specialized entanglement and separability detectors supports the research of entanglement in several ways. From a general point of view, entangled Bell states are well accessible for powerful methods of entanglement and separability detection, leveraging their symmetries and geometric properties. It was shown in that a significant share of the group of mixed Bell states related by Weyl transformations are bound entangled [@PoppACS;@PoppBoundEntComparison;@hiesmayr], offering a systematic way to generate and investigate those states with respect to the separability problem in different dimensions. In addition to general methods applicable to any Bell diagonal state, `BellDiagonalQudits` provides features to generate the special symmetries of Bell states that are related via Weyl transformations. These symmetries are leveraged for improved entanglement classification and the numerical generation of specialized entanglement witnesses in any dimension. Furthermore, the implemented methods of `BellDiagonalQudits` can be used in various quantum information processing tasks involving Bell diagonal states in any dimension like Quantum Key Distribution or entanglement verification. `BellDiagonalQudits` uses and integrates well with the general interface of `QuantumInformation` allowing the investigation of Bell states in the context of quantum channels, entanglement measures or entropy. # Relation to research projects The methods of `BellDiagonalQudits` to generate and analyze Bell diagonal states in general dimension are based on analytical properties summarized by @baumgartner. Extensions of those methods and efficient implementation in `BellDiagonalQudits` enabled the detailed analysis by @PoppACS of Bell diagonal qudits in three dimensions (qutrits), providing an operational solution to the separability problem for those states. Additionally the relative shares of separable and (bound) entangled states were precisely determined among the Bell diagonal states. In @PoppBoundEntComparison, higher dimensions were considered, focusing on a detailed comparison and geometric properties of separable states in dimension three and four. # Package information `BellDiagonalQudits` is available on Github at [https://github.com/kungfugo/BellDiagonalQudits.jl](https://github.com/kungfugo/BellDiagonalQudits.jl). The package documentation is available at [https://kungfugo.github.io/BellDiagonalQudits.jl/dev/](https://kungfugo.github.io/BellDiagonalQudits.jl/dev/) and provides examples of usage. # Acknowledgments I acknowledge support from Beatrix C. Hiesmayr for review and validation of implemented methods. # References
BellDiagonalQudits
https://github.com/kungfugo/BellDiagonalQudits.jl.git
[ "MIT" ]
1.1.4
bc4b247db8e78a9c9f223e7c4870fd2a43b68fe3
code
195
using Pkg # Load package manager Pkg.add("JuliaFormatter") # Install JuliaFormatter using JuliaFormatter # Load JuliaFormatter format("."; verbose=true) # Format all files
MultilayerGraphs
https://github.com/JuliaGraphs/MultilayerGraphs.jl.git
[ "MIT" ]
1.1.4
bc4b247db8e78a9c9f223e7c4870fd2a43b68fe3
code
785
using Revise using SimpleTraits using Distributions using Graphs using MultilayerGraphs using Documenter DocMeta.setdocmeta!( MultilayerGraphs, :DocTestSetup, :(using MultilayerGraphs); recursive=true ) makedocs(; modules=[MultilayerGraphs], authors="Pietro Monticone, Claudio Moroni", repo="https://github.com/JuliaGraphs/MultilayerGraphs.jl/blob/{commit}{path}#{line}", sitename="MultilayerGraphs.jl", format=Documenter.HTML(; prettyurls=get(ENV, "CI", "false") == "true", canonical="https://juliagraphs.org/MultilayerGraphs.jl", assets=String[], ), pages=["Home" => "index.md", "API" => "API.md"], clean=false, ) deploydocs(; repo="github.com/JuliaGraphs/MultilayerGraphs.jl", devbranch="main", push_preview=true )
MultilayerGraphs
https://github.com/JuliaGraphs/MultilayerGraphs.jl.git
[ "MIT" ]
1.1.4
bc4b247db8e78a9c9f223e7c4870fd2a43b68fe3
code
15914
# Install necessary tutorial dependencies using Pkg Pkg.add(["Revise", "Distributions", "Graphs", "SimpleValueGraphs", "LoggingExtras", "StatsBase", "SimpleWeightedGraphs", "MetaGraphs", "Agents", "MultilayerGraphs"]) # Import necessary tutorial dependencies using Revise using StatsBase, Distributions using Graphs, SimpleWeightedGraphs, MetaGraphs, SimpleValueGraphs using MultilayerGraphs # Set the minimum and maximum number of nodes_list and edges for random graphs const vertextype = Int64 const _weighttype = Float64 const min_vertices = 5 const max_vertices = 7 const n_nodes = max_vertices # The constructor for nodes (which are immutable) only requires a name (`id`) for the node const nodes_list = [Node("node_$i") for i in 1:n_nodes] ## Convert nodes to multilayer vertices without metadata const multilayervertices = MV.(nodes_list) ## Convert nodes multilayer vertices with metadata const multilayervertices_meta = [MV(node, ("I'm node $(node.id)",)) for node in nodes_list] # `MV` is an alias for `MultilayerVertex` multilayervertices_meta[1] # Utility function that returns a random number of vertices and edges each time it is called: function rand_nv_ne_layer(min_vertices, max_vertices) _nv = rand(min_vertices:max_vertices) _ne = rand(1:(_nv*(_nv-1)) ÷ 2 ) return (_nv,_ne) end # Utility function that returns two vertices of a Layer that are not adjacent. function _get_srcmv_dstmv_layer(layer::Layer) mvs = MultilayerGraphs.get_bare_mv.(collect(mv_vertices(layer))) src_mv_idx = findfirst(mv -> !isempty(setdiff( Set(mvs), Set( vcat(MultilayerGraphs.get_bare_mv.(mv_outneighbors(layer, mv)), mv) ), )), mvs) src_mv = mvs[src_mv_idx] _collection = setdiff( Set(mvs), Set( vcat(MultilayerGraphs.get_bare_mv.(mv_outneighbors(layer, src_mv)), src_mv) ), ) dst_mv = MultilayerGraphs.get_bare_mv(rand(_collection)) return mvs, src_mv, dst_mv end # An unweighted simple layer: _nv, _ne = rand_nv_ne_layer(min_vertices,max_vertices) layer_sg = Layer( :layer_sg, sample(nodes_list, _nv, replace = false), _ne, SimpleGraph{vertextype}(), _weighttype ) # A weighted `Layer` _nv, _ne = rand_nv_ne_layer(min_vertices,max_vertices) layer_swg = Layer( :layer_swg, sample(nodes_list, _nv, replace = false), _ne, SimpleWeightedGraph{vertextype, _weighttype}(), _weighttype; default_edge_weight = (src,dst) -> rand() ) # A `Layer` with an underlying `MetaGraph`: _nv, _ne = rand_nv_ne_layer(min_vertices,max_vertices) layer_mg = Layer( :layer_mg, sample(nodes_list, _nv, replace = false), _ne, MetaGraph{vertextype, _weighttype}(), _weighttype; default_edge_metadata = (src,dst) -> (from_to = "from_$(src)_to_$(dst)",) ) # `Layer` with an underlying `ValGraph` from `SimpleValueGraphs.jl` _nv, _ne = rand_nv_ne_layer(min_vertices,max_vertices) layer_vg = Layer( :layer_vg, sample(nodes_list, _nv, replace = false), _ne, MultilayerGraphs.ValGraph(SimpleGraph{vertextype}(); edgeval_types=(Float64, String, ), edgeval_init=(s, d) -> (s+d, "hi"), vertexval_types=(String,), vertexval_init=v -> ("$v",),), _weighttype; default_edge_metadata = (src,dst) -> (rand(), "from_$(src)_to_$(dst)",), default_vertex_metadata = mv -> ("This metadata had been generated via the default_vertex_metadata method",) ) # Collect all layers in an ordered list. Order will be recorded when instantiating the multilayer graph. layers = [layer_sg, layer_swg, layer_mg, layer_vg] # Utilities for Interlayer ## Utility function that returns two vertices of an Interlayer that are not adjacent. function _get_srcmv_dstmv_interlayer(interlayer::Interlayer) mvs = get_bare_mv.(collect(mv_vertices(interlayer))) src_mv = nothing _collection = [] while isempty(_collection) src_mv = rand(mvs) _collection = setdiff(Set(mvs), Set(vcat(get_bare_mv.(mv_outneighbors(interlayer, src_mv)), src_mv, get_bare_mv.(mv_vertices( eval(src_mv.layer) ))) ) ) end dst_mv = get_bare_mv(rand(_collection)) return mvs, src_mv, dst_mv end ## Utility function that returns a random number edges between its arguments `layer_1` and `layer_2`: function rand_ne_interlayer(layer_1, layer_2) nv_1 = nv(layer_1) nv_2 = nv(layer_2) _ne = rand(1: (nv_1 * nv_2 - 1) ) return _ne end # Define the random undirected simple Interlayer _ne = rand_ne_interlayer(layer_sg, layer_swg) interlayer_sg_swg = Interlayer( layer_sg, # The first layer to be connected layer_swg, # The second layer to be connected _ne, # The number of edges to randomly generate SimpleGraph{vertextype}(), # The underlying graph, passed as a null graph interlayer_name = :random_interlayer # The name of the interlayer. We will be able to access it as a property of the multilayer graph via its name. This kwarg's default value is given by a combination of the two layers' names. ) # Define a weighted `Interlayer` _ne = rand_ne_interlayer(layer_swg, layer_mg) interlayer_swg_mg = Interlayer( layer_swg, layer_mg, _ne, SimpleWeightedGraph{vertextype, _weighttype}(); default_edge_weight = (x,y) -> rand() # Arguments follow the same rules as in Layer ) # Define an `Interlayer` with an underlying `MetaGraph` _ne = rand_ne_interlayer(layer_mg, layer_vg) interlayer_mg_vg = Interlayer( layer_mg, layer_vg, _ne, MetaGraph{vertextype, _weighttype}(); default_edge_metadata = (x,y) -> (mymetadata = rand(),), transfer_vertex_metadata = true # This boolean kwarg controls whether vertex metadata found in both connected layers are carried over to the vertices of the Interlayer. NB: not all choice of underlying graph may support this feature. Graphs types that don't support metadata or that pose limitations to it may result in errors. ) # Define an `Interlayer` with an underlying `ValGraph` from `SimpleValueGraphs.jl`, with diagonal couplings only: interlayer_multiplex_sg_mg = multiplex_interlayer( layer_sg, layer_mg, ValGraph(SimpleGraph{vertextype}(); edgeval_types=(from_to = String,), edgeval_init=(s, d) -> (from_to = "from_$(s)_to_$(d)")); default_edge_metadata = (x,y) -> (from_to = "from_$(src)_to_$(dst)",) ) # Finally, An `Interlayer` with no couplings (an "empty" interlayer): interlayer_empty_sg_vg = empty_interlayer( layer_sg, layer_vg, SimpleGraph{vertextype}() ) # Collect all interlayers. Even though the list is ordered, order will not matter when instantiating the multilayer graph. interlayers = [interlayer_sg_swg, interlayer_swg_mg, interlayer_mg_vg, interlayer_multiplex_sg_mg, interlayer_empty_sg_vg] # Nodes layer_sg_nodes = nodes(layer_sg) interlayer_sg_swg_nodes = nodes(interlayer_sg_swg) has_node(layer_sg, layer_sg_nodes[1]) # Vertices layer_sg_vertices = mv_vertices(layer_sg) mv_vertices(layer_mg) interlayer_sg_swg_vertices = mv_vertices(interlayer_sg_swg) new_node = Node("missing_node") new_metadata = (meta = "my_metadata",) new_vertex = MV(new_node, new_metadata) add_vertex!(layer_mg, new_vertex) add_vertex!(layer_mg, new_node, metadata = new_metadata) add_vertex!(layer_mg, new_node, Dict(pairs(new_metadata))) metagraph = MetaGraph() add_vertex!(metagraph, Dict(pairs(new_metadata))) # true rem_vertex!(layer_sg, new_vertex) # Returns true if succeeds get_metadata(layer_mg, MV(new_node)) # Edges edgetype(layer_sg) collect(edges(layer_sg)) # Define a weighted edge for the layer_swg ## Define the weight _weight = rand() ## Select two non-adjacent vertices in layer_swg _, src_w, dst_w = _get_srcmv_dstmv_layer(layer_swg) ## Construct a weighted MultilayerEdge me_w = ME(src_w, dst_w, _weight) # ME is an alias for MultilayerEdge add_edge!(layer_swg, me_w) add_edge!(layer_swg, src_w, dst_w, weight = _weight) add_edge!(layer_swg, src_w, dst_w, _weight) simpleweightedgraph = SimpleWeightedGraph(SimpleGraph(5, 0)) add_edge!(simpleweightedgraph, 1, 2, _weight) rem_edge!(layer_swg, src_w, dst_w) # Returns true if succeeds get_weight(layer_swg, src_w, dst_w) # Define an edge with metadata for the layer_mg ## Define the metadata _metadata = (meta = "mymetadata",) ## Select two non-adjacent vertices in layer_mg _, src_m, dst_m = _get_srcmv_dstmv_layer(layer_mg) ## Construct a MultilayerEdge with metadata me_m = ME(src_m, dst_m, _metadata) add_edge!(layer_mg, me_m) add_edge!(layer_mg, src_m, dst_m, metadata = _metadata) add_edge!(layer_mg, src_m, dst_m, Dict(pairs(_metadata))) get_metadata(layer_mg, src_m, dst_m) add_edge!(layer_swg, me_w) add_edge!(layer_swg, src_w, dst_w, weight = _weight) add_edge!(layer_swg, src_w, dst_w, _weight) rem_edge!(layer_swg, src_w, dst_w) # Multilayer Graphs multilayergraph = MultilayerGraph( layers, # The (ordered) list of layers the multilayer graph will have interlayers; # The list of interlayers specified by the user. Note that the user does not need to specify all interlayers, as the unspecified ones will be automatically constructed using the indications given by the `default_interlayers_null_graph` and `default_interlayers_structure` keywords. default_interlayers_null_graph = SimpleGraph{vertextype}(), # Sets the underlying graph for the interlayers that are to be automatically specified. Defaults to `SimpleGraph{T}()`, where `T` is the `T` of all the `layers` and `interlayers`. See the `Layer` constructors for more information. default_interlayers_structure = "multiplex" # Sets the structure of the interlayers that are to be automatically specified. May be "multiplex" for diagonally coupled interlayers, or "empty" for empty interlayers (no edges). "multiplex". See the `Interlayer` constructors for more information. ) # The configuration model-like constructor will be responsible for creating the edges, so we need to provide it with empty layers and interlayers. # To create empty layers and interlayers, we will empty the above subgraphs, and, for compatibility reasons, we'll remove the ones having a `SimpleWeightedGraph`s. These lines are not necessary to comprehend the tutorial, they may be skipped. Just know that the variables `empty_layers` and `empty_interlayers` are two lists of, respectively, empty layers and interlayers that do not have `SimpleWeightedGraph`s as their underlying graphs empty_layers = deepcopy([layer for layer in layers if !(layer.graph isa SimpleWeightedGraphs.AbstractSimpleWeightedGraph)]) empty_layers_names = name.(empty_layers) empty_interlayers = deepcopy([interlayer for interlayer in interlayers if all(in.(interlayer.layers_names, Ref(empty_layers_names))) && !(interlayer.graph isa SimpleWeightedGraphs.AbstractSimpleWeightedGraph) ]) for layer in empty_layers for edge in edges(layer) rem_edge!(layer, edge) end end for interlayer in empty_interlayers for edge in edges(interlayer) rem_edge!(interlayer, edge) end end # Construct a multilayer graph that has a normal degree distribution. The support of the distribution must be positive, since negative degrees are not possible configuration_multilayergraph = MultilayerGraph(empty_layers, empty_interlayers, truncated(Normal(10), 0.0, 20.0)); new_node = Node("new_node") add_node!(multilayergraph, new_node) # Return true if succeeds new_vertex = MV(new_node, :layer_sg) add_vertex!(multilayergraph, new_vertex) rem_node!(multilayergraph, new_node) # Return true if succeeds # This will succeed random_weighted_edge = rand(collect(edges(multilayergraph.layer_swg))) set_weight!(multilayergraph, src(random_weighted_edge), dst(random_weighted_edge), rand()) # This will not succeed random_unweighted_edge = rand(collect(edges(multilayergraph.layer_sg))) set_weight!(multilayergraph, src(random_unweighted_edge), dst(random_unweighted_edge), rand()) # Instantiate a new Layer _nv, _ne = rand_nv_ne_layer(min_vertices,max_vertices) new_layer = Layer( :new_layer, sample(nodes_list, _nv, replace = false), _ne, SimpleGraph{vertextype}(), _weighttype ) # Add the Layer add_layer!( multilayergraph, # the `Multilayer(Di)Graph` which the new layer will be added to; new_layer; # the new `Layer` to add to the `multilayergraph` default_interlayers_null_graph = SimpleGraph{vertextype}(), # upon addition of a new `Layer`, all the `Interlayer`s between the new and the existing `Layer`s are immediately created. This keyword argument specifies their `null_graph` See the `Layer` constructor for more information. Defaults to `SimpleGraph{T}()` default_interlayers_structure = "empty" # The structure of the `Interlayer`s created by default. May either be "multiplex" to have diagonally-coupled only interlayers, or "empty" for empty interlayers. Defaults to "multiplex". ) # Check that the new layer now exists within the multilayer graph has_layer(multilayergraph, :new_layer) # Instantiate a new Interlayer. Notice that its name will be given by default as _ne = rand_ne_interlayer(layer_sg, new_layer) new_interlayer = Interlayer( layer_sg, new_layer, _ne, SimpleGraph{vertextype}(), interlayer_name = :new_interlayer ) # Modify an existing interlayer with the latter i.e. specify the latter interlayer: specify_interlayer!( multilayergraph, new_interlayer) # Now the interlayer between `layer_sg` and `new_layer` is `new_interlayer` # Get a layer by name multilayergraph.new_layer # Get an Interlayer by name multilayergraph.new_interlayer # Get an Interlayer from the names of the two layers that it connects get_interlayer(multilayergraph, :new_layer, :layer_sg ) # Remove the layer. This will also remove all the interlayers associated to it. rem_layer!( multilayergraph, :new_layer; remove_nodes = false # Whether to also remove all nodes represented in the to-be-removed layer from the multilayer graph ) wgt = weight_tensor(multilayergraph) array(wgt) # Get two random vertices from the MultilayerGraph mv1, mv2 = rand(mv_vertices(multilayergraph), 2) # Get the strength of the edge between them (0 for no edge): wgt[mv1, mv2]
MultilayerGraphs
https://github.com/JuliaGraphs/MultilayerGraphs.jl.git
[ "MIT" ]
1.1.4
bc4b247db8e78a9c9f223e7c4870fd2a43b68fe3
code
7327
################################################# ################# ENVIRONMENT ################### ################################################# # Import the package manager using Pkg # Activate the environment Pkg.activate(@__DIR__) # Instantiate the environment Pkg.instantiate() ################################################# ################### PACKAGES #################### ################################################# # Import necessary dependencies using Distributions, Graphs, SimpleValueGraphs using MultilayerGraphs # Set the number of nodes const n_nodes = 100 # Create a list of nodes const node_list = [Node("node_$i") for i in 1:n_nodes] ################################################# #################### LAYERS ##################### ################################################# # Create a simple directed layer n_vertices = rand(1:100) # Number of vertices layer_simple_directed = layer_simpledigraph( # Layer constructor :layer_simple_directed, # Layer name sample(node_list, n_vertices; replace=false), # Nodes represented in the layer Truncated(Normal(5, 5), 0, 20), # Indegree sequence distribution Truncated(Normal(5, 5), 0, 20), # Outdegree sequence distribution ) # Create a simple directed weighted layer n_vertices = rand(1:n_nodes) # Number of vertices n_edges = rand(n_vertices:(n_vertices * (n_vertices - 1) - 1)) # Number of edges layer_simple_directed_weighted = layer_simpleweighteddigraph( # Layer constructor :layer_simple_directed_weighted, # Layer name sample(node_list, n_vertices; replace=false), # Nodes represented in the layer n_edges; # Number of randomly distributed edges default_edge_weight=(src, dst) -> rand(), # Function assigning weights to edges ) # Create a simple directed value layer n_vertices = rand(1:n_nodes) # Number of vertices n_edges = rand(n_vertices:(n_vertices * (n_vertices - 1) - 1)) # Number of edges default_vertex_metadata = v -> ("vertex_$(v)_metadata",) # Vertex metadata default_edge_metadata = (s, d) -> (rand(),) # Edge metadata layer_simple_directed_value = Layer( # Layer constructor :layer_simple_directed_value, # Layer name sample(node_list, n_vertices; replace=false), # Nodes represented in the layer n_edges, # Number of randomly distributed edges ValDiGraph( SimpleDiGraph{Int64}(); vertexval_types=(String,), vertexval_init=default_vertex_metadata, edgeval_types=(Float64,), edgeval_init=default_edge_metadata, ), Float64; default_vertex_metadata=default_vertex_metadata, # Vertex metadata default_edge_metadata=default_edge_metadata, # Edge metadata ) # Create a list of layers layers = [ layer_simple_directed, layer_simple_directed_weighted, layer_simple_directed_value ] ################################################# ################# INTERLAYERS ################### ################################################# # Create a simple directed interlayer n_vertices_1 = nv(layer_simple_directed) # Number of vertices of layer 1 n_vertices_2 = nv(layer_simple_directed_weighted) # Number of vertices of layer 2 n_edges = rand(1:(n_vertices_1 * n_vertices_2 - 1)) # Number of interlayer edges interlayer_simple_directed = interlayer_simpledigraph( # Interlayer constructor layer_simple_directed, # Layer 1 layer_simple_directed_weighted, # Layer 2 n_edges, # Number of edges ) # Create a simple directed meta interlayer n_vertices_1 = nv(layer_simple_directed_weighted) # Number of vertices of layer 1 n_vertices_2 = nv(layer_simple_directed_value) # Number of vertices of layer 2 n_edges = rand(1:(n_vertices_1 * n_vertices_2 - 1)) # Number of interlayer edges interlayer_simple_directed_meta = interlayer_metadigraph( # Interlayer constructor layer_simple_directed_weighted, # Layer 1 layer_simple_directed_value, # Layer 2 n_edges; # Number of edges default_edge_metadata=(src, dst) -> # Edge metadata (edge_metadata="metadata_of_edge_from_$(src)_to_$(dst)",), transfer_vertex_metadata=true, # Boolean deciding layer vertex metadata inheritance ) # Create a list of interlayers interlayers = [interlayer_simple_directed, interlayer_simple_directed_meta] ################################################# ################## MULTILAYER ################### ################################################# # Create a simple directed multilayer graph multilayerdigraph = MultilayerDiGraph( # Constructor layers, # The (ordered) collection of layers interlayers; # The manually specified interlayers # The interlayers that are left unspecified # will be automatically inserted according # to the keyword argument below default_interlayers_structure="multiplex", # The automatically specified interlayers will have only diagonal couplings ) # Layers and interlayer can be accessed as properties using their names multilayerdigraph.layer_simple_directed_value # Create a node new_node_1 = Node("new_node_1") # Add the node to the multilayer graph add_node!(multilayerdigraph, new_node_1) # Create a vertex representing the node new_vertex_1 = MV( # Constructor (alias for "MultilayerVertex") new_node_1, # Node represented by the vertex :layer_simple_directed_value, # Layer containing the vertex ("new_metadata",), # Vertex metadata ) # Add the vertex add_vertex!( multilayerdigraph, # MultilayerDiGraph the vertex will be added to new_vertex_1, # MultilayerVertex to add ) # Create another node in another layer new_node_2 = Node("new_node_2") # Create another vertex representing the new node new_vertex_2 = MV(new_node_2, :layer_simple_directed) # Add the new vertex add_vertex!( multilayerdigraph, new_vertex_2; add_node=true, # Add the associated node before adding the vertex ) # Create an edge new_edge = MultilayerEdge( # Constructor new_vertex_1, # Source vertex new_vertex_2, # Destination vertex ("some_edge_metadata",), # Edge metadata ) # Add the edge add_edge!( multilayerdigraph, # MultilayerDiGraph the edge will be added to new_edge, # MultilayerVertex to add ) ################### METRICS #################### # Compute the global clustering coefficient multilayer_global_clustering_coefficient(multilayerdigraph) # Compute the overlay clustering coefficient overlay_clustering_coefficient(multilayerdigraph) # Compute the multilayer eigenvector centrality eigenvector_centrality(multilayerdigraph) # Compute the multilayer modularity modularity( multilayerdigraph, rand([1, 2, 3, 4], length(nodes(multilayerdigraph)), length(multilayerdigraph.layers)), )
MultilayerGraphs
https://github.com/JuliaGraphs/MultilayerGraphs.jl.git
[ "MIT" ]
1.1.4
bc4b247db8e78a9c9f223e7c4870fd2a43b68fe3
code
6807
# TODO: FIXME: # SimpleWeightedGraphs cannot be used for the configuration/random multilayergraph until this PR: https://github.com/JuliaGraphs/SimpleWeightedGraphs.jl/pull/14 is merged . # Default value for metadata should be `nothing` and not `NamedTuple()`? This would be more consistent with how edge weights behave. # In a future release we may implement Multiplex(Di)Graph # Implement https://en.wikipedia.org/wiki/Kleitman%E2%80%93Wang_algorithms and https://en.wikipedia.org/wiki/Havel%E2%80%93Hakimi_algorithm for wiring (un)directed configuration models. # Double check modularity. Also compare with https://juliagraphs.org/Graphs.jl/v1.5/community/#modularity-Tuple{AbstractGraph,%20AbstractVector{%3C:Integer}}. We should (probably) correct its implementation or at least compare it with a simpler one made in terms of unpadded supra adjacency matrix (that we have yet to implement). # GraphOfGraphs and DiGraphOfGraphs could be improved/redesigned. Also, they don't yet extend Graphs.jl # The δ_Ω implementation could be moved to a separate file. # The usage of mutable `MissingVertex`s (although limited to SupraWeightMatrix) points to the fact that Bijections (at least as they are used right now) are not the best way to represent integer label-MultilayerVertex associations. We my implement our own container object or use the existing ons differently. # We need a quick Multilayer(Di)Graph constructor of the form Multilayer(Di)Graph(nn, nl; nv = rand(0:nn*nl), ne = rand(0:nv*(nv-1)) kwargs...) where kwargs may be used to further specify it. module MultilayerGraphs export # Node.jl AbstractNode, Node, id, # abstractvertex.jl AbstractVertex, # multilayervertex.jl AbstractMultilayerVertex, MultilayerVertex, MV, node, layer, metadata, # missingvertex.jl MissingVertex, # multilayeredge.jl AbstractMultilayerEdge, MultilayerEdge, ME, weight, metadata, # halfedge.jl # layerdescriptor.jl # interlayerdescriptor.jl # abstractsubgraph.jl AbstractSubGraph, nodes, eltype, has_vertex, nv, vertices, mv_vertices, inneighbors, mv_inneighbors, outneighbors, mv_outneighbors, neighbors, mv_neighbors, get_v, edgetype, has_edge, ne, edges, add_edge!, rem_edge!, get_metadata, get_weight, is_directed, adjacency_matrix, weights, name, graph, # layer.jl AbstractLayer, Layer, layer_simplegraph, layer_simpledigraph, layer_simpleweightedgraph, layer_simpleweighteddigraph, layer_metadigraph, layer_valgraph, layer_valoutdigraph, layer_valdigraph, layer_metagraph, has_node, add_vertex!, rem_vertex!, # interlayer.jl AbstractInterlayer, Interlayer, interlayer_simplegraph, interlayer_simpleweightedgraph, interlayer_metagraph, interlayer_valgraph, interlayer_simpledigraph, interlayer_simpleweighteddigraph, interlayer_metadigraph, interlayer_valoutdigraph, interlayer_valdigraph, multiplex_interlayer, empty_interlayer, is_multiplex_interlayer, get_symmetric_interlayer, # abstracttensorrepresentation.jl AbstractTensorRepresentation, getindex, array, # abstractmatrixrrepresentation.jl AbstractMatrixRepresentation, # weighttensor.jl WeightTensor, # metadatatensor.jl MetadataTensor, # supraweightmatrix.jl SupraWeightMatrix, # traits.jl IsWeighted, is_weighted, IsMeta, is_meta, IsMultiplex, # abstractmultilayergraph.jl AbstractMultilayerGraph, nn, add_node!, rem_node!, set_metadata!, nl, nIn, has_layer, rem_layer!, get_interlayer, indegree, outdegree, degree, weighttype, weight_tensor, supra_weight_matrix, metadata_tensor, mean_degree, degree_second_moment, degree_variance, multilayer_global_clustering_coefficient, multilayer_weighted_global_clustering_coefficient, overlay_clustering_coefficient, eigenvector_centrality, modularity, # undirected.jl set_weight!, add_layer!, specify_interlayer!, von_neumann_entropy, # directed.jl # multilayergraph.jl MultilayerGraph, # multilayerdigraph.jl MultilayerDiGraph, # abstract_synchronized_edge_colored_graph.jl AbstractNodeAlignedEdgeColoredGraph, # synchronized_edge_colored_graph.jl NodeAlignedEdgeColoredGraph, # synchronized_edge_colored_di_graph.jl NodeAlignedEdgeColoredDiGraph, # utilities multilayer_kronecker_delta, δk, size, δ_1, δ_2, δ_3, δ_Ω, havel_hakimi_graph_generator, kleitman_wang_graph_generator # tensorfacoriazations.jl using Base, InteractiveUtils, IterTools, SimpleTraits, Bijections, PrettyTables using Distributions: Uniform using LinearAlgebra, Statistics, OMEinsum, TensorOperations, Distributions using DataStructures, SparseArrays # import Graphs: AbstractGraph, AbstractEdge, has_vertex, nv, vertices, add_vertex!, rem_vertex!, edgetype, has_edge , ne, edges, inneighbors, outneighbors,neighbors, add_edge!, rem_edge!, src, dst, weights, degree, indegree, outdegree, is_directed, inneighbors, eigenvector_centrality, modularity, SimpleGraphs, SimpleGraph, SimpleDiGraph, IsDirected,isgraphical, isdigraphical, adjacency_matrix using Graphs, SimpleWeightedGraphs, MetaGraphs, SimpleValueGraphs # Graphs, include("traits.jl") include("utilities.jl") include("node.jl") include("vertices/abstractvertex.jl") include("vertices/multilayervertex.jl") include("vertices/missingvertex.jl") include("multilayeredge.jl") include("halfedge.jl") include("subgraphs/abstractdescriptor.jl") include("subgraphs/layerdescriptor.jl") include("subgraphs/interlayerdescriptor.jl") include("subgraphs/abstractsubgraph.jl") include("subgraphs/layer.jl") include("subgraphs/interlayer.jl") include("graphs_extensions/graphs_extensions.jl") include("representations/abstracttensorrepresentation.jl") include("representations/abstractmatrixrepresentation.jl") include("representations/weighttensor.jl") include("representations/metadatatensor.jl") include("representations/supraweightmatrix.jl") include("abstractmultilayergraph.jl") include("undirected.jl") include("directed.jl") include("multilayergraph.jl") include("multilayerdigraph.jl") include( "special_multilayergraphs/node_aligned_edge_colored/abstract_node_aligned_edge_colored_graph.jl", ) include( "special_multilayergraphs/node_aligned_edge_colored/node_aligned_edge_colored_graph.jl" ) include( "special_multilayergraphs/node_aligned_edge_colored/node_aligned_edge_colored_di_graph.jl", ) include("tensorsfactorizations.jl") end
MultilayerGraphs
https://github.com/JuliaGraphs/MultilayerGraphs.jl.git
[ "MIT" ]
1.1.4
bc4b247db8e78a9c9f223e7c4870fd2a43b68fe3
code
44261
# == # nl # nIn # has_layer # _add_layer! # rem_layer! # _specify_interlayer! # get_interlayer # get_layer_idx # Base.eltype # weighttype # edgetype # has_vertex # multilayer_vertices # mv_inneighbors # inneighbors # mv_outneighbors # outneighbors # nv # nv_withmissing # vertices # nodes """ AbstractMultilayerGraph{T <: Integer, U <: Real} <: AbstractGraph{T} An abstract type for multilayer graphs. It is a subtype of AbstractGraph and its concrete subtypes may extend Graphs.jl. Its concrete subtypes must have the following fields: - `idx_N_associations::Bijection{Int64,Node}`:; - `v_V_associations::Bijection{T,<:MultilayerVertex}`:; - `v_metadata_dict::Dict{T,<:Union{<:Tuple,<:NamedTuple}}`:; - `layers`: an indexable collection of `Layer`s. - `interlayers`:a collection of `Interlayer`s; - `layers_names`: a collection of the names of the layers. - `subgraphs_names`: a collection of the names of all the subgraphs. - `fadjlist::Vector{Vector{HalfEdge{<:MultilayerVertex,<:Union{Nothing,U}}}}`: the forward adjacency list. """ abstract type AbstractMultilayerGraph{T<:Integer,U<:Real} <: AbstractGraph{T} end # General MultilayerGraph Utilities fadjlist(mg::AbstractMultilayerGraph) = mg.fadjlist # Nodes """ nodes(mg::AbstractMultilayerGraph Return the nodes of the AbstractMultilayerGraph `mg`, in order of addition. """ function nodes(mg::AbstractMultilayerGraph) return [couple[2] for couple in sort(collect(mg.idx_N_associations); by=first)] end """ nn(mg::M) where {M <: AbstractMultilayerGraph } Return the number of nodes in `mg`. """ nn(mg::AbstractMultilayerGraph) = length(nodes(mg)) """ has_node(mg::AbstractMultilayerGraph, n::Node) Return true if `n` is a node of `mg`. """ has_node(mg::AbstractMultilayerGraph, n::Node) = n in image(mg.idx_N_associations) """ _add_node!(mg::AbstractMultilayerGraph, n::Node; add_vertex_to_layers::Union{Vector{Symbol}, Symbol} = Symbol[]) Add node `n` to `mg`. Return true if succeeds. Additionally, add a corresponding vertex to all layers whose name is listed in `add_vertex_to_layers`. If `add_vertex_to_layers == :all`, then a corresponding vertex is added to all layers. """ function _add_node!( mg::AbstractMultilayerGraph, n::Node; add_vertex_to_layers::Union{Vector{Symbol},Symbol}=Symbol[], ) !has_node(mg, n) || return false maximum_idx = isempty(domain(mg.idx_N_associations)) ? 0 : maximum(domain(mg.idx_N_associations)) mg.idx_N_associations[maximum_idx + 1] = n if add_vertex_to_layers == :all for layer_name in mg.layers_names _add_vertex!(mg, MV(n, layer_name)) end elseif add_vertex_to_layers isa Vector{Symbol} for layer_name in add_vertex_to_layers _add_vertex!(mg, MV(n, layer_name)) end end return true end """ _rem_node!(mg::AbstractMultilayerGraph, n::Node) Remove node `n` to `mg`. Return true if succeeds. """ function _rem_node!(mg::AbstractMultilayerGraph, n::Node) has_node(mg, n) || return false Vs_tbr = MultilayerVertex[] for V in image(mg.v_V_associations) if V.node == n push!(Vs_tbr, V) end end for mv in Vs_tbr _rem_vertex!(mg, mv) end idx_tbr = mg.idx_N_associations(n) delete!(mg.idx_N_associations, idx_tbr) return true end # Vertices """ eltype(::M) where {T,M<:AbstractMultilayerGraph{T}} Return the vertex type of `mg`. """ Base.eltype(::M) where {T,M<:AbstractMultilayerGraph{T}} = T """ has_vertex(mg::M, v::T) where {T,M <: AbstractMultilayerGraph{T}} Return true if `v` is in mg, else false. """ function Graphs.has_vertex(mg::M, v::T) where {T,M<:AbstractMultilayerGraph{T}} return v in domain(mg.v_V_associations) end """ has_vertex(mg::AbstractMultilayerGraph, mv::MultilayerVertex) Return true if `mv` is in `mg`, else false. """ function Graphs.has_vertex(mg::AbstractMultilayerGraph, mv::MultilayerVertex) return get_bare_mv(mv) in image(mg.v_V_associations) end """ mv_vertices(mg::AbstractMultilayerGraph) Return a list of the `MultilayerVertex`s contained in `mg`. """ mv_vertices(mg::AbstractMultilayerGraph) = [get_rich_mv(mg, v) for v in vertices(mg)] """ nv(mg::M) where {M <: AbstractMultilayerGraph } Return the number of vertices in `mg`, excluding the missing vertices. """ Graphs.nv(mg::AbstractMultilayerGraph) = length(mg.v_V_associations) """ vertices(mg::M) where {M<:AbstractMultilayerGraph} Return the collection of the vertices of `mg`. """ function Graphs.vertices(mg::M) where {M<:AbstractMultilayerGraph} return sort(collect(domain(mg.v_V_associations))) end """ get_metadata(mg::AbstractMultilayerGraph, bare_mv::MultilayerVertex) Return the metadata associated to `MultilayerVertex` mv (regardless of metadata assigned to `bare_mv`). """ function get_metadata(mg::AbstractMultilayerGraph, mv::MultilayerVertex) return mg.v_metadata_dict[get_v(mg, mv)] end """ set_metadata!(mg::AbstractMultilayerGraph, mv::MultilayerVertex, metadata::Union{Tuple, NamedTuple}) Set the metadata of vertex `mv` to `metadata`. Return true if succeeds """ function set_metadata!( mg::AbstractMultilayerGraph, mv::MultilayerVertex, metadata::Union{Tuple,NamedTuple} ) descriptor = mg.layers[get_layer_idx(mg, layer(mv))] is_meta(descriptor.null_graph) || return false has_vertex(mg, mv) || return false mg.v_metadata_dict[get_v(mg, mv)] = metadata return true end # Edges """ edgetype(::M) where {T,U,M<:AbstractMultilayerGraph{T,U}} Return the edge type for `mg`. """ Graphs.edgetype(::M) where {T,U,M<:AbstractMultilayerGraph{T,U}} = MultilayerEdge{U} """ ne(mg::AbstractMultilayerGraph) Return the number of edges in `mg`. """ Graphs.ne(mg::AbstractMultilayerGraph) = length(edges(mg)) """ has_edge(mg::AbstractMultilayerGraph, edge::MultilayerEdge) Return true if `mg` has an edge between the source and the destination of `edge` (does not check edge or vertex metadata). """ function Graphs.has_edge(mg::AbstractMultilayerGraph, edge::MultilayerEdge) return has_edge(mg, get_v(mg, src(edge)), get_v(mg, dst(edge))) end """ has_edge(mg::AbstractMultilayerGraph, src::MultilayerVertex, dst::MultilayerVertex) Return true if `mg` has edge between the `src` and `dst` (does not check edge or vertex metadata). """ function Graphs.has_edge( mg::AbstractMultilayerGraph, src::MultilayerVertex, dst::MultilayerVertex ) return has_edge(mg, get_v(mg, src), get_v(mg, dst)) end """ add_edge!(mg::M, src::T, dst::T; weight::Union{Nothing, U} = one(U), metadata::Union{Tuple,NamedTuple} = NamedTuple() ) where {T,U, M <: AbstractMultilayerGraph{T,U}} Internal method. Add a MultilayerEdge between `src` and `dst` with weight `weight` and metadata `metadata`. Return true if succeeds, false otherwise. """ function Graphs.add_edge!( mg::M, src::T, dst::T; weight::Union{Nothing,U}=one(U), metadata::Union{Tuple,NamedTuple}=NamedTuple(), ) where {T,U,M<:AbstractMultilayerGraph{T,U}} return add_edge!( mg, ME(mg.v_V_associations[src], mg.v_V_associations[dst], weight, metadata) ) end """ add_edge!(mg::M, src::V, dst::V; weight::Union{Nothing, U} = one(U), metadata::Union{Tuple,NamedTuple} = NamedTuple() ) where {T,U, M <: AbstractMultilayerGraph{T,U}, V <: MultilayerVertex} Add a MultilayerEdge between `src` and `dst` with weight `weight` and metadata `metadata`. Return true if succeeds, false otherwise. """ function Graphs.add_edge!( mg::M, src::V, dst::V; weight::Union{Nothing,U}=one(U), metadata::Union{Tuple,NamedTuple}=NamedTuple(), ) where {T,U,M<:AbstractMultilayerGraph{T,U},V<:MultilayerVertex} return add_edge!(mg, ME(src, dst, weight, metadata)) end """ rem_edge!(mg::M, src::T, dst::T) where {T, M <: AbstractMultilayerGraph{T}} Remove edge from `src` to `dst` from `mg`. Return true if succeeds, false otherwise. """ function Graphs.rem_edge!(mg::M, src::T, dst::T) where {T,M<:AbstractMultilayerGraph{T}} return rem_edge!(mg, mg.v_V_associations[src], mg.v_V_associations[dst]) end """ rem_edge!(mg::AbstractMultilayerGraph, me::MultilayerEdge) Remove edge from `src(me)` to `dst(me)` from `mg`. Return true if succeeds, false otherwise. """ function Graphs.rem_edge!(mg::AbstractMultilayerGraph, me::MultilayerEdge) return rem_edge!(mg, src(me), dst(me)) end """ get_halfegde(mg::M, src::MultilayerVertex, dst::MultilayerVertex) where M <: AbstractMultilayerGraph Internal function. Return the `HalfEdge`, if it exists, between `src` and `dst`. Error if there is no `HalfEdge`. """ function get_halfegde( mg::M, src::MultilayerVertex, dst::MultilayerVertex ) where {M<:AbstractMultilayerGraph} has_edge(mg, src, dst) || throw(ErrorException("There is no `HalfEdge` from `src` to `dst`")) halfedges_from_src = fadjlist(mg)[get_v(mg, src)] return halfedges_from_src[findfirst( halfedge -> vertex(halfedge) == dst, halfedges_from_src )] end """ get_metadata(mg::AbstractMultilayerGraph, src::MultilayerVertex, dst::MultilayerVertex) Return the metadata associated to the `MultilayerEdge` from `src` to `dst`. """ function get_metadata( mg::AbstractMultilayerGraph, src::MultilayerVertex, dst::MultilayerVertex ) return get_halfegde(mg, src, dst).metadata end """ get_weight(mg::AbstractMultilayerGraph, src::MultilayerVertex, dst::MultilayerVertex)h Return the weight associated to the `MultilayerEdge` from `src` to `dst`. """ function SimpleWeightedGraphs.get_weight( mg::AbstractMultilayerGraph, src::MultilayerVertex, dst::MultilayerVertex ) return get_halfegde(mg, src, dst).weight end # Layers and Interlayers """ nl(mg::AbstractMultilayerGraph) Return the number of layers in `mg`. """ nl(mg::AbstractMultilayerGraph) = length(mg.layers) """ nIn(mg::AbstractMultilayerGraph) Return the number of interlayers in `mg`. """ nIn(mg::AbstractMultilayerGraph) = length(mg.interlayers) """ has_layer(mg::AbstractMultilayerGraph, layer_name::Symbol) Return true in `layer_name` is a name of a `[Layer](@ref)` of `mg`. """ has_layer(mg::AbstractMultilayerGraph, layer_name::Symbol) = layer_name in mg.layers_names """ _add_layer!(mg::M,new_layer::L; new_default_interlayers_type::H) where { T, U, G <: AbstractGraph{T}, H <: AbstractGraph{T}, M <: AbstractMultilayerGraph{T, U}, L <: Layer{T,U,G} Internal function. It is called by the `add_layer!` API functions, which needs to specify the default interlayer graph type. """ function _add_layer!( mg::M, new_layer::L; default_interlayers_null_graph::H, default_interlayers_structure::String="multiplex", ) where { T, U, M<:AbstractMultilayerGraph{T,U}, G<:AbstractGraph{T}, L<:Layer{T,U,G}, H<:AbstractGraph{T}, } # Check that the new layer has a name different from all the existing ones new_layer.name ∉ mg.subgraphs_names || throw( ErrorException( "The new layer has the same name as an existing layer within the multilayer graph. Layers' names must be unique. Existing layers names are $(mg.layers_names).", ), ) # Check that the default_interlayers_null_graph argument is indeed empty if !(nv(default_interlayers_null_graph) == ne(default_interlayers_null_graph) == 0) throw( ErrorException( "The `default_interlayer_empty_graph` has not been assigned to an empty graph. Expected 0 vertices and 0 edges, found $(nv(default_interlayers_null_graph)) vertices and $(ne(default_interlayers_null_graph)) edges.", ), ) end # Add the new layer push!(mg.layers, new_layer.descriptor) # Add the new nodes that the new layer represents new_nodes = setdiff(nodes(new_layer), nodes(mg)) for new_node in new_nodes add_node!(mg, new_node) end # Add vertices for vertex in mv_vertices(new_layer) _add_vertex!(mg, vertex) end # Add edges for edge in edges(new_layer) add_edge!(mg, edge) end # Add default interlayers if default_interlayers_structure == "multiplex" for layer_descriptor in mg.layers if layer_descriptor.name != new_layer.name _specify_interlayer!( mg, multiplex_interlayer( new_layer, getproperty(mg, layer_descriptor.name), default_interlayers_null_graph, ), ) end end elseif default_interlayers_structure == "empty" for layer_descriptor in mg.layers if layer_descriptor.name != new_layer.name _specify_interlayer!( mg, empty_interlayer( new_layer, getproperty(mg, layer_descriptor.name), default_interlayers_null_graph, ), ) end end else throw( ErrorException( "Default interlayer structured as '$default_interlayers_structure' not yet implemented. Only 'multiplex' and 'null' are available.", ), ) end return true end """ rem_layer!(mg::AbstractMultilayerGraph, layer_name::Symbol; remove_nodes::Bool = false) Remove layer `layer_name` from multilayer graph `mg`. If `remove_nodes` is true, also remove from the multilayer graph all the nodes associated with the layer. Warning: this action has multilayer-wide consequences, amd may inadvertently remove vertices and edges that were meant to be kept. """ function rem_layer!( mg::AbstractMultilayerGraph, layer_name::Symbol; remove_nodes::Bool=false ) layer_idx = get_layer_idx(mg, layer_name) isnothing(layer_idx) && return false layer_tbr = getproperty(mg, layer_name) if remove_nodes for node in nodes(layer_tbr) rem_node!(mg, node) end else for mv in mv_vertices(layer_tbr) rem_vertex!(mg, mv) end end deleteat!(mg.layers, layer_idx) keys_tbr = Set{Symbol}[] for connected_layers_set in keys(mg.interlayers) if layer_name ∈ connected_layers_set push!(keys_tbr, connected_layers_set) end end delete!.(Ref(mg.interlayers), keys_tbr) return true end """ function _specify_interlayer!( mg::M, new_interlayer::In ) where {T,U,G<:AbstractGraph{T},M<:AbstractMultilayerGraph{T,U},In<:Interlayer{T,U,G}} Internal function. It is called by the `specify_interlayer!` API functions. """ function _specify_interlayer!( mg::M, new_interlayer::In ) where {T,U,G<:AbstractGraph{T},M<:AbstractMultilayerGraph{T,U},In<:Interlayer{T,U,G}} all(in.([new_interlayer.layer_1, new_interlayer.layer_2], Ref(mg.layers_names))) || # throw( # ErrorException( throw( ErrorException( "The new interlayer connects two layers that are not (one or both) part of the multilayer graph. Make sure you spelled the `layer_1` and `layer_2` arguments of the `Interlayer` correctly. Available layers are $(mg.layers_names), found $(new_interlayer.layer_1) and $(new_interlayer.layer_2).", ), ) # ), # ) # Check that it has the correct number of nodes on both layers ( isempty( setdiff( Set(new_interlayer.layer_1_nodes), Set(nodes(Base.getproperty(mg, new_interlayer.layer_1))), ), ) && isempty( setdiff( Set(new_interlayer.layer_2_nodes), Set(nodes(Base.getproperty(mg, new_interlayer.layer_2))), ), ) ) || throw( ErrorException( "The nodes in the interlayer $(new_interlayer.name) do not correspond to the nodes in the respective layers $(new_interlayer.layer_1) and $(new_interlayer.layer_2). Found $( setdiff(Set(new_interlayer.layer_1_nodes), Set(nodes(Base.getproperty(mg, new_interlayer.layer_1)))) ) and $(setdiff(Set(new_interlayer.layer_2_nodes), Set(nodes(Base.getproperty(mg, new_interlayer.layer_2)))))", ), ) # A rem_interlayer! function may not exist since there always must be all interlayers. We then proceed to effectively remove the interlayer here key = Set([new_interlayer.layer_1, new_interlayer.layer_2]) if haskey(mg.interlayers, key) existing_interlayer = getproperty(mg, mg.interlayers[key].name) for edge in edges(existing_interlayer) rem_edge!(mg, edge) end end mg.interlayers[Set([new_interlayer.layer_1, new_interlayer.layer_2])] = new_interlayer.descriptor for edge in edges(new_interlayer) @assert add_edge!(mg, edge) # assert success end return true end """ get_interlayer( mg::AbstractMultilayerGraph, layer_1_name::Symbol, layer_2_name::Symbol ) Return the `Interlayer` between `layer_1` and `layer_2`. """ function get_interlayer( mg::AbstractMultilayerGraph, layer_1_name::Symbol, layer_2_name::Symbol ) layer_1_name ∈ mg.layers_names || throw( ErrorException( "$layer_1_name doesn't belong to the multilayer graph. Available layers are $(mg.layers_names).", ), ) layer_2_name ∈ mg.layers_names || throw( ErrorException( "$layer_2_name doesn't belong to the multilayer graph. Available layers are $(mg.layers_names).", ), ) layer_1_name != layer_2_name || throw( ErrorException( "`layer_1` argument is the same as `layer_2`. There is no interlayer between a layer and itself.", ), ) names = [layer_1_name, layer_2_name] for interlayer_descriptor in values(mg.interlayers) if all(interlayer_descriptor.layers_names .== names) #issetequal(interlayer_descriptor.layers_names, names_set) return get_subgraph(mg, interlayer_descriptor) elseif all(interlayer_descriptor.layers_names .== reverse(names)) interlayer = get_subgraph(mg, interlayer_descriptor) return get_symmetric_interlayer( interlayer; symmetric_interlayer_name=String(interlayer.name) * "_rev" ) end end end """ get_layer_idx(mg::M, layer_name::Symbol) where {T, U, M <: AbstractMultilayerGraph{T, U}} Return the index of the `Layer` whose name is `layer_name` within `mg.layers`. """ function get_layer_idx( mg::M, layer_name::Symbol ) where {T,U,M<:AbstractMultilayerGraph{T,U}} idx = findfirst(descriptor -> descriptor.name == layer_name, mg.layers) if !isnothing(idx) return idx else return nothing end end """ get_subgraph_descriptor(mg::M, layer_1_name::Symbol, layer_2_name::Symbol) where {T,U,M<:AbstractMultilayerGraph{T,U}} Return the descriptor associated to the interlayer connecting `layer_1` to `layer_2` (or to the Layer named `layer_1` if `layer_1` == `layer_2`) """ function get_subgraph_descriptor( mg::M, layer_1_name::Symbol, layer_2_name::Symbol ) where {T,U,M<:AbstractMultilayerGraph{T,U}} if layer_1_name == layer_2_name idx = get_layer_idx(mg, layer_1_name) if !isnothing(idx) return mg.layers[idx] else throw( ErrorException( "The multilayer graph does not contain any Layer named $(layer_1_name). Available layers are $(mg.layers_names).", ), ) end else layer_1_name ∈ mg.layers_names || throw( ErrorException( "$layer_1_name does nto belong to the multilayer graph. Available layers are $(mg.layers_names).", ), ) layer_2_name ∈ mg.layers_names || throw( ErrorException( "$layer_2_name does nto belong to the multilayer graph. Available layers are $(mg.layers_names).", ), ) return mg.interlayers[Set([layer_1_name, layer_2_name])] end end # Graphs.jl's internals and ecosystem extra overrides """ indegree( mg::AbstractMultilayerGraph, v::MultilayerVertex) Get the indegree of vertex `v` in `mg`. """ function Graphs.indegree(mg::AbstractMultilayerGraph, mv::V) where {V<:MultilayerVertex} return length(inneighbors(mg, mv)) end """ indegree( mg::M, vs::AbstractVector{V}=vertices(mg)) where {T,M<:AbstractMultilayerGraph{T,<:Real},V<:MultilayerVertex} Get the vector of indegrees of vertices `vs` in `mg`. """ function Graphs.indegree( mg::AbstractMultilayerGraph, vs::AbstractVector{<:MultilayerVertex}=mv_vertices(mg) ) return [indegree(mg, x) for x in vs] end """ outdegree(mg::AbstractMultilayerGraph, mv::MultilayerVertex) Get the outdegree of vertex `v` in `mg`. """ function Graphs.outdegree(mg::AbstractMultilayerGraph, mv::MultilayerVertex) return length(outneighbors(mg, mv)) end """ outdegree(mg::M, vs::AbstractVector{V}=vertices(mg)) where {T,M<:AbstractMultilayerGraph{T,<:Real},V<:MultilayerVertex} Get the vector of outdegrees of vertices `vs` in `mg`. """ function Graphs.outdegree( mg::AbstractMultilayerGraph, vs::AbstractVector{<:MultilayerVertex}=mv_vertices(mg) ) return [outdegree(mg, x) for x in vs] end """ degree(mg::AbstractMultilayerGraph, vs::AbstractVector{<:MultilayerVertex}=vertices(mg)) Get the degree of vertices `vs` in `mg`. """ function Graphs.degree( mg::AbstractMultilayerGraph, vs::AbstractVector{<:MultilayerVertex}=mv_vertices(mg) ) return degree.(Ref(mg), vs) end """ inneighbors( mg::AbstractMultilayerGraph, mv::MultilayerVertex ) Return the list of inneighbors of `mv` within `mg`. """ function Graphs.inneighbors(mg::AbstractMultilayerGraph, mv::MultilayerVertex) return inneighbors(mg, get_v(mg, mv)) end """ outneighbors( mg::AbstractMultilayerGraph, mv::MultilayerVertex) Return the list of outneighbors of `v` within `mg`. """ function Graphs.outneighbors(mg::AbstractMultilayerGraph, mv::MultilayerVertex) return outneighbors(mg, get_v(mg, mv)) end """ outneighbors(mg::M, v::T) where {T, M<:AbstractMultilayerGraph{T}} Return the list of outneighbors of `v` within `mg`. """ function Graphs.outneighbors(mg::M, v::T) where {T,M<:AbstractMultilayerGraph{T}} _outneighbors = T[] for helfedge in mg.fadjlist[v] push!(_outneighbors, get_v(mg, vertex(helfedge))) end return _outneighbors end """ neighbors(mg::AbstractMultilayerGraph, mv::MultilayerVertex) Get the neighbors of vertex `mv` in `mg`. Reduces to `outneighbors` for both directed and undirected multilayer graphs. """ Graphs.neighbors(mg::AbstractMultilayerGraph, mv::MultilayerVertex) = outneighbors(mg, mv) """ weighttype(::M) where {T,U,M<:AbstractMultilayerGraph{T,U}} Return the weight type of `mg` (i.e. the eltype of the weight tensor or the supra-adjacency matrix). """ weighttype(::M) where {T,U,M<:AbstractMultilayerGraph{T,U}} = U # Multilayer-specific methods """ mv_inneighbors(mg::AbstractMultilayerGraph, mv::MultilayerVertex) Return the list of `MultilayerVertex` inneighbors of `mv` within `mg`. """ function mv_inneighbors(mg::AbstractMultilayerGraph, mv::MultilayerVertex) return getindex.(Ref(mg.v_V_associations), inneighbors(mg, mv)) end """ mv_outneighbors(mg::AbstractMultilayerGraph, mv::MultilayerVertex) Return the list of `MultilayerVertex` outneighbors of `mv` within `mg`. """ function mv_outneighbors(mg::AbstractMultilayerGraph, mv::MultilayerVertex) return getindex.(Ref(mg.v_V_associations), outneighbors(mg, mv)) end """ mv_neighbors(mg::AbstractMultilayerGraph, mv::MultilayerVertex) Return the list of `MultilayerVertex` neighbors of `mv` within `mg`. """ function mv_neighbors(mg::AbstractMultilayerGraph, mv::MultilayerVertex) return getindex.(Ref(mg.v_V_associations), neighbors(mg, mv)) end """ get_supra_weight_matrix_from_weight_tensor(weight_tensor::Array{U, 4}) where { U <: Real} Internal method. Convert a weight tensor into the corresponding supra-adjacency matrix. """ function get_supra_weight_matrix_from_weight_tensor( weight_tensor::Array{U,4} ) where {U<:Real} N = size(weight_tensor, 1) L = size(weight_tensor, 3) supra_weight_matrix = Array{U}(undef, N * L, N * L) for i in 1:L for j in 1:L supra_weight_matrix[(N * (i - 1) + 1):(N * i), (N * (j - 1) + 1):(N * j)] .= weight_tensor[ 1:N, 1:N, i, j ] end end return supra_weight_matrix end """ get_weight_tensor_from_supra_weight_matrix(mg::M, supra_weight_matrix::S) where {T, U, S <: Array{U, 2}, M <: AbstractMultilayerGraph{T,U} } Internal method. Convert a supra-adjacency matrix into the corresponding weight tensor. """ function get_weight_tensor_from_supra_weight_matrix( mg::M, supra_weight_matrix::S ) where {T,U,S<:Array{U,2},M<:AbstractMultilayerGraph{T,U}} N = nn(mg) L = nl(mg) weight_tensor = zeros(U, N, N, L, L) if N != 0 for i in 1:L for j in 1:L weight_tensor[1:N, 1:N, i, j] .= supra_weight_matrix[ (N * (i - 1) + 1):(N * i), (N * (j - 1) + 1):(N * j) ] end end return weight_tensor else return weight_tensor end end """ weight_tensor(mg::M) where {T,U, M <: AbstractMultilayerGraph{T,U}} Compute the weight tensor of `mg`. Return an object of type `WeightTensor`. """ function weight_tensor(mg::M) where {T,U,M<:AbstractMultilayerGraph{T,U}} N = nn(mg) L = nl(mg) _size = (N, N, L, L) _weight_tensor = zeros(U, _size...) v_V_associations = Bijection{Int,Union{MissingVertex,MultilayerVertex}}() for (_src_v, halfedges_from_src) in enumerate(mg.fadjlist) if !isempty(halfedges_from_src) src_v = T(_src_v) src_bare_V = mg.v_V_associations[src_v] src_n_idx = mg.idx_N_associations(src_bare_V.node) src_layer_idx = get_layer_idx(mg, src_bare_V.layer) for halfedge in halfedges_from_src dst_bare_V = vertex(halfedge) dst_n_idx = mg.idx_N_associations(dst_bare_V.node) dst_layer_idx = get_layer_idx(mg, dst_bare_V.layer) _weight_tensor[src_n_idx, dst_n_idx, src_layer_idx, dst_layer_idx] = weight( halfedge ) end end end return WeightTensor(_weight_tensor, mg.layers_names, mg.idx_N_associations) end """ get_v_V_associations_withmissings(mg::M) where {T,U, M <: AbstractMultilayerGraph{T,U}} Internal function. Return the `v_V_associations` for `mg` taking into account missing vertices (the order of the vertices of each layer is induced by the order of the nodes in `mg.idx_N_associations`). """ function get_v_V_associations_withmissings( mg::M ) where {T,U,M<:AbstractMultilayerGraph{T,U}} v_V_associations = Bijection{T,Union{MissingVertex,MultilayerVertex}}() n_nodes = nn(mg) n_layers = nl(mg) for i in 1:(n_nodes * n_layers) v_V_associations[i] = MissingVertex() end for V in mv_vertices(mg) if !(V isa MissingVertex) layer_idxs = get_layer_idx(mg, V.layer) v = T(mg.idx_N_associations(V.node) + (layer_idxs[1] - 1) * n_nodes) delete!(v_V_associations, v) v_V_associations[v] = get_bare_mv(V) end end return v_V_associations end """ supra_weight_matrix(mg::M) where {T,U, M <: AbstractMultilayerGraph{T,U}} Compute the supra weight matrix of `mg`. Return an object of type `SupraWeightMatrix` """ function supra_weight_matrix(mg::M) where {T,U,M<:AbstractMultilayerGraph{T,U}} n_nodes = nn(mg) n_layers = nl(mg) v_V_associations = get_v_V_associations_withmissings(mg) _supra_weight_matrix = zeros(U, n_nodes * n_layers, n_nodes * n_layers) for (_src_v, halfedges) in enumerate(mg.fadjlist) src_v = v_V_associations(mg.v_V_associations[_src_v]) for halfedge in halfedges _weight = isnothing(weight(halfedge)) ? one(U) : weight(halfedge) dst_v = v_V_associations(vertex(halfedge)) # The loop goes through the entire fadjlist, so [dst_v, src_v] will be obtained at some point _supra_weight_matrix[src_v, dst_v] = _weight end end return SupraWeightMatrix(_supra_weight_matrix, v_V_associations) end """ metadata_tensor(mg::M) where {T,U, M <: AbstractMultilayerGraph{T,U}} Compute the weight tensor of `mg`. Return an object of type `WeightTensor`. """ function metadata_tensor(mg::M) where {T,U,M<:AbstractMultilayerGraph{T,U}} N = nn(mg) L = nl(mg) _metadata_tensor = Array{Union{Nothing,Tuple,NamedTuple}}(nothing, N, N, L, L) for (_src_v, halfedges_from_src) in enumerate(mg.fadjlist) if !isempty(halfedges_from_src) src_v = T(_src_v) src_bare_V = mg.v_V_associations[src_v] src_n_idx = mg.idx_N_associations(src_bare_V.node) src_layer_idx = get_layer_idx(mg, src_bare_V.layer) for halfedge in halfedges_from_src dst_bare_V = vertex(halfedge) dst_n_idx = mg.idx_N_associations(dst_bare_V.node) dst_layer_idx = get_layer_idx(mg, dst_bare_V.layer) _metadata_tensor[src_n_idx, dst_n_idx, src_layer_idx, dst_layer_idx] = metadata( halfedge ) end end end return MetadataTensor(_metadata_tensor, mg.layers_names, mg.idx_N_associations) end """ mean_degree(mg::AbstractMultilayerGraph) Return the mean of the degree sequence of `mg`. """ mean_degree(mg::AbstractMultilayerGraph) = mean(degree(mg)) """ degree_second_moment(mg::AbstractMultilayerGraph) Calculate the second moment of the degree sequence of `mg`. """ degree_second_moment(mg::AbstractMultilayerGraph) = mean(degree(mg) .^ 2) """ degree_variance(mg::AbstractMultilayerGraph) Return the variance of the degree sequence of `mg`. """ degree_variance(mg::AbstractMultilayerGraph) = var(degree(mg)) """ multilayer_global_clustering_coefficient( mg::AbstractMultilayerGraph, norm_factor::Union{Float64,Symbol}=:max ) Return the complete multilayer global clustering coefficient, equal to the ratio of realized triplets over all possible triplets, including those whose every or some edges belong to interlayers, normalized by `norm_factor`. If `norm_factor == :max`, then the ratio is normalized by `maximum(array(weight_tensor(mg)))`, else it is not normalized. This function does not override Graphs.jl's `global_clustering_coefficient`, since the latter does not consider cliques where two nodes are the same node but in different layers/interlayers. See [De Domenico et al. (2013)](https://doi.org/10.1103/PhysRevX.3.041022). """ function multilayer_global_clustering_coefficient( mg::AbstractMultilayerGraph, norm_factor::Union{Float64,Symbol}=:max ) wgt = weight_tensor(mg).array _normalization_inverse = 1.0 if norm_factor == :max _normalization_inverse = 1.0 / maximum(wgt) end A_right = wgt .- get_diagonal_elements(wgt) # DeDomenico2013 numerator implementation. Inconsistent with both Wikipedia and Graphs.jl's implementation num = ein"ijkm,jnmo,niok ->"(A_right, A_right, A_right)[] # Wikipedia-informed denominator implementation (consistent with Graphs.jl's global_clustering_coefficient) # ntriangles = 0 # for vertex in vertices(mg) # k = degree(mg, vertex) # ntriangles += k * (k - 1) # end # DeDomenico2013 denominator implementation F = ones(size(wgt)...) .- multilayer_kronecker_delta(size(wgt)) den = ein"ijkm,jnmo,niok ->"(A_right, F, A_right)[] return _normalization_inverse * (num / den) end """ multilayer_weighted_global_clustering_coefficient(mg::M, norm_factor::Union{Float64, Symbol} = :max) where {M <: AbstractMultilayerGraph} Return the complete multilayer global clustering coefficient, equal to the ratio of realized triplets over all possible triplets, including those whose every or some edges belong to interlayers, normalized by `norm_factor`. Each triplets contributes for `w[1]` if all of its vertices are in one layer, `w[2]` if its vertices span two layers, and `w[3]` if they span 3 layers. If `norm_factor == :max`, then the ratio is normalized by `maximum(array(weight_tensor(mg)))`, else it is not normalized. This function does not override Graphs.jl's `global_clustering_coefficient`, since the latter does not consider cliques where two nodes are the same node but in different layers/interlayers. See [De Domenico et al. (2013)](https://doi.org/10.1103/PhysRevX.3.041022). """ function multilayer_weighted_global_clustering_coefficient( mg::M, w::Vector{Float64}, norm_factor::Union{Float64,Symbol}=:max ) where {M<:AbstractMultilayerGraph} #This is well defined for both weighted and unweighted multilayer graphs wgt = weight_tensor(mg).array sum(w) == 1 || throw(ErrorException("Weight vector `w` does not sum to 1. Found $(sum(w)).")) _normalization_inverse = 1.0 if norm_factor == :max _normalization_inverse = 1.0 / maximum(wgt) end A_right = wgt .- get_diagonal_elements(wgt) num_layers = size(wgt, 3) num = ein"ijkm,jnmo,niok,skmo,s ->"(A_right, A_right, A_right, δ_Ω(num_layers), w)[] F = ones(size(wgt)...) .- multilayer_kronecker_delta(size(wgt)) den = ein"ijkm,jnmo,niok,skmo,s ->"(A_right, F, A_right, δ_Ω(num_layers), w)[] return _normalization_inverse * (num / den) end """ overlay_clustering_coefficient( mg::AbstractMultilayerGraph, norm_factor::Union{Float64,Symbol}=:max ) Return the overlay clustering coefficient as calculated in [De Domenico et al. (2013)](https://doi.org/10.1103/PhysRevX.3.041022). If `norm_factor == :max`, then the ratio is normalized by `maximum(array(weight_tensor(mg)))`, else it is not normalized. """ function overlay_clustering_coefficient( mg::AbstractMultilayerGraph, norm_factor::Union{Float64,Symbol}=:max ) wgt = weight_tensor(mg).array _normalization_inverse = 1.0 if norm_factor == :max _normalization_inverse = 1.0 / (maximum(ein"ijkl->ij"(wgt)) / length(mg.layers)) # Check that we are using OMEinsum correctly. # @assert all(ein"ijkl->ij"(mg.array) .== dropdims(sum(mg.array, dims = (3,4)), dims = (3,4))) end num = ein"ij,jm,mi ->"(ein"ijkm->ij"(wgt), ein"ijkm->ij"(wgt), ein"ijkm->ij"(wgt))[] F = ones(size(wgt)...) - multilayer_kronecker_delta(size(wgt)) den = ein"ij,jm,mi ->"(ein"ijkm->ij"(wgt), ein"ijkm->ij"(F), ein"ijkm->ij"(wgt))[] return _normalization_inverse * (num / den) end """ eigenvector_centrality( mg::M; norm::String = "1", tol::Float64 = 1e-6, maxiter::Int64 = 2000 ) where {T, U, M <: AbstractMultilayerGraph{T, U}} Calculate the eigenvector centrality of `mg` via an iterative algorithm. The `norm` parameter may be `"1"` or `"n"`, and respectively the eigenvector centrality will be normalized to 1 or further divided by the number of nodes of `mg`. The `tol` parameter terminates the approximation when two consecutive iteration differ by no more than `tol`. The `maxiters` parameter terminates the algorithm when it goes beyond `maxiters` iterations. The returned values are: the eigenvector centrality and the relative error at each algorithm iteration, that is, the summed absolute values of the componentwise differences between the centrality computed at the current iteration minus the centrality computed at the previous iteration. Note: in the limit case of a monoplex graph, this function outputs a eigenvector centrality vector that coincides the one outputted by Graphs.jl's `eigenvector_centrality`. """ function Graphs.eigenvector_centrality( mg::M; weighted::Bool=true, norm::String="1", tol::Float64=1e-6, maxiter::Int64=2000 ) where {T,U,M<:AbstractMultilayerGraph{T,U}} swm_m = nothing v_V_associations_withmissings = nothing if weighted swm = supra_weight_matrix(mg) swm_m = swm.array v_V_associations_withmissings = swm.v_V_associations else swm = supra_weight_matrix(mg) swm_m = swm.array .!= zero(U) v_V_associations_withmissings = swm.v_V_associations end num_nodes = length(nodes(mg)) X = ones(Float64, num_nodes * length(mg.layers)) err = 1.0 errs = Float64[] iter = 0 while err > tol && iter < maxiter new_X = ein"ij,i -> j"(swm_m, X) new_X = new_X ./ sqrt(sum(abs2, new_X)) err = sum(abs.(X .- new_X)) push!(errs, err) X .= new_X iter += 1 end if norm == "1" X = X ./ sum(X) elseif norm == "n" X = X ./ (sum(X) / num_nodes) end # Reorder centrality values ot march the order multilayer vertices are given in mv_vertices(mg) layers_mvs_ordered = [ couple[2] for couple in sort(collect(v_V_associations_withmissings); by=first) if !(couple[2] isa MissingVertex) ] _sortperm = sortperm(mg.v_V_associations.(layers_mvs_ordered)) X = vec(X)[[ couple[1] for couple in sort(collect(v_V_associations_withmissings); by=first) if !(couple[2] isa MissingVertex) ]] X = X[_sortperm] return X, errs end """ modularity( mg::M, c::Matrix{Int64}; null_model::Union{String,Array{U,4}} = "degree" ) where {T, U, M <: AbstractMultilayerGraph{T,U}} Calculate the modularity of `mg`, as shown in [De Domenico et al. (2013)](https://doi.org/10.1103/PhysRevX.3.041022). """ function Graphs.modularity( mg::M, c::Matrix{Int64}; null_model::Union{String,Array{U,4}}="degree" ) where {T,U,M<:AbstractMultilayerGraph{T,U}} wgt = weight_tensor(mg).array # Check that c has the correct size n_nodes = length(nodes(mg)) n_layers = length(mg.layers) size(c) == (n_nodes, n_layers) || throw( ErrorException( "The size of the community matrix does not match (nn(mg),length(mg.layers)), found $(size(c)) and $((nn(mg),length(mg.layers))).", ), ) # Build S n_communities = length(unique(c)) S = Array{Bool}(undef, n_nodes, n_layers, n_communities) for (i, community) in enumerate(unique(c)) S[:, :, i] .= (c .== community) end # Build P P = Array{Float64}(undef, size(wgt)) tot_links = length(edges(mg)) if typeof(null_model) != String && size(null_model) == size(P) P .= null_model elseif typeof(null_model) != String && size(null_model) != size(P) throw( ErrorException( "size of `null_model` does not match the size of the adjacency tensor. Got $(size(null_model)) and $(size(P)) respectively.", ), ) elseif null_model == "degree" for cart_idx in CartesianIndices(P) layer_1_idx = cart_idx[3] layer_2_idx = cart_idx[4] mv1 = MultilayerVertex( mg.idx_N_associations[cart_idx[1]], mg.layers[layer_1_idx].name ) mv2 = MultilayerVertex( mg.idx_N_associations[cart_idx[2]], mg.layers[layer_2_idx].name ) if has_vertex(mg, mv1) && has_vertex(mg, mv2) # haskey(mg.v_V_associations.finv, mv1 ) && haskey(mg.v_V_associations.finv, mv2 ) P[cart_idx] = (degree(mg, mv1) * degree(mg, mv2)) / (2 * tot_links - 1) else P[cart_idx] = 0.0 end end else throw(ErrorException("Null model '$null_model' not implemented.")) end # Build B B = wgt .- P # Build K K = ein"ijkm,jimk -> "(wgt, ones(T, size(wgt)...))[] return (1 / K) * ein"ija,ikjm,kma->"(S, B, S)[] end # Base overloads """ Base.(==)(x::AbstractMultilayerGraph, y::AbstractMultilayerGraph) Overload equality for `AbstractMultilayerGraph`s. """ function Base.:(==)(x::AbstractMultilayerGraph, y::AbstractMultilayerGraph) typeof(x) == typeof(y) || false for field in fieldnames(typeof(x)) if @eval $x.$field != $y.$field return false end end return true end # Utilities """ get_v(mg::AbstractMultilayerGraph, V::MultilayerVertex) Internal method. Get the Integer label associated to `mv` within `mg.v_V_associations`. """ function get_v(mg::AbstractMultilayerGraph, mv::MultilayerVertex) return mg.v_V_associations(get_bare_mv(mv)) end """ get_rich_mv(mg::M, i::T) where {T,U, M <: AbstractMultilayerGraph{T,U}} Return `V` together with its metadata. """ function get_rich_mv( mg::M, i::T; perform_checks::Bool=false ) where {T,U,M<:AbstractMultilayerGraph{T,U}} if perform_checks haskey(mg.v_V_associations, i) || throw(ErrorException("$i is not a vertex of the multilayer graph.")) end bare_V = mg.v_V_associations[i] return MV(bare_V.node, bare_V.layer, mg.v_metadata_dict[i]) end # Console print utilities function to_string(x::AbstractMultilayerGraph) unionall_type = typeof(x).name.wrapper parameters = typeof(x).parameters layers_names = name.(x.layers) layers_underlying_graphs = typeof.(graph.(x.layers)) layers_table = pretty_table( String, hcat(layers_names, layers_underlying_graphs); title="### LAYERS", header=(["NAME", "UNDERLYING GRAPH"]), alignment=:c, header_alignment=:c, header_crayon=crayon"yellow bold", hlines=:all, ) interlayers_names = name.(values(x.interlayers)) interlayers_underlying_graphs = typeof.(graph.(values(x.interlayers))) interlayer_layer_1s = getproperty.(values(x.interlayers), Ref(:layer_1)) interlayer_layer_2s = getproperty.(values(x.interlayers), Ref(:layer_2)) interlayer_tranfers = getproperty.(values(x.interlayers), Ref(:transfer_vertex_metadata)) interlayers_table = pretty_table( String, hcat( interlayers_names, interlayer_layer_1s, interlayer_layer_2s, interlayers_underlying_graphs, interlayer_tranfers, ); title="### INTERLAYERS", header=([ "NAME", "LAYER 1", "LAYER 2", "UNDERLYING GRAPH", "TRANSFER VERTEX METADATA" ]), alignment=:c, header_alignment=:c, header_crayon=crayon"yellow bold", hlines=:all, ) return """ `$unionall_type` with vertex type `$(parameters[1])` and weight type `$(parameters[2])`. $layers_table $interlayers_table """ end Base.show(io::IO, x::AbstractMultilayerGraph) = print(io, to_string(x)) """ getproperty(mg::AbstractMultilayerGraph, f::Symbol) """ function Base.getproperty(mg::AbstractMultilayerGraph, f::Symbol) if f in ( :v_V_associations, :fadjlist, :idx_N_associations, :layers, :interlayers, :v_metadata_dict, ) # :weight_tensor, :supra_weight_matrix, Base.getfield(mg, f) elseif f == :badjlist && is_directed(mg) Base.getfield(mg, f) elseif f == :edge_list return edges(mg) elseif f == :subgraphs return merge(mg.layers, mg.interlayers) elseif f == :layers_names return [layer.name for layer in mg.layers] elseif f == :interlayers_names return [interlayer.name for interlayer in values(mg.interlayers)] elseif f == :subgraphs_names return vcat(mg.layers_names, mg.interlayers_names) else for descriptor in mg.layers if descriptor.name == f return get_subgraph(mg, descriptor) end end for descriptor in values(mg.interlayers) if descriptor.name == f return get_subgraph(mg, descriptor) end end end end
MultilayerGraphs
https://github.com/JuliaGraphs/MultilayerGraphs.jl.git
[ "MIT" ]
1.1.4
bc4b247db8e78a9c9f223e7c4870fd2a43b68fe3
code
18547
# General MultilayerDiGraph Utilities @traitfn badjlist(mg::M) where {M <: AbstractMultilayerGraph; IsDirected{M}} = mg.badjlist # Nodes # Vertices """ _add_vertex!(mg::M, V::MultilayerVertex) where {T, U, M <: AbstractMultilayerDiGraph{T,U}} Add MultilayerVertex `V` to multilayer graph `mg`. If `add_node` is true and `node(mv)` is not already part of `mg`, then add `node(mv)` to `mg` before adding `mv` to `mg` instead of throwing an error. Return true if succeeds. """ @traitfn function _add_vertex!( mg::M, V::MultilayerVertex; add_node::Bool=true ) where {T,U,M<:AbstractMultilayerGraph{T,U};IsDirected{M}} has_vertex(mg, V) && return false if add_node _node = node(V) if add_node && !has_node(mg, _node) add_node!(mg, _node) end else !has_node(mg, node(V)) && return false end n_nodes = nn(mg) # Re-insert the associations with the proper vertex v = if isempty(domain(mg.v_V_associations)) one(T) else maximum(domain(mg.v_V_associations)) + one(T) end mg.v_V_associations[v] = get_bare_mv(V) mg.v_metadata_dict[v] = V.metadata push!(mg.fadjlist, HalfEdge{MultilayerVertex,U}[]) push!(mg.badjlist, HalfEdge{MultilayerVertex,U}[]) return true end """ _rem_vertex!(mg::AbstractMultilayerDiGraph, V::MultilayerVertex) Remove [MultilayerVertex](@ref) `mv` from `mg`. Return true if succeeds, false otherwise. """ @traitfn function _rem_vertex!( mg::M, V::MultilayerVertex ) where {M <: AbstractMultilayerGraph; IsDirected{M}} # Check that the node exists and then that the vertex exists has_node(mg, V.node) || return false has_vertex(mg, V) || return false # Get the v corresponding to V, delete the association and replace it with a MissingVertex. Also substitute the metadata with an empty NamedTuple v = get_v(mg, V) forward_halfedges_to_be_deleted = mg.fadjlist[v] # Loop over the halfedges to be removed in `forward_halfedges_to_be_deleted`, get their v and remove halfedges to `V` in their corresponding arrays for halfedge_to_be_deleted in forward_halfedges_to_be_deleted dst_v = get_v(mg, vertex(halfedge_to_be_deleted)) idx_tbr = nothing # Don't attempt to remove twice a self loop if dst_v != v idx_tbr = findfirst( halfedge -> compare_multilayervertices(vertex(halfedge), V), mg.badjlist[dst_v], ) deleteat!(mg.badjlist[dst_v], idx_tbr) end end backward_halfedges_to_be_deleted = mg.badjlist[v] # Loop over the halfedges to be removed in `backward_halfedges_to_be_deleted`, get their v and remove halfedges to `V` in their corresponding arrays for halfedge_to_be_deleted in backward_halfedges_to_be_deleted src_v = get_v(mg, vertex(halfedge_to_be_deleted)) idx_tbr = nothing # Don't attempt to remove twice a self loop if src_v != v idx_tbr = findfirst( halfedge -> compare_multilayervertices(vertex(halfedge), V), mg.fadjlist[src_v], ) deleteat!(mg.fadjlist[src_v], idx_tbr) end end maximum_v = maximum(domain(mg.v_V_associations)) if v != maximum_v mg.fadjlist[v] = mg.fadjlist[end] pop!(mg.fadjlist) mg.badjlist[v] = mg.badjlist[end] pop!(mg.badjlist) last_V = mg.v_V_associations[maximum_v] delete!(mg.v_V_associations, v) delete!(mg.v_V_associations, maximum_v) mg.v_V_associations[v] = last_V mg.v_metadata_dict[v] = mg.v_metadata_dict[maximum_v] delete!(mg.v_metadata_dict, maximum_v) else pop!(mg.fadjlist) pop!(mg.badjlist) delete!(mg.v_V_associations, v) delete!(mg.v_metadata_dict, v) end return true end # Edges """ has_edge(mg::M, src::T, dst::T) where {T,M<:AbstractMultilayerGraph{T}; IsDirected{M}} Return true if `mg` has edge between the `src` and `dst` (does not check edge or vertex metadata). """ @traitfn function Graphs.has_edge( mg::M, src::T, dst::T ) where {T,M<:AbstractMultilayerGraph{T};IsDirected{M}} # Returns true if src is a vertex of mg has_vertex(mg, src) || return false # Returns true if dst is a vertex of mg has_vertex(mg, dst) || return false halfedges_from_src = mg.fadjlist[src] halfedges_to_dst = mg.badjlist[dst] if length(halfedges_from_src) >= length(halfedges_to_dst) dsts_v = get_v.(Ref(mg), vertex.(halfedges_from_src)) return dst in dsts_v else srcs_v = get_v.(Ref(mg), vertex.(halfedges_to_dst)) return src in srcs_v end end # Overloads that make AbstractMultilayerDiGraph an extension of Graphs.jl. These are all well-inferred. """ edges(mg::M) where {T,U,M<:AbstractMultilayerGraph{T,U}; IsDirected{M}} Return an list of all the edges of `mg`. """ @traitfn function Graphs.edges( mg::M ) where {T,U,M<:AbstractMultilayerGraph{T,U}; IsDirected{M}} edge_list = MultilayerEdge{U}[] for (_src_v, halfedges) in enumerate(mg.fadjlist) src_v = T(_src_v) src_V = get_rich_mv(mg, src_v) for halfedge in halfedges dst_v = get_v(mg, vertex(halfedge)) dst_V = get_rich_mv(mg, dst_v) push!(edge_list, ME(src_V, dst_V, weight(halfedge), metadata(halfedge))) end end # Remove duplicate self loops and return return edge_list end """ _add_edge!(mg::M, me::E) where {T,U,E<:MultilayerEdge{<:Union{U,Nothing}},M<:AbstractMultilayerGraph{T,U}; IsDirected{M}} Add MultilayerEdge `me` to the AbstractMultilayerDiGraph `mg`. Return true if succeeds, false otherwise. """ @traitfn function _add_edge!( mg::M, me::E ) where { T,U,E<:MultilayerEdge{<:Union{U,Nothing}},M<:AbstractMultilayerGraph{T,U};IsDirected{M} } _src = get_bare_mv(src(me)) _dst = get_bare_mv(dst(me)) has_vertex(mg, _src) || throw(ErrorException("Vertex $_src does not belong to the multilayer graph.")) has_vertex(mg, _dst) || throw(ErrorException("Vertex $_dst does not belong to the multilayer graph.")) # Add edge to `edge_dict` src_V_idx = get_v(mg, _src) dst_V_idx = get_v(mg, _dst) _weight = isnothing(weight(me)) ? one(U) : weight(me) _metadata = metadata(me) if !has_edge(mg, _src, _dst) push!(mg.fadjlist[src_V_idx], HalfEdge(_dst, _weight, _metadata)) push!(mg.badjlist[dst_V_idx], HalfEdge(_src, _weight, _metadata)) else @debug "An edge between $(src(me)) and $(dst(me)) already exists" return false end return true end """ _rem_edge!( mg::M, src::MultilayerVertex, dst::MultilayerVertex ) where {M<:AbstractMultilayerGraph; IsDirected{M}} Remove edge from `src` to `dst` from `mg`. Return true if succeeds, false otherwise. """ @traitfn function _rem_edge!( mg::M, src::MultilayerVertex, dst::MultilayerVertex ) where {M <: AbstractMultilayerGraph; IsDirected{M}} # Perform routine checks has_vertex(mg, src) || throw(ErrorException("Vertex $_src does not belong to the multilayer graph.")) has_vertex(mg, dst) || throw(ErrorException("Vertex $_dst does not belong to the multilayer graph.")) has_edge(mg, src, dst) || return false src_V_idx = get_v(mg, src) dst_V_idx = get_v(mg, dst) _src = get_bare_mv(src) _dst = get_bare_mv(dst) src_idx_tbr = findfirst(halfedge -> vertex(halfedge) == _dst, mg.fadjlist[src_V_idx]) deleteat!(mg.fadjlist[src_V_idx], src_idx_tbr) dst_idx_tbr = findfirst(halfedge -> halfedge.vertex == _src, mg.badjlist[dst_V_idx]) deleteat!(mg.badjlist[dst_V_idx], dst_idx_tbr) return true end """ set_weight!( mg::M, src::MultilayerVertex, dst::MultilayerVertex, weight::U ) where {T,U,M<:AbstractMultilayerGraph{T,U}; IsDirected{M}} Set the weight of the edge between `src` and `dst` to `weight`. Return true if succeeds (i.e. if the edge exists and the underlying graph chosen for the Layer/Interlayer where the edge lies is weighted under the `IsWeighted` trait). """ @traitfn function set_weight!( mg::M, src::MultilayerVertex, dst::MultilayerVertex, weight::U ) where {T,U,M<:AbstractMultilayerGraph{T,U};IsDirected{M}} # Get the subgraph descriptor for the layer containing both src and dst descriptor = get_subgraph_descriptor(mg, layer(src), layer(dst)) # Check if the subgraph is weighted is_weighted(descriptor.null_graph) || return false # Check if an edge exists between src and dst has_edge(mg, src, dst) || return false # Get the halfedge from src to dst halfedges_from_src = mg.fadjlist[get_v(mg, src)] halfedge_from_src = halfedges_from_src[findfirst( he -> vertex(he) == dst, halfedges_from_src )] # Set the weight of the halfedge from src to dst halfedge_from_src.weight = weight # Get the halfedge from dst to src halfedges_to_dst = mg.badjlist[get_v(mg, dst)] halfedge_to_dst = halfedges_to_dst[findfirst(he -> vertex(he) == src, halfedges_to_dst)] # Set the weight of the halfedge from dst to src halfedge_to_dst.weight = weight return true end """ set_metadata!( mg::M, src::MultilayerVertex, dst::MultilayerVertex, metadata::Union{Tuple,NamedTuple}, ) where {M<:AbstractMultilayerGraph; IsDirected{M}} Set the metadata of the edge between `src` and `dst` to `metadata`. Return true if succeeds (i.e. if the edge exists and the underlying graph chosen for the Layer/Interlayer where the edge lies supports metadata at the edge level under the `IsMeta` trait). """ @traitfn function set_metadata!( mg::M, src::MultilayerVertex, dst::MultilayerVertex, metadata::Union{Tuple,NamedTuple} ) where {M <: AbstractMultilayerGraph; IsDirected{M}} # Get the subgraph descriptor that corresponds to the layer of src and dst descriptor = get_subgraph_descriptor(mg, layer(src), layer(dst)) # If the subgraph descriptor's null graph is true, then the edge does not exist is_meta(descriptor.null_graph) || return false # If the edge does not exist, return false has_edge(mg, src, dst) || return false # Set the halfedge from src to dst halfedges_from_src = mg.fadjlist[get_v(mg, src)] halfedge_from_src = halfedges_from_src[findfirst( he -> vertex(he) == dst, halfedges_from_src )] halfedge_from_src.metadata = metadata # Set the halfedge from dst to src halfedges_to_dst = mg.badjlist[get_v(mg, dst)] halfedge_to_dst = halfedges_to_dst[findfirst(he -> vertex(he) == src, halfedges_to_dst)] halfedge_to_dst.metadata = metadata return true end # Layers and Interlayers """ add_layer_directedness!( mg::M, new_layer::L; default_interlayers_null_graph::H=SimpleGraph{T}(), default_interlayers_structure::String="multiplex", ) where { T, U, G<:AbstractGraph{T}, L<:Layer{T,U,G}, H<:AbstractGraph{T}, M<:AbstractMultilayerGraph{T,U}; IsDirected{M} } Add layer `layer` to `mg`. # ARGUMENTS - `mg::M`: the `MultilayerDiGraph` which the new layer will be added to; - `new_layer::L`: the new `Layer` to add to `mg`; - `default_interlayers_null_graph::H`: upon addition of a new `Layer`, all the `Interlayer`s between the new and the existing `Layer`s are immediately created. This keyword argument specifies their `null_graph` See the `Layer` constructor for more information. Defaults to `SimpleGraph{T}()`; - `default_interlayers_structure::String`: The structure of the `Interlayer`s created by default. May either be "multiplex" to have diagonally-coupled only interlayers, or "empty" for empty interlayers. Defaults to "multiplex". """ @traitfn function add_layer_directedness!( mg::M, new_layer::L; default_interlayers_null_graph::H=SimpleGraph{T}(), default_interlayers_structure::String="multiplex", ) where { T, U, G<:AbstractGraph{T}, L<:Layer{T,U,G}, H<:AbstractGraph{T}, M<:AbstractMultilayerGraph{T,U};IsDirected{M}, } # Check that the layer is directed istrait(IsDirected{typeof(new_layer.graph)}) || throw( ErrorException( "The `new_layer`'s underlying graph $(new_layer.graph) is undirected, so it is not compatible with a `AbstractMultilayerDiGraph`.", ), ) return _add_layer!( mg, new_layer; default_interlayers_null_graph=default_interlayers_null_graph, default_interlayers_structure=default_interlayers_structure, ) end """ get_subgraph( mg::M, descriptor::LD ) where {T,U,LD<:LayerDescriptor{T,U}, M<:AbstractMultilayerGraph{T,U}; IsDirected{M}} Internal function. Instantiate the Layer described by `descriptor` whose vertices and edges are contained in `mg`. """ @traitfn function get_subgraph( mg::M, descriptor::LD ) where {T,U,LD<:LayerDescriptor{T,U},M<:AbstractMultilayerGraph{T,U};IsDirected{M}} vs = sort([ v for (v, mv) in collect(mg.v_V_associations) if mv.layer == descriptor.name ]) _vertices = get_rich_mv.(Ref(mg), vs) edge_list = MultilayerEdge{U}[] # We may also loop over the badjlist for (src_v, halfedges_from_src) in zip(vs, getindex.(Ref(mg.fadjlist), vs)) src_bare_V = mg.v_V_associations[src_v] for halfedge in halfedges_from_src dst_bare_V = vertex(halfedge) if dst_bare_V.layer == descriptor.name push!( edge_list, MultilayerEdge( src_bare_V, dst_bare_V, weight(halfedge), metadata(halfedge) ), ) else continue end end end return Layer(descriptor, _vertices, edge_list) end """ get_subgraph( mg::M, descriptor::InD ) where { T, U, # G<:AbstractGraph{T}, InD<:InterlayerDescriptor{T,U},# G}, M<:AbstractMultilayerGraph{T,U}; Is Internal function. Instantiate the Interlayer described by `descriptor` whose vertices and edges are contained in `mg`. """ @traitfn function get_subgraph( mg::M, descriptor::InD ) where { T, U, # G<:AbstractGraph{T}, InD<:InterlayerDescriptor{T,U},# G}, M<:AbstractMultilayerGraph{T,U};IsDirected{M}, } layer_1_vs = T[] layer_2_vs = T[] for (v, mv) in collect(mg.v_V_associations) if mv.layer == descriptor.layer_1 push!(layer_1_vs, v) elseif mv.layer == descriptor.layer_2 push!(layer_2_vs, v) else continue end end sort!(layer_1_vs) sort!(layer_2_vs) layer_1_multilayervertices = get_rich_mv.(Ref(mg), layer_1_vs) layer_2_multilayervertices = get_rich_mv.(Ref(mg), layer_2_vs) layers_vs = vcat(layer_1_vs, layer_2_vs) edge_list = MultilayerEdge{U}[] for (src_v, halfedges_from_src) in zip(layer_1_vs, getindex.(Ref(mg.fadjlist), layer_1_vs)) src_bare_V = mg.v_V_associations[src_v] for halfedge in halfedges_from_src dst_bare_V = vertex(halfedge) # dst_v = get_v(mg, dst_bare_V) # Don't take the same edge twice (except for self-loops: they will be taken twice, but are later removed using `unique`) if dst_bare_V.layer == descriptor.layer_2 push!( edge_list, MultilayerEdge( src_bare_V, dst_bare_V, weight(halfedge), metadata(halfedge) ), ) else continue end end end for (src_v, halfedges_from_src) in zip(layer_1_vs, getindex.(Ref(mg.fadjlist), layer_2_vs)) src_bare_V = mg.v_V_associations[src_v] for halfedge in halfedges_from_src dst_bare_V = vertex(halfedge) # dst_v = get_v(mg, dst_bare_V) # Don't take the same edge twice (except for self-loops: they will be taken twice, but are later removed using `unique`) if dst_bare_V.layer == descriptor.layer_1 push!( edge_list, MultilayerEdge( src_bare_V, dst_bare_V, weight(halfedge), metadata(halfedge) ), ) else continue end end end return _Interlayer( layer_1_multilayervertices, layer_2_multilayervertices, unique(edge_list), descriptor, ) end # Graphs.jl's internals extra overrides """ degree( mg::M, mv::V ) where {M<:AbstractMultilayerGraph, V<:MultilayerVertex; IsDirected{M}} Return the degree of MultilayerVertex `v` within `mg`. """ @traitfn function Graphs.degree( mg::M, mv::V ) where {M<:AbstractMultilayerGraph,V<:MultilayerVertex;IsDirected{M}} return indegree(mg, mv) + outdegree(mg, mv) end """ inneighbors(mg::M, v::T) where {T,M<:AbstractMultilayerGraph; IsDirected{M}} Return the list of inneighbors of `v` within `mg`. """ @traitfn function Graphs.inneighbors( mg::M, v::T ) where {T,M<:AbstractMultilayerGraph;IsDirected{M}} _inneighbors = T[] for helfedge in mg.badjlist[v] push!(_inneighbors, get_v(mg, vertex(helfedge))) end return _inneighbors end """ get_overlay_monoplex_graph(mg::M) where {T,U,M<:AbstractMultilayerGraph{T,U}; IsDirected{M}} Get overlay monoplex graph (i.e. the graph that has the same nodes as `mg` but the link between node `i` and `j` has weight equal to the sum of all edges weights between the various vertices representing `i` and `j` in `mg`, accounting for both layers and interlayers). See [De Domenico et al. (2013)](https://doi.org/10.1103/PhysRevX.3.041022). """ @traitfn function get_overlay_monoplex_graph( mg::M ) where {T,U,M<:AbstractMultilayerGraph{T,U};IsDirected{M}} # Convert the multilayer graph to a weight tensor wgt = weight_tensor(mg).array # Sum the weights for each edge in the multilayer graph projected_overlay_adjacency_matrix = sum([wgt[:, :, i, i] for i in 1:size(wgt, 3)]) return SimpleWeightedDiGraph{T,U}(projected_overlay_adjacency_matrix) # Approach taken from https://github.com/JuliaGraphs/Graphs.jl/blob/7152d540631219fd51c43ab761ec96f12c27680e/src/core.jl#L124 end
MultilayerGraphs
https://github.com/JuliaGraphs/MultilayerGraphs.jl.git
[ "MIT" ]
1.1.4
bc4b247db8e78a9c9f223e7c4870fd2a43b68fe3
code
1392
""" abstract type AbstractHalfEdge{T ,U} end An abstract type representing an HelfEdge (i.e. the edge structure to be used in fadjlists/badjlists). """ abstract type AbstractHalfEdge{T,U} end """ mutable struct HalfEdge{T <: AbstractMultilayerVertex , U<:Union{<:Real,Nothing}} <: AbstractHalfEdge{T,U} # FIELDS - `vertex::T`: the `MultilayerVertex` which is source/destination (depending on the backward/forward nature of the adjacency list) of the `HalfEdge`. - `weight::U`: the weight of the edge. - `metadata::Union{Tuple, NamedTuple}`: metadata associated to the edge. """ mutable struct HalfEdge{T<:AbstractMultilayerVertex,U<:Union{<:Real,Nothing}} <: AbstractHalfEdge{T,U} vertex::T weight::U metadata::Union{Tuple,NamedTuple} end """ vertex(he::HalfEdge) Return the `MultilayerVertex` which is source/destination (depending on the backward/forward nature of the adjacency list) of `he`. """ vertex(he::HalfEdge) = he.vertex """ weight(he::HalfEdge) Return the weight of the edge. """ SimpleWeightedGraphs.weight(he::HalfEdge) = he.weight """ metadata(he::HalfEdge) Return the metadata associated to the edge. """ metadata(he::HalfEdge) = he.metadata # Console print overrides to_string(x::HalfEdge) = "HalfEdge($(to_string(vertex(x))), $(weight(x)), $(metadata(x)))" Base.show(io::IO, x::HalfEdge) = print(io, to_string(x))
MultilayerGraphs
https://github.com/JuliaGraphs/MultilayerGraphs.jl.git
[ "MIT" ]
1.1.4
bc4b247db8e78a9c9f223e7c4870fd2a43b68fe3
code
14878
""" MultilayerDiGraph{T, U, G <: AbstractGraph{T}} <: AbstractMultilayerGraph{T,U} A concrete type that can represent a general multilayer graph. Its internal fields aren't meant to be modified by the user. Please prefer the provided API. """ mutable struct MultilayerDiGraph{T,U} <: AbstractMultilayerGraph{T,U} layers::Vector{LayerDescriptor{T,U}} # vector containing all the layers of the multilayer graph. Their underlying graphs must be all undirected. interlayers::OrderedDict{Set{Symbol},InterlayerDescriptor{T,U}} # the ordered dictionary containing all the interlayers of the multilayer graph. Their underlying graphs must be all undirected. v_V_associations::Bijection{T,<:MultilayerVertex} # A Bijection from Bijections.jl that associates numeric vertices to `MultilayerVertex`s. idx_N_associations::Bijection{Int64,Node} # A Bijection from Bijections.jl that associates Int64 to `Node`s. fadjlist::Vector{Vector{HalfEdge{<:MultilayerVertex,<:Union{Nothing,U}}}} # the forward adjacency list of the MultilayerDiGraph. It is a vector of vectors of `HalfEdge`s. Its i-th element are the `HalfEdge`s that originate from `v_V_associations[i]`. badjlist::Vector{Vector{HalfEdge{<:MultilayerVertex,<:Union{Nothing,U}}}} # the backward adjacency list of the MultilayerDiGraph. It is a vector of vectors of `HalfEdge`s. Its i-th element are the `HalfEdge`s that insist on `v_V_associations[i]`. v_metadata_dict::Dict{T,<:Union{<:Tuple,<:NamedTuple}} # A Dictionary that associates numeric vertices to their metadata end # Traits @traitimpl IsWeighted{MultilayerDiGraph} # @traitimpl IsDirected{MultilayerDiGraph} @traitimpl IsMeta{MultilayerDiGraph} """ is_directed(m::M) where { M <: Type{ <: MultilayerDiGraph}} Return `false` """ Graphs.is_directed(mg::M) where {M<:Type{<:MultilayerDiGraph}} = true # Constructors """ MultilayerDiGraph( layers::Vector{<:Layer{T,U}}, specified_interlayers::Vector{<:Interlayer{T,U}}; default_interlayers_null_graph::H = SimpleGraph{T}(), default_interlayers_structure::String="multiplex", ) where {T,U, H <: AbstractGraph{T}} Construct a MultilayerDiGraph with layers given by `layers`. The interlayers will be constructed by default according to `default_interlayer` where only `"multiplex"` and `"empty"` are allowed, except for those specified in `specified_interlayers`. `default_interlayer = "multiplex"` will imply that unspecified interlayers will have only diagonal couplings, while `default_interlayer = "multiplex"` will produced interlayers that have no couplings. """ function MultilayerDiGraph( layers::Vector{<:Layer{T,U}}, specified_interlayers::Vector{<:Interlayer{T,U}}; default_interlayers_null_graph::H=SimpleGraph{T}(), default_interlayers_structure::String="multiplex", ) where {T,U,H<:AbstractGraph{T}} multilayerdigraph = MultilayerDiGraph(T, U) for layer in deepcopy(layers) add_layer!( multilayerdigraph, layer; default_interlayers_null_graph=default_interlayers_null_graph, default_interlayers_structure=default_interlayers_structure, ) end if !isnothing(specified_interlayers) for interlayer in deepcopy(specified_interlayers) specify_interlayer!(multilayerdigraph, interlayer) end end return multilayerdigraph end """ MultilayerDiGraph( empty_layers::Vector{<:Layer{T,U}}, empty_interlayers::Vector{<:Interlayer{T,U}}, indegree_distribution::UnivariateDistribution, outdegree_distribution::UnivariateDistribution; allow_self_loops::Bool = false, default_interlayers_null_graph::H = SimpleGraph{T}(), ) where {T <: Integer, U <: Real, H <: AbstractGraph{T}} Return a random MultilayerDiGraph that has `empty_layers` as layers and `empty_interlayers` as specified interlayers. `empty_layers` and `empty_interlayers` must respectively be `Layer`s and `Interlayer`s with whatever number of vertices but no edges (if any edge is found, an error is thrown). The degree distribution of the returned random `MultilayerDiGraph` is given by `degree_distribution`, which must have a support that only contains positive numbers for obvious reasons. `allow_self_loops = true` allows for self loops t be present in the final random MultilayerDiGraph. `default_interlayers_null_graph` controls the `null_graph` argument passed to automatically-generated interlayers. """ function MultilayerDiGraph( empty_layers::Vector{<:Layer{T,U}}, empty_interlayers::Vector{<:Interlayer{T,U}}, indegree_distribution::UnivariateDistribution, outdegree_distribution::UnivariateDistribution; allow_self_loops::Bool=false, default_interlayers_null_graph::H=SimpleGraph{T}(), ) where {T<:Integer,U<:Real,H<:AbstractGraph{T}} !allow_self_loops || throw( ErrorException( "`allow_self_loops` must currently be set to `false`. The configuration model algorithm does not support self-loops yet.", ), ) empty_multilayerdigraph = MultilayerDiGraph( empty_layers, empty_interlayers; default_interlayers_null_graph=default_interlayers_null_graph, default_interlayers_structure="empty", ) n = nv(empty_multilayerdigraph) indegree_sequence, outdegree_sequence = sample_digraphical_degree_sequences( indegree_distribution, outdegree_distribution, n ) return MultilayerDiGraph( empty_multilayerdigraph, indegree_sequence, outdegree_sequence; allow_self_loops=false, perform_checks=false, ) end """ MultilayerDiGraph( empty_multilayerdigraph::MultilayerDiGraph{T,U}, indegree_sequence::Vector{<:Integer}, outdegree_sequence::Vector{<:Integer}; allow_self_loops::Bool = false, perform_checks::Bool = false ) where {T,U} Return a random `MultilayerDiGraph` with degree sequence `degree_sequence`. `allow_self_loops` controls the presence of self-loops, while if `perform_checks` is true, the `degree_sequence` os checked to be graphical. """ function MultilayerDiGraph( empty_multilayerdigraph::MultilayerDiGraph{T,U}, indegree_sequence::Vector{<:Integer}, outdegree_sequence::Vector{<:Integer}; allow_self_loops::Bool=false, perform_checks::Bool=false, ) where {T,U} (allow_self_loops && perform_checks) && @warn "Checks for graphicality and coherence with the provided `empty_multilayerdigraph` are currently performed without taking into account self-loops. Thus said checks may fail event though the provided `indegree_sequence` and `outdegree_sequence` may be graphical when one allows for self-loops within the directed multilayer graph to be present. If you are sure that the provided `indegree_sequence` and `outdegree_sequence` are indeed graphical under those circumstances, you may want to disable checks by setting `perform_checks = false`. We apologize for the inconvenience." _multilayerdigraph = deepcopy(empty_multilayerdigraph) ne(_multilayerdigraph) == 0 || throw( ErrorException( "The `empty_multilayerdigraph` argument should be an empty MultilayerDiGraph. Found $(ne(_multilayerdigraph)) edges.", ), ) if perform_checks n = nv(_multilayerdigraph) n == length(indegree_sequence) == length(outdegree_sequence) || throw( ErrorException( "The number of vertices of the provided empty MultilayerDiGraph does not match the length of the `indegree_sequence` or the `outdegree_sequence`. Found $(nv(_multilayerdigraph)) , $(length(indegree_sequence)) and $(length(outdegree_sequence)).", ), ) sum(indegree_sequence) == sum(outdegree_sequence) || throw( ErrorException( "The sum of the `indegree_sequence` and the `outdegree_sequence` must match. Found $(sum(indegree_sequence)) and $(sum(outdegree_sequence)).", ), ) isdigraphical(degree_sequence) || throw( ArgumentError( "`indegree_sequence` and `outdegree_sequence` must be digraphical." ), ) end # edge_list = _random_directed_configuration(_multilayerdigraph, indegree_sequence, outdegree_sequence, allow_self_loops) equivalent_graph = kleitman_wang_graph_generator(indegree_sequence, outdegree_sequence) edge_list = [ ME( _multilayerdigraph.v_V_associations[src(edge)], _multilayerdigraph.v_V_associations[dst(edge)], ) for edge in edges(equivalent_graph) ] for edge in edge_list add_edge!(_multilayerdigraph, edge) end return _multilayerdigraph end """ MultilayerDiGraph(n_nodes::Int64, T::Type{ <: Number}, U::Type{ <: Number} ) Return a null MultilayerDiGraph with with vertex type `T` weighttype `U`. Use this constructor and then add Layers and Interlayers via the `add_layer!` and `specify_interlayer!` methods. """ function MultilayerDiGraph(T::Type{<:Number}, U::Type{<:Number}) return MultilayerDiGraph{T,U}( LayerDescriptor{T,U}[], OrderedDict{Set{Symbol},InterlayerDescriptor{T,U}}(), Bijection{T,MultilayerVertex}(), Bijection{Int64,Node}(), Vector{HalfEdge{MultilayerVertex,<:Union{Nothing,U}}}[], Vector{HalfEdge{MultilayerVertex,<:Union{Nothing,U}}}[], Dict{T,Union{Tuple,NamedTuple}}(), ) end """ MultilayerDiGraph(layers::Vector{<:Layer{T,U}}; default_interlayers_null_graph::H = SimpleGraph{T}(), default_interlayers_structure::String="multiplex") where {T,U, H <: AbstractGraph{T}} Construct a MultilayerDiGraph with layers `layers` and all interlayers with structure `default_interlayers_structure` (only "multiplex" and "empty" are allowed) and type `default_interlayers_null_graph`. """ function MultilayerDiGraph( layers::Vector{<:Layer{T,U}}; default_interlayers_null_graph::H=SimpleGraph{T}(), default_interlayers_structure::String="multiplex", ) where {T,U,H<:AbstractGraph{T}} return MultilayerDiGraph( layers, Interlayer{T,U}[]; default_interlayers_null_graph=default_interlayers_null_graph, default_interlayers_structure=default_interlayers_structure, ) end # Nodes """ add_node!(mg::MultilayerDiGraph, n::Node; add_vertex_to_layers::Union{Vector{Symbol}, Symbol} = Symbol[]) Add node `n` to `mg`. Return true if succeeds. Additionally, add a corresponding vertex to all layers whose name is listed in `add_vertex_to_layers`. If `add_vertex_to_layers == :all`, then a corresponding vertex is added to all layers. """ function add_node!( mg::MultilayerDiGraph, n::Node; add_vertex_to_layers::Union{Vector{Symbol},Symbol}=Symbol[], ) return _add_node!(mg, n; add_vertex_to_layers=add_vertex_to_layers) end """ rem_node!(mg::MultilayerDiGraph, n::Node) Remove node `n` to `mg`. Return true if succeeds. """ rem_node!(mg::MultilayerDiGraph, n::Node) = _rem_node!(mg, n) # Vertices """ add_vertex!(mg::MultilayerDiGraph, mv::MultilayerVertex; add_node::Bool = true) Add MultilayerVertex `mv` to multilayer graph `mg`. If `add_node` is true and `node(mv)` is not already part of `mg`, then add `node(mv)` to `mg` before adding `mv` to `mg` instead of throwing an error. """ function Graphs.add_vertex!( mg::MultilayerDiGraph, mv::MultilayerVertex; add_node::Bool=true ) return _add_vertex!(mg, mv; add_node=add_node) end """ rem_vertex!(mg::MultilayerDiGraph, V::MultilayerVertex) Remove [MultilayerVertex](@ref) `mv` from `mg`. Return true if succeeds, false otherwise. """ Graphs.rem_vertex!(mg::MultilayerDiGraph, V::MultilayerVertex) = _rem_vertex!(mg, V) # Edges """ add_edge!(mg::M, me::E) where {T,U, M <: MultilayerDiGraph{T,U}, E <: MultilayerEdge{ <: Union{U,Nothing}}} Add a MultilayerEdge between `src` and `dst` with weight `weight` and metadata `metadata`. Return true if succeeds, false otherwise. """ function Graphs.add_edge!( mg::M, me::E ) where {T,U,M<:MultilayerDiGraph{T,U},E<:MultilayerEdge{<:Union{U,Nothing}}} return _add_edge!(mg, me) end """ rem_edge!(mg::MultilayerDiGraph, me::MultilayerEdge) Remove edge from `src(me)` to `dst(me)` from `mg`. Return true if succeeds, false otherwise. """ function Graphs.rem_edge!( mg::MultilayerDiGraph, src::MultilayerVertex, dst::MultilayerVertex ) return _rem_edge!(mg, src, dst) end # Layers and Interlayers """ add_layer!( mg::M, new_layer::L; default_interlayers_null_graph::H=SimpleGraph{T}(), default_interlayers_structure::String="multiplex", ) where { T, U, G<:AbstractGraph{T}, L<:Layer{T,U,G}, H<:AbstractGraph{T}, M<:MultilayerDiGraph{T,U} } Add layer `layer` to `mg`. # ARGUMENTS - `mg::M`: the `MultilayerDiGraph` which the new layer will be added to; - `new_layer::L`: the new `Layer` to add to `mg`; - `default_interlayers_null_graph::H`: upon addition of a new `Layer`, all the `Interlayer`s between the new and the existing `Layer`s are immediately created. This keyword argument specifies their `null_graph` See the `Layer` constructor for more information. Defaults to `SimpleGraph{T}()`; - `default_interlayers_structure::String`: The structure of the `Interlayer`s created by default. May either be "multiplex" to have diagonally-coupled only interlayers, or "empty" for empty interlayers. Defaults to "multiplex". """ function add_layer!( mg::M, new_layer::L; default_interlayers_null_graph::H=SimpleDiGraph{T}(), default_interlayers_structure::String="multiplex", ) where { T, U, G<:AbstractGraph{T}, L<:Layer{T,U,G}, H<:AbstractGraph{T}, M<:MultilayerDiGraph{T,U} } return add_layer_directedness!( mg, new_layer; default_interlayers_null_graph=default_interlayers_null_graph, default_interlayers_structure=default_interlayers_structure, ) end """ specify_interlayer!( mg::M, new_interlayer::In ) where {T,U,G<:AbstractGraph{T},M<:MultilayerDiGraph{T,U},In<:Interlayer{T,U,G}} Specify the interlayer `new_interlayer` as part of `mg`. """ @traitfn function specify_interlayer!( mg::M, new_interlayer::In ) where { T,U,G<:AbstractGraph{T},In<:Interlayer{T,U,G},M<:MultilayerDiGraph{T,U};IsDirected{M} } # and(istrait(IsDirected{M}), !istrait(IsMultiplex{M})) is_directed(new_interlayer.graph) || throw( #istrait(IsDirected{typeof(new_interlayer.graph)}) ErrorException( "The `new_interlayer`'s underlying graphs $(new_interlayer.graph) is undirected, so it is not compatible with a `MultilayerDiGraph`.", ), ) return _specify_interlayer!(mg, new_interlayer;) end
MultilayerGraphs
https://github.com/JuliaGraphs/MultilayerGraphs.jl.git
[ "MIT" ]
1.1.4
bc4b247db8e78a9c9f223e7c4870fd2a43b68fe3
code
4090
""" AbstractMultilayerEdge{T} <: AbstractEdge{T} An abstract type representing a `MultilayerGraph` edge. It must have fields: `src`, `dst`, `weight`. """ abstract type AbstractMultilayerEdge{U} <: AbstractEdge{AbstractMultilayerVertex} end """ struct MultilayerEdge{ T <: MultilayerVertex, U <: Union{ <: Real, Nothing}} <: AbstractMultilayerEdge{T} Default concrete subtype of AbstractMultilayerEdge. # FIELDS - `src::T`: the source vertex of the edge; - `dst::T`: the destination vertex of the edge; - `weight::U`: the edge weight. # CONSTRUCTORS MultilayerEdge(src::T, dst::T, weight::U) where { T <: MultilayerVertex, U <: Union{ <: Real, Nothing}} Default constructor. """ struct MultilayerEdge{U<:Union{<:Real,Nothing}} <: AbstractMultilayerEdge{U} src::AbstractMultilayerVertex dst::AbstractMultilayerVertex weight::U metadata::Union{NamedTuple,Tuple} end """ MultilayerEdge(src::AbstractMultilayerVertex, dst::AbstractMultilayerVertex) Convert to `MultilayerEdge{Nothing}(src, dst, nothing, NamedTuple())`. """ function MultilayerEdge(src::AbstractMultilayerVertex, dst::AbstractMultilayerVertex) return MultilayerEdge{Nothing}(src, dst, nothing, NamedTuple()) end """ MultilayerEdge(src::AbstractMultilayerVertex, dst::AbstractMultilayerVertex, weight::U) where {U <: Real} Convert to `MultilayerEdge{U}(src, dst, weight, NamedTuple())`. """ function MultilayerEdge( src::AbstractMultilayerVertex, dst::AbstractMultilayerVertex, weight::U ) where {U<:Real} return MultilayerEdge{U}(src, dst, weight, NamedTuple()) end """ MultilayerEdge(src::AbstractMultilayerVertex, dst::AbstractMultilayerVertex, metadata::NamedTuple) Convert to `MultilayerEdge{Nothing}(src, dst, nothing, metadata)`. """ function MultilayerEdge( src::AbstractMultilayerVertex, dst::AbstractMultilayerVertex, metadata::Union{Tuple,NamedTuple}, ) return MultilayerEdge{Nothing}(src, dst, nothing, metadata) end """ ME Shorter alias for MultilayerEdge. """ const ME = MultilayerEdge """ src(e::AbstractMultilayerEdge) Return the source `MultilayerVertex` of `e`. """ Graphs.src(e::AbstractMultilayerEdge) = e.src """ dst(e::AbstractMultilayerEdge) Return the destination `MultilayerVertex` of `e`. """ Graphs.dst(e::AbstractMultilayerEdge) = e.dst """ weight(e::AbstractMultilayerEdge) Return the weight of `e`. """ SimpleWeightedGraphs.weight(e::AbstractMultilayerEdge) = e.weight """ metadata(e::AbstractMultilayerEdge) Return the metadata of `e`. """ metadata(e::AbstractMultilayerEdge) = e.metadata """ reverse(e::MultilayerEdge) Return and edge between `dst(e)` and `src(e)` with same `weight(e)` and `metadata(e)`. """ Base.reverse(e::MultilayerEdge) = MultilayerEdge(dst(e), src(e), weight(e), metadata(e)) # Compare multilayer edges function compare_multilayeredges( lhs::MultilayerEdge, rhs::MultilayerEdge; check_weight::Bool=false, check_metadata::Bool=false, ) # Check source lhs.src != rhs.src && return false # check destination lhs.dst != rhs.dst && return false # Check weight _check_weight = false if check_weight _check_weight = lhs.weight == rhs.weight ? true : return false end # Check metadata _check_metadata = false if check_metadata _check_metadata = lhs.metadata == rhs.metadata ? true : return false else _check_metadata = true end return true end # Base overrides function Base.:(==)(lhs::MultilayerEdge, rhs::MultilayerEdge) return (lhs.src == rhs.src) && (lhs.dst == rhs.dst) && (lhs.weight == rhs.weight) && (lhs.metadata == rhs.metadata) end # function Base.isequal(lhs::E1, rhs::E2) where {E1<:MultilayerEdge,E2<:MultilayerEdge} # println("here") return lhs == rhs end # Console print utilities function to_string(x::MultilayerEdge) return "ME($(to_string(src(x))) --> $(to_string(dst(x))),\tweight = $(weight(x)),\tmetadata = $(metadata(x)))" end Base.show(io::IO, x::MultilayerEdge) = print(io, to_string(x))
MultilayerGraphs
https://github.com/JuliaGraphs/MultilayerGraphs.jl.git
[ "MIT" ]
1.1.4
bc4b247db8e78a9c9f223e7c4870fd2a43b68fe3
code
14456
""" MultilayerGraph{T, U, G <: AbstractGraph{T}} <: AbstractMultilayerGraph{T,U} A concrete type that can represent a general multilayer graph. Its internal fields aren't meant to be modified by the user. Please prefer the provided API. """ mutable struct MultilayerGraph{T,U} <: AbstractMultilayerGraph{T,U} layers::Vector{LayerDescriptor{T,U}} # vector containing all the layers of the multilayer graph. Their underlying graphs must be all undirected. interlayers::OrderedDict{Set{Symbol},InterlayerDescriptor{T,U}} # the ordered dictionary containing all the interlayers of the multilayer graph. Their underlying graphs must be all undirected. v_V_associations::Bijection{T,<:MultilayerVertex} # A Bijection from Bijections.jl that associates numeric vertices to `MultilayerVertex`s. idx_N_associations::Bijection{Int64,Node} # A Bijection from Bijections.jl that associates Int64 to `Node`s. fadjlist::Vector{Vector{HalfEdge{<:MultilayerVertex,<:Union{Nothing,U}}}} # the forward adjacency list of the MultilayerGraph. It is a vector of vectors of `HalfEdge`s. Its i-th element are the `HalfEdge`s that originate from `v_V_associations[i]`. v_metadata_dict::Dict{T,<:Union{<:Tuple,<:NamedTuple}} # A Dictionary that associates numeric vertices to their metadata. end # Traits @traitimpl IsWeighted{MultilayerGraph} @traitimpl IsMeta{MultilayerGraph} """ is_directed(m::M) where { M <: Type{ <: MultilayerGraph}} Return `false` """ Graphs.is_directed(mg::M) where {M<:Type{<:MultilayerGraph}} = false # Constructors """ MultilayerGraph( layers::Vector{<:Layer{T,U}}, specified_interlayers::Vector{<:Interlayer{T,U}}; default_interlayers_null_graph::H = SimpleGraph{T}(), default_interlayers_structure::String="multiplex", ) where {T,U, H <: AbstractGraph{T}} Construct a MultilayerGraph with layers given by `layers`. The interlayers will be constructed by default according to `default_interlayer` where only `"multiplex"` and `"empty"` are allowed, except for those specified in `specified_interlayers`. `default_interlayer = "multiplex"` will imply that unspecified interlayers will have only diagonal couplings, while `default_interlayer = "multiplex"` will produced interlayers that have no couplings. # ARGUMENTS - `layers::Vector{<:Layer{T,U}}`: The (ordered) list of layers the multilayer graph will have; - `specified_interlayers::Vector{<:Interlayer{T,U}}`: The list of interlayers specified by the user. Note that the user does not need to specify all interlayers, as the unspecified ones will be automatically constructed using the indications given by the `default_interlayers_null_graph` and `default_interlayers_structure` keywords; - `default_interlayers_null_graph::H = SimpleGraph{T}()`: Sets the underlying graph for the interlayers that are to be automatically specified. Defaults to `SimpleGraph{T}()`. See the `Interlayer` constructors for more information; - `default_interlayers_structure::String = "multiplex"`: Sets the structure of the interlayers that are to be automatically specified. May be "multiplex" for diagonally coupled interlayers, or "empty" for empty interlayers (no edges). "multiplex". See the `Interlayer` constructors for more information. """ function MultilayerGraph( layers::Vector{<:Layer{T,U}}, specified_interlayers::Vector{<:Interlayer{T,U}}; default_interlayers_null_graph::H=SimpleGraph{T}(), default_interlayers_structure::String="multiplex", ) where {T,U,H<:AbstractGraph{T}} multilayergraph = MultilayerGraph(T, U) for layer in deepcopy(layers) add_layer!( multilayergraph, layer; default_interlayers_null_graph=default_interlayers_null_graph, default_interlayers_structure=default_interlayers_structure, ) end if !isnothing(specified_interlayers) for interlayer in deepcopy(specified_interlayers) specify_interlayer!(multilayergraph, interlayer) end end return multilayergraph end """ MultilayerGraph( empty_layers::Vector{<:Layer{T,U}}, empty_interlayers::Vector{<:Interlayer{T,U}}, degree_distribution::UnivariateDistribution; allow_self_loops::Bool = false, default_interlayers_null_graph::H = SimpleGraph{T}(), ) where {T <: Integer, U <: Real, H <: AbstractGraph{T}} Return a random MultilayerGraph that has `empty_layers` as layers and `empty_interlayers` as specified interlayers. `empty_layers` and `empty_interlayers` must respectively be `Layer`s and `Interlayer`s with whatever number of vertices but no edges (if any edge is found, an error is thrown). The degree distribution of the returned random `MultilayerGraph` is given by `degree_distribution`, which must have a support that only contains positive numbers for obvious reasons. `allow_self_loops = true` allows for self loops t be present in the final random MultilayerGraph. `default_interlayers_null_graph` controls the `null_graph` argument passed to automatically-generated interlayers. """ function MultilayerGraph( empty_layers::Vector{<:Layer{T,U}}, empty_interlayers::Vector{<:Interlayer{T,U}}, degree_distribution::UnivariateDistribution; allow_self_loops::Bool=false, default_interlayers_null_graph::H=SimpleGraph{T}(), ) where {T<:Integer,U<:Real,H<:AbstractGraph{T}} !allow_self_loops || throw( ErrorException( "`allow_self_loops` must currently be set to `false`. The configuration model algorithm does not support self-loops yet.", ), ) empty_multilayergraph = MultilayerGraph( empty_layers, empty_interlayers; default_interlayers_null_graph=default_interlayers_null_graph, default_interlayers_structure="empty", ) n = nv(empty_multilayergraph) degree_sequence = sample_graphical_degree_sequence(degree_distribution, n) return MultilayerGraph( empty_multilayergraph, degree_sequence; allow_self_loops=false, perform_checks=false ) end """ MultilayerGraph(empty_multilayergraph::MultilayerGraph{T,U}, degree_sequence::Vector{<:Integer}; allow_self_loops::Bool = false, perform_checks::Bool = false) where {T,U} Return a random `MultilayerGraph` with degree sequence `degree_sequence`. `allow_self_loops` controls the presence of self-loops, while if `perform_checks` is true, the `degree_sequence` os checked to be graphical. """ function MultilayerGraph( empty_multilayergraph::MultilayerGraph{T,U}, degree_sequence::Vector{<:Integer}; allow_self_loops::Bool=false, perform_checks::Bool=true, ) where {T,U} (allow_self_loops && perform_checks) && @warn "Checks for graphicality and coherence with the provided `empty_multilayergraph` are currently performed without taking into account self-loops. Thus said checks may fail even though the provided `degree_sequence` may be graphical when one allows for self-loops within the multilayer graph to be present. If you are sure that the provided `degree_sequence` is indeed graphical under those circumstances, you may want to disable checks by setting `perform_checks = false`. We apologize for the inconvenient." _multilayergraph = deepcopy(empty_multilayergraph) ne(_multilayergraph) == 0 || throw( ErrorException( "The `empty_multilayergraph` argument should be an empty MultilayerGraph. Found $(ne(_multilayergraph)) edges.", ), ) if perform_checks n = nv(_multilayergraph) n == length(degree_sequence) || throw( ErrorException( "The number of vertices of the provided empty MultilayerGraph does not match the length of the degree sequence. Found $(nv(_multilayergraph)) and $(length(degree_sequence)).", ), ) isgraphical(degree_sequence) || throw(ArgumentError("degree_sequence must be graphical.")) end # edge_list = _random_undirected_configuration(_multilayergraph, degree_sequence, allow_self_loops) equivalent_graph = havel_hakimi_graph_generator(degree_sequence) edge_list = [ ME( empty_multilayergraph.v_V_associations[src(edge)], empty_multilayergraph.v_V_associations[dst(edge)], ) for edge in edges(equivalent_graph) ] for edge in edge_list add_edge!(_multilayergraph, edge) end return _multilayergraph end """ MultilayerGraph(T::Type{<:Number}, U::Type{<:Number}) Return a null MultilayerGraph with with vertex type `T` weighttype `U`. Use this constructor and then add Layers and Interlayers via the `add_layer!` and `specify_interlayer!` methods. """ function MultilayerGraph(T::Type{<:Number}, U::Type{<:Number}) return MultilayerGraph{T,U}( LayerDescriptor{T,U}[], OrderedDict{Set{Symbol},InterlayerDescriptor{T,U}}(), Bijection{T,MultilayerVertex}(), Bijection{Int64,Node}(), Vector{HalfEdge{MultilayerVertex,<:Union{Nothing,U}}}[], Dict{T,Union{Tuple,NamedTuple}}(), ) end """ MultilayerGraph(layers::Vector{<:Layer{T,U}}; default_interlayers_null_graph::H = SimpleGraph{T}(), default_interlayers_structure::String="multiplex") where {T,U, H <: AbstractGraph{T}} Construct a MultilayerGraph with layers `layers` and all interlayers with structure `default_interlayers_structure` (only "multiplex" and "empty" are allowed) and type `default_interlayers_null_graph`. """ function MultilayerGraph( layers::Vector{<:Layer{T,U}}; default_interlayers_null_graph::H=SimpleGraph{T}(), default_interlayers_structure::String="multiplex", ) where {T,U,H<:AbstractGraph{T}} return MultilayerGraph( layers, Interlayer{T,U}[]; default_interlayers_null_graph=default_interlayers_null_graph, default_interlayers_structure=default_interlayers_structure, ) end # Nodes """ add_node!(mg::MultilayerGraph, n::Node; add_vertex_to_layers::Union{Vector{Symbol}, Symbol} = Symbol[]) Add node `n` to `mg`. Return true if succeeds. Additionally, add a corresponding vertex to all layers whose name is listed in `add_vertex_to_layers`. If `add_vertex_to_layers == :all`, then a corresponding vertex is added to all layers. """ function add_node!( mg::MultilayerGraph, n::Node; add_vertex_to_layers::Union{Vector{Symbol},Symbol}=Symbol[], ) return _add_node!(mg, n; add_vertex_to_layers=add_vertex_to_layers) end """ rem_node!(mg::MultilayerGraph, n::Node) Remove node `n` to `mg`. Return true if succeeds. """ rem_node!(mg::MultilayerGraph, n::Node) = _rem_node!(mg, n) # Vertices """ add_vertex!(mg::MultilayerGraph, mv::MultilayerVertex; add_node::Bool = true) Add MultilayerVertex `mv` to multilayer graph `mg`. If `add_node` is true and `node(mv)` is not already part of `mg`, then add `node(mv)` to `mg` before adding `mv` to `mg` instead of throwing an error. """ function Graphs.add_vertex!(mg::MultilayerGraph, mv::MultilayerVertex; add_node::Bool=true) return _add_vertex!(mg, mv; add_node=add_node) end """ rem_vertex!(mg::MultilayerGraph, V::MultilayerVertex) Remove [MultilayerVertex](@ref) `mv` from `mg`. Return true if succeeds, false otherwise. """ Graphs.rem_vertex!(mg::MultilayerGraph, V::MultilayerVertex) = _rem_vertex!(mg, V) # Edges """ add_edge!(mg::M, me::E) where {T,U, M <: MultilayerGraph{T,U}, E <: MultilayerEdge{ <: Union{U,Nothing}}} Add a MultilayerEdge between `src` and `dst` with weight `weight` and metadata `metadata`. Return true if succeeds, false otherwise. """ function Graphs.add_edge!( mg::M, me::E ) where {T,U,M<:MultilayerGraph{T,U},E<:MultilayerEdge{<:Union{U,Nothing}}} return _add_edge!(mg, me) end """ rem_edge!(mg::MultilayerGraph, me::MultilayerEdge) Remove edge from `src(me)` to `dst(me)` from `mg`. Return true if succeeds, false otherwise. """ function Graphs.rem_edge!(mg::MultilayerGraph, src::MultilayerVertex, dst::MultilayerVertex) return _rem_edge!(mg, src, dst) end # Layers and Interlayers """ add_layer!( mg::M, new_layer::L; default_interlayers_null_graph::H=SimpleGraph{T}(), default_interlayers_structure::String="multiplex", ) where { T, U, G<:AbstractGraph{T}, L<:Layer{T,U,G}, H<:AbstractGraph{T}, M<:MultilayerGraph{T,U} } Add layer `layer` to `mg`. # ARGUMENTS - `mg::M`: the `MultilayerGraph` which the new layer will be added to; - `new_layer::L`: the new `Layer` to add to `mg`; - `default_interlayers_null_graph::H = SimpleGraph{T}()`: upon addition of a new `Layer`, all the `Interlayer`s between the new and the existing `Layer`s are immediately created. This keyword argument specifies their `null_graph` See the `Layer` constructor for more information. Defaults to `SimpleGraph{T}()`; - `default_interlayers_structure::String = "multiplex"`: The structure of the `Interlayer`s created by default. May either be "multiplex" to have diagonally-coupled only interlayers, or "empty" for empty interlayers. Defaults to "multiplex". """ function add_layer!( mg::M, new_layer::L; default_interlayers_null_graph::H=SimpleGraph{T}(), default_interlayers_structure::String="multiplex", ) where { T, U, G<:AbstractGraph{T}, L<:Layer{T,U,G}, H<:AbstractGraph{T}, M<:MultilayerGraph{T,U} } return add_layer_directedness!( mg, new_layer; default_interlayers_null_graph=default_interlayers_null_graph, default_interlayers_structure=default_interlayers_structure, ) end """ specify_interlayer!( mg::M, new_interlayer::In ) where {T,U,G<:AbstractGraph{T},In<:Interlayer{T,U,G}, M<:MultilayerGraph{T,U}; !IsDirected{M}} Specify the interlayer `new_interlayer` as part of `mg`. """ @traitfn function specify_interlayer!( mg::M, new_interlayer::In ) where { T,U,G<:AbstractGraph{T},In<:Interlayer{T,U,G},M<:MultilayerGraph{T,U};!IsDirected{M} } # and(!istrait(IsDirected{M}), !istrait(IsMultiplex{M})) !is_directed(new_interlayer.graph) || throw( # !istrait(IsDirected{typeof(new_interlayer.graph)}) ErrorException( "The `new_interlayer`'s underlying graphs $(new_interlayer.graph) is directed, so it is not compatible with a `MultilayerGraph`.", ), ) return _specify_interlayer!(mg, new_interlayer;) end
MultilayerGraphs
https://github.com/JuliaGraphs/MultilayerGraphs.jl.git
[ "MIT" ]
1.1.4
bc4b247db8e78a9c9f223e7c4870fd2a43b68fe3
code
452
""" abstract type AbstractNode An abstract type representing a node. """ abstract type AbstractNode end """ Node <: AbstractNode A custom concrete type representing a node of a multilayer graph. """ struct Node <: AbstractNode id::String end """ id(n::Node) Return the id of `n`. """ id(n::Node) = n.id # Base overrides Base.:(==)(lhs::Node, rhs::Node) = (lhs.id == rhs.id) Base.isequal(lhs::Node, rhs::Node) = (lhs.id == rhs.id)
MultilayerGraphs
https://github.com/JuliaGraphs/MultilayerGraphs.jl.git
[ "MIT" ]
1.1.4
bc4b247db8e78a9c9f223e7c4870fd2a43b68fe3
code
6636
# This script has been copy-pasted from https://github.com/mhauru/TensorFactorizations.jl """ tensoreig(A, a, b; chis=nothing, eps=0, return_error=false, print_error=false, break_degenerate=false, degeneracy_eps=1e-6, norm_type=:frobenius, hermitian=false) Finds the "right" eigenvectors and eigenvalues of A. The indices of A are permuted so that the indices listed in the Array/Tuple a are on the "left" side and indices listed in b are on the "right". The resulting tensor is then reshaped to a matrix, and eig is called on this matrix to get the vector of eigenvalues E and matrix of eigenvectors U. Finally, U is reshaped to a tensor that has as its last index the one that enumerates the eigenvectors and the indices in a as its first indices. Truncation and error printing work as with tensorsvd. Note that no iterative techniques are used, which means that choosing to truncate provides no performance benefits: All the eigenvalues are computed in any case. The keyword argument hermitian (false by default) tells the algorithm whether the reshaped matrix is Hermitian or not. If hermitian=true, then A = U*diagm(E)*U' up to the truncation error. Output is E, U, and possibly error, if return_error=true. Here E is a vector of eigenvalues values and U[:,...,:,k] is the kth eigenvector. """ function tensoreig( A, a, b; chis=nothing, eps=0, return_error=false, print_error=false, break_degenerate=false, degeneracy_eps=1e-6, norm_type=:frobenius, hermitian=false, ) # Create the matrix and decompose it. A, shp_a, shp_b = to_matrix(A, a, b; return_tensor_shape=true) if hermitian A = Hermitian((A + A') / 2) end fact = eigen(A) E, U = fact.values, fact.vectors # Sort the by largest magnitude eigenvalue first. perm = sortperm(abs.(E); rev=true) if perm != collect(1:length(E)) E = E[perm] U = U[:, perm] end # Find the dimensions to truncate to and the error caused in doing so. chi, error = find_trunc_dim(E, chis, eps, break_degenerate, degeneracy_eps, norm_type) # Truncate E = E[1:chi] U = U[:, 1:chi] if print_error println("Relative truncation error ($norm_type norm) in eig: $error") end # Reshape U to a tensor with a shape matching the shape of A and # return. dim = size(E)[1] U_tens = reshape(U, shp_a..., dim) retval = (E, U_tens) if return_error retval = (retval..., error) end return retval end """ Format the bond dimensions listed in chis to a standard format. """ function format_trunc_chis(v, chis, eps) max_dim = length(v) if chis == nothing if eps > 0 # Try all possible chis. chis = collect(1:max_dim) else # No truncation. chis = [max_dim] end else if isa(chis, Number) # Wrap an individual number in an Array. chis = [chis] else # Make sure chis is an Array, and not, say, a tuple. chis = collect(chis) end if eps == 0 chis = [maximum(chis)] else sort!(chis) end end # If some of the chis are larger than max_dim, get rid of them. for (i, chi) in enumerate(chis) if chi >= max_dim chis[i] = max_dim chis = chis[1:i] break end end return chis end """ Transpose A so that the indices listed in a are on the left and the indices listed in b on the right, and reshape A into a matrix. a and b should be arrays of Integers that together include the numbers from 1 to ndims(A). Alternatively they can be just individual Integers, if only one index is left on one side. If return_tensor_shape is true (by default it's not) return, in addition to the matrix, the shape of the tensor after the transpose but before the reshape. """ function to_matrix(A, a, b; return_tensor_shape=false) # Make sure a and b are Arrays. if isa(a, Number) a = [a] elseif !isa(a, Array) a = collect(a) end if isa(b, Number) b = [b] elseif !isa(b, Array) b = collect(b) end # Permute the indices of A to the right order perm = vcat(a, b) A = tensorcopy(A, collect(1:ndims(A)), perm) # The lists shp_a and shp_b list the dimensions of the bonds in a and b shp = size(A) shp_a = shp[1:length(a)] shp_b = shp[(end + 1 - length(b)):end] # Compute the dimensions of the the matrix that will be formed when # indices of a and b are joined together. dim_a = prod(shp_a) dim_b = prod(shp_b) A = reshape(A, dim_a, dim_b) if return_tensor_shape return A, shp_a, shp_b else return A end end """ Finds the dimension to which v should be truncated, and the error caused in this truncation. See documentation for tensorsvd for the meaning of the different arguments. """ function find_trunc_dim( v, chis, eps, break_degenerate=false, degeneracy_eps=1e-6, norm_type=:frobenius ) # Put chis in a standard format. chis = format_trunc_chis(v, chis, eps) v = abs.(v) if !issorted(v; rev=true) sort!(v; rev=true) end if norm_type == :frobenius v = v .^ 2 eps = eps^2 elseif norm_type == :trace # Nothing to be done else throw(ArgumentError("Unknown norm_type $norm_type.")) end sum_all = sum(v) # Find the smallest chi for which the error is small enough. # If none is found, use the largest chi. if sum_all != 0 for i in 1:length(chis) chi = chis[i] if !break_degenerate # Make sure that we don't break degenerate singular values by # including one but not the other by decreasing chi if # necessary. while 0 < chi < length(v) last_in = v[chi] last_out = v[chi + 1] rel_diff = abs(last_in - last_out) / last_in if rel_diff < degeneracy_eps chi -= 1 else break end end end sum_disc = sum(v[(chi + 1):end]) error = sum_disc / sum_all if error <= eps break end end if norm_type == :frobenius error = sqrt(error) end else error = 0 chi = minimum(chis) end return chi, error end
MultilayerGraphs
https://github.com/JuliaGraphs/MultilayerGraphs.jl.git
[ "MIT" ]
1.1.4
bc4b247db8e78a9c9f223e7c4870fd2a43b68fe3
code
1321
# Define traits from SimpleTraits.jl. Right now, no trait except `IsDirected` is used by MultilayerGraphs.jl """ IsWeighted{X} Trait that discerns between weighted and unweighted graphs. A graph type should take the `IsWeighted` trait IF AND ONLY IF it implements the signature add_edge!(src,dst,weight). Otherwise it should not. """ @traitdef IsWeighted{X} @traitimpl IsWeighted{SimpleWeightedGraphs.AbstractSimpleWeightedGraph} """ is_weighted(g::G) where { G <: AbstractGraph} Check whether `g` is weighted. """ is_weighted(g::G) where {G<:AbstractGraph} = is_weighted(G) """ is_weighted(g::G) where {G<:Type{<:AbstractGraph}} Check whether `g` is weighted. """ is_weighted(g::G) where {G<:Type{<:AbstractGraph}} = istrait(IsWeighted{g}) """ IsMeta{X} Trait that discerns between graphs that sport edge and vertex metadata. """ @traitdef IsMeta{X} @traitimpl IsMeta{MetaGraphs.AbstractMetaGraph} @traitimpl IsMeta{SimpleValueGraphs.AbstractValGraph} """ is_meta(g::G) where {G <: AbstractGraph} Check whether `g` supports edge AND vertex metadata. """ is_meta(g::G) where {G<:AbstractGraph} = is_meta(G) """ is_meta(g::G) where {G<:Type{<:AbstractGraph}} Check whether `g` supports edge AND vertex metadata. """ is_meta(g::G) where {G<:Type{<:AbstractGraph}} = istrait(IsMeta{g})
MultilayerGraphs
https://github.com/JuliaGraphs/MultilayerGraphs.jl.git
[ "MIT" ]
1.1.4
bc4b247db8e78a9c9f223e7c4870fd2a43b68fe3
code
17804
# Nodes # Vertices """ _add_vertex!(mg::M, V::MultilayerVertex) where {T, U, M <: AbstractMultilayerUGraph{T,U}} Add MultilayerVertex `V` to multilayer graph `mg`. If `add_node` is true and `node(mv)` is not already part of `mg`, then add `node(mv)` to `mg` before adding `mv` to `mg` instead of throwing an error. Return true if succeeds. """ @traitfn function _add_vertex!( mg::M, V::MultilayerVertex; add_node::Bool=true ) where {T,U,M<:AbstractMultilayerGraph{T,U};!IsDirected{M}} has_vertex(mg, V) && return false if add_node _node = node(V) if add_node && !has_node(mg, _node) add_node!(mg, _node) end else !has_node(mg, node(V)) && return false end n_nodes = nn(mg) # Re-insert the associations with the proper vertex v = if isempty(domain(mg.v_V_associations)) one(T) else maximum(domain(mg.v_V_associations)) + one(T) end mg.v_V_associations[v] = get_bare_mv(V) mg.v_metadata_dict[v] = V.metadata push!(mg.fadjlist, HalfEdge{MultilayerVertex,U}[]) return true end """ _rem_vertex!(mg::AbstractMultilayerUGraph, V::MultilayerVertex) Remove [MultilayerVertex](@ref) `mv` from `mg`. Return true if succeeds, false otherwise. """ @traitfn function _rem_vertex!( mg::M, V::MultilayerVertex ) where {M <: AbstractMultilayerGraph; !IsDirected{M}} # Check that the node exists and then that the vertex exists has_node(mg, node(V)) || return false has_vertex(mg, V) || return false # Get the v corresponding to V, delete the association and replace it with a MissingVertex. Also substitute the metadata with an empty NamedTuple v = get_v(mg, V) halfedges_to_be_deleted = mg.fadjlist[v] # Loop over the halfedges to be removed in `halfedges_to_be_deleted`, get their v and remove halfedges to `V` in their corresponding arrays for halfedge_to_be_deleted in halfedges_to_be_deleted dst_v = get_v(mg, vertex(halfedge_to_be_deleted)) idx_tbr = nothing # Don't attempt to remove twice a self loop if dst_v != v idx_tbr = findfirst( halfedge -> compare_multilayervertices(vertex(halfedge), V), mg.fadjlist[dst_v], ) deleteat!(mg.fadjlist[dst_v], idx_tbr) end end maximum_v = maximum(domain(mg.v_V_associations)) if v != maximum_v mg.fadjlist[v] = mg.fadjlist[end] pop!(mg.fadjlist) last_V = mg.v_V_associations[maximum_v] delete!(mg.v_V_associations, v) delete!(mg.v_V_associations, maximum_v) mg.v_V_associations[v] = last_V mg.v_metadata_dict[v] = mg.v_metadata_dict[maximum_v] delete!(mg.v_metadata_dict, maximum_v) else pop!(mg.fadjlist) delete!(mg.v_V_associations, v) delete!(mg.v_metadata_dict, v) end return true end # Edges """ has_edge( mg::M, src::T, dst::T) where {T,M<:AbstractMultilayerGraph{T};!IsDirected{M}} Return true if `mg` has edge between the `src` and `dst` (does not check edge or vertex metadata). """ @traitfn function Graphs.has_edge( mg::M, src::T, dst::T ) where {T,M<:AbstractMultilayerGraph{T};!IsDirected{M}} has_vertex(mg, src) || return false has_vertex(mg, dst) || return false halfedges_from_src = mg.fadjlist[src] halfedges_from_dst = mg.fadjlist[dst] if length(halfedges_from_src) >= length(halfedges_from_dst) dsts_v = get_v.(Ref(mg), vertex.(halfedges_from_src)) return dst in dsts_v else srcs_v = get_v.(Ref(mg), vertex.(halfedges_from_dst)) return src in srcs_v end end # Overloads that make AbstractMultilayerUGraph an extension of Graphs.jl. These are all well-inferred . """ edges(mg::M) where {T,U,M<:AbstractMultilayerGraph{T,U}; !IsDirected{M}} Return an list of all the edges of `mg`. """ @traitfn function Graphs.edges( mg::M ) where {T,U,M<:AbstractMultilayerGraph{T,U};!IsDirected{M}} edge_list = MultilayerEdge{U}[] for (_src_v, halfedges) in enumerate(mg.fadjlist) src_v = T(_src_v) src_V = get_rich_mv(mg, src_v) for halfedge in halfedges dst_v = get_v(mg, vertex(halfedge)) # Don't take the same edge twice, except for self loops that are later removed by the unique if dst_v >= src_v dst_V = get_rich_mv(mg, dst_v) push!(edge_list, ME(src_V, dst_V, weight(halfedge), metadata(halfedge))) end end end # Remove duplicate self loops and return return unique(edge_list) end """ _add_edge!(mg::M, me::E) where {T,U, M <: AbstractMultilayerUGraph{T,U}, E <: MultilayerEdge{ <: Union{U,Nothing}}} Add MultilayerEdge `me` to the AbstractMultilayerUGraph `mg`. Return true if succeeds, false otherwise. """ @traitfn function _add_edge!( mg::M, me::E ) where { T,U,E<:MultilayerEdge{<:Union{U,Nothing}},M<:AbstractMultilayerGraph{T,U};!IsDirected{M} } _src = get_bare_mv(src(me)) _dst = get_bare_mv(dst(me)) has_vertex(mg, _src) || throw(ErrorException("Vertex $_src does not belong to the multilayer graph.")) has_vertex(mg, _dst) || throw(ErrorException("Vertex $_dst does not belong to the multilayer graph.")) # Add edge to `edge_dict` src_v = get_v(mg, _src) dst_v = get_v(mg, _dst) _weight = isnothing(weight(me)) ? one(U) : weight(me) _metadata = metadata(me) if !has_edge(mg, _src, _dst) if src_v != dst_v push!(mg.fadjlist[src_v], HalfEdge(_dst, _weight, _metadata)) push!(mg.fadjlist[dst_v], HalfEdge(_src, _weight, _metadata)) else push!(mg.fadjlist[src_v], HalfEdge(_dst, _weight, _metadata)) end return true else @debug "An edge between $(src(me)) and $(dst(me)) already exists" return false end end """ _rem_edge!(mg::AbstractMultilayerUGraph, src::MultilayerVertex, dst::MultilayerVertex) Remove edge from `src` to `dst` from `mg`. Return true if succeeds, false otherwise. """ @traitfn function _rem_edge!( mg::M, src::MultilayerVertex, dst::MultilayerVertex ) where {M <: AbstractMultilayerGraph; !IsDirected{M}} # Perform routine checks has_vertex(mg, src) || throw(ErrorException("Vertex $_src does not belong to the multilayer graph.")) has_vertex(mg, dst) || throw(ErrorException("Vertex $_dst does not belong to the multilayer graph.")) has_edge(mg, src, dst) || return false src_V_idx = get_v(mg, src) dst_V_idx = get_v(mg, dst) _src = get_bare_mv(src) _dst = get_bare_mv(dst) if get_bare_mv(src) != get_bare_mv(dst) src_idx_tbr = findfirst( halfedge -> vertex(halfedge) == _dst, mg.fadjlist[src_V_idx] ) deleteat!(mg.fadjlist[src_V_idx], src_idx_tbr) dst_idx_tbr = findfirst(halfedge -> halfedge.vertex == _src, mg.fadjlist[dst_V_idx]) deleteat!(mg.fadjlist[dst_V_idx], dst_idx_tbr) else src_idx_tbr = findfirst( halfedge -> vertex(halfedge) == _dst, mg.fadjlist[src_V_idx] ) deleteat!(mg.fadjlist[src_V_idx], src_idx_tbr) end return true end """ set_weight!(mg::M, src::MultilayerVertex{L1}, dst::MultilayerVertex{L2}, weight::U) where {L1 <: Symbol, L2 <: Symbol, T,U, M <: AbstractMultilayerGraph{T,U}} Set the weight of the edge between `src` and `dst` to `weight`. Return true if succeeds (i.e. if the edge exists and the underlying graph chosen for the Layer/Interlayer where the edge lies is weighted under the `IsWeighted` trait). """ @traitfn function set_weight!( mg::M, src::MultilayerVertex, dst::MultilayerVertex, weight::U ) where {T,U,M<:AbstractMultilayerGraph{T,U};!IsDirected{M}} descriptor = get_subgraph_descriptor(mg, layer(src), layer(dst)) is_weighted(descriptor.null_graph) || return false has_edge(mg, src, dst) || return false halfedges_from_src = mg.fadjlist[get_v(mg, src)] halfedge_from_src = halfedges_from_src[findfirst( he -> vertex(he) == dst, halfedges_from_src )] halfedge_from_src.weight = weight halfedges_from_dst = mg.fadjlist[get_v(mg, dst)] halfedge_from_dst = halfedges_from_dst[findfirst( he -> vertex(he) == src, halfedges_from_dst )] halfedge_from_dst.weight = weight return true end """ set_metadata!(mg::AbstractMultilayerUGraph, src::MultilayerVertex, dst::MultilayerVertex, metadata::Union{Tuple, NamedTuple}) Set the metadata of the edge between `src` and `dst` to `metadata`. Return true if succeeds (i.e. if the edge exists and the underlying graph chosen for the Layer/Interlayer where the edge lies supports metadata at the edge level under the `IsMeta` trait). """ @traitfn function set_metadata!( mg::M, src::MultilayerVertex, dst::MultilayerVertex, metadata::Union{Tuple,NamedTuple} ) where {M <: AbstractMultilayerGraph; !IsDirected{M}} descriptor = get_subgraph_descriptor(mg, layer(src), layer(dst)) is_meta(descriptor.null_graph) || return false has_edge(mg, src, dst) || return false halfedges_from_src = mg.fadjlist[get_v(mg, src)] halfedge_from_src = halfedges_from_src[findfirst( he -> vertex(he) == dst, halfedges_from_src )] halfedge_from_src.metadata = metadata halfedges_from_dst = mg.fadjlist[get_v(mg, dst)] halfedge_from_dst = halfedges_from_dst[findfirst( he -> vertex(he) == src, halfedges_from_dst )] halfedge_from_dst.metadata = metadata return true end # Layers and Interlayers """ add_layer_directedness!( mg::M, new_layer::L; default_interlayers_null_graph::H = SimpleGraph{T}(), default_interlayers_structure::String ="multiplex" ) where {T,U,G<:AbstractGraph{T},L<:Layer{T,U,G}, H <: AbstractGraph{T}, M<:AbstractMultilayerGraph{T,U}; !IsDirected{M}} Add layer `layer` to `mg`. # ARGUMENTS - `mg::M`: the `MultilayerGraph` which the new layer will be added to; - `new_layer::L`: the new `Layer` to add to `mg`; - `default_interlayers_null_graph::H = SimpleGraph{T}()`: upon addition of a new `Layer`, all the `Interlayer`s between the new and the existing `Layer`s are immediately created. This keyword argument specifies their `null_graph` See the `Layer` constructor for more information. Defaults to `SimpleGraph{T}()`; - `default_interlayers_structure::String = "multiplex"`: The structure of the `Interlayer`s created by default. May either be "multiplex" to have diagonally-coupled only interlayers, or "empty" for empty interlayers. Defaults to "multiplex". """ @traitfn function add_layer_directedness!( mg::M, new_layer::L; default_interlayers_null_graph::H=SimpleGraph{T}(), default_interlayers_structure::String="multiplex", ) where { T, U, G<:AbstractGraph{T}, L<:Layer{T,U,G}, H<:AbstractGraph{T}, M<:AbstractMultilayerGraph{T,U};!IsDirected{M}, } # Check that the layer is directed !istrait(IsDirected{typeof(new_layer.graph)}) || throw( ErrorException( "The `new_layer`'s underlying graph $(new_layer.graph) is directed, so it is not compatible with a `AbstractMultilayerUGraph`.", ), ) return _add_layer!( mg, new_layer; default_interlayers_null_graph=default_interlayers_null_graph, default_interlayers_structure=default_interlayers_structure, ) end """ get_subgraph(mg::M, descriptor::LD) where {T,U, M <: AbstractMultilayerUGraph{T,U}, LD <: LayerDescriptor{T,U}} Internal function. Instantiate the Layer described by `descriptor` whose vertices and edges are contained in `mg`. """ @traitfn function get_subgraph( mg::M, descriptor::LD ) where {T,U,LD<:LayerDescriptor{T,U},M<:AbstractMultilayerGraph{T,U};!IsDirected{M}} vs = sort([ v for (v, mv) in collect(mg.v_V_associations) if mv.layer == descriptor.name ]) _vertices = get_rich_mv.(Ref(mg), vs) edge_list = MultilayerEdge{U}[] for (src_v, halfedges_from_src) in zip(vs, getindex.(Ref(mg.fadjlist), vs)) src_bare_V = mg.v_V_associations[src_v] for halfedge in halfedges_from_src dst_bare_V = vertex(halfedge) dst_v = get_v(mg, dst_bare_V) # Don't take the same edge twice (except for self-loops: they will be taken twice) if dst_v >= src_v && dst_bare_V.layer == descriptor.name push!( edge_list, MultilayerEdge( src_bare_V, dst_bare_V, weight(halfedge), metadata(halfedge) ), ) else continue end end end return Layer(descriptor, _vertices, unique(edge_list)) end """ get_subgraph(mg::M, descriptor::InD) where {T,U, G<: AbstractGraph{T}, M <: AbstractMultilayerUGraph{T,U}, InD <: InterlayerDescriptor{T,U,G}} Internal function. Instantiate the Interlayer described by `descriptor` whose vertices and edges are contained in `mg`. """ @traitfn function get_subgraph( mg::M, descriptor::InD ) where { T, U, # G<:AbstractGraph{T}, InD<:InterlayerDescriptor{T,U}, # G}, M<:AbstractMultilayerGraph{T,U};!IsDirected{M}, } layer_1_vs = T[] layer_2_vs = T[] for (v, mv) in collect(mg.v_V_associations) if mv.layer == descriptor.layer_1 push!(layer_1_vs, v) elseif mv.layer == descriptor.layer_2 push!(layer_2_vs, v) else continue end end sort!(layer_1_vs) sort!(layer_2_vs) layer_1_multilayervertices = get_rich_mv.(Ref(mg), layer_1_vs) layer_2_multilayervertices = get_rich_mv.(Ref(mg), layer_2_vs) shortest_name, longest_name = if length(layer_1_vs) >= length(layer_2_vs) (descriptor.layer_2, descriptor.layer_1) else (descriptor.layer_1, descriptor.layer_2) end shortest_vs = shortest_name == descriptor.layer_1 ? layer_1_vs : layer_2_vs edge_list = MultilayerEdge{U}[] for (src_v, halfedges_from_src) in zip(shortest_vs, getindex.(Ref(mg.fadjlist), shortest_vs)) src_bare_V = mg.v_V_associations[src_v] for halfedge in halfedges_from_src dst_bare_V = vertex(halfedge) # Don't take the same edge twice (except for self-loops: they will be taken twice, but are later removed using `unique`) if dst_bare_V.layer == longest_name push!( edge_list, MultilayerEdge( src_bare_V, dst_bare_V, weight(halfedge), metadata(halfedge) ), ) else continue end end end return _Interlayer( layer_1_multilayervertices, layer_2_multilayervertices, unique(edge_list), descriptor, ) end # Graphs.jl's internals extra overrides """ degree(mg::M, v::V) where {T,M<:AbstractMultilayerUGraph{T,<:Real},V<:MultilayerVertex} Return the degree of MultilayerVertex `v` within `mg`. """ @traitfn function Graphs.degree( mg::M, v::V ) where {M<:AbstractMultilayerGraph,V<:MultilayerVertex;!IsDirected{M}} return indegree(mg, v) end """ inneighbors(mg::M, v::T) where {T,M<:AbstractMultilayerUGraph{T,<:Real}} Return the list of inneighbors of `v` within `mg`. """ @traitfn function Graphs.inneighbors( mg::M, v::T ) where {T,M<:AbstractMultilayerGraph;!IsDirected{M}} return outneighbors(mg, v) end # Multilayer-specific functions # function get_overlay_monoplex_graph end #approach taken from https://github.com/JuliaGraphs/Graphs.jl/blob/7152d540631219fd51c43ab761ec96f12c27680e/src/core.jl#L124 """ get_overlay_monoplex_graph(mg::M) where {M<: AbstractMultilayerUGraph} Get overlay monoplex graph (i.e. the graph that has the same nodes as `mg` but the link between node `i` and `j` has weight equal to the sum of all edges weights between the various vertices representing `i` and `j` in `mg`, accounting for only within-layer edges). See [De Domenico et al. (2013)](https://doi.org/10.1103/PhysRevX.3.041022). """ @traitfn function get_overlay_monoplex_graph( mg::M ) where {T,U,M<:AbstractMultilayerGraph{T,U};!IsDirected{M}} wgt = weight_tensor(mg).array projected_overlay_adjacency_matrix = sum([wgt[:, :, i, i] for i in 1:size(wgt, 3)]) return SimpleWeightedGraph{T,U}(projected_overlay_adjacency_matrix) end """ von_neumann_entropy(mg::M) where {T,U, M <: AbstractMultilayerUGraph{T, U}} Compute the Von Neumann entropy of `mg`, according to [De Domenico et al. (2013)](https://doi.org/10.1103/PhysRevX.3.041022). Only for undirected multilayer graphs. """ @traitfn function von_neumann_entropy( mg::M ) where {T,U,M<:AbstractMultilayerGraph{T,U};!IsDirected{M}} wgt = weight_tensor(mg).array num_nodes = length(nodes(mg)) num_layers = length(mg.layers) # Multistrength tensor Δ = ein"ijkm,ik,nj,om -> njom"( wgt, ones(T, size(wgt)[[1, 3]]), δk(num_nodes), δk(num_layers) ) # Trace of Δ tr_Δ = ein"iikk->"(Δ)[] # Multilayer laplacian tensor L = Δ .- wgt # Multilayer density tensor ρ = (1.0 / tr_Δ) .* L eigvals, eigvects = tensoreig(ρ, [2, 4], [1, 3]) #= # Check that we are calculating the right eigenvalues lhs = ein"ijkm,ik -> jm"(ρ,eigvects[:,:,1]) rhs = eigvals[1].*eigvects[:,:,1] @assert all(lhs .≈ rhs) # Indeed we are =# Λ = get_diagonal_weight_tensor(eigvals, size(wgt)) # Correct for machine precision Λ[Λ .< eps()] .= 0.0 log2Λ = log2.(Λ) log2Λ[isinf.(log2Λ)] .= 0 return -ein"ijkm,jimk ->"(Λ, log2Λ)[] end
MultilayerGraphs
https://github.com/JuliaGraphs/MultilayerGraphs.jl.git
[ "MIT" ]
1.1.4
bc4b247db8e78a9c9f223e7c4870fd2a43b68fe3
code
27411
# Base extensions # Non package-specific utilities """ get_common_type(types::Vector{<: DataType}) Return the minimum common supertype of `types`. """ function get_common_type(types::Vector{<:DataType}) promoted_types = DataType[] if length(types) > 1 for i in 1:(length(types) - 1) push!(promoted_types, promote_type(types[i], types[i + 1])) end else return types[1] end return length(promoted_types) == 1 ? promoted_types[1] : get_common_type(promoted_types) end """ check_unique(vec::Union{Missing, <: Vector, <: Tuple}) Return `true` if all elements in `vec` are unique or if `ismissing(vec)`, else return `false`. """ function check_unique(vec::Union{Missing,<:Vector,<:Tuple}) return ismissing(vec) ? true : length(setdiff(unique(vec), vec)) == 0 end """ multilayer_kronecker_delta(dims::NTuple{4,Int64}) Return a 4-dimensional Kronecker delta with size equal to `dims`. """ function multilayer_kronecker_delta(dims::NTuple{4,Int64}) output = Array{Int64}(undef, dims...) ranges = [1:dim for dim in dims] idxs = Iterators.product(ranges...) for idx in idxs vertices_indexes = idx[1:2] layers_indexes = idx[3:4] output[idx...] = if all(length(unique(vertices_indexes)) == length(unique(layers_indexes)) .== 1) 1 else 0 end end return output end """ get_diagonal_weight_tensor(arr,dims) Return a tensor whose size is `dims` and has `arr` on the diagonal. """ function get_diagonal_weight_tensor(arr::Vector{T}, dims) where {T} output = Array{T}(undef, dims...) ranges = [1:dim for dim in dims] idxs = Iterators.product(ranges...) i = 1 for idx in idxs vertices_indexes = idx[1:2] layers_indexes = idx[3:4] on_diag = all( length(unique(vertices_indexes)) == length(unique(layers_indexes)) .== 1 ) if on_diag output[idx...] = arr[i] i += 1 else output[idx...] = zero(T) end end return output end """ mutable struct δk{T} <: AbstractVector{T} The Kronecker delta. # FIELDS - `N::Int64`: the number of dimensions; - `representation::Matrix{Int64}`: the matrix representing the Kronecker delta; - `T`: the return type when called `δk[i,j]`. ### CONSTRUCTORS δk{T}(N::Int64) where {T <: Number} Inner constructor that only requires `N` and the `eltype`. """ mutable struct δk{T} <: AbstractVector{T} N::Int64 representation::Matrix{Int64} # Inner constructor that only requires N and the eltype. function δk{T}(N::Int64) where {T<:Number} out = new{T}(N) representation = [out[h, k] for h in 1:N, k in 1:N] out.representation = representation return out end end """ δk(N::Int64) Outer constructor that only requires `N`. """ δk(N::Int64) = δk{Int64}(N) """ getindex(d::δk{T}, h::Int64, k::Int64) where T `getindex` dispatch that allows to easily construct the `representation` field of `δ_Ω` inside its inner constructor. """ Base.getindex(d::δk{T}, h::Int64, k::Int64) where {T} = I[h, k] ? one(T) : zero(T) """ getindex(d::δk{T}, i::Int) where T The getindex called by OMEinsum.jl. """ Base.getindex(d::δk{T}, i::Int) where {T} = d.representation[i] """ size(d::δk) Override required by OMEinsum.jl. """ Base.size(d::δk) = (d.N, d.N) """ struct δ_1{T<: Number} The `δ_1` from [De Domenico et al. (2013)](https://doi.org/10.1103/PhysRevX.3.041022). Evaluate it via the notation `[i,j]`. # FIELDS - `N:Int64`: the dimensionality of `δ_1`; - `T`: the return type. # CONSTRUCTORS δ_1{T<: Number}(N::Int64) """ struct δ_1{T<:Number} N::Int64 end function Base.getindex(d::δ_1{T}, h::Int64, k::Int64, l::Int64) where {T} return Bool(I[h, l] * I[h, k] * I[k, l]) ? one(T) : zero(T) end Base.size(d::δ_1) = (d.N, d.N) """ struct δ_2{T<: Number} The `δ_2` from [De Domenico et al. (2013)](https://doi.org/10.1103/PhysRevX.3.041022). Evaluate it via the notation `[i,j]`. # FIELDS - `N:Int64`: the dimensionality of `δ_2`; - `T`: the return type. # CONSTRUCTORS δ_2{T<: Number}(N::Int64) """ struct δ_2{T<:Number} N::Int64 end function Base.getindex(d::δ_2{T}, h::Int64, k::Int64, l::Int64) where {T} return if Bool( (1 - I[h, l]) * I[h, k] + (1 - I[k, l]) * I[h, l] + (1 - I[h, k]) * I[k, l] ) one(T) else zero(T) end end Base.size(d::δ_2) = (d.N, d.N) """ struct δ_3{T<: Number} The `δ_3` from [De Domenico et al. (2013)](https://doi.org/10.1103/PhysRevX.3.041022). Evaluate it via the notation `[i,j]`. # FIELDS - `N:Int64`: the dimensionality of `δ_3`; - `T`: the return type. # CONSTRUCTORS δ_3{T<: Number}(N::Int64) """ struct δ_3{T<:Number} N::Int64 end function Base.getindex(d::δ_3{T}, h::Int64, k::Int64, l::Int64) where {T} return Bool((1 - I[h, l]) * (1 - I[k, l]) * (1 - I[h, k])) ? one(T) : zero(T) end Base.size(d::δ_3) = (d.N, d.N) """ δ_Ω{T} <: AbstractVector{T} Struct that represents the `δ_Ω` defined in [De Domenico et al. (2013)](https://doi.org/10.1103/PhysRevX.3.041022). # FIELDS - `δ_1::δ_1{T}`: Instance of `δ_1`; - `δ_2::δ_2{T}`: Instance of `δ_2`; - `δ_3::δ_3{T}`: Instance of `δ_3`; - `N::Int64 ` : Maximum index (number of layers); - `representation::Array{Int64,4}`: Multidimensional-array representation of `δ_Ω`. """ mutable struct δ_Ω{T} <: AbstractVector{T} δ_1::δ_1{T} δ_2::δ_2{T} δ_3::δ_3{T} N::Int64 representation::Array{Int64,4} # Inner constructor that only requires N and the eltype. function δ_Ω{T}(N::Int64) where {T<:Number} out = new{T}(δ_1{T}(N), δ_2{T}(N), δ_3{T}(N), N) representation = [out[Ω, h, k, l] for Ω in 1:3, h in 1:N, k in 1:N, l in 1:N] out.representation = representation return out end end # Outer constructor that only requires N δ_Ω(N::Int64) = δ_Ω{Int64}(N) # getindex dispatch that allows to easily construct the `representation` field of δ_Ω inside its inner constructor function Base.getindex(d::δ_Ω{T}, Ω::Int64, h::Int64, k::Int64, l::Int64) where {T} if Ω == 1 return d.δ_1[h, k, l] elseif Ω == 2 return d.δ_2[h, k, l] elseif Ω == 3 return d.δ_3[h, k, l] end end # The getindex called by OMEinsum.jl Base.getindex(d::δ_Ω{T}, i::Int) where {T} = d.representation[i] # Override required by OMEinsum.jl Base.size(d::δ_Ω{T}) where {T} = (d.N >= 3 ? 3 : d.N, d.N, d.N, d.N) """ get_diagonal_elements(arr::Array{T,N}) where {T,N} """ function get_diagonal_elements(arr::Array{T,N}) where {T,N} output = similar(arr) for cart_idx in CartesianIndices(arr) vertices_indexes = Tuple(cart_idx)[1:2] layers_indexes = Tuple(cart_idx)[3:4] output[cart_idx] = if length(unique(vertices_indexes)) == length(unique(layers_indexes)) == 1 arr[cart_idx] else 0.0 end end return output end #Taken from https://gist.github.com/Datseris/1b1aa1287041cab1b2dff306ddc4f899 """ get_concrete_subtypes(type::Type) Return an array of all concrete subtypes of `type` (which should be abstract). """ function get_concrete_subtypes(type::Type) out = DataType[] return _subtypes!(out, type) end function _subtypes!(out, type::Type) if isconcretetype(type) push!(out, type) else foreach(T -> _subtypes!(out, T), InteractiveUtils.subtypes(type)) end return out end # Check if struct is completely initialized """ iscompletelyinitialized(obj::Any) Check whether `obj` is completely initialized. """ function iscompletelyinitialized(obj::Any) completely_initialized = true for field_name in fieldnames(typeof(obj)) try @eval $obj.$field_name catch completely_initialized = false break end end return completely_initialized end """ get_oom(x::Number) Get the order of magnitude of `x`. """ function get_oom(x::Number) float_oom = floor(log10(x)) # if float_oom == -Inf # return 0 if !isinf(float_oom) return Int64(float_oom) else return float_oom end end """ isapproxsymmetric(A::Matrix{T}) where {T <: Real } "Check whether `A` is approximately symmetric (within `eps(T)`). """ function isapproxsymmetric(A::Matrix{T}) where {T<:Real} return all(get_oom.(abs.(A .- A')) .<= get_oom(eps(T))) end """ isapproxsymmetric(A::Matrix{T}) where {T <: Real } Check whether `A` is symmetric (within `zero(T)`). """ isapproxsymmetric(A::Matrix{T}) where {T<:Integer} = all(abs.(A .- A') .<= zero(T)) """ isdigraphical(indegree_sequence::AbstractVector{<:Integer}, outdegree_sequence::AbstractVector{<:Integer},) Check whether the given indegree sequence and outdegree sequence are digraphical, that is whether they can be the indegree and outdegree sequence of a digraph. ### Implementation Notes According to Fulkerson-Chen-Anstee theorem, a sequence ``\\{(a_1, b_1), ...,(a_n, b_n)\\}`` (sorted in descending order of a) is graphic iff the sum of vertex degrees is even and ``\\sum_{i = 1}^{n} a_i = \\sum_{i = 1}^{n} b_i\\}`` and the sequence obeys the property - ```math \\sum_{i=1}^{r} a_i \\leq \\sum_{i=r+1}^n min(r-1,b_i) + \\sum_{i=r+1}^n min(r,b_i) ``` for each integer r <= n-1. """ function isdigraphical( indegree_sequence::AbstractVector{<:Integer}, outdegree_sequence::AbstractVector{<:Integer}, ) # Check whether the degree sequences have the same length length(indegree_sequence) == length(outdegree_sequence) || throw( ArgumentError("The indegree and outdegree sequences must have the same length.") ) # Check whether the degree sequence is empty !(isempty(indegree_sequence) && isempty(outdegree_sequence)) || return true # Check whether the degree sequences have only non-negative values all(indegree_sequence .>= 0) || throw( ArgumentError("The indegree sequence must contain non-negative integers only.") ) all(outdegree_sequence .>= 0) || throw( ArgumentError("The outdegree sequence must contain non-negative integers only.") ) n = length(indegree_sequence) n == length(outdegree_sequence) || return false sum(indegree_sequence) == sum(outdegree_sequence) || return false _sortperm = sortperm(indegree_sequence; rev=true) sorted_indegree_sequence = indegree_sequence[_sortperm] sorted_outdegree_sequence = outdegree_sequence[_sortperm] indegree_sum = zero(Int64) outdegree_min_sum = zero(Int64) cum_min = zero(Int64) # The following approach, which requires substituting the line # cum_min = sum([min(sorted_outdegree_sequence[i], r) for i in (1+r):n]) # with the line # cum_min -= mindeg[r] # inside the for loop below, work as well, but the values of `cum_min` at each iteration differ. To be on the safe side we implemented it as in https://en.wikipedia.org/wiki/Fulkerson%E2%80%93Chen%E2%80%93Anstee_theorem #= mindeg = Vector{Int64}(undef, n) @inbounds for i = 1:n mindeg[i] = min(i, sorted_outdegree_sequence[i]) end cum_min = sum(mindeg) =# # Similarly for `outdegree_min_sum`. @inbounds for r in 1:(n - 1) indegree_sum += sorted_indegree_sequence[r] outdegree_min_sum = sum([min(sorted_outdegree_sequence[i], r - 1) for i in 1:r]) cum_min = sum([min(sorted_outdegree_sequence[i], r) for i in (1 + r):n]) cond = indegree_sum <= (outdegree_min_sum + cum_min) cond || return false end return true end #= """ _random_undirected_configuration(empty_mg::M, degree_sequence::Vector{ <: Integer}) where {T,U,M <: MultilayerGraph{T,U}} Internal function. Returns a `MultilayerEdge` list compatible with `empty_mg`, using a relatively inefficient algorithm. """ function _random_undirected_configuration(empty_mg::M, degree_sequence::Vector{ <: Integer}, allow_self_loops::Bool) where {T,U,M <: MultilayerGraph{T,U}} # Get all MultilayerVertexs mvs = mv_vertices(empty_mg) edge_list = MultilayerEdge{U}[] # Boolean that states if the wiring was successful success = false @info "Looping through wirings to find one that works..." # Loop until a successful wiring is found while !success mvs_degree_dict = Dict(mv => deg for (mv,deg) in zip(mvs,degree_sequence) if deg != 0) edge_list = MultilayerEdge[] for src in mvs if src in keys(mvs_degree_dict) try dsts = nothing if allow_self_loops dsts = sample(collect(keys(mvs_degree_dict)), mvs_degree_dict[src]; replace = false) # This would be correct but we have no "isgraphical" function that takes into account self loops. This section of the code is thus disabled. else dsts = sample(collect(setdiff(keys(mvs_degree_dict), [src])), mvs_degree_dict[src]; replace = false) end for dst in dsts mvs_degree_dict[dst] = mvs_degree_dict[dst] - 1 if mvs_degree_dict[dst] == 0 delete!(mvs_degree_dict, dst) end descriptor = get_subgraph_descriptor(empty_mg, src.layer, dst.layer) push!(edge_list, MultilayerEdge(src, dst, descriptor.default_edge_weight(src,dst), descriptor.default_edge_metadata(src,dst))) end delete!(mvs_degree_dict, src) catch e if cmp(e.msg,"Cannot draw more samples without replacement.") == 0 break else throw(e) end end else continue end end success = length(mvs_degree_dict) == 0 end return edge_list end """ _random_directed_configuration(empty_mg::M, indegree_sequence::Vector{ <: Integer}, outdegree_sequence::Vector{ <: Integer}, allow_self_loops::Bool) where {T,U,M <: MultilayerDiGraph{T,U}} Internal function. Returns a `MultilayerEdge` list compatible with `empty_mg`, using a relatively inefficient algorithm. """ function _random_directed_configuration(empty_mg::M, indegree_sequence::Vector{ <: Integer}, outdegree_sequence::Vector{<:Integer}, allow_self_loops::Bool) where {T,U,M <: MultilayerDiGraph{T,U}} # Get all MultilayerVertexs mvs = mv_vertices(empty_mg) edge_list = MultilayerEdge{U}[] # Boolean that states if the wiring was successful success = false @info "Looping through wirings to find one that works..." # Loop until a successful wiring is found while !success mvs_indegree_dict = Dict(mv => indeg for (mv,indeg) in zip(mvs,indegree_sequence) if indeg != 0) mvs_outdegree_dict = Dict(mv => outdeg for (mv,outdeg) in zip(mvs,outdegree_sequence) if outdeg != 0) edge_list = MultilayerEdge[] for src in mvs if src in keys(mvs_outdegree_dict) try dsts = nothing if allow_self_loops dsts = sample(collect(keys(mvs_indegree_dict)), mvs_outdegree_dict[src]; replace = false) # This would be correct but we have no "isgraphical" function that takes into account self loops. This section of the code is thus disabled. else dsts = sample(collect(setdiff(keys(mvs_indegree_dict), [src])), mvs_outdegree_dict[src]; replace = false) end for dst in dsts mvs_indegree_dict[dst] = mvs_indegree_dict[dst] - 1 if mvs_indegree_dict[dst] == 0 delete!(mvs_indegree_dict, dst) end descriptor = get_subgraph_descriptor(empty_mg, src.layer, dst.layer) push!(edge_list, MultilayerEdge(src, dst, descriptor.default_edge_weight(src,dst), descriptor.default_edge_metadata(src,dst))) end delete!(mvs_outdegree_dict, src) catch e if cmp(e.msg,"Cannot draw more samples without replacement.") == 0 break else throw(e) end end else continue end end success = length(mvs_indegree_dict) == 0 && length(mvs_outdegree_dict) == 0 end return edge_list end =# """ cartIndexTovecIndex(cart_index::CartesianIndex, tensor_size::NTuple{N, <: Integer} ) where N Internal function. Converts `cart_index` to an integer index such that it corresponds to the same element under flattening of the tensor whose size is `tensor_size`. """ function cartIndexTovecIndex( cart_index::Union{NTuple{N,Integer},CartesianIndex}, tensor_size::NTuple{N,<:Integer} ) where {N} return cart_index[1] + sum(collect(Tuple(cart_index)[2:end] .- 1) .* cumprod(tensor_size[1:(end - 1)])) end """ havel_hakimi_graph_generator(degree_sequence::AbstractVector{<:Integer}) Returns a simple graph with a given finite degree sequence of non-negative integers generated via the Havel-Hakimi algorithm which works as follows: 1. successively connect the node of highest degree to other nodes of highest degree; 2. sort the remaining nodes by degree in decreasing order; 3. repeat the procedure. ## References 1. [Hakimi (1962)](https://doi.org/10.1137/0110037); 2. [Wikipedia](https://en.wikipedia.org/wiki/Havel%E2%80%93Hakimi_algorithm). """ function havel_hakimi_graph_generator(degree_sequence::AbstractVector{<:Integer}) # Check whether the degree sequence has only non-negative values all(degree_sequence .>= 0) || throw(ArgumentError("The degree sequence must contain non-negative integers only.")) # Instantiate an empty simple graph graph = SimpleGraph(length(degree_sequence)) # Create a (vertex, degree) ordered dictionary vertices_degrees_dict = OrderedDict( vertex => degree for (vertex, degree) in enumerate(degree_sequence) ) # Havel-Hakimi algorithm while (any(values(vertices_degrees_dict) .!= 0)) # Sort the new sequence in non-increasing order vertices_degrees_dict = OrderedDict( sort(collect(vertices_degrees_dict); by=last, rev=true) ) # Remove the first vertex and distribute its stabs max_vertex, max_degree = popfirst!(vertices_degrees_dict) # Check whether the new sequence has only positive values all(collect(values(vertices_degrees_dict))[1:max_degree] .> 0) || throw(ErrorException("The degree sequence is not graphical.")) # Connect the node of highest degree to other nodes of highest degree for vertex in collect(keys(vertices_degrees_dict))[1:max_degree] add_edge!(graph, max_vertex, vertex) vertices_degrees_dict[vertex] -= 1 end end # Return the simple graph return graph end """ lexicographical_order_lt(A::Vector{T}, B::Vector{T}) where T The less than (lt) function that implements lexicographical order. See [Wikipedia](https://en.wikipedia.org/wiki/Lexicographic_order). """ function lexicographical_order_lt( A::Union{Vector{T},NTuple{N,T}}, B::Union{Vector{T},NTuple{M,T}} ) where {N,M,T} A_dc = deepcopy(A) B_dc = deepcopy(B) diff_length = length(A) - length(B) if diff_length >= 0 A_dc = vcat(A_dc, repeat([-Inf], diff_length)) else B_dc = vcat(B_dc, repeat([-Inf], abs(diff_length))) end for (a, b) in zip(A_dc, B_dc) if a != b a < b end end end """ lexicographical_order_ntuple(A::NTuple{N,T}, B::NTuple{M,T}) where {N,T} The less than (lt) function that implements lexicographical order for `NTuple` of equal length. See [Wikipedia](https://en.wikipedia.org/wiki/Lexicographic_order). """ function lexicographical_order_ntuple(A::NTuple{N,T}, B::NTuple{N,T}) where {N,T} for (a, b) in zip(A, B) if a != b return a < b end end return false end """ kleitman_wang_graph_generator(indegree_sequence::AbstractVector{<:Integer},outdegree_sequence::AbstractVector{<:Integer}) Returns a simple directed graph with given finite in-degree and out-degree sequences of non-negative integers generated via the Kleitman-Wang algorithm, that works like follows: 1. Sort the indegree-outdegree pairs in lexicographical order; 2. Select a pair that has strictly positive outdegree, say the i-th pairs that has outdegree = b_i; 3. Subtract 1 to the first b_i highest indegrees (the i-th being excluded), and set b_i to 0; 4. Repeat from 1. until all indegree-outdegree pairs are of the form (0.0). ## References - [Wikipedia](https://en.wikipedia.org/wiki/Kleitman%E2%80%93Wang_algorithms); - [Kleitman and Wang (1973)](https://doi.org/10.1016/0012-365X(73)90037-X). """ function kleitman_wang_graph_generator( indegree_sequence::AbstractVector{<:Integer}, outdegree_sequence::AbstractVector{<:Integer}, ) length(indegree_sequence) == length(outdegree_sequence) || throw( ArgumentError( "The provided `indegree_sequence` and `outdegree_sequence` must be of the dame length.", ), ) # Check whether the indegree_sequence and outdegree_sequence have only non-negative values all(indegree_sequence .>= 0) || throw( ArgumentError( "The `indegree_sequence` sequence must contain non-negative integers only." ), ) all(outdegree_sequence .>= 0) || throw( ArgumentError( "The `outdegree_sequence` sequence must contain non-negative integers only." ), ) # Instantiate an empty simple graph graph = SimpleDiGraph(length(indegree_sequence)) # Create a (vertex, degree) ordered dictionary S = zip(deepcopy(indegree_sequence), deepcopy(outdegree_sequence)) vertices_degrees_dict = OrderedDict(i => tup for (i, tup) in enumerate(S)) # Kleitman-Wang algorithm while (any(Iterators.flatten(values(vertices_degrees_dict)) .!= 0)) # Sort the new sequence in non-increasing lexicographical order vertices_degrees_dict = OrderedDict( sort( collect(vertices_degrees_dict); by=last, lt=lexicographical_order_ntuple, rev=true, ), ) # Find a vertex with positive outdegree,a nd temporarily remove it from `vertices_degrees_dict` i, (a_i, b_i) = 0, (0, 0) for (_i, (_a_i, _b_i)) in collect(deepcopy(vertices_degrees_dict)) if _b_i != 0 i, a_i, b_i = (_i, _a_i, _b_i) delete!(vertices_degrees_dict, _i) break end end # Connect the vertex found above to other nodes of highest degree for (v, degs) in collect(vertices_degrees_dict)[1:b_i] add_edge!(graph, i, v) vertices_degrees_dict[v] = (degs[1] - 1, degs[2]) end # Check whether the new sequence has only positive values all( collect(Iterators.flatten(collect(values(vertices_degrees_dict))))[1:b_i] .>= 0 ) || throw( ErrorException("The in-degree and out-degree sequences are not digraphical."), ) # Reinsert the vertex, with zero outdegree vertices_degrees_dict[i] = (a_i, 0) end return graph end """ sample_graphical_degree_sequence(degree_distribution::UnivariateDistribution, n::Integer) Sample a graphical degree sequence for a graph with `n` vertices from `degree_distribution`. """ function sample_graphical_degree_sequence( degree_distribution::UnivariateDistribution, n::Integer ) minimum(support(degree_distribution)) >= 0 || throw( ErrorException( "The `degree_distribution` must have positive support. Found $(support(degree_distribution)).", ), ) @info "Trying to sample a graphical sequence from the provided distribution $degree_distribution..." degree_sequence = nothing acceptable = false while !acceptable degree_sequence = round.(Ref(Int), rand(degree_distribution, n)) acceptable = all(0 .<= degree_sequence .< n) if acceptable acceptable = isgraphical(degree_sequence) end end return degree_sequence end """ sample_digraphical_degree_sequences(indegree_distribution::UnivariateDistribution, outdegree_distribution::UnivariateDistribution, n::Integer) Sample a digraphical couple `(indegree_sequence, outdegree_sequence)` for a graph with `n` vertices from respectively `indegree_distribution` and `outdegree_distribution`. """ function sample_digraphical_degree_sequences( indegree_distribution::UnivariateDistribution, outdegree_distribution::UnivariateDistribution, n::Integer, ) minimum(support(indegree_distribution)) >= 0 && minimum(support(outdegree_distribution)) >= 0 || throw( ErrorException( "Both the `indegree_distribution` and the `outdegree_distribution` must have positive support. Found $(support(indegree_distribution)) and $(support(outdegree_distribution)).", ), ) indegree_sequence = Vector{Int64}(undef, n) outdegree_sequence = Vector{Int64}(undef, n) acceptable = false @info "Trying to sample a digraphical sequence from the two provided distributions $indegree_distribution and $outdegree_distribution..." while !acceptable indegree_sequence .= round.(Ref(Int), rand(indegree_distribution, n)) outdegree_sequence .= round.(Ref(Int), rand(outdegree_distribution, n)) acceptable = all(0 .<= vcat(indegree_sequence, outdegree_sequence) .< n) if acceptable acceptable = isdigraphical(indegree_sequence, outdegree_sequence) end end return (indegree_sequence, outdegree_sequence) end """ get_valtypes(init_function::Function) Return the `vertexval_types` (or `edgeval_types`), deduced from from the `init_function` (which must be the `vertexval_init` or the `edgeval_init` function) for SimpleValueGraphs.jl's structs. """ function get_valtypes(init_function::Function) returned_type = Base.return_types(init_function)[1] if returned_type <: Tuple tuple(returned_type.parameters...) elseif returned_type <: NamedTuple returned_namedtuple_type = returned_type.parameters type_pars = tuple(returned_namedtuple_type[end].parameters...) NamedTuple{returned_namedtuple_type[1]}(type_pars) end end """ or(conds...) Evaluate if at least one of the conditions in `conds` is true. """ or(conds...) = any(conds) """ and(conds...) Evaluate if all conditions in `conds` is true. """ and(conds...) = all(conds)
MultilayerGraphs
https://github.com/JuliaGraphs/MultilayerGraphs.jl.git
[ "MIT" ]
1.1.4
bc4b247db8e78a9c9f223e7c4870fd2a43b68fe3
code
1532
function __add_vertex!( g::Graphs.SimpleGraphs.AbstractSimpleGraph{T}; metadata::Union{Tuple,NamedTuple}=NamedTuple(), ) where {T<:Integer} !isempty(metadata) && println( "Trying to add a vertex with metadata to a graph of type $(typeof(g)). Metadata $(metadata) will be ignored.", ) return add_vertex!(g) end function _get_vertex_metadata( g::Graphs.SimpleGraphs.AbstractSimpleGraph{T}, vertex::T ) where {T} return NamedTuple() end function _add_edge!( g::Graphs.SimpleGraphs.AbstractSimpleGraph{T}, src::T, dst::T; weight::W=nothing, metadata::Union{Tuple,NamedTuple}=NamedTuple(), ) where {T<:Integer,W<:Union{<:Real,Nothing}} (isnothing(weight) || weight == 1) || @warn "Trying to add a weighted edge to an unweighted graph of type $(typeof(g)). Weight $(weight) will be ignored." !isempty(metadata) && @warn ( "Trying to add an edge with metadata to a graph of type $(typeof(g)). Metadata $(metadata) will be ignored." ) return add_edge!(g, src, dst) end function _get_edge_weight( g::Graphs.SimpleGraphs.AbstractSimpleGraph{T}, src::T, dst::T, weighttype::Type{U} ) where {T,U<:Real} return one(U) end # `_get_edge_metadata` must return NamedTuple() (or maybe `nothing` would be better?) instead of throwing an exception in order for `edges` to consistently work on layers and interlayers function _get_edge_metadata( g::Graphs.SimpleGraphs.AbstractSimpleGraph{T}, src::T, dst::T ) where {T} return NamedTuple() end
MultilayerGraphs
https://github.com/JuliaGraphs/MultilayerGraphs.jl.git