Optimization in Julia

This lecture gives an overview of some optimization tools in Julia.

In [29]:
versioninfo()
Julia Version 1.7.1
Commit ac5cc99908 (2021-12-22 19:35 UTC)
Platform Info:
  OS: macOS (x86_64-apple-darwin19.5.0)
  CPU: Intel(R) Core(TM) i7-6920HQ CPU @ 2.90GHz
  WORD_SIZE: 64
  LIBM: libopenlibm
  LLVM: libLLVM-12.0.1 (ORCJIT, skylake)
Environment:
  JULIA_EDITOR = code
  JULIA_NUM_THREADS = 4

Flowchart

  • Statisticians do optimizations in daily life: maximum likelihood estimation, machine learning, ...

  • Category of optimization problems:

    1. Problems with analytical solutions: least squares, principle component analysis, canonical correlation analysis, ...

    2. Problems subject to Disciplined Convex Programming (DCP): linear programming (LP), quadratic programming (QP), second-order cone programming (SOCP), semidefinite programming (SDP), and geometric programming (GP).

    3. Nonlinear programming (NLP): Newton type algorithms, Fisher scoring algorithm, EM algorithm, MM algorithms.

    4. Large scale optimization: ADMM, SGD, ...

Flowchart

Modeling tools and solvers

Getting familiar with good optimization softwares broadens the scope and scale of problems we are able to solve in statistics. Following table lists some of the best optimization softwares.

LP MILP SOCP MISOCP SDP GP NLP MINLP R Matlab Julia Python Cost
modeling tools
cvx x x x x x x x x x A
Convex.jl x x x x x x O
JuMP.jl x x x x x x x O
MathProgBase.jl x x x x x x x O
MathOptInterface.jl x x x x x x x O
convex solvers
Mosek x x x x x x x x x x x A
Gurobi x x x x x x x x A
CPLEX x x x x x x x x A
SCS x x x x x x O
COSMO.jl x x x x O
NLP solvers
NLopt x x x x x x O
Ipopt x x x x x x O
KNITRO x x x x x x x x $
  • O: open source
  • A: free academic license
  • $: commercial
  • Difference between modeling tool and solvers

    • Modeling tools such as cvx (for Matlab) and Convex.jl (Julia analog of cvx) implement the disciplined convex programming (DCP) paradigm proposed by Grant and Boyd (2008) http://stanford.edu/~boyd/papers/disc_cvx_prog.html. DCP prescribes a set of simple rules from which users can construct convex optimization problems easily.

    • Solvers (Mosek, Gurobi, Cplex, SCS, COSMO, ...) are concrete software implementation of optimization algorithms. My favorite ones are: Mosek/Gurobi/SCS for DCP and Ipopt/NLopt for nonlinear programming. Mosek and Gurobi are commercial software but free for academic use. SCS/Ipopt/NLopt are open source.

    • Modeling tools usually have the capability to use a variety of solvers. But modeling tools are solver agnostic so users do not have to worry about specific solver interface.

  • For this course, install following tools:

    • Gurobi: 1. Download Gurobi at link. 2. Request free academic license at link. 3. Run grbgetkey XXXXXXXXX command on terminal as suggested. It'll retrieve a license file and put it under the home folder. 4. Set up the environmental variables. On my machine, I put following two lines in the ~/.julia/config/startup.jl file: ENV["GUROBI_HOME"] = "/Library/gurobi902/mac64" and ENV["GRB_LICENSE_FILE"] = "/Users/huazhou/Documents/Gurobi/gurobi.lic".
    • Mosek: 1. Request free academic license at link. The license file will be sent to your edu email within minutes. Check Spam folder if necessary. 2. Put the license file at the default location ~/mosek/.
    • Convex.jl, SCS.jl, Gurobi.jl, Mosek.jl, MathProgBase.jl, NLopt.jl, Ipopt.jl.

DCP Using Convex.jl

Standard convex problem classes like LP (linear programming), QP (quadratic programming), SOCP (second-order cone programming), SDP (semidefinite programming), and GP (geometric programming), are becoming a technology.

DCP Hierarchy

