/
certification.jl
1657 lines (1452 loc) · 51.6 KB
/
certification.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
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using Arblib: Acb, AcbRef, AcbVector, AcbRefVector, AcbMatrix, AcbRefMatrix
export certify,
SolutionCertificate,
CertificationResult,
CertificationCache,
is_certified,
is_real,
is_complex,
is_positive,
solution_candidate,
certified_solution_interval,
certified_solution_interval_after_krawczyk,
certificate_index,
solution_approximation,
certificates,
distinct_certificates,
distinct_solutions,
ncertified,
nreal_certified,
ncomplex_certified,
ndistinct_certified,
ndistinct_real_certified,
ndistinct_complex_certified,
show_straight_line_program,
save,
DistinctCertifiedSolutions,
add_solution!,
solutions,
certificates,
distinct_certified_solutions,
distinct_certified_solutions!,
# deprecated
initial_solution,
certified_solution
abstract type AbstractSolutionCertificate end
"""
SolutionCertificate
Result of [`certify`](@ref) for a single solution. Contains the initial solutions
and if the certification was successfull a vector of complex intervals where the true
solution is contained in.
"""
Base.@kwdef struct SolutionCertificate <: AbstractSolutionCertificate
solution_candidate::AbstractVector
certified::Bool
real::Bool = false
complex::Bool = false
index::Union{Nothing,Int} = nothing
prec::Int = 53
I::Union{Nothing,AcbMatrix} = nothing
# We also store a double precision representation of the midpoint of x₁
# as the best available double precision estimate of the solution
solution::Union{Nothing,Vector{ComplexF64}} = nothing
end
Base.@kwdef struct ExtendedSolutionCertificate <: AbstractSolutionCertificate
solution_candidate::AbstractVector
certified::Bool
real::Bool = false
complex::Bool = false
index::Union{Nothing,Int} = nothing
prec::Int = 53
# I, I′ ∈ 𝕀ℂⁿ and a certified solution has I′ ⊊ I
I::Union{Nothing,AcbMatrix} = nothing
I′::Union{Nothing,AcbMatrix} = nothing
x̃::Union{Nothing,AcbMatrix} = nothing
Y::Union{Nothing,AcbMatrix} = nothing
# We also store a double precision representation of the midpoint of x₁
# as the best available double precision estimate of the solution
solution::Union{Nothing,Vector{ComplexF64}} = nothing
end
"""
solution_candidate(certificate::AbstractSolutionCertificate)
Returns the given provided solution candidate.
"""
solution_candidate(C::AbstractSolutionCertificate) = C.solution_candidate
@deprecate initial_solution(cert::AbstractSolutionCertificate) solution_candidate(cert)
"""
is_certified(certificate::AbstractSolutionCertificate)
Returns `true` if `certificate` is a certificate that `certified_solution_interval(certificate)`
contains a unique zero.
"""
is_certified(C::AbstractSolutionCertificate) = C.certified
"""
is_real(certificate::AbstractSolutionCertificate)
Returns `true` if `certificate` certifies that the certified solution interval
contains a true real zero of the system.
If `false` is returned then this does not necessarily mean that the true solution is not real.
"""
is_real(C::AbstractSolutionCertificate) = C.real
"""
is_complex(certificate::AbstractSolutionCertificate)
Returns `true` if `certificate` certifies that the certified solution interval
contains a non-real complex zero of the system.
"""
is_complex(C::AbstractSolutionCertificate) = C.complex
"""
is_positive(certificate::AbstractSolutionCertificate)
Returns `true` if `is_certified(certificate)` is `true` and the unique zero contained
in `certified_solution_interval(certificate)` is real and positive.
"""
function is_positive(C::AbstractSolutionCertificate)
if !is_certified(C) || !is_real(C)
return false
else
all(i -> Arblib.is_positive(real(Arblib.ref(C.I, i, 1))), 1:length(C.I))
end
end
"""
is_positive(certificate::AbstractSolutionCertificate, i)
Returns `true` if `is_certified(certificate)` is `true` and `i`-th coordinate of the
unique zero contained in `certified_solution_interval(certificate)` is real and positive.
"""
function is_positive(C::AbstractSolutionCertificate, i::Integer)
if !is_certified(C) || !is_real(C)
return false
else
Arblib.is_positive(real(Arblib.ref(C.I, i, 1)))
end
end
"""
certified_solution_interval(certificate::AbstractSolutionCertificate)
Returns an `Arblib.AcbMatrix` representing a vector of complex intervals where a unique
zero of the system is contained in.
Returns `nothing` if `is_certified(certificate)` is `false`.
"""
certified_solution_interval(certificate::AbstractSolutionCertificate) = certificate.I
@deprecate certified_solution(certificate) certified_solution_interval(certificate)
"""
certified_solution_interval_after_krawczyk(certificate::ExtendedSolutionCertificate)
Returns an `Arblib.AcbMatrix` representing a vector of complex intervals where a unique
zero of the system is contained in.
This is the result of applying the Krawczyk operator to `certified_solution_interval(certificate)`.
Returns `nothing` if `is_certified(certificate)` is `false`.
"""
certified_solution_interval_after_krawczyk(certificate::ExtendedSolutionCertificate) =
certificate.I′
"""
certificate_index(certificate::AbstractSolutionCertificate)
Return the index of the solution certificate. Here the index refers to the index of the
provided solution candidates.
"""
certificate_index(C::AbstractSolutionCertificate) = C.index
"""
precision(certificate::AbstractSolutionCertificate)
Returns the maximal precision used to produce the given `certificate`.
"""
Base.precision(certificate::AbstractSolutionCertificate) = certificate.prec
"""
solution_approximation(certificate::AbstractSolutionCertificate)
If `is_certified(certificate)` is `true` this returns the midpoint of the
[`certified_solution_interval`](@ref) of the given `certificate` as a `Vector{ComplexF64}`.
Returns `nothing` if `is_certified(certificate)` is `false`.
"""
solution_approximation(certificate::AbstractSolutionCertificate) = certificate.solution
"""
krawczyk_operator_parameters(cert::ExtendedSolutionCertificate)
Returns a `NamedTuple` `(x, Y)` with the parameters of the Krawczyk operator following [BRT20].
"""
krawczyk_operator_parameters(cert::ExtendedSolutionCertificate) = (x = cert.x̃, Y = cert.Y)
function Base.show(f::IO, cert::AbstractSolutionCertificate)
println(f, "SolutionCertificate:")
println(f, "solution_candidate = [")
for z in solution_candidate(cert)
print(f, " ")
print(f, z)
println(f, ",")
end
println(f, "]")
print(f, "is_certified = ", is_certified(cert))
if !isnothing(certified_solution_interval(cert))
println(f)
println(f, "certified_solution_interval = [")
for z in certified_solution_interval(cert)
print(f, " ")
print(f, z)
println(f, ",")
end
println(f, "]")
println(f, "precision = ", cert.prec)
print(f, "is_real = ", is_real(cert))
end
if !isnothing(cert.index)
println(f)
print(f, "index = ", cert.index)
end
end
"""
squared_distance_interval(cert, reference_point::Vector{ComplexF64})
Calculate the squared distance between a solution certificate and a reference point.
"""
function squared_distance_interval(
cert::AbstractSolutionCertificate,
reference_point::Vector{ComplexF64},
)
a, b = Arblib.Arf(prec = 53), Arblib.Arf(prec = 53)
n = length(solution_candidate(cert))
d = zero(IntervalArithmetic.Interval{Float64})
for i = 1:n
yᵢ = IComplexF64(cert.I[i], a, b)
d +=
IntervalArithmetic.sqr(real(yᵢ) - real(reference_point[i])) +
IntervalArithmetic.sqr(imag(yᵢ) - imag(reference_point[i]))
end
return IntervalTrees.Interval(d.lo, d.hi)
end
"""
squared_distance_interval(solution_candidate, reference_point::Vector{ComplexF64})
Calculate the squared distance between a solution certificate and a reference point.
"""
function squared_distance_interval(
solution_candidate::AbstractVector{ComplexF64},
reference_point::Vector{ComplexF64},
)
n = length(solution_candidate)
d = zero(IntervalArithmetic.Interval{Float64})
for i = 1:n
yᵢ = IComplexF64(solution_candidate[i])
d +=
IntervalArithmetic.sqr(real(yᵢ) - real(reference_point[i])) +
IntervalArithmetic.sqr(imag(yᵢ) - imag(reference_point[i]))
end
return IntervalTrees.Interval(d.lo, d.hi)
end
"""
struct DistinctSolutionCertificates
A struct that holds a reference point and an interval tree of distinct solution certificates.
"""
struct DistinctSolutionCertificates{S<:AbstractSolutionCertificate}
reference_point::Vector{ComplexF64}
distinct_tree::IntervalTrees.IntervalMap{Float64,S}
acb_solution_candidate::AcbMatrix
end
"""
DistinctSolutionCertificates(dim::Integer)
Create a DistinctSolutionCertificates object with a random reference point of the given dimension.
"""
DistinctSolutionCertificates(dim::Integer; kwargs...) =
DistinctSolutionCertificates(randn(ComplexF64, dim); kwargs...)
"""
DistinctSolutionCertificates(reference_point::Vector{ComplexF64})
Create a DistinctSolutionCertificates object with the given reference point.
"""
DistinctSolutionCertificates(
reference_point::Vector{ComplexF64};
extended_certificate::Bool = false,
) = DistinctSolutionCertificates(
reference_point,
IntervalTrees.IntervalMap{
Float64,
extended_certificate ? ExtendedSolutionCertificate : SolutionCertificate,
}(),
AcbMatrix(length(reference_point), 1),
)
"""
length(d::DistinctSolutionCertificates)
Return the number of distinct solution certificates in the interval tree.
"""
Base.length(d::DistinctSolutionCertificates) = length(d.distinct_tree)
Base.show(io::IO, d::DistinctSolutionCertificates) =
print(io, "DistinctSolutionCertificates with $(length(d)) certificates")
"""
add_certificate!(distinct_sols::DistinctSolutionCertificates, cert::SolutionCertificate)
Add a solution certificate to the interval tree if it is not a duplicate.
"""
function add_certificate!(
distinct_sols::DistinctSolutionCertificates,
cert::AbstractSolutionCertificate,
)
d = squared_distance_interval(cert, distinct_sols.reference_point)
for match in IntervalTrees.intersect(distinct_sols.distinct_tree, d)
certᵢ = IntervalTrees.value(match)
if Bool(Arblib.overlaps(cert.I, certᵢ.I))
return (false, certᵢ)
break
end
end
distinct_sols.distinct_tree[d] = cert
return (true, cert)
end
"""
is_solution_candidate_guaranteed_duplicate(distinct_sols::DistinctSolutionCertificates, s::Vector{ComplexF64})
Check if a solution candidate is a duplicate. This is the case if the point is within some certificate's interval.
"""
function is_solution_candidate_guaranteed_duplicate(
distinct_sols::DistinctSolutionCertificates,
s::Vector{ComplexF64},
)
d = squared_distance_interval(s, distinct_sols.reference_point)
assigned = false
for match in IntervalTrees.intersect(distinct_sols.distinct_tree, d)
certᵢ = IntervalTrees.value(match)
if !assigned
for (i, xᵢ) in enumerate(s)
distinct_sols.acb_solution_candidate[i] = xᵢ
end
end
# Check if s is contained in certᵢ.I
if Bool(Arblib.contains(certᵢ.I, distinct_sols.acb_solution_candidate))
return true
break
end
end
return false
end
"""
build_distinct_solution_certificates(certs::AbstractVector{SolutionCertificate})
Create a DistinctSolutionCertificates object from a vector of solution certificates.
"""
function build_distinct_solution_certificates(
certs::AbstractVector{<:AbstractSolutionCertificate},
)
distinct_sols = DistinctSolutionCertificates(length(solution_candidate(first(certs))))
for cert in certs
add_certificate!(distinct_sols, cert)
end
return distinct_sols
end
"""
CertificationResult
The result of [`certify`](@ref) for multiple solutions.
Contains a vector of [`SolutionCertificate`](@ref) as well as a list of certificates
which correspond to the same true solution.
"""
struct CertificationResult{C<:AbstractSolutionCertificate}
certificates::Vector{C}
duplicates::Vector{Vector{Int}}
slp::ModelKit.Interpreter{Vector{IComplexF64}}
slp_jacobian::ModelKit.Interpreter{Vector{IComplexF64}}
end
"""
certificates(R::CertificationResult)
Obtain the stored [`SolutionCertificate`](@ref)s.
"""
certificates(R::CertificationResult) = R.certificates
"""
distinct_certificates(R::CertificationResult)
Obtain the certificates corresponding to the determined distinct solution intervals.
"""
function distinct_certificates(C::CertificationResult)
cs = certificates(C)
isempty(C.duplicates) && return cs
indices = trues(length(cs))
for d in C.duplicates, k = 2:length(d)
indices[d[k]] = false
end
cs[indices]
end
"""
distinct_solutions(R::CertificationResult)
Obtain the certificates corresponding to the determined distinct solution intervals.
"""
function distinct_solutions(C::CertificationResult)
solution_approximation.(distinct_certificates(C))
end
"""
ncertified(R::CertificationResult)
Returns the number of certified solutions.
"""
ncertified(R::CertificationResult) = count(is_certified, R.certificates)
"""
nreal_certified(R::CertificationResult)
Returns the number of certified real solutions.
"""
nreal_certified(R::CertificationResult) =
count(r -> is_certified(r) && is_real(r), R.certificates)
"""
ncomplex_certified(R::CertificationResult)
Returns the number of certified complex solutions.
"""
ncomplex_certified(R::CertificationResult) =
count(r -> is_certified(r) && is_complex(r), R.certificates)
"""
ndistinct_certified(R::CertificationResult)
Returns the number of distinct certified solutions.
"""
function ndistinct_certified(R::CertificationResult)
ncert = ncertified(R)
if isempty(R.duplicates)
return ncert
else
return ncert - sum(length, R.duplicates) + length(R.duplicates)
end
end
"""
ndistinct_real_certified(R::CertificationResult)
Returns the number of distinct certified real solutions.
"""
function ndistinct_real_certified(R::CertificationResult)
ncert = nreal_certified(R)
if isempty(R.duplicates)
return ncert
else
ncert - sum(R.duplicates) do dup
is_real(R.certificates[dup[1]]) ? length(dup) - 1 : 0
end
end
end
"""
ndistinct_complex_certified(R::CertificationResult)
Returns the number of distinct certified complex solutions.
"""
function ndistinct_complex_certified(R::CertificationResult)
ncert = ncomplex_certified(R)
if isempty(R.duplicates)
return ncert
else
ncert - sum(R.duplicates) do dup
is_complex(R.certificates[dup[1]]) ? length(dup) - 1 : 0
end
end
end
"""
show_straight_line_program(R::CertificationResult)
show_straight_line_program(io::IO, R::CertificationResult)
Print a representation of the used straight line program.
"""
show_straight_line_program(R::CertificationResult) = show_straight_line_program(stdout, R)
show_straight_line_program(io::IO, R::CertificationResult) =
ModelKit.show_instructions(io, R.slp)
function Base.show(io::IO, R::CertificationResult)
println(io, "CertificationResult")
println(io, "===================")
println(io, "• $(length(R.certificates)) solution candidates given")
ncert = ncertified(R)
print(io, "• $ncert certified solution intervals")
nreal = nreal_certified(R)
ncomplex = ncomplex_certified(R)
print(io, " ($nreal real, $ncomplex complex")
if nreal + ncomplex < ncert
println(io, ", $(ncert - (nreal + ncomplex)) undecided)")
else
println(io, ")")
end
ndist_cert = ndistinct_certified(R)
print(io, "• $ndist_cert distinct certified solution intervals")
ndist_real = ndistinct_real_certified(R)
ndist_complex = ndistinct_complex_certified(R)
print(io, " ($ndist_real real, $ndist_complex complex")
if ndist_real + ndist_complex < ndist_cert
print(io, ", $(ndist_cert - (ndist_real + ndist_complex)) undecided)")
else
print(io, ")")
end
end
"""
save(filename, C::CertificationResult)
Store a text representation of the certification result `C` on disk.
"""
function save(filename, R::CertificationResult)
open(filename, "w") do f
println(f, "## Summary")
show(f, R)
println(f, "\n\n## Certificates")
for cert in certificates(R)
show(f, cert)
println(f)
end
end
filename
end
"""
CertificationCache(F::AbstractSystem)
Contains the necessary data structures for [`certify`](@ref).
"""
Base.@kwdef mutable struct CertificationCache
eval_interpreter_F64::ModelKit.Interpreter{Vector{IComplexF64}}
jac_interpreter_F64::ModelKit.Interpreter{Vector{IComplexF64}}
eval_interpreter_acb::ModelKit.Interpreter{AcbRefVector}
jac_interpreter_acb::ModelKit.Interpreter{AcbRefVector}
newton_cache::NewtonCache{MatrixWorkspace{Matrix{ComplexF64}}}
# data for krawczyc_step
C::Matrix{ComplexF64}
r₀::Vector{IComplexF64}
Δx₀::Vector{IComplexF64}
ix̃₀::Vector{IComplexF64}
Jx₀::Matrix{IComplexF64}
M::Matrix{IComplexF64}
δx::Vector{IComplexF64}
arb_prec::Int
arb_C::AcbRefMatrix
arb_r₀::AcbRefMatrix # m × 1
arb_Δx₀::AcbRefMatrix # m × 1
arb_x̃₀::AcbRefMatrix # m × 1
arb_x₀::AcbRefMatrix # m × 1
arb_x₁::AcbRefMatrix # m × 1
arb_J_x₀::AcbRefMatrix
arb_M::AcbRefMatrix
arb_δx::AcbRefMatrix # m × 1
arb_mag::Arblib.Mag
end
function CertificationCache(F::AbstractSystem)
m, n = size(F)
m == n || error("We can only certify square systems.")
f = System(F)
eval_interpreter_F64 = ModelKit.interpreter(IComplexF64, f)
jac_interpreter_F64 = ModelKit.jacobian_interpreter(IComplexF64, f)
eval_interpreter_acb = ModelKit.interpreter(AcbRefVector, eval_interpreter_F64)
jac_interpreter_acb = ModelKit.interpreter(AcbRefVector, jac_interpreter_F64)
arb_prec = 128
ModelKit.setprecision!(eval_interpreter_acb, arb_prec)
ModelKit.setprecision!(jac_interpreter_acb, arb_prec)
CertificationCache(;
eval_interpreter_F64 = eval_interpreter_F64,
jac_interpreter_F64 = jac_interpreter_F64,
eval_interpreter_acb = eval_interpreter_acb,
jac_interpreter_acb = jac_interpreter_acb,
newton_cache = NewtonCache(F; optimize_data_structure = false),
C = zeros(ComplexF64, m, m),
r₀ = zeros(IComplexF64, m),
Δx₀ = zeros(IComplexF64, m),
ix̃₀ = zeros(IComplexF64, m),
Jx₀ = zeros(IComplexF64, m, m),
M = zeros(IComplexF64, m, m),
δx = zeros(IComplexF64, m),
arb_prec = arb_prec,
arb_C = AcbRefMatrix(m, m; prec = arb_prec),
arb_r₀ = AcbRefMatrix(m, 1; prec = arb_prec),
arb_Δx₀ = AcbRefMatrix(m, 1; prec = arb_prec),
arb_x̃₀ = AcbRefMatrix(m, 1; prec = arb_prec),
arb_x₀ = AcbRefMatrix(m, 1; prec = arb_prec),
arb_x₁ = AcbRefMatrix(m, 1; prec = arb_prec),
arb_J_x₀ = AcbRefMatrix(m, m; prec = arb_prec),
arb_M = AcbRefMatrix(m, m; prec = arb_prec),
arb_δx = AcbRefMatrix(m, 1; prec = arb_prec),
arb_mag = Arblib.Mag(),
)
end
Base.setprecision(M::AcbRefMatrix, p::Int) = AcbRefMatrix(M.acb_mat, p)
function set_arb_precision!(cache::CertificationCache, p::Int)
cache.arb_prec == p && return cache
cache.arb_prec = p
cache.arb_r₀ = setprecision(cache.arb_r₀, p)
cache.arb_Δx₀ = setprecision(cache.arb_Δx₀, p)
cache.arb_x̃₀ = setprecision(cache.arb_x̃₀, p)
cache.arb_x₀ = setprecision(cache.arb_x₀, p)
cache.arb_x₁ = setprecision(cache.arb_x₁, p)
cache.arb_J_x₀ = setprecision(cache.arb_J_x₀, p)
cache.arb_M = setprecision(cache.arb_M, p)
cache.arb_δx = setprecision(cache.arb_δx, p)
ModelKit.setprecision!(cache.eval_interpreter_acb, p)
ModelKit.setprecision!(cache.jac_interpreter_acb, p)
cache
end
"""
certify(F, solutions, [p, certify_cache]; options...)
certify(F, result, [p, certify_cache]; options...)
Attempt to certify that the given approximate `solutions` correspond to true solutions
of the polynomial system ``F(x;p)``. The system ``F`` has to be an (affine) square
polynomial system. Also attemps to certify for each solutions whether it
approximates a real solution. The certification is done using interval arithmetic and the
Krawczyk method[^Moo77]. Returns a [`CertificationResult`](@ref) which additionall returns
the number of distinct solutions. For more details of the implementation see [^BRT20].
## Options
* `show_progress = true`: If `true` shows a progress bar of the certification process.
* `max_precision = 256`: The maximal accuracy (in bits) that is used in the certification process.
* `compile = false`: See the [`solve`](@ref) documentation.
## Example
We take the [first example](https://www.juliahomotopycontinuation.org/guides/introduction/#a-first-example) from our
introduction guide.
```julia
@var x y
# define the polynomials
f₁ = (x^4 + y^4 - 1) * (x^2 + y^2 - 2) + x^5 * y
f₂ = x^2+2x*y^2 - 2y^2 - 1/2
F = System([f₁, f₂], variables = [x,y])
result = solve(F)
```
```
Result with 18 solutions
========================
• 18 paths tracked
• 18 non-singular solutions (4 real)
• random seed: 0xcaa483cd
• start_system: :polyhedral
```
We see that we obtain 18 solutions and it seems that 4 solutions are real. However,
this is based on heuristics. To be absolute certain we can certify the result
```julia
certify(F, result)
```
```
CertificationResult
===================
• 18 solution candidates given
• 18 certified solution intervals (4 real, 14 complex)
• 18 distinct certified solution intervals (4 real, 14 complex)
```
and see that there are indeed 18 solutions and that they are all distinct.
[^Moo77]: Moore, Ramon E. "A test for existence of solutions to nonlinear systems." SIAM Journal on Numerical Analysis 14.4 (1977): 611-615.
[^BRT20]: Breiding, P., Rose, K. and Timme, S. "Certifying zeros of polynomial systems using interval arithmetic." arXiv:2011.05000.
"""
function certify end
struct CertificationParameters
params::Vector{ComplexF64}
interval_params::Vector{IComplexF64}
arb_interval_params::AcbRefVector
end
function CertificationParameters(p::AbstractVector; prec::Int = 256)
arb_ip = AcbRefVector(length(p); prec = prec)
for (i, p_i) in enumerate(p)
x = arb_ip[i]
x[] = p_i
end
CertificationParameters(
convert(Vector{ComplexF64}, p),
convert(Vector{IComplexF64}, p),
arb_ip,
)
end
certification_parameters(p::AbstractVector; prec::Int = 256) = CertificationParameters(p)
certification_parameters(::Nothing; prec::Int = 256) = nothing
complexF64_params(C::CertificationParameters) = C.params
complexF64_interval_params(C::CertificationParameters) = C.interval_params
arb_interval_params(C::CertificationParameters) = C.arb_interval_params
complexF64_params(::Nothing) = nothing
complexF64_interval_params(::Nothing) = nothing
arb_interval_params(::Nothing) = nothing
function _certify(
F::AbstractSystem,
solution_candidates::AbstractArray{<:AbstractArray{<:Number}},
p::Union{Nothing,CertificationParameters},
cache::CertificationCache;
show_progress::Bool = true,
check_distinct::Bool = true,
extended_certificate::Bool = false,
threading::Bool = true,
certify_solution_kwargs...,
)
N = length(solution_candidates)
certificates =
extended_certificate ? Vector{ExtendedSolutionCertificate}(undef, N) :
Vector{SolutionCertificate}(undef, N)
m, n = size(F)
m == n || throw(ArgumentError("We can only certify solutions to square systems."))
if isnothing(p) && nparameters(System(F)) > 0
throw(ArgumentError("The given system expects parameters but none are given."))
end
is_real_system = ModelKit.is_real(F)
distinct_sols =
DistinctSolutionCertificates(n; extended_certificate = extended_certificate)
ncertified = Threads.Atomic{Int}(0)
nreal_certified = Threads.Atomic{Int}(0)
nconsidered = Threads.Atomic{Int}(0)
ndistinct = Threads.Atomic{Int}(0)
ndistinct_real = Threads.Atomic{Int}(0)
desc = "Certifying $N solutions... "
barlen = min(ProgressMeter.tty_width(desc, stdout, false), 40)
progress = nothing
if show_progress
progress = ProgressMeter.Progress(
N;
dt = 0.2,
desc = desc,
barlen = barlen,
color = :green,
output = stdout,
)
progress.tlast += progress.dt
end
duplicates_dict = Dict{Int,Vector{Int}}()
if threading
distinct_lock = ReentrantLock()
nthreads = Threads.nthreads()
Tf = [F; [deepcopy(F) for _ = 2:nthreads]]
Tcache = [cache; [deepcopy(cache) for _ = 2:nthreads]]
Tp = [p; [deepcopy(p) for _ = 2:nthreads]]
Threads.@threads for i = 1:N
tid = Threads.threadid()
s = solution_candidates[i]
cert = certify_solution(
Tf[tid],
s,
Tp[tid],
Tcache[tid],
i,
is_real_system;
extended_certificate = extended_certificate,
certify_solution_kwargs...,
)
certificates[i] = cert
Threads.atomic_add!(nconsidered, 1)
if is_certified(cert)
Threads.atomic_add!(ncertified, 1)
Threads.atomic_add!(nreal_certified, Int(is_real(cert)))
@lock distinct_lock begin
(is_distinct, distinct_cert) = add_certificate!(distinct_sols, cert)
if is_distinct
Threads.atomic_add!(ndistinct, 1)
Threads.atomic_add!(ndistinct_real, Int(is_real(cert)))
else
if !haskey(duplicates_dict, distinct_cert.index)
duplicates_dict[distinct_cert.index] =
[distinct_cert.index, cert.index]
else
push!(duplicates_dict[distinct_cert.index], cert.index)
end
end
if !isnothing(progress)
update_certify_progress!(
progress,
nconsidered[],
ncertified[],
nreal_certified[],
ndistinct[],
ndistinct_real[],
)
end
end
else
@lock distinct_lock begin
if !isnothing(progress)
update_certify_progress!(
progress,
nconsidered[],
ncertified[],
nreal_certified[],
ndistinct[],
ndistinct_real[],
)
end
end
end
end
else
for i = 1:N
s = solution_candidates[i]
cert = certify_solution(
F,
s,
p,
cache,
i,
is_real_system;
extended_certificate = extended_certificate,
certify_solution_kwargs...,
)
certificates[i] = cert
Threads.atomic_add!(nconsidered, 1)
if is_certified(cert)
Threads.atomic_add!(ncertified, 1)
Threads.atomic_add!(nreal_certified, Int(is_real(cert)))
(is_distinct, distinct_cert) = add_certificate!(distinct_sols, cert)
if is_distinct
Threads.atomic_add!(ndistinct, 1)
Threads.atomic_add!(ndistinct_real, Int(is_real(cert)))
else
if !haskey(duplicates_dict, distinct_cert.index)
duplicates_dict[distinct_cert.index] =
[distinct_cert.index, cert.index]
else
push!(duplicates_dict[distinct_cert.index], cert.index)
end
end
end
if !isnothing(progress)
update_certify_progress!(
progress,
nconsidered[],
ncertified[],
nreal_certified[],
ndistinct[],
ndistinct_real[],
)
end
end
end
duplicates = isempty(duplicates_dict) ? Vector{Int}[] : collect(values(duplicates_dict))
CertificationResult(
certificates,
duplicates,
cache.eval_interpreter_F64,
cache.jac_interpreter_F64,
)
end
function update_certify_progress!(
progress,
k,
ncertified,
nreal_certified,
ndistinct,
ndistinct_real,
)
showvalues =
make_certify_showvalues(k, ncertified, nreal_certified, ndistinct, ndistinct_real)
ProgressMeter.update!(progress, k; showvalues = showvalues)
nothing
end
@noinline function make_certify_showvalues(
k,
ncertified,
nreal_certified,
ndistinct,
ndistinct_real,
)
(
("# processed", "$k"),
("# certified (real)", "$(ncertified) ($nreal_certified)"),
("# distinct (real)", "$(ndistinct) ($ndistinct_real)"),
)
end
function certify_solution(
F::AbstractSystem,
solution_candidate::AbstractVector,
cert_params::Union{Nothing,CertificationParameters},
cert_cache::CertificationCache,
index::Int;
max_precision::Int = 256,
refine_solution::Bool = true,
extended_certificate::Bool = false,
)
certify_solution(
F,
solution_candidate,
cert_params,
cert_cache,
index,
ModelKit.is_real(F);
max_precision = max_precision,
refine_solution = refine_solution,
extended_certificate = extended_certificate,
)
end
function certify_solution(
F::AbstractSystem,
solution_candidate::AbstractVector,
cert_params::Union{Nothing,CertificationParameters},
cert_cache::CertificationCache,
index::Int,
is_real_system::Bool;
max_precision::Int = 256,
refine_solution::Bool = true,
extended_certificate::Bool = false,
)
@unpack C, arb_C, arb_x̃₀ = cert_cache
# refine solution to machine precicision
if refine_solution
res = newton(
F,
solution_candidate,
complexF64_params(cert_params),
InfNorm(),
cert_cache.newton_cache;
rtol = 8 * eps(),
atol = 0.0,
# this should already be an approximate zero
extended_precision = true,
max_iters = 8,
)
x̃₀ = solution(res)
else
x̃₀ = solution_candidate
end
LA.inv!(C, cert_cache.newton_cache.J)
certified, x₁, x₀, is_real = ε_inflation_krawczyk(x̃₀, cert_params, C, cert_cache)
if !is_real_system
is_real = false
end
if certified
is_complex = any(xi -> !(0.0 in imag(xi)), x₁)