Optimization in Julia

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

In [57]:
versioninfo()
Julia Version 1.4.1
Commit 381693d3df* (2020-04-14 17:20 UTC)
Platform Info:
  OS: macOS (x86_64-apple-darwin18.7.0)
  CPU: Intel(R) Core(TM) i7-6920HQ CPU @ 2.90GHz
  WORD_SIZE: 64
  LIBM: libopenlibm
  LLVM: libLLVM-8.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 O
Ipopt 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 [58]:
using Random, LinearAlgebra, SparseArrays

Random.seed!(123) # 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 [59]:
using Convex

β̂cls = Variable(size(X, 2))
problem = minimize(0.5sumsquares(y - X * β̂cls)) # objective
problem.constraints += sum(β̂cls) == 0; # constraint
problem
Out[59]:
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: 487…565)
   └─ 0

status: `solve!` not called yet

Mosek

We first use the Mosek solver to solve this QP.

In [60]:
using MosekTools

@time solve!(problem, () -> Mosek.Optimizer(LOG=1))
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   3.1e+00  5.0e-01  2.0e+00  0.00e+00   0.000000000e+00   -1.000000000e+00  1.0e+00  0.00  
1   3.0e-01  4.9e-02  5.6e-01  -9.20e-01  2.867941086e+00   9.477091029e+00   9.7e-02  0.00  
2   4.7e-02  7.7e-03  1.2e-01  -6.86e-01  1.722444627e+01   3.234235233e+01   1.5e-02  0.00  
3   2.1e-03  3.4e-04  4.3e-04  7.79e-01   2.647527819e+01   2.654097410e+01   6.8e-04  0.00  
4   1.5e-06  2.5e-07  1.0e-08  1.00e+00   2.645044655e+01   2.645052960e+01   5.0e-07  0.01  
5   2.7e-10  4.4e-11  2.9e-14  1.00e+00   2.645074179e+01   2.645074181e+01   8.6e-11  0.01  
Optimizer terminated. Time: 0.01    

  0.018088 seconds (15.87 k allocations: 2.507 MiB)
In [61]:
# Check the status, optimal value, and minimizer of the problem
problem.status, problem.optval, β̂cls.value
Out[61]:
(MathOptInterface.OPTIMAL, 26.450741793794975, [20.17363830989884; 2.118676448941195; … ; 24.140193669533474; -4.517825960973969])
In [62]:
# check constraint satisfication
sum(β̂cls.value)
Out[62]:
-1.1226575225009583e-10

Gurobi

Switch to Gurobi solver:

In [63]:
using Gurobi