Example: microbiome regression analysis

We illustrate optimization tools in Julia using microbiome analysis as an example.

16S microbiome sequencing techonology generates sequence counts of various organisms (OTUs, operational taxonomic units) in samples.

Microbiome Data

For statistical analysis, counts are normalized into proportions for each sample, resulting in a covariate matrix $\mathbf{X}$ with all rows summing to 1. For identifiability, we need to add a sum-to-zero constraint to the regression cofficients. In other words, we need to solve a constrained least squares problem
$$ \text{minimize} \frac{1}{2} \|\mathbf{y} - \mathbf{X} \beta\|_2^2 $$ subject to the constraint $\sum_{j=1}^p \beta_j = 0$. For simplicity we ignore intercept and non-OTU covariates in this presentation.

Let's first generate an artifical data set.

In [30]:
using Random, LinearAlgebra, SparseArrays

Random.seed!(257) # seed

n, p = 100, 50
X = rand(n, p)
# scale each row of X sum to 1
lmul!(Diagonal(1 ./ vec(sum(X, dims=2))), X)
# true β is a sparse vector with about 10% non-zero entries
β = sprandn(p, 0.1) 
y = X * β + randn(n);

Sum-to-zero regression

The sum-to-zero contrained least squares is a standard quadratic programming (QP) problem so should be solved easily by any QP solver.

Modeling using Convex.jl

We use the Convex.jl package to model this QP problem. For a complete list of operations supported by Convex.jl, see http://www.juliaopt.org/Convex.jl/stable/operations/.

In [31]:
using Convex

β̂cls = Variable(size(X, 2))
problem = minimize(0.5sumsquares(y - X * β̂cls)) # objective
problem.constraints += sum(β̂cls) == 0; # constraint
problem
Out[31]:
minimize
└─ * (convex; positive)
   ├─ 0.5
   └─ qol_elem (convex; positive)
      ├─ norm2 (convex; positive)
      │  └─ …
      └─ [1.0;;]
subject to
└─ == constraint (affine)
   ├─ sum (affine; real)
   │  └─ 50-element real variable (id: 213…990)
   └─ 0

status: `solve!` not called yet

Mosek

We first use the Mosek solver to solve this QP.

In [32]:
using MosekTools, MathOptInterface
const MOI = MathOptInterface

#solver = Model(optimizer_with_attributes(Mosek.Optimizer, "LOG" => 1))
solver = Mosek.Optimizer()
MOI.set(solver, MOI.RawOptimizerAttribute("LOG"), 1)

@time solve!(problem, solver)
Problem
  Name                   :                 
  Objective sense        : min             
  Type                   : CONIC (conic optimization problem)
  Constraints            : 107             
  Cones                  : 2               
  Scalar variables       : 157             
  Matrix variables       : 0               
  Integer variables      : 0               

Optimizer started.
Presolve started.
Linear dependency checker started.
Linear dependency checker terminated.
Eliminator started.
Freed constraints in eliminator : 0
Eliminator terminated.
Eliminator - tries                  : 1                 time                   : 0.00            
Lin. dep.  - tries                  : 1                 time                   : 0.00            
Lin. dep.  - number                 : 0               
Presolve terminated. Time: 0.00    
Problem
  Name                   :                 
  Objective sense        : min             
  Type                   : CONIC (conic optimization problem)
  Constraints            : 107             
  Cones                  : 2               
  Scalar variables       : 157             
  Matrix variables       : 0               
  Integer variables      : 0               

