# Nearest correlation

This example illustrates the sensitivity analysis of the nearest correlation problem studied in [H02].

Higham, Nicholas J. Computing the nearest correlation matrix—a problem from finance. IMA journal of Numerical Analysis 22.3 (2002): 329-343.

using DiffOpt, JuMP, SCS, LinearAlgebra
solver = SCS.Optimizer

function proj(A, dH = Diagonal(ones(size(A, 1))), H = ones(size(A)))
n = LinearAlgebra.checksquare(A)
model = Model(() -> DiffOpt.diff_optimizer(solver))
@variable(model, X[1:n, 1:n] in PSDCone())
@constraint(model, [i in 1:n], X[i, i] == 1)
@objective(model, Min, sum((H .* (X - A)) .^ 2))
MOI.set(
model,
DiffOpt.ForwardObjectiveFunction(),
sum((dH .* (X - A)) .^ 2),
)
optimize!(model)
DiffOpt.forward_differentiate!(model)
dX = MOI.get.(model, DiffOpt.ForwardVariablePrimal(), X)
return value.(X), dX
end
proj (generic function with 3 methods)

Example from [H02, p. 334-335]:

A = LinearAlgebra.Tridiagonal(ones(2), ones(3), ones(2))
3×3 LinearAlgebra.Tridiagonal{Float64, Vector{Float64}}:
1.0  1.0   ⋅
1.0  1.0  1.0
⋅   1.0  1.0

The projection is computed as follows:

X, dX = proj(A)

The projection of A is:

X
3×3 Matrix{Float64}:
1.0       0.760692  0.157299
0.760692  1.0       0.760692
0.157299  0.760692  1.0

The derivative of the projection with respect to a uniform increase of the weights of the diagonal entries is:

dX
3×3 Matrix{Float64}:
4.51811e-10  -0.320667     0.388476
-0.320667     -4.95757e-9  -0.320667
0.388476     -0.320667     1.01046e-8

Example from [H02, Section 4, p. 340]:

A = LinearAlgebra.Tridiagonal(-ones(3), 2ones(4), -ones(3))
4×4 LinearAlgebra.Tridiagonal{Float64, Vector{Float64}}:
2.0  -1.0    ⋅     ⋅
-1.0   2.0  -1.0    ⋅
⋅   -1.0   2.0  -1.0
⋅     ⋅   -1.0   2.0

The projection is computed as follows:

X, dX = proj(A)

The projection of A is:

X
4×4 Matrix{Float64}:
1.0       -0.808429   0.191591   0.106775
-0.808429   1.0       -0.656241   0.191591
0.191591  -0.656241   1.0       -0.808429
0.106775   0.191591  -0.808429   1.0

The derivative of the projection with respect to a uniform increase of the weights of the diagonal entries is:

dX
4×4 Matrix{Float64}:
0.101794    0.228659   -0.0880999  -0.0490992
0.228659    0.0565821   0.158679   -0.0880999
-0.0880999   0.158679    0.0565821   0.228659
-0.0490992  -0.0880999   0.228659    0.101794