From 26e94773d5578dc11fb82b73a2e1901f268a3140 Mon Sep 17 00:00:00 2001 From: Oscar Dowson Date: Mon, 22 Jul 2024 15:50:57 +1200 Subject: [PATCH] Fix performance issue in _canonical_quadratic_reduction (#296) --- Project.toml | 4 ++-- src/KNITRO.jl | 1 - src/MOI_wrapper.jl | 10 +++++----- 3 files changed, 7 insertions(+), 8 deletions(-) diff --git a/Project.toml b/Project.toml index c2cb013..fff14aa 100644 --- a/Project.toml +++ b/Project.toml @@ -6,7 +6,6 @@ version = "0.14.2" [deps] Libdl = "8f399da3-3557-5675-b5ff-fb832c97cbdb" MathOptInterface = "b8f27783-ece8-5eb3-8dc8-9495eed66fee" -SparseArrays = "2f01184e-e22b-5df5-ae63-d93ebab69eaf" [compat] Libdl = "<0.0.1, 1.6" @@ -18,7 +17,8 @@ julia = "1.6" [extras] Printf = "de0858da-6303-5e67-8744-51eddeeeb8d7" +SparseArrays = "2f01184e-e22b-5df5-ae63-d93ebab69eaf" Test = "8dfed614-e22c-5e08-85e1-65c5234f0b40" [targets] -test = ["Test", "Printf"] +test = ["Printf", "SparseArrays", "Test"] diff --git a/src/KNITRO.jl b/src/KNITRO.jl index fa335a1..baa4b35 100644 --- a/src/KNITRO.jl +++ b/src/KNITRO.jl @@ -7,7 +7,6 @@ module KNITRO import Libdl import MathOptInterface as MOI -import SparseArrays const _DEPS_FILE = joinpath(dirname(@__FILE__), "..", "deps", "deps.jl") if isfile(_DEPS_FILE) diff --git a/src/MOI_wrapper.jl b/src/MOI_wrapper.jl index 1bb4fef..4f40317 100644 --- a/src/MOI_wrapper.jl +++ b/src/MOI_wrapper.jl @@ -18,8 +18,11 @@ const _SETS = Union{ } function _canonical_quadratic_reduction(f::MOI.ScalarQuadraticFunction) - I = Cint[term.variable_1.value for term in f.quadratic_terms] - J = Cint[term.variable_2.value for term in f.quadratic_terms] + if !MOI.Utilities.is_canonical(f) + f = MOI.Utilities.canonicalize!(copy(f)) + end + I = Cint[_c_column(term.variable_1) for term in f.quadratic_terms] + J = Cint[_c_column(term.variable_2) for term in f.quadratic_terms] V = Cdouble[term.coefficient for term in f.quadratic_terms] for i in 1:length(V) if I[i] == J[i] @@ -28,9 +31,6 @@ function _canonical_quadratic_reduction(f::MOI.ScalarQuadraticFunction) I[i], J[i] = J[i], I[i] end end - I, J, V = SparseArrays.findnz(SparseArrays.sparse(I, J, V)) - I .-= Cint(1) - J .-= Cint(1) return return length(I), I, J, V end