Optimizer  - threads                : 8               
Optimizer  - solved problem         : the dual        
Optimizer  - Constraints            : 52
Optimizer  - Cones                  : 3
Optimizer  - Scalar variables       : 106               conic                  : 106             
Optimizer  - Semi-definite variables: 0                 scalarized             : 0               
Factor     - setup time             : 0.00              dense det. time        : 0.00            
Factor     - ML order time          : 0.00              GP order time          : 0.00            
Factor     - nonzeros before factor : 1328              after factor           : 1328            
Factor     - dense dim.             : 0                 flops                  : 3.08e+05        
ITE PFEAS    DFEAS    GFEAS    PRSTATUS   POBJ              DOBJ              MU       TIME  
0   2.9e+00  5.0e-01  2.0e+00  0.00e+00   0.000000000e+00   -1.000000000e+00  1.0e+00  0.00  
1   2.8e-01  4.8e-02  5.7e-01  -9.26e-01  2.912603689e+00   9.691427176e+00   9.7e-02  0.00  
2   4.3e-02  7.4e-03  1.3e-01  -7.09e-01  1.838299683e+01   3.554444177e+01   1.5e-02  0.01  
3   2.1e-03  3.5e-04  4.6e-04  7.65e-01   2.886542611e+01   2.893355750e+01   7.0e-04  0.01  
4   1.7e-06  2.9e-07  1.3e-08  1.00e+00   2.884632081e+01   2.884642145e+01   5.7e-07  0.01  
5   2.5e-10  4.3e-11  2.6e-14  1.00e+00   2.884672306e+01   2.884672307e+01   8.6e-11  0.01  
Optimizer terminated. Time: 0.01    

  0.133191 seconds (204.29 k allocations: 12.232 MiB, 91.80% compilation time)
In [33]:
# Check the status, optimal value, and minimizer of the problem
problem.status, problem.optval, β̂cls.value
Out[33]:
(MathOptInterface.OPTIMAL, 28.846723057200105, [5.509993075737464; 2.3835671852621703; … ; -3.5233708685235854; -14.863428484802004;;])
In [34]:
# check constraint satisfication
sum(β̂cls.value)
Out[34]:
-5.384492851590039e-11

Gurobi

Switch to Gurobi solver:

In [35]:
using Gurobi
solver = Gurobi.Optimizer()
MOI.set(solver, MOI.RawOptimizerAttribute("OutputFlag"), 1)

@time solve!(problem, solver)
Academic license - for non-commercial use only
Gurobi Optimizer version 9.0.2 build v9.0.2rc0 (mac64)
Optimize a model with 107 rows, 157 columns and 5160 nonzeros
Model fingerprint: 0x7d84cdf1
Model has 2 quadratic constraints
Coefficient statistics:
  Matrix range     [3e-05, 2e+00]
  QMatrix range    [1e+00, 1e+00]
  Objective range  [1e+00, 1e+00]
  Bounds range     [0e+00, 0e+00]
  RHS range        [3e-02, 3e+00]
Presolve removed 2 rows and 1 columns
Presolve time: 0.00s
Presolved: 105 rows, 156 columns, 5158 nonzeros
Presolved model has 2 second-order cone constraints
Ordering time: 0.00s

Barrier statistics:
 Free vars  : 50
 AA' NZ     : 5.154e+03
 Factor NZ  : 5.262e+03
 Factor Ops : 3.590e+05 (less than 1 second per iteration)
 Threads    : 1

                  Objective                Residual
Iter       Primal          Dual         Primal    Dual     Compl     Time
   0   1.14608693e+01 -5.01000000e-01  2.33e+01 1.00e-01  2.03e-01     0s
   1   3.26784892e+00  4.11069551e-02  4.53e+00 3.22e-05  3.94e-02     0s
   2   4.52620705e+00  5.85786331e+00  3.30e+00 3.28e-05  2.44e-02     0s
   3   8.07209203e+00  8.82923627e+00  2.06e+00 1.45e-05  2.89e-02     0s
   4   1.95394719e+01  1.81638141e+01  8.68e-01 7.80e-06  6.27e-02     0s
   5   2.75683201e+01  2.54440396e+01  1.09e-01 2.92e-06  3.27e-02     0s
   6   2.93870257e+01  2.86945236e+01  1.80e-04 1.28e-07  6.57e-03     0s
   7   2.88955436e+01  2.88455031e+01  1.45e-08 4.13e-08  4.72e-04     0s
   8   2.88467823e+01  2.88467113e+01  1.14e-09 3.16e-09  6.75e-07     0s
   9   2.88467273e+01  2.88467230e+01  5.80e-09 4.90e-13  3.93e-08     0s

Barrier solved model in 9 iterations and 0.01 seconds
Optimal objective 2.88467273e+01


