/
simple_interface.jl
105 lines (84 loc) · 2.32 KB
/
simple_interface.jl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
"""
nearest_cor!(A, alg=nothing; kwargs...)
Return the nearest positive definite correlation matrix to ``A``.
This method will overwrite ``A``.
This is a "batteries included" method, and is designed to just work with as little thought
as possible. Unlike `solve!`, this method will return the nearest correlation matrix
directly instead of a `NCMSolution` object. Additionally the solution is checked to be
positive definite, and corrected if it is not.
# Examples
```julia-repl
julia> import LinearAlgebra: isposdef
julia> r = [
1.00 0.82 0.56 0.44
0.82 1.00 0.28 0.85
0.56 0.28 1.00 0.22
0.44 0.85 0.22 1.00
];
julia> isposdef(r)
false
julia> nearest_cor!(r)
4×4 Matrix{Float64}:
1.0 0.817095 0.559306 0.440514
0.817095 1.0 0.280196 0.847352
0.559306 0.280196 1.0 0.219582
0.440514 0.847352 0.219582 1.0
julia> isposdef(r)
true
```
"""
function nearest_cor!(A, alg; kwargs...)
sol = solve(
NCMProblem(A),
alg;
alias_A=true,
fix_sym=true,
convert_f16=true,
ensure_pd=true,
kwargs...
)
copyto!(A, sol.X)
return A
end
nearest_cor!(A; kwargs...) = nearest_cor!(A, nothing; kwargs...)
"""
nearest_cor(A, alg; kwargs...)
Return the nearest positive definite correlation matrix to ``A``.
This is a "batteries included" method, and is designed to just work with as little thought
as possible. Unlike `solve!`, this method will return the nearest correlation matrix
directly instead of a `NCMSolution` object. Additionally the solution is checked to be
positive definite, and corrected if it is not.
# Examples
```julia-repl
julia> import LinearAlgebra: isposdef
julia> r = [
1.00 0.82 0.56 0.44
0.82 1.00 0.28 0.85
0.56 0.28 1.00 0.22
0.44 0.85 0.22 1.00
];
julia> isposdef(r)
false
julia> p = nearest_cor(r)
4×4 Matrix{Float64}:
1.0 0.817095 0.559306 0.440514
0.817095 1.0 0.280196 0.847352
0.559306 0.280196 1.0 0.219582
0.440514 0.847352 0.219582 1.0
julia> isposdef(p)
true
```
"""
function nearest_cor(A, alg; kwargs...)
sol = solve(
NCMProblem(A),
alg;
alias_A=false,
fix_sym=true,
convert_f16=true,
ensure_pd=true,
kwargs...
)
return sol.X
end
nearest_cor(A; kwargs...) = nearest_cor(A, nothing; kwargs...)