@time solve!(problem, () -> Gurobi.Optimizer(OutputFlag=1))
Academic license - for non-commercial use only
Optimize a model with 107 rows, 157 columns and 5160 nonzeros
Model has 2 quadratic constraints
Coefficient statistics:
  Matrix range     [1e-05, 2e+00]
  QMatrix range    [1e+00, 1e+00]
  Objective range  [1e+00, 1e+00]
  Bounds range     [0e+00, 0e+00]
  RHS range        [4e-03, 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.18451802e+01 -5.01000000e-01  2.40e+01 1.00e-01  2.10e-01     0s
   1   3.33648461e+00 -3.24029170e-02  4.58e+00 4.72e-05  4.06e-02     0s
   2   3.12915622e+00  4.52501039e+00  3.61e+00 4.47e-05  1.99e-02     0s
   3   1.51263772e+01  7.51185121e+00  1.79e+00 4.02e-05  1.02e-01     0s
   4   1.38248014e+01  2.01142309e+01  1.08e+00 9.67e-05  1.68e-02     0s
   5   3.30715906e+01  2.40146272e+01  3.35e-03 1.01e-05  8.59e-02     0s
   6   2.71094293e+01  2.63988011e+01  3.69e-09 2.91e-06  6.71e-03     0s
   7   2.64515175e+01  2.64506426e+01  6.00e-10 4.75e-08  8.22e-06     0s
   8   2.64507431e+01  2.64507419e+01  1.92e-09 1.54e-09  1.39e-08     0s

Barrier solved model in 8 iterations and 0.01 seconds
Optimal objective 2.64507431e+01

  0.020980 seconds (10.96 k allocations: 2.126 MiB)
In [64]:
# Check the status, optimal value, and minimizer of the problem
problem.status, problem.optval, β̂cls.value
Out[64]:
(MathOptInterface.OPTIMAL, 26.450743119117902, [20.174776417650953; 2.1186615532700315; … ; 24.14219140188035; -4.519078491747891])
In [65]:
# check constraint satisfication
sum(β̂cls.value)
Out[65]:
1.8189894035458565e-12

COSMO

Switch to COSMO solver (pure Julia implementation:

In [66]:
# Use COSMO solver
using COSMO

@time solve!(problem, () -> COSMO.Optimizer(max_iter=5000))
------------------------------------------------------------------
          COSMO v0.7.1 - A Quadratic Objective Conic Solver
                         Michael Garstka
                University of Oxford, 2017 - 2020
------------------------------------------------------------------

Problem:  x ∈ R^{53},
          constraints: A ∈ R^{107x53} (5056 nnz),
          matrix size to factor: 160x160 (10272 nnz)
Sets:     SecondOrderCone of dim: 101
          SecondOrderCone of dim: 3
          ZeroSet of dim: 2
          Nonnegatives of dim: 1
Settings: ϵ_abs = 1.0e-04, ϵ_rel = 1.0e-04,
          ϵ_prim_inf = 1.0e-06, ϵ_dual_inf = 1.0e-04,
          ρ = 0.1, σ = 1.0e-6, α = 1.6,
          max_iter = 5000,
          scaling iter = 10 (on),
          check termination every 40 iter,
          check infeasibility every 40 iter,
          KKT system solver: CHOLMOD
Setup Time: 3.16ms

Iter:	Objective:	Primal Res:	Dual Res:	Rho:
40	2.4750e+01	2.8769e-01	5.4650e+00	1.0000e-01
80	1.6662e+01	2.7462e+00	1.6656e-02	3.6032e-03
120	2.3311e+01	1.2387e+00	2.8423e-03	3.6032e-03
160	2.0585e+01	4.9285e-01	7.9942e-05	3.6032e-03
200	2.1593e+01	2.2278e-01	6.6380e-04	1.9865e-02
240	2.1854e+01	2.0477e-01	2.4821e-04	1.9865e-02
280	2.2103e+01	1.9149e-01	2.4240e-04	1.9865e-02
320	2.2334e+01	1.7953e-01	2.2529e-04	1.9865e-02
360	2.2549e+01	1.6862e-01	2.0953e-04	1.9865e-02
400	2.2749e+01	1.5864e-01	1.9537e-04	1.9865e-02
440	2.2936e+01	1.4946e-01	1.8256e-04	1.9865e-02
480	2.3111e+01	1.4101e-01	1.7092e-04	1.9865e-02
520	2.3274e+01	1.3320e-01	1.6031e-04	1.9865e-02
560	2.3428e+01	1.2597e-01	1.5059e-04	1.9865e-02
600	2.3573e+01	1.1925e-01	1.4167e-04	1.9865e-02
640	2.3709e+01	1.1299e-01	1.3346e-04	1.9865e-02
680	2.3837e+01	1.0715e-01	1.2588e-04	1.9865e-02
720	2.3958e+01	1.0170e-01	1.1887e-04	1.9865e-02
760	2.4072e+01	9.6600e-02	1.1236e-04	1.9865e-02
800	2.4180e+01	9.1816e-02	1.0631e-04	1.9865e-02
840	2.4282e+01	8.7325e-02	1.0068e-04	1.9865e-02
880	2.4379e+01	8.3103e-02	9.5431e-05	1.9865e-02
920	2.4471e+01	7.9130e-02	9.0523e-05	1.9865e-02
960	2.4559e+01	7.5385e-02	8.5930e-05	1.9865e-02
1000	2.4641e+01	7.1853e-02	8.1626e-05	1.9865e-02
1040	2.4720e+01	6.8518e-02	7.7587e-05	1.9865e-02
1080	2.4795e+01	6.5366e-02	7.3792e-05	1.9865e-02
1120	2.4866e+01	6.2383e-02	7.0221e-05	1.9865e-02
1160	2.4934e+01	5.9560e-02	6.6859e-05	1.9865e-02
1200	2.4998e+01	5.6885e-02	6.3689e-05	1.9865e-02
1240	2.5060e+01	5.4348e-02	6.0698e-05	1.9865e-02
1280	2.5119e+01	5.1941e-02	5.7873e-05	1.9865e-02
1320	2.5174e+01	4.9655e-02	5.5202e-05	1.9865e-02
1360	2.5228e+01	4.7484e-02	5.2675e-05	1.9865e-02
1400	2.5279e+01	4.5419e-02	5.0283e-05	1.9865e-02
1440	2.5327e+01	4.3456e-02	4.8016e-05	1.9865e-02
1480	2.5374e+01	4.1587e-02	4.5867e-05	1.9865e-02
1520	2.5418e+01	3.9808e-02	4.3827e-05	1.9865e-02
1560	2.5460e+01	3.8114e-02	4.1891e-05	1.9865e-02
1600	2.5501e+01	3.6499e-02	4.0051e-05	1.9865e-02
1640	2.5540e+01	3.4959e-02	3.8303e-05	1.9865e-02
1680	2.5577e+01	3.3491e-02	3.6641e-05	1.9865e-02
1720	2.5612e+01	3.2090e-02	3.5059e-05	1.9865e-02
1760	2.5646e+01	3.0752e-02	3.3553e-05	1.9865e-02
1800	2.5679e+01	2.9476e-02	3.2119e-05	1.9865e-02
1840	2.5710e+01	2.8256e-02	3.0752e-05	1.9865e-02
1880	2.5739e+01	2.7091e-02	2.9450e-05	1.9865e-02
1920	2.5768e+01	2.5978e-02	2.8208e-05	1.9865e-02
1960	2.5795e+01	2.4914e-02	2.7024e-05	1.9865e-02
2000	2.5821e+01	2.3896e-02	2.5893e-05	1.9865e-02
2040	2.5846e+01	2.2923e-02	2.4814e-05	1.9865e-02
2080	2.5870e+01	2.1992e-02	2.3784e-05	1.9865e-02
2120	2.5894e+01	2.1101e-02	2.2800e-05	1.9865e-02
2160	2.5916e+01	2.0248e-02	2.1860e-05	1.9865e-02
2200	2.5937e+01	1.9432e-02	2.0961e-05	1.9865e-02
2240	2.5957e+01	1.8650e-02	2.0102e-05	1.9865e-02
2280	2.5977e+01	1.7901e-02	1.9281e-05	1.9865e-02
2320	2.5995e+01	1.7184e-02	1.8495e-05	1.9865e-02
2360	2.6013e+01	1.6498e-02	1.7743e-05	1.9865e-02
2400	2.6030e+01	1.5839e-02	1.7024e-05	1.9865e-02
2440	2.6047e+01	1.5209e-02	1.6336e-05	1.9865e-02
2480	2.6063e+01	1.4604e-02	1.5677e-05	1.9865e-02
2520	2.6078e+01	1.4025e-02	1.5046e-05	1.9865e-02
2560	2.6092e+01	1.3469e-02	1.4442e-05	1.9865e-02
2600	2.6106e+01	1.2936e-02	1.3863e-05	1.9865e-02
2640	2.6120e+01	1.2426e-02	1.3309e-05	1.9865e-02
2680	2.6133e+01	1.1936e-02	1.2777e-05	1.9865e-02
2720	2.6145e+01	1.1465e-02	1.2268e-05	1.9865e-02
2760	2.6157e+01	1.1015e-02	1.1781e-05	1.9865e-02
2800	2.6168e+01	1.0582e-02	1.1313e-05	1.9865e-02
2840	2.6179e+01	1.0167e-02	1.0864e-05	1.9865e-02
2880	2.6190e+01	9.7684e-03	1.0434e-05	1.9865e-02
2920	2.6200e+01	9.3861e-03	1.0022e-05	1.9865e-02
2960	2.6210e+01	9.0192e-03	9.6267e-06	1.9865e-02
3000	2.6219e+01	8.6669e-03	9.2474e-06	1.9865e-02
3040	2.6228e+01	8.3288e-03	8.8836e-06	1.9865e-02
3080	2.6237e+01	8.0041e-03	8.5345e-06	1.9865e-02
3120	2.6245e+01	7.6924e-03	8.1995e-06	1.9865e-02
3160	2.6253e+01	7.3931e-03	7.8781e-06	1.9865e-02
3200	2.6261e+01	7.1057e-03	7.5696e-06	1.9865e-02
3240	2.6268e+01	6.8297e-03	7.2735e-06	1.9865e-02
3280	2.6275e+01	6.5646e-03	6.9893e-06	1.9865e-02
3320	2.6282e+01	6.3100e-03	6.7165e-06	1.9865e-02
3360	2.6288e+01	6.0655e-03	6.4546e-06	1.9865e-02
3400	2.6294e+01	5.8306e-03	6.2031e-06	1.9865e-02
3440	2.6300e+01	5.6049e-03	5.9617e-06	1.9865e-02
3480	2.6306e+01	5.3881e-03	5.7298e-06	1.9865e-02

------------------------------------------------------------------
>>> Results
Status: Solved
Iterations: 3480
Optimal objective: 26.3063
Runtime: 0.137s (137.49ms)

  0.146957 seconds (128.67 k allocations: 39.556 MiB)
In [67]:
# Check the status, optimal value, and minimizer of the problem
problem.status, problem.optval, β̂cls.value
Out[67]:
(MathOptInterface.OPTIMAL, 26.306269427372754, [20.17363836254043; 2.1186764548269714; … ; 24.140193716696025; -4.517825972724566])

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

In [68]:
sum(β̂cls.value)
Out[68]:
-3.499444289900566e-8

SCS

Switch to the open source SCS solver:

In [69]:
# Use SCS solver
using SCS

@time solve!(problem, () -> SCS.Optimizer(verbose=1))
  0.026601 seconds (9.36 k allocations: 2.867 MiB)
----------------------------------------------------------------------------
	SCS v2.1.1 - Splitting Conic Solver
	(c) Brendan O'Donoghue, Stanford University, 2012
----------------------------------------------------------------------------
Lin-sys: sparse-indirect, nnz in A = 5056, CG tol ~ 1/iter^(2.00)
eps = 1.00e-05, alpha = 1.50, max_iters = 5000, normalize = 1, scale = 1.00
acceleration_lookback = 10, rho_x = 1.00e-03
Variables n = 53, constraints m = 107
Cones:	primal zero / dual free vars: 2
	linear vars: 1
	soc vars: 104, soc blks: 2
Setup time: 4.13e-04s
----------------------------------------------------------------------------
 Iter | pri res | dua res | rel gap | pri obj | dua obj | kap/tau | time (s)
----------------------------------------------------------------------------
     0| 1.01e+20  5.75e+19  1.00e+00 -1.20e+21  8.21e+20  1.66e+21  8.33e-04 
   100| 1.25e-06  1.38e-06  1.69e-07  2.65e+01  2.65e+01  6.94e-16  1.60e-02 
----------------------------------------------------------------------------
Status: Solved
Timing: Solve time: 1.60e-02s
	Lin-sys: avg # CG iterations: 8.71, avg solve time: 1.40e-04s
	Cones: avg projection time: 3.04e-07s
	Acceleration: avg step time: 1.34e-05s
----------------------------------------------------------------------------
Error metrics:
dist(s, K) = 3.1974e-14, dist(y, K*) = 1.7764e-15, s'y/|s||y| = -5.5387e-16
primal res: |Ax + s - b|_2 / (1 + |b|_2) = 1.2498e-06
dual res:   |A'y + c|_2 / (1 + |c|_2) = 1.3832e-06
rel gap:    |c'x + b'y| / (1 + |c'x| + |b'y|) = 1.6881e-07
----------------------------------------------------------------------------
c'x = 26.4506, -b'y = 26.4506
============================================================================
In [70]:
# Check the status, optimal value, and minimizer of the problem
problem.status, problem.optval, β̂cls.value
Out[70]:
(MathOptInterface.OPTIMAL, 26.450639232450104, [20.17364374512858; 2.1185962604472524; … ; 24.140254779383294; -4.517748101542147])
In [71]:
# check constraint satisfication
sum(β̂cls.value)
Out[71]:
3.115659552577199e-6

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 [72]:
using Convex

# # Use Mosek solver
# using Mosek

# # Use Gurobi solver
# using Gurobi

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

# Use SCS solver
using SCS

# 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
    solve!(problem, () -> SCS.Optimizer(verbose=0))
    β̂path[i, :] = β̂classo.value
end
  1.032796 seconds (1.38 M allocations: 168.998 MiB, 5.63% gc time)
In [73]:
using Plots; gr()
using LaTeXStrings

p = plot(collect(λgrid), β̂path, legend=:none)
xlabel!(p, L"\lambda")
ylabel!(p, L"\hat \beta")
title!(p, "Sum-to-Zero Lasso")
Out[73]:

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 [74]:
# # Use Mosek solver
# using Mosek

# # 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
    solve!(problem, () -> SCS.Optimizer(verbose=0))
    β̂pathgrp[i, :] = β̂classo.value
end
  2.193572 seconds (617.02 k allocations: 274.937 MiB, 2.27% gc time)

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

In [75]:
p2 = plot(collect(λgrid), β̂pathgrp, legend=:none)
xlabel!(p2, L"\lambda")
ylabel!(p2, L"\hat \beta")
title!(p2, "Sum-to-Zero Group Lasso")
Out[75]:

Example: matrix completion

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

In [76]:
using FileIO

lena = load("lena128missing.png")
Out[76]:
In [77]:
# convert to real matrices
Y = Float64.(lena)
Out[77]:
128×128 Array{Float64,2}:
 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 [78]:
# Use COSMO solver
using COSMO

# Linear indices of obs. entries
obsidx = findall(Y[:] .≠ 0.0)
# Create optimization variables
X = Convex.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.7.1 - A Quadratic Objective Conic Solver
                         Michael Garstka
                University of Oxford, 2017 - 2020
------------------------------------------------------------------

Problem:  x ∈ R^{49153},
          constraints: A ∈ R^{73665x49153} (73793 nnz),
          matrix size to factor: 122818x122818 (270404 nnz)
Sets:     ZeroSet of dim: 40769
          DensePsdConeTriangle of dim: 32896
Settings: ϵ_abs = 1.0e-04, ϵ_rel = 1.0e-04,
          ϵ_prim_inf = 1.0e-06, ϵ_dual_inf = 1.0e-04,
          ρ = 0.1, σ = 1.0e-6, α = 1.6,
          max_iter = 2500,
          scaling iter = 10 (on),
          check termination every 40 iter,
          check infeasibility every 40 iter,
          KKT system solver: CHOLMOD
Setup Time: 102.66ms

Iter:	Objective:	Primal Res:	Dual Res:	Rho:
40	1.4739e+02	1.7996e-02	2.4732e-04	1.0000e-01
80	1.4797e+02	4.6598e-04	4.2189e-05	6.8117e-01
120	1.4797e+02	3.9276e-05	2.6024e-06	6.8117e-01

------------------------------------------------------------------
>>> Results
Status: Solved
Iterations: 120
Optimal objective: 147.971
Runtime: 1.695s (1694.61ms)

  1.911576 seconds (892.51 k allocations: 1.064 GiB, 3.56% gc time)
In [79]:
using Images

Gray.(X.value)
Out[79]:

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 [80]:
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[80]:
-3.0916184386224517

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 [81]:
using ForwardDiff

ForwardDiff.gradient(θ -> gamma_logpdf(x, θ...), [1.0; 1.0])
Out[81]:
2-element Array{Float64,1}:
 0.07828535245887835
 1.9083815613775483
In [82]:
ForwardDiff.hessian(θ -> gamma_logpdf(x, θ...), [1.0; 1.0])
Out[82]:
2×2 Array{Float64,2}:
 -8.22467   5.0
  5.0      -5.0

Generate data:

In [83]:
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:
α = 3.8422383759828493, β = 4.7025750035759355

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

In [84]:
using JuMP, Ipopt, NLopt

m = Model(with_optimizer(Ipopt.Optimizer, print_level=3))
# m = Model(with_optimizer(NLopt.Optimizer, algorithm=:LD_MMA))

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))
Max myf(α, β)
Subject to
 α ≥ 1.0e-8
 β ≥ 1.0e-8
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....: 19

                                   (scaled)                 (unscaled)
Objective...............:   3.5872527661489071e+03    3.5872527661489071e+03
Dual infeasibility......:   1.9624872101004507e-10    1.9624872101004507e-10
Constraint violation....:   0.0000000000000000e+00    0.0000000000000000e+00
Complementarity.........:   1.0000000000000001e-11    1.0000000000000001e-11
Overall NLP error.......:   1.9624872101004507e-10    1.9624872101004507e-10


Number of objective function evaluations             = 39
Number of objective gradient evaluations             = 20
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 CPU secs in IPOPT (w/o function evaluations)   =      0.042
Total CPU secs in NLP function evaluations           =      0.001

EXIT: Optimal Solution Found.
MLE (JuMP):
α = α, β = β
Objective value: -3587.252766148907
α = 3.6354635513745093, β = 5.058746017922452
MLE (Distribution package):
Gamma{Float64}(α=3.635463551374468, θ=5.058746017922469)