User-callback calls 59, time in user-callback 0.00 sec
  0.225574 seconds (259.09 k allocations: 14.821 MiB, 94.68% compilation time)
In [36]:
# Check the status, optimal value, and minimizer of the problem
problem.status, problem.optval, β̂cls.value
Out[36]:
(MathOptInterface.OPTIMAL, 28.846727259891278, [5.510025912433847; 2.3835504644353662; … ; -3.523386377358247; -14.863377590391314;;])
In [37]:
# check constraint satisfication
sum(β̂cls.value)
Out[37]:
2.4584778657299466e-12

COSMO

Switch to COSMO solver (pure Julia implementation):

In [38]:
# Use COSMO solver
using COSMO

solver = COSMO.Optimizer()
MOI.set(solver, MOI.RawOptimizerAttribute("max_iter"), 5000)

@time solve!(problem, solver)
------------------------------------------------------------------
          COSMO v0.8.5 - A Quadratic Objective Conic Solver
                         Michael Garstka
                University of Oxford, 2017 - 2022
------------------------------------------------------------------

Problem:  x ∈ R^{53},
          constraints: A ∈ R^{107x53} (5056 nnz),
          matrix size to factor: 160x160,
          Floating-point precision: Float64
Sets:     SecondOrderCone of dim: 101
          SecondOrderCone of dim: 3
          ZeroSet of dim: 2
          Nonnegatives of dim: 1
Settings: ϵ_abs = 1.0e-05, ϵ_rel = 1.0e-05,
          ϵ_prim_inf = 1.0e-04, ϵ_dual_inf = 1.0e-04,
          ρ = 0.1, σ = 1e-06, α = 1.6,
          max_iter = 5000,
          scaling iter = 10 (on),
          check termination every 25 iter,
          check infeasibility every 40 iter,
          KKT system solver: QDLDL
Acc:      Anderson Type2{QRDecomp},
          Memory size = 15, RestartedMemory,	
          Safeguarded: true, tol: 2.0
Setup Time: 0.95ms

Iter:	Objective:	Primal Res:	Dual Res:	Rho:
1	-2.4722e+00	6.0761e+00	3.7946e+02	1.0000e-01
25	 2.8602e+01	3.1788e-02	1.8143e-02	1.0000e-01
50	 2.8847e+01	8.9599e-06	3.0693e-06	1.3548e-02

------------------------------------------------------------------
>>> Results
Status: Solved
Iterations: 62 (incl. 12 safeguarding iter)
Optimal objective: 28.85
Runtime: 0.004s (3.57ms)

  0.299001 seconds (349.27 k allocations: 21.400 MiB, 98.00% compilation time)
In [39]:
# Check the status, optimal value, and minimizer of the problem
problem.status, problem.optval, β̂cls.value
Out[39]:
(MathOptInterface.OPTIMAL, 28.84655984693939, [5.509991702253209; 2.383568738201016; … ; -3.5233705863445617; -14.863433543361133;;])

We see COSMO have a looser criterion for constraint satisfication, resulting a lower objective value.

In [40]:
sum(β̂cls.value)
Out[40]:
5.363552091353085e-7

SCS

Switch to the open source SCS solver:

In [41]:
# Use SCS solver
using SCS

solver = SCS.Optimizer()
MOI.set(solver, MOI.RawOptimizerAttribute("verbose"), 1)

@time solve!(problem, solver)
  0.836762 seconds (1.18 M allocations: 64.084 MiB, 7.09% gc time, 98.81% compilation time)
------------------------------------------------------------------
	       SCS v3.2.0 - Splitting Conic Solver
	(c) Brendan O'Donoghue, Stanford University, 2012
------------------------------------------------------------------
problem:  variables n: 53, constraints m: 107
cones: 	  z: primal zero / dual free vars: 2
	  l: linear vars: 1
	  q: soc vars: 104, qsize: 2
settings: eps_abs: 1.0e-04, eps_rel: 1.0e-04, eps_infeas: 1.0e-07
	  alpha: 1.50, scale: 1.00e-01, adaptive_scale: 1
	  max_iters: 100000, normalize: 1, rho_x: 1.00e-06
	  acceleration_lookback: 10, acceleration_interval: 10
