Skip to content

Instantly share code, notes, and snippets.

@tshort
Created January 20, 2016 14:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tshort/9f025194a72370ebcde9 to your computer and use it in GitHub Desktop.
Save tshort/9f025194a72370ebcde9 to your computer and use it in GitHub Desktop.
Example of complex numbers with JuMP
using JuMP
function Base.real{T <: JuMP.JuMPTypes}(x::Matrix{T})
@assert size(x,1) == 2
vec(x[1,:])
end
function Base.imag{T <: JuMP.JuMPTypes}(x::Matrix{T})
@assert size(x,1) == 2
vec(x[2,:])
end
function cmul{T <: JuMP.JuMPTypes}(z::Matrix{Complex128}, x::Matrix{T})
## `z` is a Matrix{Complex128} of size (N,N)
## `x` is a JuMP variable or AffExpr of size (2,N)
## - the first row is the real component
## - the second row is the imaginary component
N = size(z, 1)
@assert size(x, 1) == 2
@assert size(x, 2) == N
res = Array(JuMP.GenericAffExpr{Float64, JuMP.Variable}, (2,N))
res[1,:] = real(z) * real(x) - imag(z) * imag(x)
res[2,:] = imag(z) * real(x) + real(z) * imag(x)
res
end
m = Model()
@defVar(m, v1[1:2,1:3])
@defVar(m, v2[1:2,1:3])
@defVar(m, i[1:2,1:3])
z₁ = 3.0 + 6im
z₀ = 6.0 + 9im
Z = fill((z₀ - z₁)/3, 3, 3)
Z[1:4:9] = fill((z₀ + 2z₁)/3, 3) # diagonal
@addConstraint(m, cmul(Z, i) .== v1 - v2)
@addConstraint(m, v1 .== 10 * [2. -1 -1
0 -1.73 1.73])
@addConstraint(m, v2 .== 0.0)
solve(m)
iv = getValue(i)
I = reinterpret(Complex128, vec(iv))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment