-
Notifications
You must be signed in to change notification settings - Fork 3
/
specialsolver.jl
338 lines (313 loc) · 11.3 KB
/
specialsolver.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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
## Specialized solver for sparse symmetric integer linear systems with exact rational solution
include("Modulos.jl")
using .Modulos
import Base.GMP: MPZ
import LinearAlgebra: BlasInt, checknonsingular, LU, tril!, triu!, ipiv2perm,
lu, lu!, ldiv!, Factorization, issuccess
using SparseArrays
import SparseArrays: getcolptr
using BigRationals
function rational_lu!(B::SparseMatrixCSC, col_offset, check=true)
Tf = eltype(B)
m, n = size(B)
minmn = min(m, n)
info = 0
@inbounds begin
for k in 1:minmn
ipiv = getcolptr(B)[k] + col_offset[k]
piv = nonzeros(B)[ipiv]
if iszero(piv)
check && checknonsingular(k-1, Val(false)) # TODO update with Pivot
return LU{Tf,SparseMatrixCSC{Tf,Int}}(B, collect(1:minmn), convert(BlasInt, k-1))
end
Bkkinv = inv(piv)
@simd for i in ipiv+1:getcolptr(B)[k+1]-1
nonzeros(B)[i] *= Bkkinv
end
for j in k+1:n
r1 = getcolptr(B)[j]
r2 = getcolptr(B)[j+1]-1
r = searchsortedfirst(rowvals(B), k, r1, r2, Base.Forward)
((r > r2) || (rowvals(B)[r] != k)) && continue
Bkj = nonzeros(B)[r]
for i in ipiv+1:getcolptr(B)[k+1]-1
Bik = nonzeros(B)[i]
l = i - ipiv
while rowvals(B)[l+r] < rowvals(B)[i]
r += 1
end
nonzeros(B)[l+r] -= Bik * Bkj
end
end
end
end
check && checknonsingular(info, Val(false))
return LU{Tf,SparseMatrixCSC{Tf,Int}}(B, Vector{BlasInt}(1:minmn), convert(BlasInt, info))
end
# function lu!(B::SparseMatrixCSC{<:Rational}, ::Val{Pivot} = Val(false);
# col_offset, check::Bool = true) where Pivot
function rational_lu!(B::SparseMatrixCSC{BigRational}, col_offset, check::Bool=true)
Tf = Rational{BigInt}
m, n = size(B)
minmn = min(m, n)
info = 0
Bkkinv = BigRational()
tmp = BigRational()
@inbounds begin
for k in 1:minmn
ipiv = getcolptr(B)[k] + col_offset[k]
piv = nonzeros(B)[ipiv]
if iszero(piv)
check && checknonsingular(k-1, Val(false)) # TODO update with Pivot
return LU{Tf,SparseMatrixCSC{Tf,Int}}(B, collect(1:minmn), convert(BlasInt, k-1))
end
BigRationals.inv!(Bkkinv, piv)
@simd for i in ipiv+1:getcolptr(B)[k+1]-1
BigRationals.mul!(nonzeros(B)[i], Bkkinv)
end
for j in k+1:n
r1 = getcolptr(B)[j]
r2 = getcolptr(B)[j+1]-1
r = searchsortedfirst(rowvals(B), k, r1, r2, Base.Forward)
((r > r2) || (rowvals(B)[r] != k)) && continue
Bkj = nonzeros(B)[r]
for i in ipiv+1:getcolptr(B)[k+1]-1
Bik = nonzeros(B)[i]
l = i - ipiv
while rowvals(B)[l+r] < rowvals(B)[i]
r += 1
end
# Base.GMP.MPZ.mul!(tmp, Bik, Bkj)
# Base.GMP.MPZ.sub!(nonzeros(B)[l+r], tmp)
BigRationals.mul!(tmp, Bik, Bkj)
BigRationals.sub!(nonzeros(B)[l+r], tmp)
end
end
end
end
check && checknonsingular(info, Val(false))
return LU{Tf,SparseMatrixCSC{Tf,Int}}(Tf.(B), Vector{BlasInt}(1:minmn), convert(BlasInt, info))
end
# function lu(A::SparseMatrixCSC{<:Rational}, pivot::Union{Val{false}, Val{true}} = Val(false); check::Bool = true)
function rational_lu(A::SparseMatrixCSC, check::Bool=true, ::Type{Ti}=BigRational) where {Ti}
Tf = Ti == BigRational ? Rational{BigInt} : Ti
Base.require_one_based_indexing(A)
_I, _J, _V = findnz(A)
I, J, V = issorted(_J) ? (_I, _J, _V) : begin
_indices = sortperm(_J)
@inbounds (_I[_indices], _J[_indices], _V[_indices])
end
# @inbounds if !issorted(_J)
# indices = sortperm(J)
# I = I[indices]; J = J[indices]; V = V[indices]
# end
isempty(J) && return LU{Tf,SparseMatrixCSC{Tf,Int}}(A, Int[], convert(BlasInt, 0))
m, n = size(A)
minmn = min(m, n)
if J[1] != 1 || I[1] != 1
check && checknonsingular(1, Val(false)) # TODO update with Pivot
# return LU{eltype(A), typeof(A)}(A, collect(1:minmn), convert(BlasInt, 1))
return LU{Tf,SparseMatrixCSC{Tf,Int}}(A, collect(1:minmn), convert(BlasInt, 1))
end
col_offset = zeros(Int, minmn) # for each col, index of the pivot element
idx_cols = [[I[i] for i in getcolptr(A)[col+1]-1:-1:getcolptr(A)[col]] for col in 1:minmn]
# For each column, indices of the non-zeros elements
@inbounds for col in 2:minmn
sort!(idx_cols[col-1]; rev=true)
# All idx_added_cols[x] are sorted by decreasing order for x < col
for row_j in idx_cols[col]
row_j >= col && continue
col_offset[col] += 1
for row_i in idx_cols[row_j]
row_i <= row_j && break # Because the row_i are sorted in decreasing order
row_i ∈ idx_cols[col] && continue
push!(idx_cols[col], row_i)
push!(J, col)
push!(I, row_i)
push!(V, 0)
end
end
end
B = sparse(I, J, Ti.(V)) # TODO update with Pivot
# lu!(B, col_offset, check)
rational_lu!(B, col_offset, check)
end
#=
function lu(A::Hermitian{T, <:SparseMatrixCSC{T}}, pivot::Union{Val{false}, Val{true}} = Val(false); check::Bool = true) where {T<:Rational, Pivot}
lu(ishermitian(A.data) ? A.data : sparse(A), pivot)
end
function Base.getproperty(F::LU{T,<:SparseMatrixCSC{<:Rational{<:Integer}, <:Integer}}, d::Symbol) where T
m, n = size(F)
if d === :L
L = tril!(getfield(F, :factors)[1:m, 1:min(m,n)])
for i = 1:min(m,n); L[i,i] = one(T); end
return L
elseif d === :U
return triu!(getfield(F, :factors)[1:min(m,n), 1:n])
elseif d === :p
return ipiv2perm(getfield(F, :ipiv), m)
elseif d === :P
return Matrix{T}(LinearAlgebra.I, m, m)[:,invperm(F.p)]
else
getfield(F, d)
end
end
=#
function forward_substitution!(L::SparseMatrixCSC, b)
_, n = size(L)
@inbounds for col in 1:n
i = getcolptr(L)[col]
rowvals(L)[i] == col || checknonsingular(col, Val(true))
x = b[col,:] / nonzeros(L)[i]
b[col,:] .= x
@simd for i in (i+1):getcolptr(L)[col+1]-1
b[rowvals(L)[i],:] .-= nonzeros(L)[i]*x
end
end
nothing
end
function backward_substitution!(U::SparseMatrixCSC, b)
_, n = size(U)
@inbounds for col in n:-1:1
i = getcolptr(U)[col+1]-1
rowvals(U)[i] == col || checknonsingular(col, Val(true))
x = b[col,:] / nonzeros(U)[i]
b[col,:] .= x
@simd for i in (i-1):-1:getcolptr(U)[col]
b[rowvals(U)[i],:] .-= nonzeros(U)[i]*x
end
end
nothing
end
function linsolve!(F::LU{<:Any,<:AbstractSparseMatrix}, B::Base.StridedVecOrMat)
TFB = typeof(oneunit(eltype(B)) / oneunit(eltype(F)))
BB = similar(B, TFB, size(B))
copyto!(BB, B)
m, n = size(F)
minmn = min(m,n)
L = tril!(getfield(F, :factors)[1:m, 1:minmn])
for i = 1:minmn; L[i,i] = 1; end
forward_substitution!(L, BB)
backward_substitution!(triu!(getfield(F, :factors)[1:minmn, 1:n]), BB)
return BB
end
#=
function ldiv!(F::LU{<:Any,<:AbstractSparseMatrix}, B::Base.StridedVecOrMat)
forward_substitution!(F.L, B)
backward_substitution!(F.U, B)
return B
end
=#
function rational_solve(::Val{N}, A, Y) where N
B = rational_lu(A, false)
if !issuccess(B)
throw("Singular exception while equilibrating. Is the graph connected?")
end
Z = linsolve!(B, Rational{BigInt}.(Y))
return hcat(zeros(Rational{Int128}, N), Rational{Int128}.(Z)')
# Rational{Int64} is not enough for tep for instance.
end
function dixon_p(::Val{N}, A, C::Factorization{Modulo{p,T}}, Y) where {N,p,T}
λs = [norm(x) for x in eachcol(A)]
append!(λs, [norm(x) for x in eachcol(Y)])
partialsort!(λs, N)
for _ in 1:N
popfirst!(λs)
end
δ = prod(BigFloat, λs; init=one(BigFloat))
# @show δ
# @show p
m = ceil(Int, 2*log(δ / (MathConstants.φ - 1))/log(p))
@assert m ≥ 1
# @show m
B = copy(Y)
x̄ = BigInt.(linsolve!(C, B))
X = copy(x̄)
@assert A * Modulo{p,T}.(X) == B
h = one(BigInt) # = p^i
tmp = BigInt()
for i in 1:m-1
MPZ.mul_si!(h, p)
B .= (B .- A*Integer.(X)) .÷ p
X .= Integer.(linsolve!(C, B))
@assert A * Modulo{p,T}.(X) == B
# x̄ .+= h .* X
@inbounds for j in eachindex(x̄)
MPZ.mul!(tmp, X[j], h)
MPZ.add!(x̄[j], tmp)
end
end
MPZ.mul_si!(h, p) # h = p^m
@assert mod.(A * x̄, h) == mod.(Y, h)
sqh = MPZ.sqrt(h) # h = p^{m/2}
Z = similar(Y, Rational{Int128})
for j in eachindex(Z)
ua = MPZ.set(h)
ub = @inbounds x̄[j]
va = Int128(0)
vb = Int128(1)
k = 0
while ub >= sqh
k += 1
# cpua = deepcopy(ua)
# cpub = deepcopy(ub)
MPZ.tdiv_qr!(tmp, ua, ua, ub)
ua, ub = ub, ua
# @assert tmp == cpua ÷ cpub
# @assert ua == cpub
# @assert ub == cpua - tmp * cpub
# cpuc = deepcopy(va)
if typemin(Clong) < vb < typemax(Clong)
MPZ.mul_si!(tmp, vb % Clong)
else
tmp *= vb
end
flag = signbit(va)
va = abs(va)
if va < typemax(Culong)
if flag
MPZ.sub_ui!(tmp, va)
else
MPZ.add_ui!(tmp, va)
end
va, vb = vb, Int128(tmp)
else
va, vb = vb, va + tmp
end
# @assert vb == cpuc + tmp * va
end
@inbounds Z[j] = (-1)^isodd(k) * Rational{Int128}(ub, vb)
# @show Z[j]
# @assert mod((-1)^isodd(k) * ub, h) == mod(vb * x̄[j], h)
end
@assert eltype(Y).(A * big.(Z)) == Y
return Z
# return hcat(zeros(Rational{Int128}, N), Rational{Int128}.(x̄)')
# Rational{Int64} is not enough for tep for instance.
end
"""
dixon_solve(::Val{N}, A, Y) where N
Specialized solver for the linear system `A*X = Y` where `A` is a sparse symmetric
integer `n×n` matrix and `Y` is a dense integer `n×N` matrix, using Dixon's method.
Return `X` as a matrix of `Rational{Int128}`.
"""
function dixon_solve(::Val{N}, A, Y) where N
# @show time_ns()
B = rational_lu(A, false, Modulo{2147483647,Int32})
if issuccess(B)
Z = Rational{Int128}.(dixon_p(Val(N), A, B, Y)')
else
B = rational_lu(A, false, Modulo{2147483629,Int32})
if issuccess(B)
Z = Rational{Int128}.(dixon_p(Val(N), A, B, Y)')
else
B = rational_lu(A, false, Modulo{2147483629,Int32})
if issuccess(B)
Z = Rational{Int128}.(dixon_p(Val(N), A, B, Y)')
else
return rational_solve(Val(N), A, Y)
end
end
end
return hcat(zeros(Rational{Int128}, N), Z)
end