lin-sys:  sparse-direct
	  nnz(A): 5056, nnz(P): 0
------------------------------------------------------------------
 iter | pri res | dua res |   gap   |   obj   |  scale  | time (s)
------------------------------------------------------------------
     0| 1.10e+01  6.36e+00  5.33e+01  2.16e+01  1.00e-01  1.22e-04 
   175| 7.26e-07  7.21e-07  5.64e-05  2.88e+01  1.00e-01  4.22e-03 
------------------------------------------------------------------
status:  solved
timings: total: 6.80e-03s = setup: 2.58e-03s + solve: 4.22e-03s
	 lin-sys: 3.59e-03s, cones: 9.89e-05s, accel: 9.52e-05s
------------------------------------------------------------------
objective = 28.846715
------------------------------------------------------------------
In [42]:
# Check the status, optimal value, and minimizer of the problem
problem.status, problem.optval, β̂cls.value
Out[42]:
(MathOptInterface.OPTIMAL, 28.846742781880327, [5.509993089336525; 2.3835671895276724; … ; -3.523370875539716; -14.863428522853521;;])
In [43]:
# check constraint satisfication
sum(β̂cls.value)
Out[43]:
-6.829878884673235e-10

Sum-to-zero lasso

Suppose we want to know which organisms (OTU) are associated with the response. We can answer this question using a sum-to-zero contrained lasso $$ \text{minimize} \frac 12 \|\mathbf{y} - \mathbf{X} \beta\|_2^2 + \lambda \|\beta\|_1 $$ subject to the constraint $\sum_{j=1}^p \beta_j = 0$. Varying $\lambda$ from small to large values will generate a solution path.

In [44]:
using Convex

# # Use Mosek solver
# using Mosek
# solver = Mosek.Optimizer()
# MOI.set(solver, MOI.RawOptimizerAttribute("LOG"), 0)

# # Use Gurobi solver
# using Gurobi
# solver = () -> Gurobi.Optimizer(OutputFlag=0)

# Use Cplex solver
# using CPLEX
# solver = CplexSolver(CPXPARAM_ScreenOutput=0)

# # Use SCS solver
# using SCS
# solver = () -> SCS.Optimizer(verbose=0)

# solve at a grid of λ
λgrid = 0:0.01:0.35

# holder for solution path
β̂path = zeros(length(λgrid), size(X, 2)) # each row is β̂ at a λ
# optimization variable
β̂classo = Variable(size(X, 2))
# obtain solution path using warm start
@time for i in 1:length(λgrid)
    λ = λgrid[i]
    # define optimization problem
    # objective
    problem = minimize(0.5sumsquares(y - X * β̂classo) + λ * sum(abs, β̂classo))
    # constraint
    problem.constraints += sum(β̂classo) == 0 # constraint
    solver = Mosek.Optimizer()
    MOI.set(solver, MOI.RawOptimizerAttribute("LOG"), 0)
    solve!(problem, solver)
    β̂path[i, :] = β̂classo.value
end
  0.463893 seconds (2.04 M allocations: 189.108 MiB)
In [45]:
using CairoMakie

f = Figure()
Axis(
    f[1, 1], 
    title = "Sum-to-Zero Lasso",
    xlabel = L"\lambda",
    ylabel = L"\beta_j"
)
series!(λgrid, β̂path', color = :glasbey_category10_n256)
f
Out[45]:

Sum-to-zero group lasso

Suppose we want to do variable selection not at the OTU level, but at the Phylum level. OTUs are clustered into various Phyla. We can answer this question using a sum-to-zero contrained group lasso $$ \text{minimize} \frac 12 \|\mathbf{y} - \mathbf{X} \beta\|_2^2 + \lambda \sum_j \|\mathbf{\beta}_j\|_2 $$ subject to the constraint $\sum_{j=1}^p \beta_j = 0$, where $\mathbf{\beta}_j$ are regression coefficients corresponding to the $j$-th phylum. This is a second-order cone programming (SOCP) problem readily modeled by Convex.jl.

Let's assume each 10 contiguous OTUs belong to one Phylum.

In [46]:
# Use Mosek solver
using MosekTools

# # Use Gurobi solver
# using Gurobi

# # Use Cplex solver
# using CPLEX
# solver = CplexSolver(CPXPARAM_ScreenOutput=0)

# # Use SCS solver
# using SCS
# solver = SCSSolver(verbose=0)

# solve at a grid of λ
λgrid = 0.0:0.005:0.5
β̂pathgrp = zeros(length(λgrid), size(X, 2)) # each row is β̂ at a λ
β̂classo = Variable(size(X, 2))
@time for i in 1:length(λgrid)
    λ = λgrid[i]
    # loss
    obj = 0.5sumsquares(y - X * β̂classo)
    # group lasso penalty term
    for j in 1:(size(X, 2)/10)
        βj = β̂classo[(10(j-1)+1):10j]
        obj = obj + λ * norm(βj)
    end
    problem = minimize(obj)
    # constraint
    problem.constraints += sum(β̂classo) == 0 # constraint
    solver = Mosek.Optimizer()
    MOI.set(solver, MOI.RawOptimizerAttribute("LOG"), 0)
    solve!(problem, solver)
    β̂pathgrp[i, :] = β̂classo.value
end
  1.118362 seconds (2.02 M allocations: 287.770 MiB, 5.36% gc time)

We see it took Mosek <2 second to solve this seemingly hard optimization problem at 101 different $\lambda$ values.

In [47]:
using CairoMakie

f = Figure()
Axis(
    f[1, 1], 
    title = "Sum-to-Zero Group Lasso",
    xlabel = L"\lambda",
    ylabel = L"\beta_j"
)
series!(λgrid, β̂pathgrp', color = :glasbey_category10_n256)
f
Out[47]:

Example: matrix completion

Load the $128 \times 128$ Lena picture with missing pixels.

In [48]:
using FileIO

lena = load("lena128missing.png")
Out[48]:
In [49]:
# convert to real matrices
Y = Float64.(lena)
Out[49]:
128×128 Matrix{Float64}:
 0.0       0.0       0.635294  0.0       …  0.0       0.0       0.627451
 0.627451  0.623529  0.0       0.611765     0.0       0.0       0.388235
 0.611765  0.611765  0.0       0.0          0.403922  0.219608  0.0
 0.0       0.0       0.611765  0.0          0.223529  0.176471  0.192157
 0.611765  0.0       0.615686  0.615686     0.0       0.0       0.0
 0.0       0.0       0.0       0.619608  …  0.0       0.0       0.2
 0.607843  0.0       0.623529  0.0          0.176471  0.192157  0.0
 0.0       0.0       0.623529  0.0          0.0       0.0       0.215686
 0.619608  0.619608  0.0       0.0          0.2       0.0       0.207843
 0.0       0.0       0.635294  0.635294     0.2       0.192157  0.188235
 0.635294  0.0       0.0       0.0       …  0.192157  0.180392  0.0
 0.631373  0.0       0.0       0.0          0.0       0.0       0.0
 0.0       0.627451  0.635294  0.666667     0.172549  0.0       0.184314
 ⋮                                       ⋱  ⋮                   
 0.0       0.129412  0.0       0.541176     0.0       0.286275  0.0
 0.14902   0.129412  0.196078  0.537255     0.345098  0.0       0.0
 0.215686  0.0       0.262745  0.0          0.301961  0.0       0.207843
 0.345098  0.341176  0.356863  0.513725     0.0       0.0       0.231373
 0.0       0.0       0.0       0.0       …  0.0       0.243137  0.258824
 0.298039  0.415686  0.458824  0.0          0.0       0.0       0.258824
 0.0       0.368627  0.4       0.0          0.0       0.0       0.235294
 0.0       0.0       0.34902   0.0          0.0       0.239216  0.207843
 0.219608  0.0       0.0       0.0          0.0       0.0       0.2
 0.0       0.219608  0.235294  0.356863  …  0.0       0.0       0.0
 0.196078  0.207843  0.211765  0.0          0.0       0.270588  0.345098
 0.192157  0.0       0.196078  0.309804     0.266667  0.356863  0.0

We fill out the missin pixels uisng a matrix completion technique developed by Candes and Tao $$ \text{minimize } \|\mathbf{X}\|_* $$ $$ \text{subject to } x_{ij} = y_{ij} \text{ for all observed entries } (i, j). $$ Here $\|\mathbf{M}\|_* = \sum_i \sigma_i(\mathbf{M})$ is the nuclear norm. In words we seek the matrix with minimal nuclear norm that agrees with the observed entries. This is a semidefinite programming (SDP) problem readily modeled by Convex.jl.

This example takes long because of high dimensionality.

In [50]:
# Use COSMO solver
using COSMO

# Linear indices of obs. entries
obsidx = findall(Y[:] .≠ 0.0)
# Create optimization variables
X = Variable(size(Y))
# Set up optmization problem
problem = minimize(nuclearnorm(X))
problem.constraints += X[obsidx] == Y[obsidx]
# Solve the problem by calling solve
# @time solve!(problem, () -> Mosek.Optimizer(LOG=1)) # Mosek takes about 20min
@time solve!(problem, COSMO.Optimizer()) # fast
------------------------------------------------------------------
          COSMO v0.8.5 - A Quadratic Objective Conic Solver
                         Michael Garstka
                University of Oxford, 2017 - 2022
------------------------------------------------------------------

Problem:  x ∈ R^{49153},
          constraints: A ∈ R^{73665x49153} (73793 nnz),
          matrix size to factor: 122818x122818,
          Floating-point precision: Float64
Sets:     ZeroSet of dim: 40769
          DensePsdConeTriangle of dim: 32896 (256x256)
Settings: ϵ_abs = 1.0e-05, ϵ_rel = 1.0e-05,
          ϵ_prim_inf = 1.0e-04, ϵ_dual_inf = 1.0e-04,
          ρ = 0.1, σ = 1e-06, α = 1.6,
          max_iter = 5000,
          scaling iter = 10 (on),
          check termination every 25 iter,
          check infeasibility every 40 iter,
          KKT system solver: QDLDL
Acc:      Anderson Type2{QRDecomp},
          Memory size = 15, RestartedMemory,	
          Safeguarded: true, tol: 2.0
Setup Time: 75.45ms

Iter:	Objective:	Primal Res:	Dual Res:	Rho:
1	-1.4426e+03	1.1678e+01	5.9856e-01	1.0000e-01
25	 1.4495e+02	5.5360e-02	1.1033e-03	1.0000e-01
50	 1.4754e+02	1.2369e-02	1.6744e-03	7.4179e-01
75	 1.4797e+02	4.9490e-04	5.5696e-05	7.4179e-01
100	 1.4797e+02	1.4115e-05	1.3438e-06	7.4179e-01

------------------------------------------------------------------
>>> Results
Status: Solved
Iterations: 100
Optimal objective: 148
Runtime: 1.683s (1683.14ms)

  1.907699 seconds (739.78 k allocations: 602.994 MiB, 5.94% gc time)
In [51]:
using Images

#Gray.(X.value)
colorview(Gray, X.value)
Out[51]:

Nonlinear programming (NLP)

We use MLE of Gamma distribution to illustrate some rudiments of nonlinear programming (NLP) in Julia.

Let $x_1,\ldots,x_m$ be a random sample from the gamma density $$ f(x) = \Gamma(\alpha)^{-1} \beta^{\alpha} x^{\alpha-1} e^{-\beta x} $$ on $(0,\infty)$. The loglikelihood function is $$ L(\alpha, \beta) = m [- \ln \Gamma(\alpha) + \alpha \ln \beta + (\alpha - 1)\overline{\ln x} - \beta \bar x], $$ where $\overline{x} = \frac{1}{m} \sum_{i=1}^m x_i$ and $\overline{\ln x} = \frac{1}{m} \sum_{i=1}^m \ln x_i$.

In [52]:
using Random, Statistics, SpecialFunctions
Random.seed!(123)

function gamma_logpdf(x::Vector, α::Real, β::Real)
    m = length(x)
    avg = mean(x)
    logavg = sum(log, x) / m
    m * (- log(gamma(α)) + α * log(β) + (α - 1) * logavg - β * avg)
end

x = rand(5)
gamma_logpdf(x, 1.0, 1.0)
Out[52]:
-2.7154683416493226

Many optimization algorithms involve taking derivatives of the objective function. The ForwardDiff.jl package implements automatic differentiation. For example, to compute the derivative and Hessian of the log-likelihood with data x at α=1.0 and β=1.0.

In [53]:
using ForwardDiff

ForwardDiff.gradient(θ -> gamma_logpdf(x, θ...), [1.0; 1.0])
Out[53]:
2-element Vector{Float64}:
 -0.7131899304276518
  2.2845316583506774
In [54]:
ForwardDiff.hessian(θ -> gamma_logpdf(x, θ...), [1.0; 1.0])
Out[54]:
2×2 Matrix{Float64}:
 -8.22467   5.0
  5.0      -5.0

Generate data:

In [55]:
using Distributions, Random

Random.seed!(123)
(n, p) = (1000, 2)
(α, β) = 5.0 * rand(p)
x = rand(Gamma(α, β), n)
println("True parameter values:")
println("α = ", α, ", β = ", β)
True parameter values:
α = 2.606068977676915, β = 2.934033787266742

We use JuMP.jl to define and solve our NLP problem.

In [56]:
using JuMP

# using NLopt
# m = Model(NLopt.Optimizer)
# set_optimizer_attribute(m, "algorithm", :LD_MMA)

using Ipopt
m = Model(Ipopt.Optimizer)
set_optimizer_attribute(m, "print_level", 3)

myf(a, b) = gamma_logpdf(x, a, b)
JuMP.register(m, :myf, 2, myf, autodiff=true)
@variable(m, α >= 1e-8)
@variable(m, β >= 1e-8)
@NLobjective(m, Max, myf(α, β))

print(m)
status = JuMP.optimize!(m)

println("MLE (JuMP):")
println("α = ", α, ", β = ", β)
println("Objective value: ", JuMP.objective_value(m))
println("α = ", JuMP.value(α), ", β = ", 1 / JuMP.value(β))
println("MLE (Distribution package):")
println(fit_mle(Gamma, x))
$$ \begin{aligned} \max\quad & myf(α, β)\\ \text{Subject to} \quad & α \geq 1.0e-8\\ & β \geq 1.0e-8\\ \end{aligned} $$
Total number of variables............................:        2
                     variables with only lower bounds:        2
                variables with lower and upper bounds:        0
                     variables with only upper bounds:        0
Total number of equality constraints.................:        0
Total number of inequality constraints...............:        0
        inequality constraints with only lower bounds:        0
   inequality constraints with lower and upper bounds:        0
        inequality constraints with only upper bounds:        0


Number of Iterations....: 17

                                   (scaled)                 (unscaled)
Objective...............:   2.7795335767973427e-05   -2.7795335767973424e+03
Dual infeasibility......:   8.6797812935343862e-09    8.6797812935343865e-01
Constraint violation....:   0.0000000000000000e+00    0.0000000000000000e+00
Variable bound violation:   0.0000000000000000e+00    0.0000000000000000e+00
Complementarity.........:   5.0023954602700218e-13    5.0023954602700217e-05
Overall NLP error.......:   8.6797812935343862e-09    8.6797812935343865e-01


Number of objective function evaluations             = 23
Number of objective gradient evaluations             = 18
Number of equality constraint evaluations            = 0
Number of inequality constraint evaluations          = 0
Number of equality constraint Jacobian evaluations   = 0
Number of inequality constraint Jacobian evaluations = 0
Number of Lagrangian Hessian evaluations             = 0
Total seconds in IPOPT                               = 0.140

EXIT: Optimal Solution Found.
MLE (JuMP):
α = α, β = β
Objective value: -2779.5335767973424
α = 2.7843068927897807, β = 2.6624193385695283
MLE (Distribution package):
Gamma{Float64}(α=2.783766554825778, θ=2.663247970371006)