forked from jump-dev/JuMP.jl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
fuzzer.jl
109 lines (99 loc) · 2.92 KB
/
fuzzer.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
# Copyright 2015, Iain Dunning, Joey Huchette, Miles Lubin, and contributors
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
function random_aff_expr(N, vars::Vector)
ex = Expr(:call, :+)
for _ in 1:N
vl, vr = Any[], Any[]
for i in randperm(length(vars))
v = vars[i]
if rand(Bool)
push!(vl, :($(rand()-0.5)))
end
if rand(Bool)
push!(vr, :($(rand()-0.5)))
end
if rand(Bool)
push!(vl, :($(rand()-0.5) * $v))
end
if rand(Bool)
push!(vr, :($(rand()-0.5) * $v))
end
if rand(Bool)
push!(vl, :($v * $(rand()-0.5)))
end
if rand(Bool)
push!(vl, :($v * $(rand()-0.5)))
end
end
if rand(Bool)
push!(vl, :($(rand()-0.5)))
end
if rand(Bool)
push!(vr, :($(rand()-0.5)))
end
if !isempty(vl) || !isempty(vr)
if isempty(vl)
tmp = Expr(:call, :+, vr...)
elseif isempty(vr)
tmp = Expr(:call, :+, vl...)
else
tmp = Expr(:call, :*,
Expr(:call, :+, vl...),
Expr(:call, :+, vr...))
end
push!(ex.args, tmp)
end
end
return ex
end
m = Model()
@defVar(m, x)
@defVar(m, y)
@defVar(m, z)
@defVar(m, w)
@defVar(m, v)
N = 5
vars = [:x, :y, :z, :w, :v, :(identity(x)), :(identity(y)), :(identity(z))]
const ε = 10eps()
nvars = length(vars)
function test_approx_equal_exprs(ex1, ex2)
res = true
# test constant term
abs(ex1.aff.constant - ex2.aff.constant) < ε || (res = false)
# test aff terms
vals = zeros(nvars)
for i in 1:length(ex1.aff.vars)
vals[ex1.aff.vars[i].col] += ex1.aff.coeffs[i]
end
for i in 1:length(ex2.aff.vars)
vals[ex2.aff.vars[i].col] -= ex2.aff.coeffs[i]
end
for v in vals
abs(v) < ε || (res = false)
end
# test quad terms
qvals = zeros(nvars,nvars)
for i in 1:length(ex1.qcoeffs)
j,k = sort([ex1.qvars1[i].col, ex1.qvars2[i].col])
qvals[j,k] += ex1.qcoeffs[i]
end
for i in 1:length(ex2.qcoeffs)
j,k = sort([ex2.qvars1[i].col, ex2.qvars2[i].col])
qvals[j,k] -= ex2.qcoeffs[i]
end
for v in vals
abs(v) < ε || (res = false)
end
if !res
warn("The following expression did not pass the fuzzer:\n ex1 = $ex1\n ex2 = $ex2")
end
return res
end
println("[fuzzer] Check macros for expression construction")
for _ in 1:100
raff = random_aff_expr(N, vars)
ex = @eval @defExpr($raff)
@fact test_approx_equal_exprs(ex, eval(raff)) --> true
end