From 3a5628e7b3a8bf6038fb75858b50cb82ce9eab90 Mon Sep 17 00:00:00 2001 From: Emiko Soroka Date: Sun, 16 Jul 2023 16:36:26 -0700 Subject: [PATCH 01/36] Fixed including Base.:(==) in the documentation. --- docs/src/functions.md | 16 +--------------- src/IntExpr.jl | 2 +- 2 files changed, 2 insertions(+), 16 deletions(-) diff --git a/docs/src/functions.md b/docs/src/functions.md index 2e90f1a..f11efa5 100644 --- a/docs/src/functions.md +++ b/docs/src/functions.md @@ -49,22 +49,8 @@ Base.:/(a::RealExpr, b::RealExpr) ``` ### Comparison operators -`Base.==` - Method -```julia - a == b - a == 1.0 -``` -Returns the Boolean expression a == b (arithmetic equivalence). Use dot broadcasting for vector-valued and matrix-valued expressions. - -```julia -@satvariable(a[1:n], :Int) -@satvariable(b[1:n, 1:m], :Int) -a .== b -``` - -**Note:** To test whether two `AbstractExpr`s are eqivalent (in the sense that all properties are equal, not in the shared-memory-location sense of `===`), use `isequal`. - ```@docs +Base.:(==)(a::AbstractExpr, b::AbstractExpr) Base.:<(a::AbstractExpr, b::AbstractExpr) Base.:<=(a::AbstractExpr, b::AbstractExpr) Base.:>(a::AbstractExpr, b::AbstractExpr) diff --git a/src/IntExpr.jl b/src/IntExpr.jl index 5efd3e3..b204546 100644 --- a/src/IntExpr.jl +++ b/src/IntExpr.jl @@ -187,7 +187,7 @@ a .== b **Note:** To test whether two `AbstractExpr`s are eqivalent (in the sense that all properties are equal, not in the shared-memory-location sense of `===`), use `isequal`. """ -function Base.:(==)(e1::T, e2::T) where T <: AbstractExpr +function Base.:(==)(e1::AbstractExpr, e2::AbstractExpr) value = isnothing(e1.value) || isnothing(e2.value) ? nothing : e1.value == e2.value name = __get_hash_name(:EQ, [e1, e2]) return BoolExpr(:EQ, [e1, e2], value, name) From b4ab596c0ad01398a8f560d48a31cba3402075b2 Mon Sep 17 00:00:00 2001 From: Emiko Soroka Date: Tue, 25 Jul 2023 16:13:24 -0700 Subject: [PATCH 02/36] Added support and unittest coverage for os-dependent line endings when writing SMT files and interacting with solvers. Users can override behavior by providing a kwarg line_endings="" in smt() and save(). --- TODOS.txt | 6 ++- src/BoolExpr.jl | 2 +- src/call_solver.jl | 15 +++--- src/smt_representation.jl | 78 ++++++++++++++++++-------------- test/runtests.jl | 2 + test/smt_representation_tests.jl | 8 ++-- 6 files changed, 63 insertions(+), 48 deletions(-) diff --git a/TODOS.txt b/TODOS.txt index 0e056ad..ad8968e 100644 --- a/TODOS.txt +++ b/TODOS.txt @@ -69,10 +69,14 @@ Add a check at this stage so invoking the solver throws a WARNING or ERROR if th Add documentation about specifying a solver. Specifically, update advanced.md and the examples + tutorial - done 7/5/23 Discuss Kochenderfer's API change for variables to match JuMP - done 7/7/23 Update documentation to use value.(x) -Print the error-causing solver output when a parsing error occurs - already happens +Print the error-causing solver output when a parsing error occurs - done, already happens Update call_solver.jl to expose a function send_command(cmd::String; is_valid=nested_parens_match) which issues a command to an open solver process and returns the input when is_done is true. - done 7/5/23 # TODO 7/8/23 Make final API change of @satvariable to mirror JuMP @variable - done 7/8/23 Update documentation and examples for variable macro. Use repo2docker to publish examples https://repo2docker.readthedocs.io/en/latest/usage.html + +# TODO 7/25/23 +Change @satvariable to use Bool instead of :Bool, etc. +Use system newline in smt() - done 7/25/23 \ No newline at end of file diff --git a/src/BoolExpr.jl b/src/BoolExpr.jl index c4051ee..5a9c4e0 100644 --- a/src/BoolExpr.jl +++ b/src/BoolExpr.jl @@ -89,7 +89,7 @@ macro satvariable(expr, exprtype) iterable1, iterable2 = expr.args[2], expr.args[3] return esc(:($stem = [$(exprtype.value)("$(:($$name))_$(i)_$(j)") for i in $iterable1, j in $iterable2])) else - @error "Unable to create Bool from expression $expr. Recommended usage: \"@Bool(x)\", \"@Bool(x[1:n])\", or \"@Bool(x[1:m, 1:n])\"." + @error "Unable to create variable from expression $expr. Recommended usage: \"@Bool(x)\", \"@Bool(x[1:n])\", or \"@Bool(x[1:m, 1:n])\"." end end diff --git a/src/call_solver.jl b/src/call_solver.jl index d0e60e1..cd63b68 100644 --- a/src/call_solver.jl +++ b/src/call_solver.jl @@ -42,13 +42,13 @@ end Open a solver in a new process with in, out, and err pipes. Uses Base.process. Check the source code to see the exact implementation. """ -function send_command(pstdin::Base.Pipe, pstdout::Base.Pipe, cmd::String; is_done = f(output::String) = false) +function send_command(pstdin::Base.Pipe, pstdout::Base.Pipe, cmd::String; is_done = f(output::String) = false, line_ending='\n') # f() is required because Task can only schedule functions with no inputs f() = __wait_for_result(pstdout, is_done) t = Task(f) schedule(t) # now send the command - write(pstdin, cmd*"\n") # in case the input is missing \n + write(pstdin, cmd*line_ending) # in case the input is missing a line ending output = fetch(t) # throws automatically if t fails return output @@ -75,12 +75,13 @@ end function talk_to_solver(input::String, s::Solver) + line_ending = Sys.iswindows() ? "\r\n" : '\n' proc, pstdin, pstdout, pstderr = open_solver(s) is_sat_or_unsat(output) = occursin("sat", output) - output = send_command(pstdin, pstdout, input, is_done=is_sat_or_unsat) + output = send_command(pstdin, pstdout, input, is_done=is_sat_or_unsat, line_ending=line_ending) - @debug "Solver output for (check-sat):\n\"$output\"" + @debug "Solver output for (check-sat):$line_ending\"$output\"" if length(output) == 0 @error "Unable to retrieve solver output." return :ERROR, Dict{String, Bool}(), proc @@ -95,14 +96,14 @@ function talk_to_solver(input::String, s::Solver) return :UNSAT, Dict{String, Bool}(), proc elseif output == "sat" # the problem is satisfiable - output = send_command(pstdin, pstdout, "(get-model)\n", is_done=nested_parens_match) - @debug "Solver output for (get-model):\n\"$output\"" + output = send_command(pstdin, pstdout, "(get-model)$line_ending", is_done=nested_parens_match, line_ending=line_ending) + @debug "Solver output for (get-model):$line_ending\"$output\"" satisfying_assignment = parse_smt_output(output) return :SAT, satisfying_assignment, proc else - @error "Solver error:\n$(output)" + @error "Solver error:$line_ending $(output)" return :ERROR, Dict{String, Bool}(), proc end end diff --git a/src/smt_representation.jl b/src/smt_representation.jl index 6e06f78..b44fabc 100644 --- a/src/smt_representation.jl +++ b/src/smt_representation.jl @@ -10,7 +10,7 @@ __smt_typenames = Dict( ##### GENERATING SMTLIB REPRESENTATION ##### """ - declare(z) + declare(z; line_ending='\n') Generate SMT variable declarations for a BoolExpr variable (operation = :IDENTITY). @@ -18,30 +18,30 @@ Examples: * `declare(a::IntExpr)` returns `"(declare-const a Int)\\n"` * `declare(and(z1, z2))` returns `"(declare-const z1 Bool)\\n(declare-const z2 Bool)\\n"`. """ -function declare(z::AbstractExpr) +function declare(z::AbstractExpr; line_ending='\n') # There is only one variable vartype = __smt_typenames[typeof(z)] if length(z) == 1 - return "(declare-const $(z.name) $vartype)\n" + return "(declare-const $(z.name) $vartype)$line_ending" # Variable is 1D elseif length(size(z)) == 1 - return join(map( (i) -> "(declare-const $(z.name)_$i $vartype)\n", 1:size(z)[1])) + return join(map( (i) -> "(declare-const $(z.name)_$i $vartype)$line_ending", 1:size(z)[1])) # Variable is 2D elseif length(size(z)) == 2 declarations = String[] # map over 2D variable rows, then cols inside m,n = size(z) map(1:m) do i - append_unique!(declarations, map( (j) -> "(declare-const $(z.name)_$(i)_$j $vartype)\n", 1:size(z)[2])) + append_unique!(declarations, map( (j) -> "(declare-const $(z.name)_$(i)_$j $vartype)$line_ending", 1:size(z)[2])) end return join(declarations) else error("Invalid size $(z.shape) for variable!") end - join(declarations, '\n') + join(declarations, line_ending) end -declare(zs::Array{T}) where T <: AbstractExpr = reduce(*, map(declare, zs)) +declare(zs::Array{T}; line_ending='\n') where T <: AbstractExpr = reduce(*, declare.(zs; line_ending=line_ending)) # Determine the return type of an expression with operation op and children zs @@ -77,12 +77,12 @@ end cache is a Dict where each value is an SMT statement and its key is the hash of the statement. This allows us to avoid two things: 1. Redeclaring SMT statements, which causes the solver to emit errors. 2. Re-using named functions. For example if we \"(define-fun FUNC_NAME or(z1, z2))\" and then the expression or(z1, z2) re-appears later in the expression \"and(or(z1, z2), z3)\", we can write and(FUNC_NAME, z3)." -function __define_n_op!(zs::Array{T}, op::Symbol, cache::Dict{UInt64, String}, depth::Int) where T <: AbstractExpr +function __define_n_op!(zs::Array{T}, op::Symbol, cache::Dict{UInt64, String}, depth::Int, line_ending='\n') where T <: AbstractExpr if length(zs) == 0 return "" elseif length(zs) == 1 - return depth == 0 ? "(assert ($(zs[1].name)))\n" : "" + return depth == 0 ? "(assert ($(zs[1].name)))$line_ending" : "" else fname = __get_hash_name(op, zs) @@ -93,16 +93,16 @@ function __define_n_op!(zs::Array{T}, op::Symbol, cache::Dict{UInt64, String}, d if op ∈ __commutative_ops varnames = sort(varnames) end - declaration = "(define-fun $fname () $outname ($(__smt_n_opnames[op]) $(join(varnames, " "))))\n" + declaration = "(define-fun $fname () $outname ($(__smt_n_opnames[op]) $(join(varnames, " "))))$line_ending" cache_key = hash(declaration) # we use this to find out if we already declared this item prop = "" if cache_key in keys(cache) prop = depth == 0 ? cache[cache_key] : "" else if op ∈ __boolean_ops && depth == 0 - prop = declaration*"(assert $fname)\n" + prop = declaration*"(assert $fname)$line_ending" # the proposition is generated and cached now. - cache[cache_key] = "(assert $fname)\n" + cache[cache_key] = "(assert $fname)$line_ending" else prop = declaration end @@ -112,15 +112,15 @@ function __define_n_op!(zs::Array{T}, op::Symbol, cache::Dict{UInt64, String}, d end -function __define_1_op!(z::AbstractExpr, op::Symbol, cache::Dict{UInt64, String}, depth::Int) +function __define_1_op!(z::AbstractExpr, op::Symbol, cache::Dict{UInt64, String}, depth::Int, line_ending='\n') fname = __get_hash_name(op, z.children) outname = __return_type(op, [z]) prop = "" - declaration = "(define-fun $fname () $outname ($(__smt_1_opnames[op]) $(__get_smt_name(z.children[1]))))\n" + declaration = "(define-fun $fname () $outname ($(__smt_1_opnames[op]) $(__get_smt_name(z.children[1]))))$line_ending" cache_key = hash(declaration) if depth == 0 && !isa(z, BoolEx) - @warn("Cannot assert non-Boolean expression\n$z") + @warn("Cannot assert non-Boolean expression $z") end if cache_key in keys(cache) && depth == 0 @@ -129,9 +129,9 @@ function __define_1_op!(z::AbstractExpr, op::Symbol, cache::Dict{UInt64, String} # if depth = 0 that means we are at the top-level of a nested expression. # thus, if the expr is Boolean we should assert it. if op ∈ __boolean_ops && depth == 0 - prop = declaration*"(assert $fname)\n" + prop = declaration*"(assert $fname)$line_ending" # the proposition is generated and cached now. - cache[cache_key] = "(assert $fname)\n" + cache[cache_key] = "(assert $fname)$line_ending" else prop = declaration end @@ -143,21 +143,21 @@ end "smt!(prob, declarations, propositions) is an INTERNAL version of smt(prob). We use it to iteratively build a list of declarations and propositions. -Users should call smt(prob)." -function smt!(z::AbstractExpr, declarations::Array{T}, propositions::Array{T}, cache::Dict{UInt64, String}, depth::Int) :: Tuple{Array{T}, Array{T}} where T <: String +Users should call smt(prob, line_ending)." +function smt!(z::AbstractExpr, declarations::Array{T}, propositions::Array{T}, cache::Dict{UInt64, String}, depth::Int, line_ending) :: Tuple{Array{T}, Array{T}} where T <: String if z.op == :IDENTITY n = length(declarations) - push_unique!(declarations, declare(z)) + push_unique!(declarations, declare(z; line_ending=line_ending)) elseif z.op == :CONST ; else - map( (c) -> smt!(c, declarations, propositions, cache, depth+1) , z.children) + map( (c) -> smt!(c, declarations, propositions, cache, depth+1, line_ending) , z.children) if z.op ∈ keys(__smt_1_opnames) - props = [__define_1_op!(z, z.op, cache, depth),] + props = [__define_1_op!(z, z.op, cache, depth, line_ending),] elseif z.op ∈ keys(__smt_n_opnames) # all n-ary ops where n >= 2 - props = broadcast((zs::Vararg{AbstractExpr}) -> __define_n_op!(collect(zs), z.op, cache, depth), z.children...) + props = broadcast((zs::Vararg{AbstractExpr}) -> __define_n_op!(collect(zs), z.op, cache, depth, line_ending), z.children...) #n = length(propositions) props = collect(props) else @@ -173,7 +173,7 @@ end # Example: # * `smt(and(z1, z2))` yields the statements `(declare-const z1 Bool)\n(declare-const z2 Bool)\n(define-fun AND_31df279ea7439224 Bool (and z1 z2))\n(assert AND_31df279ea7439224)\n` """ - smt(z::AbstractExpr) + smt(z::AbstractExpr; line_ending='\n') smt(z1,...,zn) smt([z1,...,zn]) @@ -181,43 +181,51 @@ Generate the SMT representation of `z` or `and(z1,...,zn)`. When calling `smt([z1,...,zn])`, the array must have type `Array{AbstractExpr}`. Note that list comprehensions do not preserve array typing. For example, if `z` is an array of `BoolExpr`, `[z[i] for i=1:n]` will be an array of type `Any`. To preserve the correct type, use `BoolExpr[z[i] for i=1:n]`. """ -function smt(zs::Array{T}) where T <: AbstractExpr +function smt(zs::Array{T}; line_ending=nothing) where T <: AbstractExpr + if isnothing(line_ending) + line_ending = Sys.iswindows() ? "\r\n" : '\n' + end + declarations = String[] propositions = String[] cache = Dict{UInt64, String}() if length(zs) == 1 - declarations, propositions = smt!(zs[1], declarations, propositions, cache, 0) + declarations, propositions = smt!(zs[1], declarations, propositions, cache, 0, line_ending) else - map((z) -> smt!(z, declarations, propositions, cache, 0), zs) + map((z) -> smt!(z, declarations, propositions, cache, 0, line_ending), zs) end # this expression concatenates all the strings in row 1, then all the strings in row 2, etc. return reduce(*, declarations)*reduce(*,propositions) end -smt(zs::Vararg{Union{Array{T}, T}}) where T <: AbstractExpr = smt(collect(zs)) +smt(zs::Vararg{Union{Array{T}, T}}; line_ending=nothing) where T <: AbstractExpr = smt(collect(zs), line_ending=line_ending) ##### WRITE TO FILE ##### """ - save(z::AbstractExpr, filename) - save(z::Array{AbstractExpr}, filename=filename) + save(z::AbstractExpr, filename; line_ending='\n') + save(z::Array{AbstractExpr}, filename=filename, line_ending='\n') save(z1, z2,..., filename) # z1, z2,... are type AbstractExpr Write the SMT representation of `z` or `and(z1,...,zn)` to filename.smt. """ -function save(prob::AbstractExpr, filename="out") +function save(prob::AbstractExpr, filename="out"; line_ending=nothing) + if isnothing(line_ending) + line_ending = Sys.iswindows() ? "\r\n" : '\n' + end + if !isa(prob, BoolExpr) @warn "Top-level expression must be Boolean to produce a valid SMT program." end open("$filename.smt", "w") do io - write(io, smt(prob)) - write(io, "(check-sat)\n") + write(io, smt(prob, line_ending=line_ending)) + write(io, "(check-sat)$line_ending") end end # this is the version that accepts a list of exprs, for example save(z1, z2, z3). This is necessary because if z1::BoolExpr and z2::Array{BoolExpr}, etc, then the typing is too difficult to make an array. -save(zs::Vararg{Union{Array{T}, T}}; filename="out") where T <: AbstractExpr = save(__flatten_nested_exprs(all, zs...), filename) +save(zs::Vararg{Union{Array{T}, T}}; filename="out", line_ending=nothing) where T <: AbstractExpr = save(__flatten_nested_exprs(all, zs...), filename, line_ending=line_ending) # array version for convenience. THIS DOES NOT ACCEPT ARRAYS OF MIXED AbstractExpr and Array{AbstractExpr}. -save(zs::Array{T}, filename="out") where T <: AbstractExpr = save(all(zs), filename) +save(zs::Array{T}, filename="out"; line_ending=nothing) where T <: AbstractExpr = save(all(zs), filename, line_ending=line_ending) diff --git a/test/runtests.jl b/test/runtests.jl index 0de90fa..ac68f47 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -1,3 +1,5 @@ +push!(LOAD_PATH, "../src") +push!(LOAD_PATH, "./") using BooleanSatisfiability using Test, Logging diff --git a/test/smt_representation_tests.jl b/test/smt_representation_tests.jl index 43f7840..30f13e6 100644 --- a/test/smt_representation_tests.jl +++ b/test/smt_representation_tests.jl @@ -45,13 +45,13 @@ end @satvariable(z1, :Bool) @satvariable(z12[1:1, 1:2], :Bool) - # implies + # implies, also tests \r\n hashname = BooleanSatisfiability.__get_hash_name(:IMPLIES, [z1, z12[1,2]]) - @test smt(z1 ⟹ z12[1,2]) == smt(z1)*smt(z12[1,2])*"(define-fun $hashname () Bool (=> z1 z12_1_2))\n(assert $hashname)\n" + @test smt(z1 ⟹ z12[1,2], line_ending="\r\n") == "(declare-const z1 Bool)\r\n(declare-const z12_1_2 Bool)\r\n(define-fun $hashname () Bool (=> z1 z12_1_2))\r\n(assert $hashname)\r\n" - # iff + # iff, also tests \r\n hashname = BooleanSatisfiability.__get_hash_name(:IFF, [z1, z12[1,2]]) - @test smt(z1 ⟺ z12[1,2]) == smt(z1)*smt(z12[1,2])*"(define-fun $hashname () Bool (= z1 z12_1_2))\n(assert $hashname)\n" + @test smt(z1 ⟺ z12[1,2], line_ending="\r\n") == smt(z1, line_ending="\r\n")*smt(z12[1,2], line_ending="\r\n")*"(define-fun $hashname () Bool (= z1 z12_1_2))\r\n(assert $hashname)\r\n" # xor hashname = BooleanSatisfiability.__get_hash_name(:XOR, z12) From 3f6383fb598e9116ff38e8e6de1618ea3fab2edc Mon Sep 17 00:00:00 2001 From: Emiko Soroka Date: Tue, 25 Jul 2023 16:36:46 -0700 Subject: [PATCH 03/36] Changed @satvariable to match JuMP, @satvariable(x, Bool) instead of @satvariable(x, :Bool) etc. Changed tests and docs. --- TODOS.txt | 2 +- docs/src/advanced.md | 2 +- docs/src/example_job_shop.md | 4 +-- docs/src/example_scheduling.md | 2 +- docs/src/faq.md | 4 +-- docs/src/tutorial.md | 12 +++---- examples/job_shop_scheduling.jl | 4 +-- examples/mini_example.jl | 6 ++-- examples/schedule_example.jl | 2 +- examples/scheduling_example.ipynb | 3 +- src/BoolExpr.jl | 26 +++++++------- src/BooleanOperations.jl | 10 +++--- src/IntExpr.jl | 58 +++++++++++++++---------------- src/smt_representation.jl | 2 +- test/boolean_operation_tests.jl | 32 ++++++++--------- test/int_parse_tests.jl | 8 ++--- test/int_real_tests.jl | 20 +++++------ test/runtests.jl | 2 +- test/smt_representation_tests.jl | 24 ++++++------- test/solver_interface_tests.jl | 16 ++++----- 20 files changed, 119 insertions(+), 120 deletions(-) diff --git a/TODOS.txt b/TODOS.txt index ad8968e..28df337 100644 --- a/TODOS.txt +++ b/TODOS.txt @@ -78,5 +78,5 @@ Update documentation and examples for variable macro. Use repo2docker to publish examples https://repo2docker.readthedocs.io/en/latest/usage.html # TODO 7/25/23 -Change @satvariable to use Bool instead of :Bool, etc. +Change @satvariable to use Bool instead of :Bool, etc. - done 7/25/23 Use system newline in smt() - done 7/25/23 \ No newline at end of file diff --git a/docs/src/advanced.md b/docs/src/advanced.md index c58fb8b..ba022b2 100644 --- a/docs/src/advanced.md +++ b/docs/src/advanced.md @@ -26,7 +26,7 @@ In the SMT2 specification, after entering a problem and issuing the command `(ch Here's an example. ```julia -@satvariable(x[1:2], :Bool) +@satvariable(x[1:2], Bool) expr = (x[1] ∧ ¬x[1]) ∧ any(x) # unsat solver = Z3() diff --git a/docs/src/example_job_shop.md b/docs/src/example_job_shop.md index 9313d4e..c59e5a9 100644 --- a/docs/src/example_job_shop.md +++ b/docs/src/example_job_shop.md @@ -19,8 +19,8 @@ We'd like to find a solution such that all three jobs can be completed in an 8-h using BooleanSatisfiability n = 3 # number of jobs m = 2 # number of tasks per job -@satvariable(t1[1:n], :Int) -@satvariable(t2[1:n], :Int) +@satvariable(t1[1:n], Int) +@satvariable(t2[1:n], Int) d1 = [2; 3; 2] d2 = [1; 1; 3] ``` diff --git a/docs/src/example_scheduling.md b/docs/src/example_scheduling.md index e79f880..8768230 100644 --- a/docs/src/example_scheduling.md +++ b/docs/src/example_scheduling.md @@ -27,7 +27,7 @@ A_bar = Bool[ ] # A is a matrix-valued variable such that ``A_{it} = 1`` if attendee ``i`` is in a meeting at time ``t`` and 0 otherwise. -@satvariable(A[1:n, 1:T], :Bool) +@satvariable(A[1:n, 1:T], Bool) ``` The `index_sets` represent which meeting attendees are required at each meeting ``\mathcal{I_j}``. diff --git a/docs/src/faq.md b/docs/src/faq.md index 52cfdd6..da2e1ab 100644 --- a/docs/src/faq.md +++ b/docs/src/faq.md @@ -49,8 +49,8 @@ To prevent names from being duplicated, BooleanSatisfiability.jl names new expre For example, suppose you have ```@example -@satvariable(a, :Int) -@satvariable(b, :Int) +@satvariable(a, Int) +@satvariable(b, Int) expr = a <= b print(smt(expr)) ``` diff --git a/docs/src/tutorial.md b/docs/src/tutorial.md index dba4fd3..a29312d 100644 --- a/docs/src/tutorial.md +++ b/docs/src/tutorial.md @@ -8,8 +8,8 @@ We say a formula is **valid** if it is true for every assignment of values to it One famous transformation is De Morgan's law: `a ∧ b = ¬(¬a ∨ ¬b)`. To show validity of De Morgan's law, we can construct the bidirectional implication `a ∧ b ⟺ ¬(¬a ∨ ¬b)`. It suffices to show that the negation of this formula is unsatisfiable. ```@example -@satvariable(a, :Bool) -@satvariable(b, :Bool) +@satvariable(a, Bool) +@satvariable(b, Bool) conjecture = iff(a ∧ b, ¬(¬a ∨ ¬b)) status = sat!(¬conjecture, Z3()) # status will be either :SAT or :UNSAT @@ -18,9 +18,9 @@ status = sat!(¬conjecture, Z3()) # status will be either :SAT or :UNSAT Suppose you have Boolean variables `p`, `q` and `r`. A common mistake made by students in discrete math classes is to think that if `p` implies `q` and `q` implies `r` (`(p ⟹ q) ∧ (q ⟹ r)`) then `p` must imply `r` (`p ⟹ r`). Are these statements equivalent? We can use a SAT solver to check. ```@example -@satvariable(p, :Bool) -@satvariable(q, :Bool) -@satvariable(r, :Bool) +@satvariable(p, Bool) +@satvariable(q, Bool) +@satvariable(r, Bool) conjecture = iff((p ⟹ q) ∧ (q ⟹ r), p ⟹ r) status = sat!(¬conjecture, Z3()) @@ -40,7 +40,7 @@ A simpler version, illustrated in this [classic XKCD strip](https://xkcd.com/287 In fact, the problem in the XKCD strip can be expressed as a linear equation over integers. ```@example -@satvariable(a[1:6], :Bool) +@satvariable(a[1:6], Bool) c = [215; 275; 335; 355; 420; 580] expr = and([all(a .>= 0), sum(a .* c) == 1505]) sat!(expr, Z3()) diff --git a/examples/job_shop_scheduling.jl b/examples/job_shop_scheduling.jl index 778f666..b270783 100644 --- a/examples/job_shop_scheduling.jl +++ b/examples/job_shop_scheduling.jl @@ -16,8 +16,8 @@ using BooleanSatisfiability n = 3 # number of jobs m = 2 # number of tasks per job -@satvariable(t1[1:n], :Int) -@satvariable(t2[1:n], :Int) +@satvariable(t1[1:n], Int) +@satvariable(t2[1:n], Int) d1 = [2; 3; 2] d2 = [1; 1; 3] diff --git a/examples/mini_example.jl b/examples/mini_example.jl index 7235391..a77cf24 100644 --- a/examples/mini_example.jl +++ b/examples/mini_example.jl @@ -4,9 +4,9 @@ using BooleanSatisfiability # let's define a matrix of Boolean statements n = 3 m = 2 -@satvariable(x[1:m, 1:n], :Bool) -@satvariable(y[1:m, 1:n], :Bool) -@satvariable(z[1:n], :Bool) +@satvariable(x[1:m, 1:n], Bool) +@satvariable(y[1:m, 1:n], Bool) +@satvariable(z[1:n], Bool) # At each step, either x or y has to be true expr1 = all(x .∨ y) .∨ and.(¬z, z) diff --git a/examples/schedule_example.jl b/examples/schedule_example.jl index 265b742..197c2bb 100644 --- a/examples/schedule_example.jl +++ b/examples/schedule_example.jl @@ -26,7 +26,7 @@ A_bar = Bool[ index_sets = [[1,2,3], [3,4,5], [1,3,5], [1,4]] J = length(index_sets) # number of meetings -@satvariable(A[1:n, 1:T], :Bool) +@satvariable(A[1:n, 1:T], Bool) unavailability = and(¬A_bar .⟹ ¬A) diff --git a/examples/scheduling_example.ipynb b/examples/scheduling_example.ipynb index 406ba36..6c17759 100644 --- a/examples/scheduling_example.ipynb +++ b/examples/scheduling_example.ipynb @@ -120,8 +120,7 @@ } ], "source": [ - "A = Bool(n,T,\"A\")\n", - "value(A)\n", + "@satvariable(A[1:n, 1:T], Bool)\n", "\n", "#past_availability = all(¬A_bar .⟹ ¬A)\n", "booked = BoolExpr[]\n", diff --git a/src/BoolExpr.jl b/src/BoolExpr.jl index 5a9c4e0..2ebbddb 100644 --- a/src/BoolExpr.jl +++ b/src/BoolExpr.jl @@ -54,42 +54,42 @@ Bool(m::Int, n::Int, name::String) :: Matrix{BoolExpr} = BoolExpr[Bool("$(name)_ __valid_vartypes = [:Bool, :Int, :Real] """ - @satvariable(z, :Bool) - @satvariable(a[1:n], :Int) + @satvariable(z, Bool) + @satvariable(a[1:n], Int) -Construct a SAT variable with name z, optional array dimensions, and specified type (`:Bool`, `:Int` or `:Real`). +Construct a SAT variable with name z, optional array dimensions, and specified type (`Bool`, `Int` or `Real`). One and two-dimensional variables can be constructed with the following syntax. ```julia -@satvariable(a[1:n], :Int) # an Int vector of length n -@satvariable(x[1:m, 1:n], :Real) # an m x n Int matrix +@satvariable(a[1:n], Int) # an Int vector of length n +@satvariable(x[1:m, 1:n], Real) # an m x n Int matrix ``` """ -macro satvariable(expr, exprtype) - # check exprtype - if !isa(exprtype, QuoteNode) || !(exprtype.value ∈ __valid_vartypes) # unknown - @error "Unknown expression type $exprtype" +macro satvariable(expr, typename) + # check typename + if !isa(typename, Symbol) || !(typename ∈ __valid_vartypes) # unknown + @error "Unknown expression type $typename" end # inside here name and t are exprs if isa(expr, Symbol) # one variable, eg @Bool(x) name = string(expr) # this line resolves to something like x = Bool("x") - return esc(:($expr = $(exprtype.value)($name))) + return esc(:($expr = $(typename)($name))) elseif length(expr.args) == 2 && isa(expr.args[1], Symbol) stem = expr.args[1] name = string(stem) iterable = expr.args[2] - return esc(:($stem = [$(exprtype.value)("$(:($$name))_$(i)") for i in $iterable])) + return esc(:($stem = [$(typename)("$(:($$name))_$(i)") for i in $iterable])) elseif length(expr.args) == 3 stem = expr.args[1] name = string(stem) iterable1, iterable2 = expr.args[2], expr.args[3] - return esc(:($stem = [$(exprtype.value)("$(:($$name))_$(i)_$(j)") for i in $iterable1, j in $iterable2])) + return esc(:($stem = [$(typename)("$(:($$name))_$(i)_$(j)") for i in $iterable1, j in $iterable2])) else - @error "Unable to create variable from expression $expr. Recommended usage: \"@Bool(x)\", \"@Bool(x[1:n])\", or \"@Bool(x[1:m, 1:n])\"." + @error "Unable to create variable from expression $expr. Recommended usage: \"@satvariable(x, Bool)\", \"@satvariable(x[1:n], Int)\", or \"@satvariable(x[1:m, 1:n], Bool)\"." end end diff --git a/src/BooleanOperations.jl b/src/BooleanOperations.jl index 753eac2..0c3d28a 100644 --- a/src/BooleanOperations.jl +++ b/src/BooleanOperations.jl @@ -45,7 +45,7 @@ Return the logical negation of `z`. Note: Broacasting a unary operator requires the syntax `.¬z` which can be confusing to new Julia users. We define `¬(z::Array{BoolExpr})` for convenience. ```julia - @satvariable(z[1:n], :Bool) + @satvariable(z[1:n], Bool) ¬z # syntactic sugar for map(¬, z) .¬z # also valid ``` @@ -92,8 +92,8 @@ end Returns the logical AND of two or more variables. Use dot broadcasting for vector-valued and matrix-valued Boolean expressions. ```julia -@satvariable(z1[1:n], :Bool) -@satvariable(z2[n, 1:m], :Bool) +@satvariable(z1[1:n], Bool) +@satvariable(z2[n, 1:m], Bool) z1 .∧ z2 and.(z1, z2) # equivalent to z1 .∧ z2 ``` @@ -136,8 +136,8 @@ end Returns the logical OR of two or more variables. Use dot broadcasting for vector-valued and matrix-valued Boolean expressions. ```julia -@satvariable(z1[1:n], :Bool) -@satvariable(z2[1:m, 1:n], :Bool) +@satvariable(z1[1:n], Bool) +@satvariable(z2[1:m, 1:n], Bool) z1 .∨ z2 or.(z1, z2) # equivalent to z1 .∨ z2 ``` diff --git a/src/IntExpr.jl b/src/IntExpr.jl index b204546..f8c9e1f 100644 --- a/src/IntExpr.jl +++ b/src/IntExpr.jl @@ -95,10 +95,10 @@ __wrap_const(c::Union{Int, Bool}) = IntExpr(:CONST, AbstractExpr[], c, "const_$c Returns the Boolean expression a < b. Use dot broadcasting for vector-valued and matrix-valued expressions. ```julia -@satvariable(a[1:n], :Int) -@satvariable(b[1:n, 1:m], :Int) +@satvariable(a[1:n], Int) +@satvariable(b[1:n, 1:m], Int) a .< b -@satvariable(z, :Bool) +@satvariable(z, Bool) a .< z ``` """ @@ -115,10 +115,10 @@ end Returns the Boolean expression a <= b. Use dot broadcasting for vector-valued and matrix-valued expressions. ```julia -@satvariable(a[1:n], :Int) -@satvariable(b[1:n, 1:m], :Int) +@satvariable(a[1:n], Int) +@satvariable(b[1:n, 1:m], Int) a .<= b -@satvariable(z, :Bool) +@satvariable(z, Bool) a .<= z ``` """ @@ -135,10 +135,10 @@ end Returns the Boolean expression a >= b. Use dot broadcasting for vector-valued and matrix-valued expressions. ```julia -@satvariable(a[1:n], :Int) -@satvariable(b[1:n, 1:m], :Int) +@satvariable(a[1:n], Int) +@satvariable(b[1:n, 1:m], Int) a .>= b -@satvariable(z, :Bool) +@satvariable(z, Bool) a .>= z ``` """ @@ -155,10 +155,10 @@ end Returns the Boolean expression a > b. Use dot broadcasting for vector-valued and matrix-valued expressions. ```julia -@satvariable(a[1:n], :Int) -@satvariable(b[1:n, 1:m], :Int) +@satvariable(a[1:n], Int) +@satvariable(b[1:n, 1:m], Int) a .> b -@satvariable(z, :Bool) +@satvariable(z, Bool) a .> z ``` """ @@ -180,8 +180,8 @@ end Returns the Boolean expression a == b (arithmetic equivalence). Use dot broadcasting for vector-valued and matrix-valued expressions. ```julia -@satvariable(a[1:n], :Int) -@satvariable(b[1:n, 1:m], :Int) +@satvariable(a[1:n], Int) +@satvariable(b[1:n, 1:m], Int) a .== b ``` @@ -216,7 +216,7 @@ Base.:(==)(e1::NumericInteroperableConst, e2::AbstractExpr) = __wrap_const(e1) = Return the negative of an Int or Real expression. ```julia -@satvariable(a[1:n, 1:m], :Int) +@satvariable(a[1:n, 1:m], Int) -a # this also works ``` @@ -301,15 +301,15 @@ Return the `Int` | `Real` expression `a+b` (inherits the type of `a+b`). Use dot ```julia -@satvariable(a[1:n], :Int) -@satvariable(b[1:n, 1:m], :Int) +@satvariable(a[1:n], Int) +@satvariable(b[1:n, 1:m], Int) a .+ b println("typeof a+b: \$(typeof(a[1] + b[1]))") -@satvariable(c, :Real) +@satvariable(c, Real) println("typeof a+c: \$(typeof(a[1] + c))") -@satvariable(z, :Bool) +@satvariable(z, Bool) a .+ z println("typeof a+z: \$(typeof(a[1] + z))") ``` @@ -326,15 +326,15 @@ Base.:+(e1::Union{NumericInteroperableConst}, e2::NumericInteroperableExpr) = e2 Returns the `Int` | `Real` expression `a-b` (inherits the type of `a-b`). Use dot broadcasting for vector-valued and matrix-valued Boolean expressions. ```julia -@satvariable(a[1:n], :Int) -@satvariable(b[1:n, 1:m], :Int) +@satvariable(a[1:n], Int) +@satvariable(b[1:n, 1:m], Int) a .- b println("typeof a-b: \$(typeof(a[1] - b[1]))") -@satvariable(c, :Real) +@satvariable(c, Real) println("typeof a-c: \$(typeof(a[1] - c))") -@satvariable(z, :Bool) +@satvariable(z, Bool) a .- z println("typeof a-z: \$(typeof(a[1] - z))") ``` @@ -350,15 +350,15 @@ Base.:-(e1::Union{NumericInteroperableConst}, e2::NumericInteroperableExpr) = __ Returns the `Int` | `Real` multiplication expression `a*b` (inherits the type of `a*b`). Use dot broadcasting for vector-valued and matrix-valued Boolean expressions. ```julia -@satvariable(a[1:n], :Int) -@satvariable(b[1:n, 1:m], :Int) +@satvariable(a[1:n], Int) +@satvariable(b[1:n, 1:m], Int) a .* b println("typeof a*b: \$(typeof(a[1]*b[1]))") -@satvariable(c, :Real) +@satvariable(c, Real) println("typeof a*c: \$(typeof(a[1]*c))") -@satvariable(z, :Bool) +@satvariable(z, Bool) a .- z println("typeof a*z: \$(typeof(a[1]*z))") ``` @@ -374,8 +374,8 @@ Base.:*(e1::Union{NumericInteroperableConst}, e2::NumericInteroperableExpr) = e2 Returns the `Real` division expression `a/b`. Note: `a` and `b` must be `Real`). Use dot broadcasting for vector-valued and matrix-valued Boolean expressions. ```julia -@satvariable(a[1:n], :Real) -@satvariable(b[1:n, 1:m], :Real) +@satvariable(a[1:n], Real) +@satvariable(b[1:n, 1:m], Real) a ./ b println("typeof a/b: \$(typeof(a[1]/b[1]))") ``` diff --git a/src/smt_representation.jl b/src/smt_representation.jl index b44fabc..8a042a4 100644 --- a/src/smt_representation.jl +++ b/src/smt_representation.jl @@ -59,7 +59,7 @@ end # Return either z.name or the correct (as z.name Type) if z.name is defined for multiple types # This multiple name misbehavior is allowed in SMT2; the expression (as z.name Type) is called a fully qualified name. -# It would arise if someone wrote something like @satvariable(x, :Bool); x = xb; @satvariable(x, :Int) +# It would arise if someone wrote something like @satvariable(x, Bool); x = xb; @satvariable(x, Int) function __get_smt_name(z::AbstractExpr) if z.op == :CONST return string(z.value) diff --git a/test/boolean_operation_tests.jl b/test/boolean_operation_tests.jl index f8ddd6c..7922deb 100644 --- a/test/boolean_operation_tests.jl +++ b/test/boolean_operation_tests.jl @@ -3,18 +3,18 @@ using Test @testset "Construct variables" begin # Write your tests here. - @satvariable(z1, :Bool) + @satvariable(z1, Bool) @test isa(z1,BoolExpr) - @satvariable(z32[1:3, 1:2], :Bool) + @satvariable(z32[1:3, 1:2], Bool) @test isa(z32,Array{BoolExpr}) @test size(z32) == (3,2) - @satvariable(z23[1:2,1:3], :Bool) + @satvariable(z23[1:2,1:3], Bool) # Sizes are broadcastable - @satvariable(z12[1:1,1:2], :Bool) - @satvariable(z21[1:2,1:1], :Bool) + @satvariable(z12[1:1,1:2], Bool) + @satvariable(z21[1:2,1:1], Bool) # (1,) broadcasts with (1,2) @test all(size(z1 .∨ z12) .== (1,2)) # (1,) broadcasts with (2,3) @@ -35,11 +35,11 @@ using Test end @testset "Print variables" begin - @satvariable(z[1:2, 1:3], :Bool) + @satvariable(z[1:2, 1:3], Bool) string_z = "BoolExpr[z_1_1\n z_1_2\n z_1_3\n; z_2_1\n z_2_2\n z_2_3\n]" @test string(z) == string_z - @satvariable(z1, :Bool) + @satvariable(z1, Bool) z1.value = true @test string(z1) == "z1 = true\n" end @@ -87,9 +87,9 @@ end end @testset "Additional operations" begin - @satvariable(z, :Bool) - @satvariable(z1[1:1], :Bool) - @satvariable(z12[1:1, 1:2], :Bool) + @satvariable(z, Bool) + @satvariable(z1[1:1], Bool) + @satvariable(z12[1:1, 1:2], Bool) # xor @test all(isequal.(xor.(z1, z12), BoolExpr[xor(z12[1,1], z1[1]) xor(z12[1,2], z1[1])])) @@ -114,7 +114,7 @@ end end @testset "Operations with 1D literals and 1D exprs" begin - @satvariable(z, :Bool) + @satvariable(z, Bool) # Can operate on all literals @test all([not(false), ¬(¬(true))]) @@ -132,7 +132,7 @@ end end @testset "Operations with 1D literals and nxm exprs" begin - @satvariable(z[1:2, 1:3], :Bool) + @satvariable(z[1:2, 1:3], Bool) # Can operate on mixed literals and BoolExprs @test isequal(and.(true, z), z) @@ -146,8 +146,8 @@ end @testset "Operations with nxm literals and nxm exprs" begin A = [true false false; false true true] B = [true true true; true true true] - @satvariable(z1, :Bool) - @satvariable(z[1:2, 1:3], :Bool) + @satvariable(z1, Bool) + @satvariable(z[1:2, 1:3], Bool) # Can operate on all literal matrices @test any([not(A); ¬(¬(A))]) @@ -168,7 +168,7 @@ end @testset "More operations with literals" begin A = [true false false; false true true] - @satvariable(z[1:1], :Bool) + @satvariable(z[1:1], Bool) @test !any(xor.(A, A)) # all false @test all(isequal.(xor.(A, z), [¬z z z; z ¬z ¬z])) @@ -176,7 +176,7 @@ end @test all(isequal.(iff.(A, z), [z ¬z ¬z; ¬z z z])) @test all(isequal.(iff.(z, A), iff.(A, z))) - y = @satvariable(y[1:1], :Bool) + y = @satvariable(y[1:1], Bool) @test all( isequal.(ite.(z, true, false), or.(and.(z, true), and.(¬z, false)) )) @test all( isequal.(ite.(false, y, z), or.(and.(false, y), and.(true, z)) )) end \ No newline at end of file diff --git a/test/int_parse_tests.jl b/test/int_parse_tests.jl index 3d09080..2bc49cd 100644 --- a/test/int_parse_tests.jl +++ b/test/int_parse_tests.jl @@ -3,8 +3,8 @@ using Test @testset "Solving an integer-valued problem" begin CLEAR_VARNAMES!() -@satvariable(a, :Int) -@satvariable(b, :Int) +@satvariable(a, Int) +@satvariable(b, Int) expr1 = a + b + 2 @test smt(expr1) == "(declare-const a Int) (declare-const b Int) @@ -60,9 +60,9 @@ end # Who would do this?? But it's supported anyway. @testset "Define fully-qualified names" begin - @satvariable(a, :Int) + @satvariable(a, Int) b = a - @satvariable(a, :Real) + @satvariable(a, Real) hashname = BooleanSatisfiability.__get_hash_name(:ADD, [b, a]) @test smt(b+a) == "(declare-const a Int) (declare-const a Real) diff --git a/test/int_real_tests.jl b/test/int_real_tests.jl index bd66d90..0703c47 100644 --- a/test/int_real_tests.jl +++ b/test/int_real_tests.jl @@ -2,13 +2,13 @@ using BooleanSatisfiability using Test @testset "Construct Int and Real expressions" begin - @satvariable(a, :Int) - @satvariable(b[1:2], :Int) - @satvariable(c[1:1,1:2], :Int) + @satvariable(a, Int) + @satvariable(b[1:2], Int) + @satvariable(c[1:1,1:2], Int) - @satvariable(ar, :Real) - @satvariable(br[1:2], :Real) - @satvariable(cr[1:1,1:2], :Real) + @satvariable(ar, Real) + @satvariable(br[1:2], Real) + @satvariable(cr[1:1,1:2], Real) a.value = 2; b[1].value = 1 @test isequal((a .< b)[1], BoolExpr(:LT, AbstractExpr[a, b[1]], false, BooleanSatisfiability.__get_hash_name(:LT, [a,b[1]]))) @@ -37,10 +37,10 @@ using Test end @testset "Construct n-ary ops" begin - @satvariable(a, :Int) - @satvariable(b[1:2], :Int) - @satvariable(ar, :Real) - @satvariable(br[1:2], :Real) + @satvariable(a, Int) + @satvariable(b[1:2], Int) + @satvariable(ar, Real) + @satvariable(br[1:2], Real) # Operations with expressions only @test all(isa.(a .+ b, IntExpr)) diff --git a/test/runtests.jl b/test/runtests.jl index ac68f47..998b551 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -21,7 +21,7 @@ include("int_parse_tests.jl") # Extra: Check that defining duplicate variables yields a warning @testset "Duplicate variable warning" begin SET_DUPLICATE_NAME_WARNING!(true) - @satvariable(z, :Bool) + @satvariable(z, Bool) @test_logs (:warn, "Duplicate variable name z of type Bool") Bool("z") # now we should have no warnings diff --git a/test/smt_representation_tests.jl b/test/smt_representation_tests.jl index 30f13e6..182f716 100644 --- a/test/smt_representation_tests.jl +++ b/test/smt_representation_tests.jl @@ -2,9 +2,9 @@ using BooleanSatisfiability using Test @testset "Individual SMTLIB2 statements" begin - @satvariable(z1, :Bool) - @satvariable(z2[1:1], :Bool) - @satvariable(z12[1:1, 1:2], :Bool) + @satvariable(z1, Bool) + @satvariable(z2[1:1], Bool) + @satvariable(z12[1:1, 1:2], Bool) # indexed expression correctly declared @test smt(z12[1,2]) == "(declare-const z12_1_2 Bool)\n" @@ -42,8 +42,8 @@ using Test end @testset "Generate additional exprs" begin - @satvariable(z1, :Bool) - @satvariable(z12[1:1, 1:2], :Bool) + @satvariable(z1, Bool) + @satvariable(z12[1:1, 1:2], Bool) # implies, also tests \r\n hashname = BooleanSatisfiability.__get_hash_name(:IMPLIES, [z1, z12[1,2]]) @@ -58,16 +58,16 @@ end @test smt(xor(z12[1,1], z12[1,2])) == smt(z12[1,1])*smt(z12[1,2])*"(define-fun $hashname () Bool (xor z12_1_1 z12_1_2))\n(assert $hashname)\n" # if-then-else - @satvariable(x, :Bool) - @satvariable(y, :Bool) - @satvariable(z, :Bool) + @satvariable(x, Bool) + @satvariable(y, Bool) + @satvariable(z, Bool) hashname = BooleanSatisfiability.__get_hash_name(:ITE, [x,y,z]) @test smt(ite(x,y,z)) == smt(x)*smt(y)*smt(z)*"(define-fun $hashname () Bool (ite x y z))\n(assert $hashname)\n" end @testset "Generate nested expr without duplications" begin - @satvariable(x, :Bool) - @satvariable(y, :Bool) + @satvariable(x, Bool) + @satvariable(y, Bool) xyname = BooleanSatisfiability.__get_hash_name(:AND, [x,y]) xy = and(x,y) @@ -89,8 +89,8 @@ end end @testset "Generate SMT file" begin - @satvariable(z1, :Bool) - @satvariable(z12[1:1, 1:2], :Bool) + @satvariable(z1, Bool) + @satvariable(z12[1:1, 1:2], Bool) save(z1 .∧ z12, "outfile") text = read(open("outfile.smt", "r"), String) diff --git a/test/solver_interface_tests.jl b/test/solver_interface_tests.jl index c20b53c..5c962a7 100644 --- a/test/solver_interface_tests.jl +++ b/test/solver_interface_tests.jl @@ -3,9 +3,9 @@ using Test, Logging # assign is used after calling the solver so it belongs here. @testset "Assign values" begin - @satvariable(x[1:3], :Bool) - @satvariable(y[1:2], :Bool) - @satvariable(z, :Bool) + @satvariable(x[1:3], Bool) + @satvariable(y[1:2], Bool) + @satvariable(z, Bool) prob = and( all(x), @@ -86,9 +86,9 @@ end @testset "Solving a SAT problem" begin - @satvariable(x[1:3], :Bool) - @satvariable(y[1:2], :Bool) - @satvariable(z, :Bool) + @satvariable(x[1:3], Bool) + @satvariable(y[1:2], Bool) + @satvariable(z, Bool) exprs = BoolExpr[ all(x), @@ -112,8 +112,8 @@ end end @testset "Custom solver interactions" begin - @satvariable(x[1:3], :Bool) - @satvariable(y[1:2], :Bool) + @satvariable(x[1:3], Bool) + @satvariable(y[1:2], Bool) exprs = BoolExpr[ all(x), From 921ca92940bd1b63772cd28da04a0c34c9ed4861 Mon Sep 17 00:00:00 2001 From: Emiko Soroka Date: Sat, 29 Jul 2023 14:36:18 -0700 Subject: [PATCH 04/36] drafting SAT paper --- .../IEEEtran.cls | 6347 +++++++++++++++++ .../bibliography.bib | 76 + .../conference_101719.tex | 288 + .../paper-blx.bib | 11 + .../paper.tex | 292 + TODOS.txt | 2 +- 6 files changed, 7015 insertions(+), 1 deletion(-) create mode 100644 SAT_package_paper/Conference-LaTeX-template_10-17-19/IEEEtran.cls create mode 100644 SAT_package_paper/Conference-LaTeX-template_10-17-19/bibliography.bib create mode 100644 SAT_package_paper/Conference-LaTeX-template_10-17-19/conference_101719.tex create mode 100644 SAT_package_paper/Conference-LaTeX-template_10-17-19/paper-blx.bib create mode 100644 SAT_package_paper/Conference-LaTeX-template_10-17-19/paper.tex diff --git a/SAT_package_paper/Conference-LaTeX-template_10-17-19/IEEEtran.cls b/SAT_package_paper/Conference-LaTeX-template_10-17-19/IEEEtran.cls new file mode 100644 index 0000000..905a10c --- /dev/null +++ b/SAT_package_paper/Conference-LaTeX-template_10-17-19/IEEEtran.cls @@ -0,0 +1,6347 @@ +%% +%% IEEEtran.cls 2015/08/26 version V1.8b +%% +%% This is the IEEEtran LaTeX class for authors of the Institute of +%% Electrical and Electronics Engineers (IEEE) Transactions journals and +%% conferences. +%% +%% Support sites: +%% http://www.michaelshell.org/tex/ieeetran/ +%% http://www.ctan.org/pkg/ieeetran +%% and +%% http://www.ieee.org/ +%% +%% Based on the original 1993 IEEEtran.cls, but with many bug fixes +%% and enhancements (from both JVH and MDS) over the 1996/7 version. +%% +%% +%% Contributors: +%% Gerry Murray (1993), Silvano Balemi (1993), +%% Jon Dixon (1996), Peter N"uchter (1996), +%% Juergen von Hagen (2000), and Michael Shell (2001-2014) +%% +%% +%% Copyright (c) 1993-2000 by Gerry Murray, Silvano Balemi, +%% Jon Dixon, Peter N"uchter, +%% Juergen von Hagen +%% and +%% Copyright (c) 2001-2015 by Michael Shell +%% +%% Current maintainer (V1.3 to V1.8b): Michael Shell +%% See: +%% http://www.michaelshell.org/ +%% for current contact information. +%% +%% Special thanks to Peter Wilson (CUA) and Donald Arseneau +%% for allowing the inclusion of the \@ifmtarg command +%% from their ifmtarg LaTeX package. +%% +%%************************************************************************* +%% Legal Notice: +%% This code is offered as-is without any warranty either expressed or +%% implied; without even the implied warranty of MERCHANTABILITY or +%% FITNESS FOR A PARTICULAR PURPOSE! +%% User assumes all risk. +%% In no event shall the IEEE or any contributor to this code be liable for +%% any damages or losses, including, but not limited to, incidental, +%% consequential, or any other damages, resulting from the use or misuse +%% of any information contained here. +%% +%% All comments are the opinions of their respective authors and are not +%% necessarily endorsed by the IEEE. +%% +%% This work is distributed under the LaTeX Project Public License (LPPL) +%% ( http://www.latex-project.org/ ) version 1.3, and may be freely used, +%% distributed and modified. A copy of the LPPL, version 1.3, is included +%% in the base LaTeX documentation of all distributions of LaTeX released +%% 2003/12/01 or later. +%% Retain all contribution notices and credits. +%% ** Modified files should be clearly indicated as such, including ** +%% ** renaming them and changing author support contact information. ** +%% +%% File list of work: IEEEtran.cls, IEEEtran_HOWTO.pdf, bare_adv.tex, +%% bare_conf.tex, bare_jrnl.tex, bare_conf_compsoc.tex, +%% bare_jrnl_compsoc.tex +%% +%% Major changes to the user interface should be indicated by an +%% increase in the version numbers. If a version is a beta, it will +%% be indicated with a BETA suffix, i.e., 1.4 BETA. +%% Small changes can be indicated by appending letters to the version +%% such as "IEEEtran_v14a.cls". +%% In all cases, \Providesclass, any \typeout messages to the user, +%% \IEEEtransversionmajor and \IEEEtransversionminor must reflect the +%% correct version information. +%% The changes should also be documented via source comments. +%%************************************************************************* +%% +% +% Available class options +% e.g., \documentclass[10pt,conference]{IEEEtran} +% +% *** choose only one from each category *** +% +% 9pt, 10pt, 11pt, 12pt +% Sets normal font size. The default is 10pt. +% +% conference, journal, technote, peerreview, peerreviewca +% determines format mode - conference papers, journal papers, +% correspondence papers (technotes), or peer review papers. The user +% should also select 9pt when using technote. peerreview is like +% journal mode, but provides for a single-column "cover" title page for +% anonymous peer review. The paper title (without the author names) is +% repeated at the top of the page after the cover page. For peer review +% papers, the \IEEEpeerreviewmaketitle command must be executed (will +% automatically be ignored for non-peerreview modes) at the place the +% cover page is to end, usually just after the abstract (keywords are +% not normally used with peer review papers). peerreviewca is like +% peerreview, but allows the author names to be entered and formatted +% as with conference mode so that author affiliation and contact +% information can be easily seen on the cover page. +% The default is journal. +% +% draft, draftcls, draftclsnofoot, final +% determines if paper is formatted as a widely spaced draft (for +% handwritten editor comments) or as a properly typeset final version. +% draftcls restricts draft mode to the class file while all other LaTeX +% packages (i.e., \usepackage{graphicx}) will behave as final - allows +% for a draft paper with visible figures, etc. draftclsnofoot is like +% draftcls, but does not display the date and the word "DRAFT" at the foot +% of the pages. If using one of the draft modes, the user will probably +% also want to select onecolumn. +% The default is final. +% +% letterpaper, a4paper, cspaper +% determines paper size: 8.5in X 11in, 210mm X 297mm or 7.875in X 10.75in. +% Changing the paper size in the standard journal and conference modes +% will not alter the typesetting of the document - only the margins will +% be affected. In particular, documents using the a4paper option will +% have reduced side margins (A4 is narrower than US letter) and a longer +% bottom margin (A4 is longer than US letter). For both cases, the top +% margins will be the same and the text will be horizontally centered. +% For the compsoc conference and draft modes, it is the margins that will +% remain constant, and thus the text area size will vary, with changes in +% the paper size. +% The cspaper option is the special ``trim'' paper size (7.875in x 10.75in) +% used in the actual publication of Computer Society journals. Under +% compsoc journal mode, this option does not alter the typesetting of the +% document. Authors should invoke the cspaper option only if requested to +% do so by the editors of the specific journal they are submitting to. +% For final submission to the IEEE, authors should generally use US letter +% (8.5 X 11in) paper unless otherwise instructed. Note that authors should +% ensure that all post-processing (ps, pdf, etc.) uses the same paper +% specificiation as the .tex document. Problems here are by far the number +% one reason for incorrect margins. IEEEtran will automatically set the +% default paper size under pdflatex (without requiring any change to +% pdftex.cfg), so this issue is more important to dvips users. Fix +% config.ps, config.pdf, or ~/.dvipsrc for dvips, or use the +% dvips -t papersize option instead as needed. For the cspaper option, +% the corresponding dvips paper name is "ieeecs". +% See the testflow documentation +% http://www.ctan.org/tex-archive/macros/latex/contrib/IEEEtran/testflow +% for more details on dvips paper size configuration. +% The default is letterpaper. +% +% oneside, twoside +% determines if layout follows single sided or two sided (duplex) +% printing. The only notable change is with the headings at the top of +% the pages. +% The default is oneside. +% +% onecolumn, twocolumn +% determines if text is organized into one or two columns per page. One +% column mode is usually used only with draft papers. +% The default is twocolumn. +% +% comsoc, compsoc, transmag +% Use the format of the IEEE Communications Society, IEEE Computer Society +% or IEEE Transactions on Magnetics, respectively. +% +% romanappendices +% Use the "Appendix I" convention when numbering appendices. IEEEtran.cls +% now defaults to Alpha "Appendix A" convention - the opposite of what +% v1.6b and earlier did. +% +% captionsoff +% disables the display of the figure/table captions. Some IEEE journals +% request that captions be removed and figures/tables be put on pages +% of their own at the end of an initial paper submission. The endfloat +% package can be used with this class option to achieve this format. +% +% nofonttune +% turns off tuning of the font interword spacing. Maybe useful to those +% not using the standard Times fonts or for those who have already "tuned" +% their fonts. +% The default is to enable IEEEtran to tune font parameters. +% +% +%---------- +% Available CLASSINPUTs provided (all are macros unless otherwise noted): +% \CLASSINPUTbaselinestretch +% \CLASSINPUTinnersidemargin +% \CLASSINPUToutersidemargin +% \CLASSINPUTtoptextmargin +% \CLASSINPUTbottomtextmargin +% +% Available CLASSINFOs provided: +% \ifCLASSINFOpdf (TeX if conditional) +% \CLASSINFOpaperwidth (macro) +% \CLASSINFOpaperheight (macro) +% \CLASSINFOnormalsizebaselineskip (length) +% \CLASSINFOnormalsizeunitybaselineskip (length) +% +% Available CLASSOPTIONs provided: +% all class option flags (TeX if conditionals) unless otherwise noted, +% e.g., \ifCLASSOPTIONcaptionsoff +% point size options provided as a single macro: +% \CLASSOPTIONpt +% which will be defined as 9, 10, 11, or 12 depending on the document's +% normalsize point size. +% also, class option peerreviewca implies the use of class option peerreview +% and classoption draft implies the use of class option draftcls + + + + + +\ProvidesClass{IEEEtran}[2015/08/26 V1.8b by Michael Shell] +\typeout{-- See the "IEEEtran_HOWTO" manual for usage information.} +\typeout{-- http://www.michaelshell.org/tex/ieeetran/} +\NeedsTeXFormat{LaTeX2e} + +% IEEEtran.cls version numbers, provided as of V1.3 +% These values serve as a way a .tex file can +% determine if the new features are provided. +% The version number of this IEEEtrans.cls can be obtained from +% these values. i.e., V1.4 +% KEEP THESE AS INTEGERS! i.e., NO {4a} or anything like that- +% (no need to enumerate "a" minor changes here) +\def\IEEEtransversionmajor{1} +\def\IEEEtransversionminor{8} + + +% hook to allow easy changeover to IEEEtran.cls/tools.sty error reporting +\def\@IEEEclspkgerror{\ClassError{IEEEtran}} + + +% These do nothing, but provide them like in article.cls +\newif\if@restonecol +\newif\if@titlepage + + +% class option conditionals +\newif\ifCLASSOPTIONonecolumn \CLASSOPTIONonecolumnfalse +\newif\ifCLASSOPTIONtwocolumn \CLASSOPTIONtwocolumntrue + +\newif\ifCLASSOPTIONoneside \CLASSOPTIONonesidetrue +\newif\ifCLASSOPTIONtwoside \CLASSOPTIONtwosidefalse + +\newif\ifCLASSOPTIONfinal \CLASSOPTIONfinaltrue +\newif\ifCLASSOPTIONdraft \CLASSOPTIONdraftfalse +\newif\ifCLASSOPTIONdraftcls \CLASSOPTIONdraftclsfalse +\newif\ifCLASSOPTIONdraftclsnofoot \CLASSOPTIONdraftclsnofootfalse + +\newif\ifCLASSOPTIONpeerreview \CLASSOPTIONpeerreviewfalse +\newif\ifCLASSOPTIONpeerreviewca \CLASSOPTIONpeerreviewcafalse + +\newif\ifCLASSOPTIONjournal \CLASSOPTIONjournaltrue +\newif\ifCLASSOPTIONconference \CLASSOPTIONconferencefalse +\newif\ifCLASSOPTIONtechnote \CLASSOPTIONtechnotefalse + +\newif\ifCLASSOPTIONnofonttune \CLASSOPTIONnofonttunefalse + +\newif\ifCLASSOPTIONcaptionsoff \CLASSOPTIONcaptionsofffalse + +\newif\ifCLASSOPTIONcomsoc \CLASSOPTIONcomsocfalse +\newif\ifCLASSOPTIONcompsoc \CLASSOPTIONcompsocfalse +\newif\ifCLASSOPTIONtransmag \CLASSOPTIONtransmagfalse + +\newif\ifCLASSOPTIONromanappendices \CLASSOPTIONromanappendicesfalse + + +% class info conditionals + +% indicates if pdf (via pdflatex) output +\newif\ifCLASSINFOpdf \CLASSINFOpdffalse + + +% V1.6b internal flag to show if using a4paper +\newif\if@IEEEusingAfourpaper \@IEEEusingAfourpaperfalse +% V1.6b internal flag to show if using cspaper +\newif\if@IEEEusingcspaper \@IEEEusingcspaperfalse + + +% IEEEtran class scratch pad registers +% dimen +\newdimen\@IEEEtrantmpdimenA +\newdimen\@IEEEtrantmpdimenB +\newdimen\@IEEEtrantmpdimenC +% count +\newcount\@IEEEtrantmpcountA +\newcount\@IEEEtrantmpcountB +\newcount\@IEEEtrantmpcountC +% token list +\newtoks\@IEEEtrantmptoksA + +% we use \CLASSOPTIONpt so that we can ID the point size (even for 9pt docs) +% as well as LaTeX's \@ptsize to retain some compatability with some +% external packages +\def\@ptsize{0} +% LaTeX does not support 9pt, so we set \@ptsize to 0 - same as that of 10pt +\DeclareOption{9pt}{\def\CLASSOPTIONpt{9}\def\@ptsize{0}} +\DeclareOption{10pt}{\def\CLASSOPTIONpt{10}\def\@ptsize{0}} +\DeclareOption{11pt}{\def\CLASSOPTIONpt{11}\def\@ptsize{1}} +\DeclareOption{12pt}{\def\CLASSOPTIONpt{12}\def\@ptsize{2}} + + + +\DeclareOption{letterpaper}{\setlength{\paperwidth}{8.5in}% + \setlength{\paperheight}{11in}% + \@IEEEusingAfourpaperfalse + \@IEEEusingcspaperfalse + \def\CLASSOPTIONpaper{letter}% + \def\CLASSINFOpaperwidth{8.5in}% + \def\CLASSINFOpaperheight{11in}} + + +\DeclareOption{a4paper}{\setlength{\paperwidth}{210mm}% + \setlength{\paperheight}{297mm}% + \@IEEEusingAfourpapertrue + \@IEEEusingcspaperfalse + \def\CLASSOPTIONpaper{a4}% + \def\CLASSINFOpaperwidth{210mm}% + \def\CLASSINFOpaperheight{297mm}} + +% special paper option for compsoc journals +\DeclareOption{cspaper}{\setlength{\paperwidth}{7.875in}% + \setlength{\paperheight}{10.75in}% + \@IEEEusingcspapertrue + \@IEEEusingAfourpaperfalse + \def\CLASSOPTIONpaper{ieeecs}% + \def\CLASSINFOpaperwidth{7.875in}% + \def\CLASSINFOpaperheight{10.75in}} + +\DeclareOption{oneside}{\@twosidefalse\@mparswitchfalse + \CLASSOPTIONonesidetrue\CLASSOPTIONtwosidefalse} +\DeclareOption{twoside}{\@twosidetrue\@mparswitchtrue + \CLASSOPTIONtwosidetrue\CLASSOPTIONonesidefalse} + +\DeclareOption{onecolumn}{\CLASSOPTIONonecolumntrue\CLASSOPTIONtwocolumnfalse} +\DeclareOption{twocolumn}{\CLASSOPTIONtwocolumntrue\CLASSOPTIONonecolumnfalse} + +% If the user selects draft, then this class AND any packages +% will go into draft mode. +\DeclareOption{draft}{\CLASSOPTIONdrafttrue\CLASSOPTIONdraftclstrue + \CLASSOPTIONdraftclsnofootfalse} +% draftcls is for a draft mode which will not affect any packages +% used by the document. +\DeclareOption{draftcls}{\CLASSOPTIONdraftfalse\CLASSOPTIONdraftclstrue + \CLASSOPTIONdraftclsnofootfalse} +% draftclsnofoot is like draftcls, but without the footer. +\DeclareOption{draftclsnofoot}{\CLASSOPTIONdraftfalse\CLASSOPTIONdraftclstrue + \CLASSOPTIONdraftclsnofoottrue} +\DeclareOption{final}{\CLASSOPTIONdraftfalse\CLASSOPTIONdraftclsfalse + \CLASSOPTIONdraftclsnofootfalse} + +\DeclareOption{journal}{\CLASSOPTIONpeerreviewfalse\CLASSOPTIONpeerreviewcafalse + \CLASSOPTIONjournaltrue\CLASSOPTIONconferencefalse\CLASSOPTIONtechnotefalse} + +\DeclareOption{conference}{\CLASSOPTIONpeerreviewfalse\CLASSOPTIONpeerreviewcafalse + \CLASSOPTIONjournalfalse\CLASSOPTIONconferencetrue\CLASSOPTIONtechnotefalse} + +\DeclareOption{technote}{\CLASSOPTIONpeerreviewfalse\CLASSOPTIONpeerreviewcafalse + \CLASSOPTIONjournalfalse\CLASSOPTIONconferencefalse\CLASSOPTIONtechnotetrue} + +\DeclareOption{peerreview}{\CLASSOPTIONpeerreviewtrue\CLASSOPTIONpeerreviewcafalse + \CLASSOPTIONjournalfalse\CLASSOPTIONconferencefalse\CLASSOPTIONtechnotefalse} + +\DeclareOption{peerreviewca}{\CLASSOPTIONpeerreviewtrue\CLASSOPTIONpeerreviewcatrue + \CLASSOPTIONjournalfalse\CLASSOPTIONconferencefalse\CLASSOPTIONtechnotefalse} + +\DeclareOption{nofonttune}{\CLASSOPTIONnofonttunetrue} + +\DeclareOption{captionsoff}{\CLASSOPTIONcaptionsofftrue} + +\DeclareOption{comsoc}{\CLASSOPTIONcomsoctrue\CLASSOPTIONcompsocfalse\CLASSOPTIONtransmagfalse} + +\DeclareOption{compsoc}{\CLASSOPTIONcomsocfalse\CLASSOPTIONcompsoctrue\CLASSOPTIONtransmagfalse} + +\DeclareOption{transmag}{\CLASSOPTIONtransmagtrue\CLASSOPTIONcomsocfalse\CLASSOPTIONcompsocfalse} + +\DeclareOption{romanappendices}{\CLASSOPTIONromanappendicestrue} + + +% default to US letter paper, 10pt, twocolumn, one sided, final, journal +\ExecuteOptions{letterpaper,10pt,twocolumn,oneside,final,journal} +% overrride these defaults per user requests +\ProcessOptions + + + +%% -- Command Argument Scanning Support Functions -- + +% Sets the category codes for punctuation to their normal values. +% For local use with argument scanning. +\def\IEEEnormalcatcodespunct{\catcode`\!=12 \catcode`\,=12 \catcode`\:=12 +\catcode`\;=12 \catcode`\`=12 \catcode`\'=12 \catcode`\"=12 \catcode`\.=12 +\catcode`\/=12 \catcode`\?=12 \catcode`\*=12 \catcode`\+=12 \catcode`\-=12 +\catcode`\<=12 \catcode`\>=12 \catcode`\(=12 \catcode`\)=12 \catcode`\[=12 +\catcode`\]=12 \catcode`\==12 \catcode`\|=12} +% Sets the category codes for numbers to their normal values. +% For local use with argument scanning. +\def\IEEEnormalcatcodesnum{\catcode`\0=12 \catcode`\1=12 \catcode`\2=12 +\catcode`\3=12 \catcode`\4=12 \catcode`\5=12 \catcode`\6=12 \catcode`\7=12 +\catcode`\8=12 \catcode`\9=12} +% combined action of \IEEEnormalcatcodespunct and \IEEEnormalcatcodesnum +\def\IEEEnormalcatcodes{\IEEEnormalcatcodespunct\IEEEnormalcatcodesnum} + + +% usage: \@IEEEextracttoken*{} +% \@IEEEextracttoken fully expands its argument (which it then stores in +% \@IEEEextracttokenarg) via \edef and then the meaning of the first +% nonbrace (but including the empty group) token found is assigned via \let +% to \@IEEEextractedtoken as well as stored in the macro +% \@IEEEextractedtokenmacro. Tokens that would otherwise be discarded during +% the acquisition of the first are stored in \@IEEEextractedtokensdiscarded, +% however their original relative brace nesting depths are not guaranteed to +% be preserved. +% If the argument is empty, or if a first nonbrace token does not exist (or +% is an empty group), \@IEEEextractedtoken will be \relax and +% \@IEEEextractedtokenmacro and \@IEEEextractedtokensdiscarded will be empty. +% +% For example: +% \@IEEEextracttoken{{{ab}{cd}}{{ef}g}} +% results in: +% +% \@IEEEextracttokenarg ==> a macro containing {{ab}{cd}}{{ef}g} +% \@IEEEextractedtoken ==> the letter a +% \@IEEEextractedtokenmacro ==> a macro containing a +% \@IEEEextractedtokensdiscarded ==> a macro containing bcd{ef}g +% +% the *-star form, \@IEEEextracttoken*, does not expand its argument +% contents during processing. +\def\@IEEEextracttoken{\@ifstar{\let\@IEEEextracttokendef=\def\@@IEEEextracttoken}{\let\@IEEEextracttokendef=\edef\@@IEEEextracttoken}} + +\def\@@IEEEextracttoken#1{\@IEEEextracttokendef\@IEEEextracttokenarg{#1}\relax +\def\@IEEEextractedtokensdiscarded{}\relax % initialize to empty +% if the macro is unchanged after being acquired as a single undelimited argument +% with anything after it being stripped off as a delimited argument +% we know we have one token without any enclosing braces. loop until this is true. +\let\@IEEEextracttokencurgroup\@IEEEextracttokenarg +\loop + % trap case of an empty argument as this would cause a problem with + % \@@@IEEEextracttoken's first (nondelimited) argument acquisition + \ifx\@IEEEextracttokencurgroup\@empty + \def\@IEEEextractedtokenmacro{}\relax + \else + \expandafter\@@@IEEEextracttoken\@IEEEextracttokencurgroup\@IEEEgeneralsequenceDELIMITER\relax + \fi + \ifx\@IEEEextractedtokenmacro\@IEEEextracttokencurgroup + \else + \let\@IEEEextracttokencurgroup=\@IEEEextractedtokenmacro +\repeat +% we can safely do a \let= here because there should be at most one token +% the relax is needed to handle the case of no token found +\expandafter\let\expandafter\@IEEEextractedtoken\@IEEEextractedtokenmacro\relax} + +\def\@@@IEEEextracttoken#1#2\@IEEEgeneralsequenceDELIMITER{\def\@IEEEextractedtokenmacro{#1}\relax +\def\@@IEEEextractedtokensdiscarded{#2}\expandafter\expandafter\expandafter\def\expandafter\expandafter\expandafter +\@IEEEextractedtokensdiscarded\expandafter\expandafter\expandafter +{\expandafter\@@IEEEextractedtokensdiscarded\@IEEEextractedtokensdiscarded}} +%% +%% -- End of Command Argument Scanning Support Functions -- + + + +% Computer Society conditional execution command +\long\def\@IEEEcompsoconly#1{\relax\ifCLASSOPTIONcompsoc\relax#1\relax\fi\relax} +% inverse +\long\def\@IEEEnotcompsoconly#1{\relax\ifCLASSOPTIONcompsoc\else\relax#1\relax\fi\relax} +% compsoc conference +\long\def\@IEEEcompsocconfonly#1{\relax\ifCLASSOPTIONcompsoc\ifCLASSOPTIONconference\relax#1\relax\fi\fi\relax} +% compsoc not conference +\long\def\@IEEEcompsocnotconfonly#1{\relax\ifCLASSOPTIONcompsoc\ifCLASSOPTIONconference\else\relax#1\relax\fi\fi\relax} + + +% comsoc verify that newtxmath, mtpro2, mt11p or mathtime has been loaded +\def\@IEEEcomsocverifymathfont{\typeout{-- Verifying Times compatible math font.}\relax + \@ifpackageloaded{newtxmath}{\typeout{-- newtxmath loaded, OK.}}{\@@IEEEcomsocverifymathfont}} +\def\@@IEEEcomsocverifymathfont{\@ifpackageloaded{mtpro2}{\typeout{-- mtpro2 loaded, OK.}}{\@@@IEEEcomsocverifymathfont}} +\def\@@@IEEEcomsocverifymathfont{\@ifpackageloaded{mt11p}{\typeout{-- mt11p2 loaded, OK.}}{\@@@@IEEEcomsocverifymathfont}} +\def\@@@@IEEEcomsocverifymathfont{\@ifpackageloaded{mathtime}{\typeout{-- mathtime loaded, OK.}}{\@IEEEcomsocenforcemathfont}} + +% comsoc, if a Times math font was not loaded by user, enforce it +\def\@IEEEcomsocenforcemathfont{\typeout{** Times compatible math font not found, forcing.}\relax +\IfFileExists{newtxmath.sty}{\typeout{-- Found newtxmath, loading.}\RequirePackage{newtxmath}}{\@@IEEEcomsocenforcemathfont}} +\def\@@IEEEcomsocenforcemathfont{\IfFileExists{mtpro2.sty}{\typeout{-- Found mtpro2, loading.}\RequirePackage{mtpro2}}{\@@@IEEEcomsocenforcemathfont}} +\def\@@@IEEEcomsocenforcemathfont{\IfFileExists{mt11p.sty}{\typeout{-- Found mt11p, loading.}\RequirePackage{mt11p}}{\@@@@IEEEcomsocenforcemathfont}} +\def\@@@@IEEEcomsocenforcemathfont{\IfFileExists{mathtime.sty}{\typeout{-- Found mathtime, loading.}\RequirePackage{mathtime}}{\@@@@@IEEEcomsocenforcemathfont}} +% if no acceptable Times math font package found, error with newtxmath requirement +\def\@@@@@IEEEcomsocenforcemathfont{\typeout{** No Times compatible math font package found. newtxmath is required.}\RequirePackage{newtxmath}} + + +\ifCLASSOPTIONcomsoc + % ensure that if newtxmath is used, the cmintegrals option is also invoked + \PassOptionsToPackage{cmintegrals}{newtxmath} + % comsoc requires a Times like math font + % ensure this requirement is satisfied at document start + \AtBeginDocument{\@IEEEcomsocverifymathfont} +\fi + + + +% The IEEE uses Times Roman font, so we'll default to Times. +% These three commands make up the entire times.sty package. +\renewcommand{\sfdefault}{phv} +\renewcommand{\rmdefault}{ptm} +\renewcommand{\ttdefault}{pcr} + +% V1.7 compsoc nonconference papers, use Palatino/Palladio as the main text font, +% not Times Roman. +\@IEEEcompsocnotconfonly{\renewcommand{\rmdefault}{ppl}} + +% enable the selected main text font +\normalfont\selectfont + + +\ifCLASSOPTIONcomsoc + \typeout{-- Using IEEE Communications Society mode.} +\fi + +\ifCLASSOPTIONcompsoc + \typeout{-- Using IEEE Computer Society mode.} +\fi + + +% V1.7 conference notice message hook +\def\@IEEEconsolenoticeconference{\typeout{}% +\typeout{** Conference Paper **}% +\typeout{Before submitting the final camera ready copy, remember to:}% +\typeout{}% +\typeout{ 1. Manually equalize the lengths of two columns on the last page}% +\typeout{ of your paper;}% +\typeout{}% +\typeout{ 2. Ensure that any PostScript and/or PDF output post-processing}% +\typeout{ uses only Type 1 fonts and that every step in the generation}% +\typeout{ process uses the appropriate paper size.}% +\typeout{}} + + +% we can send console reminder messages to the user here +\AtEndDocument{\ifCLASSOPTIONconference\@IEEEconsolenoticeconference\fi} + + +% warn about the use of single column other than for draft mode +\ifCLASSOPTIONtwocolumn\else% + \ifCLASSOPTIONdraftcls\else% + \typeout{** ATTENTION: Single column mode is not typically used with IEEE publications.}% + \fi% +\fi + + +% V1.7 improved paper size setting code. +% Set pdfpage and dvips paper sizes. Conditional tests are similar to that +% of ifpdf.sty. Retain within {} to ensure tested macros are never altered, +% even if only effect is to set them to \relax. +% if \pdfoutput is undefined or equal to relax, output a dvips special +{\@ifundefined{pdfoutput}{\AtBeginDvi{\special{papersize=\CLASSINFOpaperwidth,\CLASSINFOpaperheight}}}{% +% pdfoutput is defined and not equal to \relax +% check for pdfpageheight existence just in case someone sets pdfoutput +% under non-pdflatex. If exists, set them regardless of value of \pdfoutput. +\@ifundefined{pdfpageheight}{\relax}{\global\pdfpagewidth\paperwidth +\global\pdfpageheight\paperheight}% +% if using \pdfoutput=0 under pdflatex, send dvips papersize special +\ifcase\pdfoutput +\AtBeginDvi{\special{papersize=\CLASSINFOpaperwidth,\CLASSINFOpaperheight}}% +\else +% we are using pdf output, set CLASSINFOpdf flag +\global\CLASSINFOpdftrue +\fi}} + +% let the user know the selected papersize +\typeout{-- Using \CLASSINFOpaperwidth\space x \CLASSINFOpaperheight\space +(\CLASSOPTIONpaper)\space paper.} + +\ifCLASSINFOpdf +\typeout{-- Using PDF output.} +\else +\typeout{-- Using DVI output.} +\fi + + +% The idea hinted here is for LaTeX to generate markleft{} and markright{} +% automatically for you after you enter \author{}, \journal{}, +% \journaldate{}, journalvol{}, \journalnum{}, etc. +% However, there may be some backward compatibility issues here as +% well as some special applications for IEEEtran.cls and special issues +% that may require the flexible \markleft{}, \markright{} and/or \markboth{}. +% We'll leave this as an open future suggestion. +%\newcommand{\journal}[1]{\def\@journal{#1}} +%\def\@journal{} + + + +% pointsize values +% used with ifx to determine the document's normal size +\def\@IEEEptsizenine{9} +\def\@IEEEptsizeten{10} +\def\@IEEEptsizeeleven{11} +\def\@IEEEptsizetwelve{12} + + + +% FONT DEFINITIONS (No sizexx.clo file needed) +% V1.6 revised font sizes, displayskip values and +% revised normalsize baselineskip to reduce underfull vbox problems +% on the 58pc = 696pt = 9.5in text height we want +% normalsize #lines/column baselineskip (aka leading) +% 9pt 63 11.0476pt (truncated down) +% 10pt 58 12pt (exact) +% 11pt 52 13.3846pt (truncated down) +% 12pt 50 13.92pt (exact) +% + +% we need to store the nominal baselineskip for the given font size +% in case baselinestretch ever changes. +% this is a dimen, so it will not hold stretch or shrink +\newdimen\@IEEEnormalsizeunitybaselineskip +\@IEEEnormalsizeunitybaselineskip\baselineskip + + + +%% ******* WARNING! ******* +%% +%% Authors should not alter font sizes, baselineskip ("leading"), +%% margins or other spacing values in an attempt to squeeze more +%% material on each page. +%% +%% The IEEE's own typesetting software will restore the correct +%% values when re-typesetting/proofing the submitted document, +%% possibly resulting in unexpected article over length charges. +%% +%% ******* WARNING! ******* + + +% 9pt option defaults +\ifx\CLASSOPTIONpt\@IEEEptsizenine +\typeout{-- This is a 9 point document.} +\def\normalsize{\@setfontsize{\normalsize}{9}{11.0476pt}} +\setlength{\@IEEEnormalsizeunitybaselineskip}{11.0476pt} +\normalsize +\abovedisplayskip 1.5ex plus 3pt minus 1pt +\belowdisplayskip \abovedisplayskip +\abovedisplayshortskip 0pt plus 3pt +\belowdisplayshortskip 1.5ex plus 3pt minus 1pt +\def\small{\@setfontsize{\small}{8.5}{10pt}} +\def\footnotesize{\@setfontsize{\footnotesize}{8}{9pt}} +\def\scriptsize{\@setfontsize{\scriptsize}{7}{8pt}} +\def\tiny{\@setfontsize{\tiny}{5}{6pt}} +% sublargesize is the same as large - 10pt +\def\sublargesize{\@setfontsize{\sublargesize}{10}{12pt}} +\def\large{\@setfontsize{\large}{10}{12pt}} +\def\Large{\@setfontsize{\Large}{12}{14pt}} +\def\LARGE{\@setfontsize{\LARGE}{14}{17pt}} +\def\huge{\@setfontsize{\huge}{17}{20pt}} +\def\Huge{\@setfontsize{\Huge}{20}{24pt}} +\fi +% +% 10pt option defaults +\ifx\CLASSOPTIONpt\@IEEEptsizeten +\typeout{-- This is a 10 point document.} +\def\normalsize{\@setfontsize{\normalsize}{10}{12.00pt}} +\setlength{\@IEEEnormalsizeunitybaselineskip}{12pt} +\normalsize +\abovedisplayskip 1.5ex plus 4pt minus 2pt +\belowdisplayskip \abovedisplayskip +\abovedisplayshortskip 0pt plus 4pt +\belowdisplayshortskip 1.5ex plus 4pt minus 2pt +\def\small{\@setfontsize{\small}{9}{10pt}} +\def\footnotesize{\@setfontsize{\footnotesize}{8}{9pt}} +\def\scriptsize{\@setfontsize{\scriptsize}{7}{8pt}} +\def\tiny{\@setfontsize{\tiny}{5}{6pt}} +% sublargesize is a tad smaller than large - 11pt +\def\sublargesize{\@setfontsize{\sublargesize}{11}{13.4pt}} +\def\large{\@setfontsize{\large}{12}{14pt}} +\def\Large{\@setfontsize{\Large}{14}{17pt}} +\def\LARGE{\@setfontsize{\LARGE}{17}{20pt}} +\def\huge{\@setfontsize{\huge}{20}{24pt}} +\def\Huge{\@setfontsize{\Huge}{24}{28pt}} +\fi +% +% 11pt option defaults +\ifx\CLASSOPTIONpt\@IEEEptsizeeleven +\typeout{-- This is an 11 point document.} +\def\normalsize{\@setfontsize{\normalsize}{11}{13.3846pt}} +\setlength{\@IEEEnormalsizeunitybaselineskip}{13.3846pt} +\normalsize +\abovedisplayskip 1.5ex plus 5pt minus 3pt +\belowdisplayskip \abovedisplayskip +\abovedisplayshortskip 0pt plus 5pt +\belowdisplayshortskip 1.5ex plus 5pt minus 3pt +\def\small{\@setfontsize{\small}{10}{12pt}} +\def\footnotesize{\@setfontsize{\footnotesize}{9}{10.5pt}} +\def\scriptsize{\@setfontsize{\scriptsize}{8}{9pt}} +\def\tiny{\@setfontsize{\tiny}{6}{7pt}} +% sublargesize is the same as large - 12pt +\def\sublargesize{\@setfontsize{\sublargesize}{12}{14pt}} +\def\large{\@setfontsize{\large}{12}{14pt}} +\def\Large{\@setfontsize{\Large}{14}{17pt}} +\def\LARGE{\@setfontsize{\LARGE}{17}{20pt}} +\def\huge{\@setfontsize{\huge}{20}{24pt}} +\def\Huge{\@setfontsize{\Huge}{24}{28pt}} +\fi +% +% 12pt option defaults +\ifx\CLASSOPTIONpt\@IEEEptsizetwelve +\typeout{-- This is a 12 point document.} +\def\normalsize{\@setfontsize{\normalsize}{12}{13.92pt}} +\setlength{\@IEEEnormalsizeunitybaselineskip}{13.92pt} +\normalsize +\abovedisplayskip 1.5ex plus 6pt minus 4pt +\belowdisplayskip \abovedisplayskip +\abovedisplayshortskip 0pt plus 6pt +\belowdisplayshortskip 1.5ex plus 6pt minus 4pt +\def\small{\@setfontsize{\small}{10}{12pt}} +\def\footnotesize{\@setfontsize{\footnotesize}{9}{10.5pt}} +\def\scriptsize{\@setfontsize{\scriptsize}{8}{9pt}} +\def\tiny{\@setfontsize{\tiny}{6}{7pt}} +% sublargesize is the same as large - 14pt +\def\sublargesize{\@setfontsize{\sublargesize}{14}{17pt}} +\def\large{\@setfontsize{\large}{14}{17pt}} +\def\Large{\@setfontsize{\Large}{17}{20pt}} +\def\LARGE{\@setfontsize{\LARGE}{20}{24pt}} +\def\huge{\@setfontsize{\huge}{22}{26pt}} +\def\Huge{\@setfontsize{\Huge}{24}{28pt}} +\fi + + + +% V1.8a compsoc font sizes +% compsoc font sizes use bp "Postscript" point units (1/72in) +% rather than the traditional pt (1/72.27) +\ifCLASSOPTIONcompsoc +% -- compsoc defaults -- +% ** will override some of these values later ** +% 9pt +\ifx\CLASSOPTIONpt\@IEEEptsizenine +\def\normalsize{\@setfontsize{\normalsize}{9bp}{11bp}} +\setlength{\@IEEEnormalsizeunitybaselineskip}{11bp} +\normalsize +\abovedisplayskip 1.5ex plus 3bp minus 1bp +\belowdisplayskip \abovedisplayskip +\abovedisplayshortskip 0bp plus 3bp +\belowdisplayshortskip 1.5ex plus 3bp minus 1bp +\def\small{\@setfontsize{\small}{8.5bp}{10bp}} +\def\footnotesize{\@setfontsize{\footnotesize}{8bp}{9bp}} +\def\scriptsize{\@setfontsize{\scriptsize}{7bp}{8bp}} +\def\tiny{\@setfontsize{\tiny}{5bp}{6bp}} +% sublargesize is the same as large - 10bp +\def\sublargesize{\@setfontsize{\sublargesize}{10bp}{12bp}} +\def\large{\@setfontsize{\large}{10bp}{12bp}} +\def\Large{\@setfontsize{\Large}{12bp}{14bp}} +\def\LARGE{\@setfontsize{\LARGE}{14bp}{17bp}} +\def\huge{\@setfontsize{\huge}{17bp}{20bp}} +\def\Huge{\@setfontsize{\Huge}{20bp}{24bp}} +\fi +% +% 10pt +\ifx\CLASSOPTIONpt\@IEEEptsizeten +\def\normalsize{\@setfontsize{\normalsize}{10bp}{12bp}} +\setlength{\@IEEEnormalsizeunitybaselineskip}{12bp} +\normalsize +\abovedisplayskip 1.5ex plus 4bp minus 2bp +\belowdisplayskip \abovedisplayskip +\abovedisplayshortskip 0pt plus 4bp +\belowdisplayshortskip 1.5ex plus 4bp minus 2bp +\def\small{\@setfontsize{\small}{9bp}{10bp}} +\def\footnotesize{\@setfontsize{\footnotesize}{8bp}{9bp}} +\def\scriptsize{\@setfontsize{\scriptsize}{7bp}{8bp}} +\def\tiny{\@setfontsize{\tiny}{5bp}{6bp}} +% sublargesize is a tad smaller than large - 11bp +\def\sublargesize{\@setfontsize{\sublargesize}{11bp}{13.5bp}} +\def\large{\@setfontsize{\large}{12bp}{14bp}} +\def\Large{\@setfontsize{\Large}{14bp}{17bp}} +\def\LARGE{\@setfontsize{\LARGE}{17bp}{20bp}} +\def\huge{\@setfontsize{\huge}{20bp}{24bp}} +\def\Huge{\@setfontsize{\Huge}{24bp}{28bp}} +\fi +% +% 11pt +\ifx\CLASSOPTIONpt\@IEEEptsizeeleven +\def\normalsize{\@setfontsize{\normalsize}{11bp}{13.5bp}} +\setlength{\@IEEEnormalsizeunitybaselineskip}{13.5bp} +\normalsize +\abovedisplayskip 1.5ex plus 5bp minus 3bp +\belowdisplayskip \abovedisplayskip +\abovedisplayshortskip 0pt plus 5bp +\belowdisplayshortskip 1.5ex plus 5bp minus 3bp +\def\small{\@setfontsize{\small}{10bp}{12bp}} +\def\footnotesize{\@setfontsize{\footnotesize}{9bp}{10.5bp}} +\def\scriptsize{\@setfontsize{\scriptsize}{8bp}{9bp}} +\def\tiny{\@setfontsize{\tiny}{6bp}{7bp}} +% sublargesize is the same as large - 12bp +\def\sublargesize{\@setfontsize{\sublargesize}{12bp}{14bp}} +\def\large{\@setfontsize{\large}{12bp}{14bp}} +\def\Large{\@setfontsize{\Large}{14bp}{17bp}} +\def\LARGE{\@setfontsize{\LARGE}{17bp}{20bp}} +\def\huge{\@setfontsize{\huge}{20bp}{24bp}} +\def\Huge{\@setfontsize{\Huge}{24bp}{28bp}} +\fi +% +% 12pt +\ifx\CLASSOPTIONpt\@IEEEptsizetwelve +\def\normalsize{\@setfontsize{\normalsize}{12bp}{14bp}}% +\setlength{\@IEEEnormalsizeunitybaselineskip}{14bp}% +\normalsize +\abovedisplayskip 1.5ex plus 6bp minus 4bp +\belowdisplayskip \abovedisplayskip +\abovedisplayshortskip 0pt plus 6bp +\belowdisplayshortskip 1.5ex plus 6bp minus 4bp +\def\small{\@setfontsize{\small}{10bp}{12bp}} +\def\footnotesize{\@setfontsize{\footnotesize}{9bp}{10.5bp}} +\def\scriptsize{\@setfontsize{\scriptsize}{8bp}{9bp}} +\def\tiny{\@setfontsize{\tiny}{6bp}{7bp}} +% sublargesize is the same as large - 14bp +\def\sublargesize{\@setfontsize{\sublargesize}{14bp}{17bp}} +\def\large{\@setfontsize{\large}{14bp}{17bp}} +\def\Large{\@setfontsize{\Large}{17bp}{20bp}} +\def\LARGE{\@setfontsize{\LARGE}{20bp}{24bp}} +\def\huge{\@setfontsize{\huge}{22bp}{26bp}} +\def\Huge{\@setfontsize{\Huge}{24bp}{28bp}} +\fi +% +% -- override defaults: compsoc journals use special normalsizes -- +\ifCLASSOPTIONconference +% +% compsoc conferences +% 9pt +\ifx\CLASSOPTIONpt\@IEEEptsizenine +\def\normalsize{\@setfontsize{\normalsize}{9bp}{10.8bp}} +\setlength{\@IEEEnormalsizeunitybaselineskip}{10.8bp} +\normalsize +\abovedisplayskip 1.5ex plus 3bp minus 1bp +\belowdisplayskip \abovedisplayskip +\abovedisplayshortskip 0bp plus 3bp +\belowdisplayshortskip 1.5ex plus 3bp minus 1bp +\fi +% 10pt +\ifx\CLASSOPTIONpt\@IEEEptsizeten +\def\normalsize{\@setfontsize{\normalsize}{10bp}{11.2bp}} +\setlength{\@IEEEnormalsizeunitybaselineskip}{11.2bp} +\normalsize +\abovedisplayskip 1.5ex plus 4bp minus 2bp +\belowdisplayskip \abovedisplayskip +\abovedisplayshortskip 0pt plus 4bp +\belowdisplayshortskip 1.5ex plus 4bp minus 2bp +\fi +% 11pt +\ifx\CLASSOPTIONpt\@IEEEptsizeeleven +\def\normalsize{\@setfontsize{\normalsize}{11bp}{13.2bp}} +\setlength{\@IEEEnormalsizeunitybaselineskip}{13.2bp} +\normalsize +\abovedisplayskip 1.5ex plus 5bp minus 3bp +\belowdisplayskip \abovedisplayskip +\abovedisplayshortskip 0pt plus 5bp +\belowdisplayshortskip 1.5ex plus 5bp minus 3bp +\fi +% 12pt +\ifx\CLASSOPTIONpt\@IEEEptsizetwelve +\def\normalsize{\@setfontsize{\normalsize}{12bp}{14.4bp}} +\setlength{\@IEEEnormalsizeunitybaselineskip}{14.4bp} +\normalsize +\abovedisplayskip 1.5ex plus 6bp minus 4bp +\belowdisplayskip \abovedisplayskip +\abovedisplayshortskip 0pt plus 6bp +\belowdisplayshortskip 1.5ex plus 6bp minus 4bp +\fi +% +% compsoc nonconferences +\else +% 9pt +\ifx\CLASSOPTIONpt\@IEEEptsizenine +\def\normalsize{\@setfontsize{\normalsize}{9bp}{10.8bp}} +\setlength{\@IEEEnormalsizeunitybaselineskip}{10.8bp} +\normalsize +\abovedisplayskip 1.5ex plus 3bp minus 1bp +\belowdisplayskip \abovedisplayskip +\abovedisplayshortskip 0bp plus 3bp +\belowdisplayshortskip 1.5ex plus 3bp minus 1bp +\fi +% 10pt +\ifx\CLASSOPTIONpt\@IEEEptsizeten +% the official spec is 9.5bp with 11.4bp leading for 10pt, +% but measurements of proofs suggest upto 11.723bp leading +% here we'll use 11.54bp which gives 61 lines per column +% with the standard compsoc margins +\def\normalsize{\@setfontsize{\normalsize}{9.5bp}{11.54bp}} +\setlength{\@IEEEnormalsizeunitybaselineskip}{11.54bp} +\normalsize +\abovedisplayskip 1.5ex plus 4bp minus 2bp +\belowdisplayskip \abovedisplayskip +\abovedisplayshortskip 0pt plus 4bp +\belowdisplayshortskip 1.5ex plus 4bp minus 2bp +\fi +% 11pt +\ifx\CLASSOPTIONpt\@IEEEptsizeeleven +\def\normalsize{\@setfontsize{\normalsize}{11bp}{13.2bp}} +\setlength{\@IEEEnormalsizeunitybaselineskip}{13.2bp} +\normalsize +\abovedisplayskip 1.5ex plus 5bp minus 3bp +\belowdisplayskip \abovedisplayskip +\abovedisplayshortskip 0pt plus 5bp +\belowdisplayshortskip 1.5ex plus 5bp minus 3bp +\fi +% 12pt +\ifx\CLASSOPTIONpt\@IEEEptsizetwelve +\def\normalsize{\@setfontsize{\normalsize}{12bp}{14.4bp}} +\setlength{\@IEEEnormalsizeunitybaselineskip}{14.4bp} +\normalsize +\abovedisplayskip 1.5ex plus 6bp minus 4bp +\belowdisplayskip \abovedisplayskip +\abovedisplayshortskip 0pt plus 6bp +\belowdisplayshortskip 1.5ex plus 6bp minus 4bp +\fi +\fi\fi + + + + +% V1.6 The Computer Modern Fonts will issue a substitution warning for +% 24pt titles (24.88pt is used instead, but the default and correct +% Times font will scale exactly as needed) increase the substitution +% tolerance to turn off this warning. +% +% V1.8a, the compsoc bp font sizes can also cause bogus font substitution +% warnings with footnote or scriptsize math and the $\bullet$ itemized +% list of \IEEEcompsocitemizethanks. So, increase this to 1.5pt or more. +\def\fontsubfuzz{1.7bp} + + +% warn the user in case they forget to use the 9pt option with +% technote +\ifCLASSOPTIONtechnote% + \ifx\CLASSOPTIONpt\@IEEEptsizenine\else% + \typeout{** ATTENTION: Technotes are normally 9pt documents.}% + \fi% +\fi + + +% V1.7 +% Improved \textunderscore to provide a much better fake _ when used with +% OT1 encoding. Under OT1, detect use of pcr or cmtt \ttfamily and use +% available true _ glyph for those two typewriter fonts. +\def\@IEEEstringptm{ptm} % Times Roman family +\def\@IEEEstringppl{ppl} % Palatino Roman family +\def\@IEEEstringphv{phv} % Helvetica Sans Serif family +\def\@IEEEstringpcr{pcr} % Courier typewriter family +\def\@IEEEstringcmtt{cmtt} % Computer Modern typewriter family +\DeclareTextCommandDefault{\textunderscore}{\leavevmode +\ifx\f@family\@IEEEstringpcr\string_\else +\ifx\f@family\@IEEEstringcmtt\string_\else +\ifx\f@family\@IEEEstringptm\kern 0em\vbox{\hrule\@width 0.5em\@height 0.5pt\kern -0.3ex}\else +\ifx\f@family\@IEEEstringppl\kern 0em\vbox{\hrule\@width 0.5em\@height 0.5pt\kern -0.3ex}\else +\ifx\f@family\@IEEEstringphv\kern -0.03em\vbox{\hrule\@width 0.62em\@height 0.52pt\kern -0.33ex}\kern -0.03em\else +\kern 0.09em\vbox{\hrule\@width 0.6em\@height 0.44pt\kern -0.63pt\kern -0.42ex}\kern 0.09em\fi\fi\fi\fi\fi\relax} + + + + +% set the default \baselinestretch +\def\baselinestretch{1} +\ifCLASSOPTIONdraftcls + \def\baselinestretch{1.5}% default baselinestretch for draft modes +\fi + + +% process CLASSINPUT baselinestretch +\ifx\CLASSINPUTbaselinestretch\@IEEEundefined +\else + \edef\baselinestretch{\CLASSINPUTbaselinestretch} % user CLASSINPUT override + \typeout{** ATTENTION: Overriding \string\baselinestretch\space to + \baselinestretch\space via \string\CLASSINPUT.} +\fi + +\small\normalsize % make \baselinestretch take affect + + + + +% store the normalsize baselineskip +\newdimen\CLASSINFOnormalsizebaselineskip +\CLASSINFOnormalsizebaselineskip=\baselineskip\relax +% and the normalsize unity (baselinestretch=1) baselineskip +% we could save a register by giving the user access to +% \@IEEEnormalsizeunitybaselineskip. However, let's protect +% its read only internal status +\newdimen\CLASSINFOnormalsizeunitybaselineskip +\CLASSINFOnormalsizeunitybaselineskip=\@IEEEnormalsizeunitybaselineskip\relax +% store the nominal value of jot +\newdimen\IEEEnormaljot +\IEEEnormaljot=0.25\baselineskip\relax + +% set \jot +\jot=\IEEEnormaljot\relax + + + + +% V1.6, we are now going to fine tune the interword spacing +% The default interword glue for Times under TeX appears to use a +% nominal interword spacing of 25% (relative to the font size, i.e., 1em) +% a maximum of 40% and a minimum of 19%. +% For example, 10pt text uses an interword glue of: +% +% 2.5pt plus 1.49998pt minus 0.59998pt +% +% However, the IEEE allows for a more generous range which reduces the need +% for hyphenation, especially for two column text. Furthermore, the IEEE +% tends to use a little bit more nominal space between the words. +% The IEEE's interword spacing percentages appear to be: +% 35% nominal +% 23% minimum +% 50% maximum +% (They may even be using a tad more for the largest fonts such as 24pt.) +% +% for bold text, the IEEE increases the spacing a little more: +% 37.5% nominal +% 23% minimum +% 55% maximum + +% here are the interword spacing ratios we'll use +% for medium (normal weight) +\def\@IEEEinterspaceratioM{0.35} +\def\@IEEEinterspaceMINratioM{0.23} +\def\@IEEEinterspaceMAXratioM{0.50} + +% for bold +\def\@IEEEinterspaceratioB{0.375} +\def\@IEEEinterspaceMINratioB{0.23} +\def\@IEEEinterspaceMAXratioB{0.55} + + +% compsoc nonconference papers use Palatino, +% tweak settings to better match the proofs +\ifCLASSOPTIONcompsoc +\ifCLASSOPTIONconference\else +% for medium (normal weight) +\def\@IEEEinterspaceratioM{0.28} +\def\@IEEEinterspaceMINratioM{0.21} +\def\@IEEEinterspaceMAXratioM{0.47} +% for bold +\def\@IEEEinterspaceratioB{0.305} +\def\@IEEEinterspaceMINratioB{0.21} +\def\@IEEEinterspaceMAXratioB{0.52} +\fi\fi + + +% command to revise the interword spacing for the current font under TeX: +% \fontdimen2 = nominal interword space +% \fontdimen3 = interword stretch +% \fontdimen4 = interword shrink +% since all changes to the \fontdimen are global, we can enclose these commands +% in braces to confine any font attribute or length changes +\def\@@@IEEEsetfontdimens#1#2#3{{% +\setlength{\@IEEEtrantmpdimenB}{\f@size pt}% grab the font size in pt, could use 1em instead. +\setlength{\@IEEEtrantmpdimenA}{#1\@IEEEtrantmpdimenB}% +\fontdimen2\font=\@IEEEtrantmpdimenA\relax +\addtolength{\@IEEEtrantmpdimenA}{-#2\@IEEEtrantmpdimenB}% +\fontdimen3\font=-\@IEEEtrantmpdimenA\relax +\setlength{\@IEEEtrantmpdimenA}{#1\@IEEEtrantmpdimenB}% +\addtolength{\@IEEEtrantmpdimenA}{-#3\@IEEEtrantmpdimenB}% +\fontdimen4\font=\@IEEEtrantmpdimenA\relax}} + +% revise the interword spacing for each font weight +\def\@@IEEEsetfontdimens{{% +\mdseries +\@@@IEEEsetfontdimens{\@IEEEinterspaceratioM}{\@IEEEinterspaceMAXratioM}{\@IEEEinterspaceMINratioM}% +\bfseries +\@@@IEEEsetfontdimens{\@IEEEinterspaceratioB}{\@IEEEinterspaceMAXratioB}{\@IEEEinterspaceMINratioB}% +}} + +% revise the interword spacing for each font shape +% \slshape is not often used for IEEE work and is not altered here. The \scshape caps are +% already a tad too large in the free LaTeX fonts (as compared to what the IEEE uses) so we +% won't alter these either. +\def\@IEEEsetfontdimens{{% +\normalfont +\@@IEEEsetfontdimens +\normalfont\itshape +\@@IEEEsetfontdimens +}} + +% command to revise the interword spacing for each font size (and shape +% and weight). Only the \rmfamily is done here as \ttfamily uses a +% fixed spacing and \sffamily is not used as the main text of IEEE papers. +\def\@IEEEtunefonts{{\selectfont\rmfamily +\tiny\@IEEEsetfontdimens +\scriptsize\@IEEEsetfontdimens +\footnotesize\@IEEEsetfontdimens +\small\@IEEEsetfontdimens +\normalsize\@IEEEsetfontdimens +\sublargesize\@IEEEsetfontdimens +\large\@IEEEsetfontdimens +\LARGE\@IEEEsetfontdimens +\huge\@IEEEsetfontdimens +\Huge\@IEEEsetfontdimens}} + +% if the nofonttune class option is not given, revise the interword spacing +% now - in case IEEEtran makes any default length measurements, and make +% sure all the default fonts are loaded +\ifCLASSOPTIONnofonttune\else +\@IEEEtunefonts +\fi + +% and again at the start of the document in case the user loaded different fonts +\AtBeginDocument{\ifCLASSOPTIONnofonttune\else\@IEEEtunefonts\fi} + + + + + +% -- V1.8a page setup commands -- + +% The default sample text for calculating margins +% Note that IEEE publications use \scriptsize for headers and footers. +\def\IEEEdefaultsampletext{\normalfont\normalsize gT} +\def\IEEEdefaultheadersampletext{\normalfont\scriptsize T}% IEEE headers default to uppercase +\def\IEEEdefaultfootersampletext{\normalfont\scriptsize gT} + + + +% usage: \IEEEsettextwidth{inner margin}{outer margin} +% Sets \textwidth to allow the specified inner and outer margins +% for the current \paperwidth. +\def\IEEEsettextwidth#1#2{\@IEEEtrantmpdimenA\paperwidth +\@IEEEtrantmpdimenB#1\relax +\advance\@IEEEtrantmpdimenA by -\@IEEEtrantmpdimenB +\@IEEEtrantmpdimenB#2\relax +\advance\@IEEEtrantmpdimenA by -\@IEEEtrantmpdimenB +\textwidth\@IEEEtrantmpdimenA} + + + +% usage: \IEEEsetsidemargin{mode: i, o, c, a}{margin/offset} +% Sets \oddsidemargin and \evensidemargin to yield the specified margin +% of the given mode. +% The available modes are: +% i = inner margin +% o = outer margin +% c = centered, with the given offset +% a = adjust the margins using the given offset +% For the offsets, positive values increase the inner margin. +% \textwidth should be set properly for the given margins before calling this +% function. +\def\IEEEsetsidemargin#1#2{\@IEEEtrantmpdimenA #2\relax +\@IEEEextracttoken{#1}\relax +% check for mode errors +\ifx\@IEEEextractedtokenmacro\@empty + \@IEEEclspkgerror{Empty mode type in \string\IEEEsetsidemargin\space (line \the\inputlineno).\MessageBreak + Defaulting to `i'}{Valid modes for \string\IEEEsetsidemargin\space are: i, o, c and a.}\relax + \let\@IEEEextractedtoken=i\relax + \def\@IEEEextractedtokenmacro{i}\relax +\else + \ifx\@IEEEextractedtokensdiscarded\@empty\else + \typeout{** WARNING: \string\IEEEsetsidemargin\space mode specifiers after the first in `\@IEEEextracttokenarg' ignored (line \the\inputlineno).}\relax + \fi +\fi +% handle each mode +\if\@IEEEextractedtoken a\relax + \advance\oddsidemargin by \@IEEEtrantmpdimenA\relax +\else +\if\@IEEEextractedtoken c\relax + \oddsidemargin\paperwidth + \advance\oddsidemargin by -\textwidth + \divide\oddsidemargin by 2\relax + \advance\oddsidemargin by -1in\relax + \advance\oddsidemargin by \@IEEEtrantmpdimenA\relax +\else +\if\@IEEEextractedtoken o\relax + \oddsidemargin\paperwidth + \advance\oddsidemargin by -\textwidth + \advance\oddsidemargin by -\@IEEEtrantmpdimenA + \advance\oddsidemargin by -1in\relax +\else + \if\@IEEEextractedtoken i\relax + \else + \@IEEEclspkgerror{Unknown mode type `\@IEEEextractedtokenmacro' in \string\IEEEsetsidemargin\space (line \the\inputlineno).\MessageBreak + Defaulting to `i'}% + {Valid modes for \string\IEEEsetsidemargin\space are: i, o, c and a.}% + \fi + \oddsidemargin\@IEEEtrantmpdimenA + \advance\oddsidemargin by -1in\relax +\fi\fi\fi +% odd and even side margins both mean "inner" for single sided pages +\evensidemargin\oddsidemargin +% but are mirrors of each other when twosided is in effect +\if@twoside + \evensidemargin\paperwidth + \advance\evensidemargin by -\textwidth + \advance\evensidemargin by -\oddsidemargin + % have to compensate for both the builtin 1in LaTex offset + % and the fact we already subtracted this offset from \oddsidemargin + \advance\evensidemargin -2in\relax +\fi} + + + +% usage: \IEEEsettextheight[sample text]{top text margin}{bottom text margin} +% Sets \textheight based on the specified top margin and bottom margin. +% Takes into consideration \paperheight, \topskip, and (by default) the +% the actual height and depth of the \IEEEdefaultsampletext text. +\def\IEEEsettextheight{\@ifnextchar [{\@IEEEsettextheight}{\@IEEEsettextheight[\IEEEdefaultsampletext]}} +\def\@IEEEsettextheight[#1]#2#3{\textheight\paperheight\relax + \@IEEEtrantmpdimenA #2\relax + \advance \textheight by -\@IEEEtrantmpdimenA% subtract top margin + \@IEEEtrantmpdimenA #3\relax + \advance \textheight by -\@IEEEtrantmpdimenA% subtract bottom margin + \advance \textheight by \topskip% add \topskip + % subtract off everything above the top, and below the bottom, baselines + \settoheight{\@IEEEtrantmpdimenA}{\begingroup #1\relax\relax\relax\endgroup}\relax + \advance \textheight by -\@IEEEtrantmpdimenA + \settodepth{\@IEEEtrantmpdimenA}{\begingroup #1\relax\relax\relax\endgroup}\relax + \advance \textheight by -\@IEEEtrantmpdimenA} + + + +\newdimen\IEEEquantizedlength +\IEEEquantizedlength 0sp\relax +\newdimen\IEEEquantizedlengthdiff +\IEEEquantizedlengthdiff 0sp\relax +\def\IEEEquantizedlengthint{0} + +% usage: \IEEEquantizelength{mode: d, c, i}{base unit}{length} +% Sets the length \IEEEquantizedlength to be an integer multiple of the given +% (nonzero) base unit such that \IEEEquantizedlength approximates the given +% length. +% \IEEEquantizedlengthdiff is a length equal to the difference between the +% \IEEEquantizedlength and the given length. +% \IEEEquantizedlengthint is a macro containing the integer number of base units +% in \IEEEquantizedlength. +% i.e., \IEEEquantizedlength = \IEEEquantizedlengthint * base unit +% The mode determines how \IEEEquantizedlength is quantized: +% d = always decrease (always round down \IEEEquantizeint) +% c = use the closest match +% i = always increase (always round up \IEEEquantizeint) +% In anycase, if the given length is already quantized, +% \IEEEquantizedlengthdiff will be set to zero. +\def\IEEEquantizelength#1#2#3{\begingroup +% work in isolation so as not to externally disturb the \@IEEEtrantmp +% variables +% load the argument values indirectly via \IEEEquantizedlengthdiff +% in case the user refers to our \@IEEEtrantmpdimenX, \IEEEquantizedlength, +% etc. in the arguments. we also will work with these as counters, +% i.e., in sp units +% A has the base unit +\IEEEquantizedlengthdiff #2\relax\relax\relax\relax +\@IEEEtrantmpcountA\IEEEquantizedlengthdiff +% B has the input length +\IEEEquantizedlengthdiff #3\relax\relax\relax\relax +\@IEEEtrantmpcountB\IEEEquantizedlengthdiff +\@IEEEtrantmpdimenA\the\@IEEEtrantmpcountA sp\relax +\@IEEEtrantmpdimenB\the\@IEEEtrantmpcountB sp\relax +% \@IEEEtrantmpcountC will have the quantized int +% \IEEEquantizedlength will have the quantized length +% \@IEEEtrantmpdimenC will have the quantized diff +% initialize them to zero as this is what will be +% exported if an error occurs +\@IEEEtrantmpcountC 0\relax +\IEEEquantizedlength 0sp\relax +\@IEEEtrantmpdimenC 0sp\relax +% extract mode +\@IEEEextracttoken{#1}\relax +% check for mode errors +\ifx\@IEEEextractedtokenmacro\@empty + \@IEEEclspkgerror{Empty mode type in \string\IEEEquantizelength\space (line \the\inputlineno).\MessageBreak + Defaulting to `d'}{Valid modes for \string\IEEEquantizelength\space are: d, c and i.}\relax + \let\@IEEEextractedtoken=d\relax + \def\@IEEEextractedtokenmacro{d}\relax +\else + \ifx\@IEEEextractedtokensdiscarded\@empty\else + \typeout{** WARNING: \string\IEEEquantizelength\space mode specifiers after the first in `\@IEEEextracttokenarg' ignored (line \the\inputlineno).}\relax + \fi +\fi +% check for base unit is zero error +\ifnum\@IEEEtrantmpcountA=0\relax +\@IEEEclspkgerror{Base unit is zero in \string\IEEEquantizelength\space (line \the\inputlineno).\MessageBreak + \string\IEEEquantizedlength\space and \string\IEEEquantizedlengthdiff\space are set to zero}{Division by zero is not allowed.}\relax +\else% base unit is nonzero + % \@IEEEtrantmpcountC carries the number of integer units + % in the quantized length (integer length \ base) + \@IEEEtrantmpcountC\@IEEEtrantmpcountB\relax + \divide\@IEEEtrantmpcountC by \@IEEEtrantmpcountA\relax + % \IEEEquantizedlength has the (rounded down) quantized length + % = base * int + \IEEEquantizedlength\@IEEEtrantmpdimenA\relax + \multiply\IEEEquantizedlength by \@IEEEtrantmpcountC\relax + % \@IEEEtrantmpdimenC has the difference + % = quantized length - length + \@IEEEtrantmpdimenC\IEEEquantizedlength\relax + \advance\@IEEEtrantmpdimenC by -\@IEEEtrantmpdimenB\relax + % trap special case of length being already quantized + % to avoid a roundup under i option + \ifdim\@IEEEtrantmpdimenC=0sp\relax + \else % length not is already quantized + % set dimenA to carry the upper quantized (absolute value) difference: + % quantizedlength + base - length + \advance\@IEEEtrantmpdimenA by \IEEEquantizedlength\relax + \advance\@IEEEtrantmpdimenA by -\@IEEEtrantmpdimenB\relax + % set dimenB to carry the lower quantized (absolute value) difference: + % length - quantizedlength + \advance\@IEEEtrantmpdimenB by -\IEEEquantizedlength\relax + % handle each mode + \if\@IEEEextractedtoken c\relax + % compare upper and lower amounts, select upper if lower > upper + \ifdim\@IEEEtrantmpdimenB>\@IEEEtrantmpdimenA\relax + % use upper + \advance\IEEEquantizedlength by \the\@IEEEtrantmpcountA sp\relax + \advance\@IEEEtrantmpcountC by 1\relax + \@IEEEtrantmpdimenC\@IEEEtrantmpdimenA + \else% <=. uselower + % no need to do anything for lower, use output values already setup + \fi + \else% not mode c + \if\@IEEEextractedtoken i\relax + % always round up under i mode + \advance\IEEEquantizedlength by \the\@IEEEtrantmpcountA sp\relax + \advance\@IEEEtrantmpcountC by 1\relax + \@IEEEtrantmpdimenC\@IEEEtrantmpdimenA + \else + \if\@IEEEextractedtoken d\relax + \else + \@IEEEclspkgerror{Unknown mode type `\@IEEEextractedtokenmacro' in \string\IEEEquantizelength\space (line \the\inputlineno).\MessageBreak + Defaulting to `d'}% + {Valid modes for \string\IEEEquantizelength\space are: d, c, and i.}\relax + \fi % if d + % no need to do anything for d, use output values already setup + \fi\fi % if i, c + \fi % if length is already quantized +\fi% if base unit is zero +% globally assign the results to macros we use here to escape the enclosing +% group without needing to call \global on any of the \@IEEEtrantmp variables. +% \@IEEEtrantmpcountC has the quantized int +% \IEEEquantizedlength has the quantized length +% \@IEEEtrantmpdimenC has the quantized diff +\xdef\@IEEEquantizedlengthintmacro{\the\@IEEEtrantmpcountC}\relax +\@IEEEtrantmpcountC\IEEEquantizedlength\relax +\xdef\@IEEEquantizedlengthmacro{\the\@IEEEtrantmpcountC}\relax +\@IEEEtrantmpcountC\@IEEEtrantmpdimenC\relax +\xdef\@IEEEquantizedlengthdiffmacro{\the\@IEEEtrantmpcountC}\relax +\endgroup +% locally assign the outputs here from the macros +\expandafter\IEEEquantizedlength\@IEEEquantizedlengthmacro sp\relax +\expandafter\IEEEquantizedlengthdiff\@IEEEquantizedlengthdiffmacro sp\relax +\edef\IEEEquantizedlengthint{\@IEEEquantizedlengthintmacro}\relax} + + + +\newdimen\IEEEquantizedtextheightdiff +\IEEEquantizedtextheightdiff 0sp\relax + +% usage: \IEEEquantizetextheight[base unit]{mode: d, c, i} +% Sets \textheight to be an integer multiple of the current \baselineskip +% (or the optionally specified base unit) plus the first (\topskip) line. +% \IEEEquantizedtextheightdiff is a length equal to the difference between +% the new quantized and original \textheight. +% \IEEEquantizedtextheightlpc is a macro containing the integer number of +% lines per column under the quantized \textheight. i.e., +% \textheight = \IEEEquantizedtextheightlpc * \baselineskip + \topskip +% The mode determines how \textheight is quantized: +% d = always decrease (always round down the number of lines per column) +% c = use the closest match +% i = always increase (always round up the number of lines per column) +% In anycase, if \textheight is already quantized, it will remain unchanged, +% and \IEEEquantizedtextheightdiff will be set to zero. +% Depends on: \IEEEquantizelength +\def\IEEEquantizetextheight{\@ifnextchar [{\@IEEEquantizetextheight}{\@IEEEquantizetextheight[\baselineskip]}} +\def\@IEEEquantizetextheight[#1]#2{\begingroup +% use our \IEEEquantizedtextheightdiff as a scratch pad +% we need to subtract off \topskip before quantization +\IEEEquantizedtextheightdiff\textheight +\advance\IEEEquantizedtextheightdiff by -\topskip\relax +\IEEEquantizelength{#2}{#1}{\IEEEquantizedtextheightdiff} +% add back \topskip line +\advance\IEEEquantizedlength by \topskip +\@IEEEtrantmpcountC\IEEEquantizedlengthint\relax +\advance\@IEEEtrantmpcountC by 1\relax +% globally assign the results to macros we use here to escape the enclosing +% group without needing to call \global on any of the \@IEEEtrantmp variables. +\xdef\@IEEEquantizedtextheightlpcmacro{\the\@IEEEtrantmpcountC}\relax +\@IEEEtrantmpcountC\IEEEquantizedlength\relax +\xdef\@IEEEquantizedtextheightmacro{\the\@IEEEtrantmpcountC}\relax +\@IEEEtrantmpcountC\IEEEquantizedlengthdiff\relax +\xdef\@IEEEquantizedtextheightdiffmacro{\the\@IEEEtrantmpcountC}\relax +\endgroup +% locally assign the outputs here from the macros +\textheight\@IEEEquantizedtextheightmacro sp\relax +\IEEEquantizedtextheightdiff\@IEEEquantizedtextheightdiffmacro sp\relax +\edef\IEEEquantizedtextheightlpc{\@IEEEquantizedtextheightlpcmacro}} + + + +% usage: \IEEEsettopmargin[sample text]{mode: t, b, c, a, q}{margin/offset} +% Sets \topmargin based on the specified vertical margin. +% Takes into consideration the base 1in offset, \headheight, \headsep, +% \topskip, and (by default) the the actual height (or, for the bottom, depth) +% of the \IEEEdefaultsampletext text. +% The available modes are: +% t = top margin +% b = bottom margin +% c = vertically centered, with the given offset +% a = adjust the vertical margins using the given offset +% q = adjust the margins using \IEEEquantizedtextheightdiff and the given offset +% For the offsets, positive values increase the top margin. +% \headheight, \headsep, \topskip and \textheight should be set properly for the +% given margins before calling this function. +\def\IEEEsettopmargin{\@ifnextchar [{\@IEEEsettopmargin}{\@IEEEsettopmargin[\IEEEdefaultsampletext]}} +\def\@IEEEsettopmargin[#1]#2#3{\@IEEEtrantmpdimenA #3\relax +\@IEEEextracttoken{#2}\relax +% check for mode errors +\ifx\@IEEEextractedtokenmacro\@empty + \@IEEEclspkgerror{Empty mode type in \string\IEEEsettopmargin\space (line \the\inputlineno).\MessageBreak + Defaulting to `t'}{Valid modes for \string\IEEEsettopmargin\space are: t, b, c, a and q.}\relax + \let\@IEEEextractedtoken=t\relax + \def\@IEEEextractedtokenmacro{t}\relax +\else + \ifx\@IEEEextractedtokensdiscarded\@empty\else + \typeout{** WARNING: \string\IEEEsettopmargin\space mode specifiers after the first in `\@IEEEextracttokenarg' ignored (line \the\inputlineno).}\relax + \fi +\fi +% handle each mode +\if\@IEEEextractedtoken a\relax + \advance\topmargin by \@IEEEtrantmpdimenA\relax +\else +\if\@IEEEextractedtoken q\relax + % we need to adjust by half the \IEEEquantizedtextheightdiff value + \@IEEEtrantmpdimenB\IEEEquantizedtextheightdiff\relax + \divide\@IEEEtrantmpdimenB by 2\relax + % a positive \IEEEquantizedtextheightdiff means we need to reduce \topmargin + % because \textheight has been lenghtened + \advance\topmargin by -\@IEEEtrantmpdimenB\relax + \advance\topmargin by \@IEEEtrantmpdimenA\relax +\else +\if\@IEEEextractedtoken c\relax + \topmargin\paperheight + \advance\topmargin by -\textheight + % \textheight includes \topskip, but we should not count topskip whitespace here, backout + \advance \topmargin by \topskip + \settoheight{\@IEEEtrantmpdimenB}{\begingroup #1\relax\relax\relax\endgroup}\relax + \advance\topmargin by -\@IEEEtrantmpdimenB\relax + \settodepth{\@IEEEtrantmpdimenB}{\begingroup #1\relax\relax\relax\endgroup}\relax + \advance\topmargin by -\@IEEEtrantmpdimenB\relax + \divide\topmargin by 2\relax + \advance\topmargin by \@IEEEtrantmpdimenA\relax +\else +\if\@IEEEextractedtoken b\relax + \topmargin\paperheight + \advance\topmargin by -\textheight + % \textheight includes \topskip, but we should not count topskip whitespace here, backout + \advance \topmargin by \topskip + \settodepth{\@IEEEtrantmpdimenB}{\begingroup #1\relax\relax\relax\endgroup}\relax + \advance\topmargin by -\@IEEEtrantmpdimenB\relax + \advance\topmargin by -\@IEEEtrantmpdimenA\relax +\else + \if\@IEEEextractedtoken t\relax + \else + \@IEEEclspkgerror{Unknown mode type `\@IEEEextractedtokenmacro' in \string\IEEEsettopmargin\space (line \the\inputlineno).\MessageBreak + Defaulting to `t'}% + {Valid modes for \string\IEEEsettopmargin\space are: t, b, c, a and q.}\relax + \fi + \topmargin\@IEEEtrantmpdimenA\relax + \settoheight{\@IEEEtrantmpdimenB}{\begingroup #1\relax\relax\relax\endgroup}\relax + \advance\topmargin by \@IEEEtrantmpdimenB\relax +\fi\fi % if t, b, c +% convert desired top margin into actual \topmargin +% this is not done for the q or a modes because they are only adjustments +\advance \topmargin by -\topskip +\advance \topmargin by -1in +\advance \topmargin by -\headheight +\advance \topmargin by -\headsep +\fi\fi % if q, a +} + + + +% usage: \IEEEsetheadermargin[header sample][text sample]{mode: t, b, c, a}{margin/offset} +% Differentially adjusts \topmargin and \headsep (such that their sum is unchanged) +% based on the specified header margin. +% Takes into consideration the base 1in offset, \headheight, \topskip, and (by default) +% the actual height (or depth) of the \IEEEdefaultheadersampletext and +% \IEEEdefaultsampletext text. +% The available modes are: +% t = top margin (top of the header text to the top of the page) +% b = bottom margin (bottom of the header text to the top of the main text) +% c = vertically centered between the main text and the top of the page, +% with the given offset +% a = adjust the vertical position using the given offset +% For the offsets, positive values move the header downward. +% \headheight, \headsep, \topskip and \topmargin should be set properly before +% calling this function. +\def\IEEEsetheadermargin{\@ifnextchar [{\@IEEEsetheadermargin}{\@IEEEsetheadermargin[\IEEEdefaultheadersampletext]}} +\def\@IEEEsetheadermargin[#1]{\@ifnextchar [{\@@IEEEsetheadermargin[#1]}{\@@IEEEsetheadermargin[#1][\IEEEdefaultsampletext]}} +\def\@@IEEEsetheadermargin[#1][#2]#3#4{\@IEEEtrantmpdimenA #4\relax +\@IEEEextracttoken{#3}\relax +% check for mode errors +\ifx\@IEEEextractedtokenmacro\@empty + \@IEEEclspkgerror{Empty mode type in \string\IEEEsetheadermargin\space (line \the\inputlineno).\MessageBreak + Defaulting to `t'}{Valid modes for \string\IEEEsetheadermargin\space are: t, b, c, and a.}\relax + \let\@IEEEextractedtoken=t\relax + \def\@IEEEextractedtokenmacro{t}\relax +\else + \ifx\@IEEEextractedtokensdiscarded\@empty\else + \typeout{** WARNING: \string\IEEEsetheadermargin\space mode specifiers after the first in `\@IEEEextracttokenarg' ignored (line \the\inputlineno).}\relax + \fi +\fi +% handle each mode +\if\@IEEEextractedtoken a\relax + % No need to do anything here and can pass through the adjustment + % value as is. The end adjustment of \topmargin and \headsep will + % do all that is needed +\else +\if\@IEEEextractedtoken c\relax + % get the bottom margin + \@IEEEtrantmpdimenB\headsep\relax + \settodepth{\@IEEEtrantmpdimenC}{\begingroup #1\relax\relax\relax\endgroup}\relax + \advance\@IEEEtrantmpdimenB by -\@IEEEtrantmpdimenC + \advance\@IEEEtrantmpdimenB by \topskip + \settoheight{\@IEEEtrantmpdimenC}{\begingroup #2\relax\relax\relax\endgroup}\relax + \advance\@IEEEtrantmpdimenB by -\@IEEEtrantmpdimenC + % at this point \@IEEEtrantmpdimenB has the actual header bottom margin + % subtract from it the top header margin + \advance\@IEEEtrantmpdimenB -1in\relax % take into consideration the system 1in offset of the top margin + \advance\@IEEEtrantmpdimenB by -\topmargin + \advance\@IEEEtrantmpdimenB by -\headheight + \settoheight{\@IEEEtrantmpdimenC}{\begingroup #1\relax\relax\relax\endgroup}\relax + \advance\@IEEEtrantmpdimenB by \@IEEEtrantmpdimenC + % at this point \@IEEEtrantmpdimenB has the difference between the bottom and top margins + % we need to adjust by half this amount to center the header + \divide\@IEEEtrantmpdimenB by 2\relax + % and add to offset + \advance\@IEEEtrantmpdimenA by \@IEEEtrantmpdimenB +\else +\if\@IEEEextractedtoken b\relax + \@IEEEtrantmpdimenB\headsep\relax + \settodepth{\@IEEEtrantmpdimenC}{\begingroup #1\relax\relax\relax\endgroup}\relax + \advance\@IEEEtrantmpdimenB by -\@IEEEtrantmpdimenC + \advance\@IEEEtrantmpdimenB by \topskip + \settoheight{\@IEEEtrantmpdimenC}{\begingroup #2\relax\relax\relax\endgroup}\relax + \advance\@IEEEtrantmpdimenB by -\@IEEEtrantmpdimenC + % at this point \@IEEEtrantmpdimenB has the actual header bottom margin + % get the difference between the actual and the desired + \advance\@IEEEtrantmpdimenB by -\@IEEEtrantmpdimenA + \@IEEEtrantmpdimenA\@IEEEtrantmpdimenB +\else + \if\@IEEEextractedtoken t\relax + \else + \@IEEEclspkgerror{Unknown mode type `\@IEEEextractedtokenmacro' in \string\IEEEsetheadermargin\space (line \the\inputlineno).\MessageBreak + Defaulting to `t'}% + {Valid modes for \string\IEEEsetheadermargin\space are: t, b, c and a.}\relax + \fi + \@IEEEtrantmpdimenB 1in\relax % take into consideration the system 1in offset of the top margin + \advance\@IEEEtrantmpdimenB by \topmargin + \advance\@IEEEtrantmpdimenB by \headheight + \settoheight{\@IEEEtrantmpdimenC}{\begingroup #1\relax\relax\relax\endgroup}\relax + \advance\@IEEEtrantmpdimenB by -\@IEEEtrantmpdimenC + % at this point \@IEEEtrantmpdimenB has the actual header top margin + % get the difference between the desired and the actual + \advance\@IEEEtrantmpdimenA by -\@IEEEtrantmpdimenB +\fi\fi % if t, b, c +\fi % if a +% advance \topmargin by the needed amount and reduce \headsep by the same +% so as not to disturb the location of the main text +\advance\topmargin by \@IEEEtrantmpdimenA\relax +\advance\headsep by -\@IEEEtrantmpdimenA\relax +} + + + +% usage: \IEEEsetfootermargin[footer sample][text sample]{mode: t, b, c, a}{margin/offset} +% Adjusts \footskip based on the specified footer margin. +% Takes into consideration the base 1in offset, \paperheight, \headheight, +% \headsep, \textheight and (by default) the actual height (or depth) of the +% \IEEEdefaultfootersampletext and \IEEEdefaultsampletext text. +% The available modes are: +% t = top margin (top of the footer text to the bottom of the main text) +% b = bottom margin (bottom of the footer text to the bottom of page) +% c = vertically centered between the main text and the bottom of the page, +% with the given offset +% a = adjust the vertical position using the given offset +% For the offsets, positive values move the footer downward. +% \headheight, \headsep, \topskip, \topmargin, and \textheight should be set +% properly before calling this function. +\def\IEEEsetfootermargin{\@ifnextchar [{\@IEEEsetfootermargin}{\@IEEEsetfootermargin[\IEEEdefaultfootersampletext]}} +\def\@IEEEsetfootermargin[#1]{\@ifnextchar [{\@@IEEEsetfootermargin[#1]}{\@@IEEEsetfootermargin[#1][\IEEEdefaultsampletext]}} +\def\@@IEEEsetfootermargin[#1][#2]#3#4{\@IEEEtrantmpdimenA #4\relax +\@IEEEextracttoken{#3}\relax +% check for mode errors +\ifx\@IEEEextractedtokenmacro\@empty + \@IEEEclspkgerror{Empty mode type in \string\IEEEsetfootermargin\space (line \the\inputlineno).\MessageBreak + Defaulting to `t'}{Valid modes for \string\IEEEsetfootermargin\space are: t, b, c, and a.}\relax + \let\@IEEEextractedtoken=t\relax + \def\@IEEEextractedtokenmacro{t}\relax +\else + \ifx\@IEEEextractedtokensdiscarded\@empty\else + \typeout{** WARNING: \string\IEEEsetfootermargin\space mode specifiers after the first in `\@IEEEextracttokenarg' ignored (line \the\inputlineno).}\relax + \fi +\fi +% handle each mode +\if\@IEEEextractedtoken a\relax + % No need to do anything here and can pass through the adjustment + % value as is. The end adjustment of \footskip will do all that + % is needed +\else +\if\@IEEEextractedtoken c\relax + % calculate the bottom margin + \@IEEEtrantmpdimenB 1in\relax % system 1in offset + \advance\@IEEEtrantmpdimenB\topmargin\relax + \advance\@IEEEtrantmpdimenB\headheight\relax + \advance\@IEEEtrantmpdimenB\headsep\relax + \advance\@IEEEtrantmpdimenB\textheight\relax + \advance\@IEEEtrantmpdimenB\footskip\relax + \settodepth{\@IEEEtrantmpdimenC}{\begingroup #1\relax\relax\relax\endgroup}\relax + \advance\@IEEEtrantmpdimenC by \@IEEEtrantmpdimenB + \@IEEEtrantmpdimenB\paperheight + \advance\@IEEEtrantmpdimenB by -\@IEEEtrantmpdimenC + % at this point \@IEEEtrantmpdimenB has the actual footer bottom margin + % now subtract off the footer top margin + \advance\@IEEEtrantmpdimenB -\footskip\relax + \settodepth{\@IEEEtrantmpdimenC}{\begingroup #2\relax\relax\relax\endgroup}\relax + \advance\@IEEEtrantmpdimenB by \@IEEEtrantmpdimenC + \settoheight{\@IEEEtrantmpdimenC}{\begingroup #1\relax\relax\relax\endgroup}\relax + \advance\@IEEEtrantmpdimenB by \@IEEEtrantmpdimenC + % at this point \@IEEEtrantmpdimenB has the difference between the bottom + % and top footer margins + % our adjustment must be half this value to center the footer + \divide\@IEEEtrantmpdimenB by 2\relax + % add to the offset + \advance\@IEEEtrantmpdimenA by \@IEEEtrantmpdimenB +\else +\if\@IEEEextractedtoken b\relax + % calculate the bottom margin + \@IEEEtrantmpdimenB 1in\relax % system 1in offset + \advance\@IEEEtrantmpdimenB\topmargin\relax + \advance\@IEEEtrantmpdimenB\headheight\relax + \advance\@IEEEtrantmpdimenB\headsep\relax + \advance\@IEEEtrantmpdimenB\textheight\relax + \advance\@IEEEtrantmpdimenB\footskip\relax + \settodepth{\@IEEEtrantmpdimenC}{\begingroup #1\relax\relax\relax\endgroup}\relax + \advance\@IEEEtrantmpdimenC by \@IEEEtrantmpdimenB + \@IEEEtrantmpdimenB\paperheight + \advance\@IEEEtrantmpdimenB by -\@IEEEtrantmpdimenC + % at this point \@IEEEtrantmpdimenB has the actual footer bottom margin + % get the difference between the actual and the desired + \advance\@IEEEtrantmpdimenB by -\@IEEEtrantmpdimenA + \@IEEEtrantmpdimenA\@IEEEtrantmpdimenB +\else + \if\@IEEEextractedtoken t\relax + \else + \@IEEEclspkgerror{Unknown mode type `\@IEEEextractedtokenmacro' in \string\IEEEsetfootermargin\space (line \the\inputlineno).\MessageBreak + Defaulting to `t'}% + {Valid modes for \string\IEEEsetfootermargin\space are: t, b, c and a.}\relax + \fi + \@IEEEtrantmpdimenB\footskip\relax + \settodepth{\@IEEEtrantmpdimenC}{\begingroup #2\relax\relax\relax\endgroup}\relax + \advance\@IEEEtrantmpdimenB by -\@IEEEtrantmpdimenC + \settoheight{\@IEEEtrantmpdimenC}{\begingroup #1\relax\relax\relax\endgroup}\relax + \advance\@IEEEtrantmpdimenB by -\@IEEEtrantmpdimenC + % at this point \@IEEEtrantmpdimenB has the actual footer top margin + % get the difference between the desired and the actual + \advance\@IEEEtrantmpdimenA by -\@IEEEtrantmpdimenB +\fi\fi % if t, b, c +\fi % if a +% advance \footskip by the needed amount +\advance\footskip by \@IEEEtrantmpdimenA\relax +} + +% -- End V1.8a page setup commands -- + + + + + +% V1.6 +% LaTeX is a little to quick to use hyphenations +% So, we increase the penalty for their use and raise +% the badness level that triggers an underfull hbox +% warning. The author may still have to tweak things, +% but the appearance will be much better "right out +% of the box" than that under V1.5 and prior. +% TeX default is 50 +\hyphenpenalty=750 +\ifCLASSOPTIONcompsoc +\hyphenpenalty 500 +\fi +% If we didn't adjust the interword spacing, 2200 might be better. +% The TeX default is 1000 +\hbadness=1350 +% The IEEE does not use extra spacing after punctuation +\frenchspacing + +% V1.7 increase this a tad to discourage equation breaks +\binoppenalty=1000 % default 700 +\relpenalty=800 % default 500 + +% v1.8a increase these to discourage widows and orphans +\clubpenalty=1000 % default 150 +\widowpenalty=1000 % default 150 +\displaywidowpenalty=1000 % default 50 + + +% margin note stuff +\marginparsep 10pt +\marginparwidth 20pt +\marginparpush 25pt + + +% if things get too close, go ahead and let them touch +\lineskip 0pt +\normallineskip 0pt +\lineskiplimit 0pt +\normallineskiplimit 0pt + +% The distance from the lower edge of the text body to the +% footline +\footskip 0.4in + +% normally zero, should be relative to font height. +% put in a little rubber to help stop some bad breaks (underfull vboxes) +\parskip 0ex plus 0.2ex minus 0.1ex + +\parindent 1.0em +\ifCLASSOPTIONcompsoc + \parindent 1.5em +\fi + +\headheight 12pt +\headsep 18pt +% use the normal font baselineskip +% so that \topskip is unaffected by changes in \baselinestretch +\topskip=\@IEEEnormalsizeunitybaselineskip + + +% V1.8 \maxdepth defaults to 4pt, but should be font size dependent +\maxdepth=0.5\@IEEEnormalsizeunitybaselineskip +\textheight 58pc % 9.63in, 696pt + +% set the default top margin to 58pt +% which results in a \topmargin of -49.59pt for 10pt documents +\IEEEsettopmargin{t}{58pt} +% tweak textheight to a perfect integer number of lines/column. +% standard is: 9pt/63 lpc; 10pt/58 lpc; 11pt/52 lpc; 12pt/50 lpc +\IEEEquantizetextheight{c} +% tweak top margin so that the error is shared equally at the top and bottom +\IEEEsettopmargin{q}{0sp} + + +\columnsep 1pc +\textwidth 43pc % 2 x 21pc + 1pc = 43pc + +% set the default side margins to center the text +\IEEEsetsidemargin{c}{0pt} + + +% adjust margins for default conference mode +\ifCLASSOPTIONconference + \textheight 9.25in % The standard for conferences (668.4975pt) + \IEEEsettopmargin{t}{0.75in} + % tweak textheight to a perfect integer number of lines/page. + % standard is: 9pt/61 lpc; 10pt/56 lpc; 11pt/50 lpc; 12pt/48 lpc + \IEEEquantizetextheight{c} + % tweak top margin so that the error is shared equally at the top and bottom + \IEEEsettopmargin{q}{0sp} +\fi + + +% compsoc text sizes, margins and spacings +\ifCLASSOPTIONcompsoc + \columnsep 12bp + % CS specs for \textwdith are 6.875in + % \textwidth 6.875in + % however, measurements from proofs show they are using 3.5in columns + \textwidth 7in + \advance\textwidth by \columnsep + % set the side margins to center the text + \IEEEsetsidemargin{c}{0pt} + % top/bottom margins to center + % could just set \textheight to 9.75in for all the different paper sizes + % and then quantize, but we'll do it the long way here to allow for easy + % future per-paper size adjustments + \IEEEsettextheight{0.625in}{0.625in}% 11in - 2 * 0.625in = 9.75in is the standard text height for compsoc journals + \IEEEsettopmargin{t}{0.625in} + \if@IEEEusingcspaper + \IEEEsettextheight{0.5in}{0.5in}% 10.75in - 2 * 0.5in = 9.75in + \IEEEsettopmargin{t}{0.5in} + \fi + \if@IEEEusingAfourpaper + \IEEEsettextheight{24.675mm}{24.675mm}% 297mm - 2 * 24.675mm = 247.650mm (9.75in) + \IEEEsettopmargin{t}{24.675mm} + \fi + % tweak textheight to a perfect integer number of lines/page. + % standard is: 9pt/65 lpc; 10pt/61 lpc; 11pt/53 lpc; 12pt/49 lpc + \IEEEquantizetextheight{c} + % tweak top margin so that the error is shared equally at the top and bottom + \IEEEsettopmargin{q}{0sp} + +% compsoc conference + \ifCLASSOPTIONconference + % compsoc conference use a larger value for columnsep + \columnsep 0.25in + \IEEEsettextwidth{0.75in}{0.75in} + % set the side margins to center the text (0.75in for letterpaper) + \IEEEsetsidemargin{c}{0pt} + % compsoc conferences want 1in top and bottom margin + \IEEEsettextheight{1in}{1in} + \IEEEsettopmargin{t}{1in} + % tweak textheight to a perfect integer number of lines/page. + % standard is: 9pt/58 lpc; 10pt/53 lpc; 11pt/48 lpc; 12pt/46 lpc + \IEEEquantizetextheight{c} + % tweak top margin so that the error is shared equally at the top and bottom + \IEEEsettopmargin{q}{0sp} + \fi +\fi + + + +% draft mode settings override that of all other modes +% provides a nice 1in margin all around the paper and extra +% space between the lines for editor's comments +\ifCLASSOPTIONdraftcls + % we want 1in side margins regardless of paper type + \IEEEsettextwidth{1in}{1in} + \IEEEsetsidemargin{c}{0pt} + % want 1in top and bottom margins + \IEEEsettextheight{1in}{1in} + \IEEEsettopmargin{t}{1in} + % digitize textheight to be an integer number of lines. + % this may cause the top and bottom margins to be off a tad + \IEEEquantizetextheight{c} + % tweak top margin so that the error is shared equally at the top and bottom + \IEEEsettopmargin{q}{0sp} +\fi + + + +% process CLASSINPUT inner/outer margin +% if inner margin defined, but outer margin not, set outer to inner. +\ifx\CLASSINPUTinnersidemargin\@IEEEundefined +\else + \ifx\CLASSINPUToutersidemargin\@IEEEundefined + \edef\CLASSINPUToutersidemargin{\CLASSINPUTinnersidemargin} + \fi +\fi + +\ifx\CLASSINPUToutersidemargin\@IEEEundefined +\else + % if outer margin defined, but inner margin not, set inner to outer. + \ifx\CLASSINPUTinnersidemargin\@IEEEundefined + \edef\CLASSINPUTinnersidemargin{\CLASSINPUToutersidemargin} + \fi + \IEEEsettextwidth{\CLASSINPUTinnersidemargin}{\CLASSINPUToutersidemargin} + \IEEEsetsidemargin{i}{\CLASSINPUTinnersidemargin} + \typeout{** ATTENTION: Overriding inner side margin to \CLASSINPUTinnersidemargin\space and + outer side margin to \CLASSINPUToutersidemargin\space via \string\CLASSINPUT.} +\fi + + + +% process CLASSINPUT top/bottom text margin +% if toptext margin defined, but bottomtext margin not, set bottomtext to toptext margin +\ifx\CLASSINPUTtoptextmargin\@IEEEundefined +\else + \ifx\CLASSINPUTbottomtextmargin\@IEEEundefined + \edef\CLASSINPUTbottomtextmargin{\CLASSINPUTtoptextmargin} + \fi +\fi + +\ifx\CLASSINPUTbottomtextmargin\@IEEEundefined +\else + % if bottomtext margin defined, but toptext margin not, set toptext to bottomtext margin + \ifx\CLASSINPUTtoptextmargin\@IEEEundefined + \edef\CLASSINPUTtoptextmargin{\CLASSINPUTbottomtextmargin} + \fi + \IEEEsettextheight{\CLASSINPUTtoptextmargin}{\CLASSINPUTbottomtextmargin} + \IEEEsettopmargin{t}{\CLASSINPUTtoptextmargin} + \typeout{** ATTENTION: Overriding top text margin to \CLASSINPUTtoptextmargin\space and + bottom text margin to \CLASSINPUTbottomtextmargin\space via \string\CLASSINPUT.} +\fi + + + +% default to center header and footer text in the margins +\IEEEsetheadermargin{c}{0pt} +\IEEEsetfootermargin{c}{0pt} + +% adjust header and footer positions for compsoc journals +\ifCLASSOPTIONcompsoc + \ifCLASSOPTIONjournal + \IEEEsetheadermargin{b}{\@IEEEnormalsizeunitybaselineskip} + \IEEEsetfootermargin{t}{\@IEEEnormalsizeunitybaselineskip} + \fi +\fi + + +% V1.8a display lines per column info message on user's console +\def\IEEEdisplayinfolinespercolumn{\@IEEEtrantmpdimenA=\textheight +% topskip represents only one line even if > baselineskip +\advance\@IEEEtrantmpdimenA by -1\topskip +\@IEEEtrantmpcountA=\@IEEEtrantmpdimenA +\@IEEEtrantmpcountB=\@IEEEtrantmpdimenA +\divide\@IEEEtrantmpcountB by \baselineskip +% need to add one line to include topskip (first) line +\advance\@IEEEtrantmpcountB by 1 +% save lines per column value as text +\edef\@IEEEnumlinespercolumninfotxt{\the\@IEEEtrantmpcountB} +% backout topskip advance to allow direct \@IEEEtrantmpcountA comparison +\advance\@IEEEtrantmpcountB by -1 +% restore value as text height (without topskip) rather than just as number of lines +\multiply\@IEEEtrantmpcountB by \baselineskip +% is the column height an integer number of lines per column? +\ifnum\@IEEEtrantmpcountA=\@IEEEtrantmpcountB +\edef\@IEEEnumlinespercolumnexactinfotxt{exact} +\else +\@IEEEtrantmpdimenA\@IEEEtrantmpcountA sp\relax +\advance\@IEEEtrantmpdimenA by -\@IEEEtrantmpcountB sp\relax +\edef\@IEEEnumlinespercolumnexactinfotxt{approximate, difference = \the\@IEEEtrantmpdimenA} +\fi +\typeout{-- Lines per column: \@IEEEnumlinespercolumninfotxt\space (\@IEEEnumlinespercolumnexactinfotxt).}} +% delay execution till start of document to allow for user changes +\AtBeginDocument{\IEEEdisplayinfolinespercolumn} + + + +% LIST SPACING CONTROLS + +% Controls the amount of EXTRA spacing +% above and below \trivlist +% Both \list and IED lists override this. +% However, \trivlist will use this as will most +% things built from \trivlist like the \center +% environment. +\topsep 0.5\baselineskip + +% Controls the additional spacing around lists preceded +% or followed by blank lines. the IEEE does not increase +% spacing before or after paragraphs so it is set to zero. +% \z@ is the same as zero, but faster. +\partopsep \z@ + +% Controls the spacing between paragraphs in lists. +% The IEEE does not increase spacing before or after paragraphs +% so this is also zero. +% With IEEEtran.cls, global changes to +% this value DO affect lists (but not IED lists). +\parsep \z@ + +% Controls the extra spacing between list items. +% The IEEE does not put extra spacing between items. +% With IEEEtran.cls, global changes to this value DO affect +% lists (but not IED lists). +\itemsep \z@ + +% \itemindent is the amount to indent the FIRST line of a list +% item. It is auto set to zero within the \list environment. To alter +% it, you have to do so when you call the \list. +% However, the IEEE uses this for the theorem environment +% There is an alternative value for this near \leftmargini below +\itemindent -1em + +% \leftmargin, the spacing from the left margin of the main text to +% the left of the main body of a list item is set by \list. +% Hence this statement does nothing for lists. +% But, quote and verse do use it for indention. +\leftmargin 2em + +% we retain this stuff from the older IEEEtran.cls so that \list +% will work the same way as before. However, itemize, enumerate and +% description (IED) could care less about what these are as they +% all are overridden. +\leftmargini 2em +%\itemindent 2em % Alternative values: sometimes used. +%\leftmargini 0em +\leftmarginii 1em +\leftmarginiii 1.5em +\leftmarginiv 1.5em +\leftmarginv 1.0em +\leftmarginvi 1.0em +\labelsep 0.5em +\labelwidth \z@ + + +% The old IEEEtran.cls behavior of \list is retained. +% However, the new V1.3 IED list environments override all the +% @list stuff (\@listX is called within \list for the +% appropriate level just before the user's list_decl is called). +% \topsep is now 2pt as the IEEE puts a little extra space around +% lists - used by those non-IED macros that depend on \list. +% Note that \parsep and \itemsep are not redefined as in +% the sizexx.clo \@listX (which article.cls uses) so global changes +% of these values DO affect \list +% +\def\@listi{\leftmargin\leftmargini \topsep 2pt plus 1pt minus 1pt} +\let\@listI\@listi +\def\@listii{\leftmargin\leftmarginii\labelwidth\leftmarginii% + \advance\labelwidth-\labelsep \topsep 2pt} +\def\@listiii{\leftmargin\leftmarginiii\labelwidth\leftmarginiii% + \advance\labelwidth-\labelsep \topsep 2pt} +\def\@listiv{\leftmargin\leftmarginiv\labelwidth\leftmarginiv% + \advance\labelwidth-\labelsep \topsep 2pt} +\def\@listv{\leftmargin\leftmarginv\labelwidth\leftmarginv% + \advance\labelwidth-\labelsep \topsep 2pt} +\def\@listvi{\leftmargin\leftmarginvi\labelwidth\leftmarginvi% + \advance\labelwidth-\labelsep \topsep 2pt} + + +% The IEEE uses 5) not 5. +\def\labelenumi{\theenumi)} \def\theenumi{\arabic{enumi}} + +% The IEEE uses a) not (a) +\def\labelenumii{\theenumii)} \def\theenumii{\alph{enumii}} + +% The IEEE uses iii) not iii. +\def\labelenumiii{\theenumiii)} \def\theenumiii{\roman{enumiii}} + +% The IEEE uses A) not A. +\def\labelenumiv{\theenumiv)} \def\theenumiv{\Alph{enumiv}} + +% exactly the same as in article.cls +\def\p@enumii{\theenumi} +\def\p@enumiii{\theenumi(\theenumii)} +\def\p@enumiv{\p@enumiii\theenumiii} + +% itemized list label styles +\def\labelitemi{$\scriptstyle\bullet$} +\def\labelitemii{\textbf{--}} +\def\labelitemiii{$\ast$} +\def\labelitemiv{$\cdot$} + + + +% **** V1.3 ENHANCEMENTS **** +% Itemize, Enumerate and Description (IED) List Controls +% *************************** +% +% +% The IEEE seems to use at least two different values by +% which ITEMIZED list labels are indented to the right +% For The Journal of Lightwave Technology (JLT) and The Journal +% on Selected Areas in Communications (JSAC), they tend to use +% an indention equal to \parindent. For Transactions on Communications +% they tend to indent ITEMIZED lists a little more--- 1.3\parindent. +% We'll provide both values here for you so that you can choose +% which one you like in your document using a command such as: +% setlength{\IEEEilabelindent}{\IEEEilabelindentB} +\newdimen\IEEEilabelindentA +\IEEEilabelindentA \parindent + +\newdimen\IEEEilabelindentB +\IEEEilabelindentB 1.3\parindent +% However, we'll default to using \parindent +% which makes more sense to me +\newdimen\IEEEilabelindent +\IEEEilabelindent \IEEEilabelindentA + + +% This controls the default amount the enumerated list labels +% are indented to the right. +% Normally, this is the same as the paragraph indention +\newdimen\IEEEelabelindent +\IEEEelabelindent \parindent + +% This controls the default amount the description list labels +% are indented to the right. +% Normally, this is the same as the paragraph indention +\newdimen\IEEEdlabelindent +\IEEEdlabelindent \parindent + +% This is the value actually used within the IED lists. +% The IED environments automatically set its value to +% one of the three values above, so global changes do +% not have any effect +\newdimen\IEEElabelindent +\IEEElabelindent \parindent + +% The actual amount labels will be indented is +% \IEEElabelindent multiplied by the factor below +% corresponding to the level of nesting depth +% This provides a means by which the user can +% alter the effective \IEEElabelindent for deeper +% levels +% There may not be such a thing as correct "standard IEEE" +% values. What the IEEE actually does may depend on the specific +% circumstances. +% The first list level almost always has full indention. +% The second levels I've seen have only 75% of the normal indentation +% Three level or greater nestings are very rare. I am guessing +% that they don't use any indentation. +\def\IEEElabelindentfactori{1.0} % almost always one +\def\IEEElabelindentfactorii{0.75} % 0.0 or 1.0 may be used in some cases +\def\IEEElabelindentfactoriii{0.0} % 0.75? 0.5? 0.0? +\def\IEEElabelindentfactoriv{0.0} +\def\IEEElabelindentfactorv{0.0} +\def\IEEElabelindentfactorvi{0.0} + +% value actually used within IED lists, it is auto +% set to one of the 6 values above +% global changes here have no effect +\def\IEEElabelindentfactor{1.0} + +% This controls the default spacing between the end of the IED +% list labels and the list text, when normal text is used for +% the labels. +% compsoc uses a larger value here, but we'll set that later +% in the class so that this code block area can be extracted +% as-is for IEEEtrantools.sty +\newdimen\IEEEiednormlabelsep +\IEEEiednormlabelsep 0.6em + +% This controls the default spacing between the end of the IED +% list labels and the list text, when math symbols are used for +% the labels (nomenclature lists). The IEEE usually increases the +% spacing in these cases +\newdimen\IEEEiedmathlabelsep +\IEEEiedmathlabelsep 1.2em + +% This controls the extra vertical separation put above and +% below each IED list. the IEEE usually puts a little extra spacing +% around each list. However, this spacing is barely noticeable. +% compsoc uses a larger value here, but we'll set that later +% in the class so that this code block area can be extracted +% as-is for IEEEtrantools.sty +\newskip\IEEEiedtopsep +\IEEEiedtopsep 2pt plus 1pt minus 1pt + + +% This command is executed within each IED list environment +% at the beginning of the list. You can use this to set the +% parameters for some/all your IED list(s) without disturbing +% global parameters that affect things other than lists. +% i.e., renewcommand{\IEEEiedlistdecl}{\setlength{\labelsep}{5em}} +% will alter the \labelsep for the next list(s) until +% \IEEEiedlistdecl is redefined. +\def\IEEEiedlistdecl{\relax} + +% This command provides an easy way to set \leftmargin based +% on the \labelwidth, \labelsep and the argument \IEEElabelindent +% Usage: \IEEEcalcleftmargin{width-to-indent-the-label} +% output is in the \leftmargin variable, i.e., effectively: +% \leftmargin = argument + \labelwidth + \labelsep +% Note controlled spacing here, shield end of lines with % +\def\IEEEcalcleftmargin#1{\setlength{\leftmargin}{#1}% +\addtolength{\leftmargin}{\labelwidth}% +\addtolength{\leftmargin}{\labelsep}} + +% This command provides an easy way to set \labelwidth to the +% width of the given text. It is the same as +% \settowidth{\labelwidth}{label-text} +% and useful as a shorter alternative. +% Typically used to set \labelwidth to be the width +% of the longest label in the list +\def\IEEEsetlabelwidth#1{\settowidth{\labelwidth}{#1}} + +% When this command is executed, IED lists will use the +% IEEEiedmathlabelsep label separation rather than the normal +% spacing. To have an effect, this command must be executed via +% the \IEEEiedlistdecl or within the option of the IED list +% environments. +\def\IEEEusemathlabelsep{\setlength{\labelsep}{\IEEEiedmathlabelsep}} + +% A flag which controls whether the IED lists automatically +% calculate \leftmargin from \IEEElabelindent, \labelwidth and \labelsep +% Useful if you want to specify your own \leftmargin +% This flag must be set (\IEEEnocalcleftmargintrue or \IEEEnocalcleftmarginfalse) +% via the \IEEEiedlistdecl or within the option of the IED list +% environments to have an effect. +\newif\ifIEEEnocalcleftmargin +\IEEEnocalcleftmarginfalse + +% A flag which controls whether \IEEElabelindent is multiplied by +% the \IEEElabelindentfactor for each list level. +% This flag must be set via the \IEEEiedlistdecl or within the option +% of the IED list environments to have an effect. +\newif\ifIEEEnolabelindentfactor +\IEEEnolabelindentfactorfalse + + +% internal variable to indicate type of IED label +% justification +% 0 - left; 1 - center; 2 - right +\def\@IEEEiedjustify{0} + + +% commands to allow the user to control IED +% label justifications. Use these commands within +% the IED environment option or in the \IEEEiedlistdecl +% Note that changing the normal list justifications +% is nonstandard and the IEEE may not like it if you do so! +% I include these commands as they may be helpful to +% those who are using these enhanced list controls for +% other non-IEEE related LaTeX work. +% itemize and enumerate automatically default to right +% justification, description defaults to left. +\def\IEEEiedlabeljustifyl{\def\@IEEEiedjustify{0}}%left +\def\IEEEiedlabeljustifyc{\def\@IEEEiedjustify{1}}%center +\def\IEEEiedlabeljustifyr{\def\@IEEEiedjustify{2}}%right + + + + +% commands to save to and restore from the list parameter copies +% this allows us to set all the list parameters within +% the list_decl and prevent \list (and its \@list) +% from overriding any of our parameters +% V1.6 use \edefs instead of dimen's to conserve dimen registers +% Note controlled spacing here, shield end of lines with % +\def\@IEEEsavelistparams{\edef\@IEEEiedtopsep{\the\topsep}% +\edef\@IEEEiedlabelwidth{\the\labelwidth}% +\edef\@IEEEiedlabelsep{\the\labelsep}% +\edef\@IEEEiedleftmargin{\the\leftmargin}% +\edef\@IEEEiedpartopsep{\the\partopsep}% +\edef\@IEEEiedparsep{\the\parsep}% +\edef\@IEEEieditemsep{\the\itemsep}% +\edef\@IEEEiedrightmargin{\the\rightmargin}% +\edef\@IEEEiedlistparindent{\the\listparindent}% +\edef\@IEEEieditemindent{\the\itemindent}} + +% Note controlled spacing here +\def\@IEEErestorelistparams{\topsep\@IEEEiedtopsep\relax% +\labelwidth\@IEEEiedlabelwidth\relax% +\labelsep\@IEEEiedlabelsep\relax% +\leftmargin\@IEEEiedleftmargin\relax% +\partopsep\@IEEEiedpartopsep\relax% +\parsep\@IEEEiedparsep\relax% +\itemsep\@IEEEieditemsep\relax% +\rightmargin\@IEEEiedrightmargin\relax% +\listparindent\@IEEEiedlistparindent\relax% +\itemindent\@IEEEieditemindent\relax} + + +% v1.6b provide original LaTeX IED list environments +% note that latex.ltx defines \itemize and \enumerate, but not \description +% which must be created by the base classes +% save original LaTeX itemize and enumerate +\let\LaTeXitemize\itemize +\let\endLaTeXitemize\enditemize +\let\LaTeXenumerate\enumerate +\let\endLaTeXenumerate\endenumerate + +% provide original LaTeX description environment from article.cls +\newenvironment{LaTeXdescription} + {\list{}{\labelwidth\z@ \itemindent-\leftmargin + \let\makelabel\descriptionlabel}} + {\endlist} +\newcommand*\descriptionlabel[1]{\hspace\labelsep + \normalfont\bfseries #1} + + +% override LaTeX's default IED lists +\def\itemize{\@IEEEitemize} +\def\enditemize{\@endIEEEitemize} +\def\enumerate{\@IEEEenumerate} +\def\endenumerate{\@endIEEEenumerate} +\def\description{\@IEEEdescription} +\def\enddescription{\@endIEEEdescription} + +% provide the user with aliases - may help those using packages that +% override itemize, enumerate, or description +\def\IEEEitemize{\@IEEEitemize} +\def\endIEEEitemize{\@endIEEEitemize} +\def\IEEEenumerate{\@IEEEenumerate} +\def\endIEEEenumerate{\@endIEEEenumerate} +\def\IEEEdescription{\@IEEEdescription} +\def\endIEEEdescription{\@endIEEEdescription} + + +% V1.6 we want to keep the IEEEtran IED list definitions as our own internal +% commands so they are protected against redefinition +\def\@IEEEitemize{\@ifnextchar[{\@@IEEEitemize}{\@@IEEEitemize[\relax]}} +\def\@IEEEenumerate{\@ifnextchar[{\@@IEEEenumerate}{\@@IEEEenumerate[\relax]}} +\def\@IEEEdescription{\@ifnextchar[{\@@IEEEdescription}{\@@IEEEdescription[\relax]}} +\def\@endIEEEitemize{\endlist} +\def\@endIEEEenumerate{\endlist} +\def\@endIEEEdescription{\endlist} + + +% DO NOT ALLOW BLANK LINES TO BE IN THESE IED ENVIRONMENTS +% AS THIS WILL FORCE NEW PARAGRAPHS AFTER THE IED LISTS +% IEEEtran itemized list MDS 1/2001 +% Note controlled spacing here, shield end of lines with % +\def\@@IEEEitemize[#1]{% + \ifnum\@itemdepth>3\relax\@toodeep\else% + \ifnum\@listdepth>5\relax\@toodeep\else% + \advance\@itemdepth\@ne% + \edef\@itemitem{labelitem\romannumeral\the\@itemdepth}% + % get the IEEElabelindentfactor for this level + \advance\@listdepth\@ne% we need to know what the level WILL be + \edef\IEEElabelindentfactor{\csname IEEElabelindentfactor\romannumeral\the\@listdepth\endcsname}% + \advance\@listdepth-\@ne% undo our increment + \def\@IEEEiedjustify{2}% right justified labels are default + % set other defaults + \IEEEnocalcleftmarginfalse% + \IEEEnolabelindentfactorfalse% + \topsep\IEEEiedtopsep% + \IEEElabelindent\IEEEilabelindent% + \labelsep\IEEEiednormlabelsep% + \partopsep 0ex% + \parsep 0ex% + \itemsep 0ex% + \rightmargin 0em% + \listparindent 0em% + \itemindent 0em% + % calculate the label width + % the user can override this later if + % they specified a \labelwidth + \settowidth{\labelwidth}{\csname labelitem\romannumeral\the\@itemdepth\endcsname}% + \@IEEEsavelistparams% save our list parameters + \list{\csname\@itemitem\endcsname}{% + \@IEEErestorelistparams% override any list{} changes + % to our globals + \let\makelabel\@IEEEiedmakelabel% v1.6b setup \makelabel + \IEEEiedlistdecl% let user alter parameters + #1\relax% + % If the user has requested not to use the + % IEEElabelindent factor, don't revise \IEEElabelindent + \ifIEEEnolabelindentfactor\relax% + \else\IEEElabelindent=\IEEElabelindentfactor\IEEElabelindent% + \fi% + % Unless the user has requested otherwise, + % calculate our left margin based + % on \IEEElabelindent, \labelwidth and + % \labelsep + \ifIEEEnocalcleftmargin\relax% + \else\IEEEcalcleftmargin{\IEEElabelindent}% + \fi}\fi\fi}% + + +% DO NOT ALLOW BLANK LINES TO BE IN THESE IED ENVIRONMENTS +% AS THIS WILL FORCE NEW PARAGRAPHS AFTER THE IED LISTS +% IEEEtran enumerate list MDS 1/2001 +% Note controlled spacing here, shield end of lines with % +\def\@@IEEEenumerate[#1]{% + \ifnum\@enumdepth>3\relax\@toodeep\else% + \ifnum\@listdepth>5\relax\@toodeep\else% + \advance\@enumdepth\@ne% + \edef\@enumctr{enum\romannumeral\the\@enumdepth}% + % get the IEEElabelindentfactor for this level + \advance\@listdepth\@ne% we need to know what the level WILL be + \edef\IEEElabelindentfactor{\csname IEEElabelindentfactor\romannumeral\the\@listdepth\endcsname}% + \advance\@listdepth-\@ne% undo our increment + \def\@IEEEiedjustify{2}% right justified labels are default + % set other defaults + \IEEEnocalcleftmarginfalse% + \IEEEnolabelindentfactorfalse% + \topsep\IEEEiedtopsep% + \IEEElabelindent\IEEEelabelindent% + \labelsep\IEEEiednormlabelsep% + \partopsep 0ex% + \parsep 0ex% + \itemsep 0ex% + \rightmargin 0em% + \listparindent 0em% + \itemindent 0em% + % calculate the label width + % We'll set it to the width suitable for all labels using + % normalfont 1) to 9) + % The user can override this later + \settowidth{\labelwidth}{9)}% + \@IEEEsavelistparams% save our list parameters + \list{\csname label\@enumctr\endcsname}{\usecounter{\@enumctr}% + \@IEEErestorelistparams% override any list{} changes + % to our globals + \let\makelabel\@IEEEiedmakelabel% v1.6b setup \makelabel + \IEEEiedlistdecl% let user alter parameters + #1\relax% + % If the user has requested not to use the + % IEEElabelindent factor, don't revise \IEEElabelindent + \ifIEEEnolabelindentfactor\relax% + \else\IEEElabelindent=\IEEElabelindentfactor\IEEElabelindent% + \fi% + % Unless the user has requested otherwise, + % calculate our left margin based + % on \IEEElabelindent, \labelwidth and + % \labelsep + \ifIEEEnocalcleftmargin\relax% + \else\IEEEcalcleftmargin{\IEEElabelindent}% + \fi}\fi\fi}% + + +% DO NOT ALLOW BLANK LINES TO BE IN THESE IED ENVIRONMENTS +% AS THIS WILL FORCE NEW PARAGRAPHS AFTER THE IED LISTS +% IEEEtran description list MDS 1/2001 +% Note controlled spacing here, shield end of lines with % +\def\@@IEEEdescription[#1]{% + \ifnum\@listdepth>5\relax\@toodeep\else% + % get the IEEElabelindentfactor for this level + \advance\@listdepth\@ne% we need to know what the level WILL be + \edef\IEEElabelindentfactor{\csname IEEElabelindentfactor\romannumeral\the\@listdepth\endcsname}% + \advance\@listdepth-\@ne% undo our increment + \def\@IEEEiedjustify{0}% left justified labels are default + % set other defaults + \IEEEnocalcleftmarginfalse% + \IEEEnolabelindentfactorfalse% + \topsep\IEEEiedtopsep% + \IEEElabelindent\IEEEdlabelindent% + % assume normal labelsep + \labelsep\IEEEiednormlabelsep% + \partopsep 0ex% + \parsep 0ex% + \itemsep 0ex% + \rightmargin 0em% + \listparindent 0em% + \itemindent 0em% + % Bogus label width in case the user forgets + % to set it. + % TIP: If you want to see what a variable's width is you + % can use the TeX command \showthe\width-variable to + % display it on the screen during compilation + % (This might be helpful to know when you need to find out + % which label is the widest) + \settowidth{\labelwidth}{Hello}% + \@IEEEsavelistparams% save our list parameters + \list{}{\@IEEErestorelistparams% override any list{} changes + % to our globals + \let\makelabel\@IEEEiedmakelabel% v1.6b setup \makelabel + \IEEEiedlistdecl% let user alter parameters + #1\relax% + % If the user has requested not to use the + % labelindent factor, don't revise \IEEElabelindent + \ifIEEEnolabelindentfactor\relax% + \else\IEEElabelindent=\IEEElabelindentfactor\IEEElabelindent% + \fi% + % Unless the user has requested otherwise, + % calculate our left margin based + % on \IEEElabelindent, \labelwidth and + % \labelsep + \ifIEEEnocalcleftmargin\relax% + \else\IEEEcalcleftmargin{\IEEElabelindent}\relax% + \fi}\fi} + +% v1.6b we use one makelabel that does justification as needed. +\def\@IEEEiedmakelabel#1{\relax\if\@IEEEiedjustify 0\relax +\makebox[\labelwidth][l]{\normalfont #1}\else +\if\@IEEEiedjustify 1\relax +\makebox[\labelwidth][c]{\normalfont #1}\else +\makebox[\labelwidth][r]{\normalfont #1}\fi\fi} + + +% compsoc uses a larger value for the normal labelsep +% and also extra spacing above and below each list +\ifCLASSOPTIONcompsoc + \IEEEiednormlabelsep 1.2em + \IEEEiedtopsep 6pt plus 3pt minus 3pt +\fi + + +% VERSE and QUOTE +% V1.7 define environments with newenvironment +\newenvironment{verse}{\let\\=\@centercr + \list{}{\itemsep\z@ \itemindent -1.5em \listparindent \itemindent + \rightmargin\leftmargin\advance\leftmargin 1.5em}\item\relax} + {\endlist} +\newenvironment{quotation}{\list{}{\listparindent 1.5em \itemindent\listparindent + \rightmargin\leftmargin \parsep 0pt plus 1pt}\item\relax} + {\endlist} +\newenvironment{quote}{\list{}{\rightmargin\leftmargin}\item\relax} + {\endlist} + + +% \titlepage +% provided only for backward compatibility. \maketitle is the correct +% way to create the title page. +\def\titlepage{\@restonecolfalse\if@twocolumn\@restonecoltrue\onecolumn + \else \newpage \fi \thispagestyle{empty}\c@page\z@} +\def\endtitlepage{\if@restonecol\twocolumn \else \newpage \fi} + +% standard values from article.cls +\arraycolsep 5pt +\arrayrulewidth .4pt +\doublerulesep 2pt + +\tabcolsep 6pt +\tabbingsep 0.5em + + +%% FOOTNOTES +% +%\skip\footins 10pt plus 4pt minus 2pt +% V1.6 respond to changes in font size +% space added above the footnotes (if present) +\skip\footins 0.9\baselineskip plus 0.4\baselineskip minus 0.2\baselineskip + +% V1.6, we need to make \footnotesep responsive to changes +% in \baselineskip or strange spacings will result when in +% draft mode. Here is a little LaTeX secret - \footnotesep +% determines the height of an invisible strut that is placed +% *above* the baseline of footnotes after the first. Since +% LaTeX considers the space for characters to be 0.7\baselineskip +% above the baseline and 0.3\baselineskip below it, we need to +% use 0.7\baselineskip as a \footnotesep to maintain equal spacing +% between all the lines of the footnotes. The IEEE often uses a tad +% more, so use 0.8\baselineskip. This slightly larger value also helps +% the text to clear the footnote marks. Note that \thanks in IEEEtran +% uses its own value of \footnotesep which is set in \maketitle. +{\footnotesize +\global\footnotesep 0.8\baselineskip} + + +\skip\@mpfootins = \skip\footins +\fboxsep = 3pt +\fboxrule = .4pt +% V1.6 use 1em, then use LaTeX2e's \@makefnmark +% Note that the IEEE normally *left* aligns the footnote marks, so we don't need +% box resizing tricks here. +\long\def\@makefntext#1{\parindent 1em\indent\hbox{\@makefnmark}#1}% V1.6 use 1em +% V1.7 compsoc does not use superscipts for footnote marks +\ifCLASSOPTIONcompsoc +\def\@IEEEcompsocmakefnmark{\hbox{\normalfont\@thefnmark.\ }} +\long\def\@makefntext#1{\parindent 1em\indent\hbox{\@IEEEcompsocmakefnmark}#1} +\fi + +% The IEEE does not use footnote rules +\def\footnoterule{} + +% V1.7 for compsoc, the IEEE uses a footnote rule only for \thanks. We devise a "one-shot" +% system to implement this. +\newif\if@IEEEenableoneshotfootnoterule +\@IEEEenableoneshotfootnoterulefalse +\ifCLASSOPTIONcompsoc +\def\footnoterule{\relax\if@IEEEenableoneshotfootnoterule +\kern-5pt +\hbox to \columnwidth{\hfill\vrule width 0.5\columnwidth height 0.4pt\hfill} +\kern4.6pt +\global\@IEEEenableoneshotfootnoterulefalse +\else +\relax +\fi} +\fi + +% V1.6 do not allow LaTeX to break a footnote across multiple pages +\interfootnotelinepenalty=10000 + +% V1.6 discourage breaks within equations +% Note that amsmath normally sets this to 10000, +% but LaTeX2e normally uses 100. +\interdisplaylinepenalty=2500 + +% default allows section depth up to /paragraph +\setcounter{secnumdepth}{4} + +% technotes do not allow /paragraph +\ifCLASSOPTIONtechnote + \setcounter{secnumdepth}{3} +\fi +% neither do compsoc conferences +\@IEEEcompsocconfonly{\setcounter{secnumdepth}{3}} + + +\newcounter{section} +\newcounter{subsection}[section] +\newcounter{subsubsection}[subsection] +\newcounter{paragraph}[subsubsection] + +% used only by IEEEtran's IEEEeqnarray as other packages may +% have their own, different, implementations +\newcounter{IEEEsubequation}[equation] + +% as shown when called by user from \ref, \label and in table of contents +\def\theequation{\arabic{equation}} % 1 +\def\theIEEEsubequation{\theequation\alph{IEEEsubequation}} % 1a (used only by IEEEtran's IEEEeqnarray) +\ifCLASSOPTIONcompsoc +% compsoc is all arabic +\def\thesection{\arabic{section}} +\def\thesubsection{\thesection.\arabic{subsection}} +\def\thesubsubsection{\thesubsection.\arabic{subsubsection}} +\def\theparagraph{\thesubsubsection.\arabic{paragraph}} +\else +\def\thesection{\Roman{section}} % I +% V1.7, \mbox prevents breaks around - +\def\thesubsection{\mbox{\thesection-\Alph{subsection}}} % I-A +% V1.7 use I-A1 format used by the IEEE rather than I-A.1 +\def\thesubsubsection{\thesubsection\arabic{subsubsection}} % I-A1 +\def\theparagraph{\thesubsubsection\alph{paragraph}} % I-A1a +\fi + +% From Heiko Oberdiek. Because of the \mbox in \thesubsection, we need to +% tell hyperref to disable the \mbox command when making PDF bookmarks. +% This done already with hyperref.sty version 6.74o and later, but +% it will not hurt to do it here again for users of older versions. +\@ifundefined{pdfstringdefPreHook}{\let\pdfstringdefPreHook\@empty}{}% +\g@addto@macro\pdfstringdefPreHook{\let\mbox\relax} + + +% Main text forms (how shown in main text headings) +% V1.6, using \thesection in \thesectiondis allows changes +% in the former to automatically appear in the latter +\ifCLASSOPTIONcompsoc + \ifCLASSOPTIONconference% compsoc conference + \def\thesectiondis{\thesection.} + \def\thesubsectiondis{\thesectiondis\arabic{subsection}.} + \def\thesubsubsectiondis{\thesubsectiondis\arabic{subsubsection}.} + \def\theparagraphdis{\thesubsubsectiondis\arabic{paragraph}.} + \else% compsoc not conferencs + \def\thesectiondis{\thesection} + \def\thesubsectiondis{\thesectiondis.\arabic{subsection}} + \def\thesubsubsectiondis{\thesubsectiondis.\arabic{subsubsection}} + \def\theparagraphdis{\thesubsubsectiondis.\arabic{paragraph}} + \fi +\else% not compsoc + \def\thesectiondis{\thesection.} % I. + \def\thesubsectiondis{\Alph{subsection}.} % B. + \def\thesubsubsectiondis{\arabic{subsubsection})} % 3) + \def\theparagraphdis{\alph{paragraph})} % d) +\fi + +% just like LaTeX2e's \@eqnnum +\def\theequationdis{{\normalfont \normalcolor (\theequation)}}% (1) +% IEEEsubequation used only by IEEEtran's IEEEeqnarray +\def\theIEEEsubequationdis{{\normalfont \normalcolor (\theIEEEsubequation)}}% (1a) +% redirect LaTeX2e's equation number display and all that depend on +% it, through IEEEtran's \theequationdis +\def\@eqnnum{\theequationdis} + + + +% V1.7 provide string macros as article.cls does +\def\contentsname{Contents} +\def\listfigurename{List of Figures} +\def\listtablename{List of Tables} +\def\refname{References} +\def\indexname{Index} +\def\figurename{Fig.} +\def\tablename{TABLE} +\@IEEEcompsocconfonly{\def\figurename{Figure}} +\def\partname{Part} +\def\appendixname{Appendix} +\def\abstractname{Abstract} +% IEEE specific names +\def\IEEEkeywordsname{Index Terms} +\def\IEEEproofname{Proof} + + +% LIST OF FIGURES AND TABLES AND TABLE OF CONTENTS +% +\def\@pnumwidth{1.55em} +\def\@tocrmarg{2.55em} +\def\@dotsep{4.5} +\setcounter{tocdepth}{3} + +% adjusted some spacings here so that section numbers will not easily +% collide with the section titles. +% VIII; VIII-A; and VIII-A.1 are usually the worst offenders. +% MDS 1/2001 +\def\tableofcontents{\section*{\contentsname}\@starttoc{toc}} +\def\l@section#1#2{\addpenalty{\@secpenalty}\addvspace{1.0em plus 1pt}% + \@tempdima 2.75em \begingroup \parindent \z@ \rightskip \@pnumwidth% + \parfillskip-\@pnumwidth {\bfseries\leavevmode #1}\hfil\hbox to\@pnumwidth{\hss #2}\par% + \endgroup} +% argument format #1:level, #2:labelindent,#3:labelsep +\def\l@subsection{\@dottedtocline{2}{2.75em}{3.75em}} +\def\l@subsubsection{\@dottedtocline{3}{6.5em}{4.5em}} +% must provide \l@ defs for ALL sublevels EVEN if tocdepth +% is such as they will not appear in the table of contents +% these defs are how TOC knows what level these things are! +\def\l@paragraph{\@dottedtocline{4}{6.5em}{5.5em}} +\def\l@subparagraph{\@dottedtocline{5}{6.5em}{6.5em}} +\def\listoffigures{\section*{\listfigurename}\@starttoc{lof}} +\def\l@figure{\@dottedtocline{1}{0em}{2.75em}} +\def\listoftables{\section*{\listtablename}\@starttoc{lot}} +\let\l@table\l@figure + + +% Definitions for floats +% +% Normal Floats +% V1.8 floatsep et al. revised down by 0.15\baselineskip +% to account for the sideeffects of \topskip compensation +\floatsep 0.85\baselineskip plus 0.2\baselineskip minus 0.2\baselineskip +\textfloatsep 1.55\baselineskip plus 0.2\baselineskip minus 0.4\baselineskip +\@fptop 0pt plus 1fil +\@fpsep 0.75\baselineskip plus 2fil +\@fpbot 0pt plus 1fil +\def\topfraction{0.9} +\def\bottomfraction{0.4} +\def\floatpagefraction{0.8} +% V1.7, let top floats approach 90% of page +\def\textfraction{0.1} + +% Double Column Floats +\dblfloatsep 0.85\baselineskip plus 0.2\baselineskip minus 0.2\baselineskip + +\dbltextfloatsep 1.55\baselineskip plus 0.2\baselineskip minus 0.4\baselineskip +% Note that it would be nice if the rubber here actually worked in LaTeX2e. +% There is a long standing limitation in LaTeX, first discovered (to the best +% of my knowledge) by Alan Jeffrey in 1992. LaTeX ignores the stretchable +% portion of \dbltextfloatsep, and as a result, double column figures can and +% do result in an non-integer number of lines in the main text columns with +% underfull vbox errors as a consequence. A post to comp.text.tex +% by Donald Arseneau confirms that this had not yet been fixed in 1998. +% IEEEtran V1.6 will fix this problem for you in the titles, but it doesn't +% protect you from other double floats. Happy vspace'ing. + +\@dblfptop 0pt plus 1fil +\@dblfpsep 0.75\baselineskip plus 2fil +\@dblfpbot 0pt plus 1fil +\def\dbltopfraction{0.8} +\def\dblfloatpagefraction{0.8} +\setcounter{dbltopnumber}{4} + +\intextsep 0.85\baselineskip plus 0.2\baselineskip minus 0.2\baselineskip +\setcounter{topnumber}{2} +\setcounter{bottomnumber}{2} +\setcounter{totalnumber}{4} + + + +% article class provides these, we should too. +\newlength\abovecaptionskip +\newlength\belowcaptionskip +% but only \abovecaptionskip is used above figure captions and *below* table +% captions +\setlength\abovecaptionskip{0.5\baselineskip} +% compsoc journals are a little more generous +\ifCLASSOPTIONcompsoc\ifCLASSOPTIONjournal + \setlength\abovecaptionskip{0.75\baselineskip} +\fi\fi +\setlength\belowcaptionskip{0pt} +% V1.6 create hooks in case the caption spacing ever needs to be +% overridden by a user +\def\@IEEEfigurecaptionsepspace{\vskip\abovecaptionskip\relax}% +\def\@IEEEtablecaptionsepspace{\vskip\abovecaptionskip\relax}% + + +% 1.6b revise caption system so that \@makecaption uses two arguments +% as with LaTeX2e. Otherwise, there will be problems when using hyperref. +\def\@IEEEtablestring{table} + + +% V1.8 compensate for \topskip so top of top figures align with tops of the first lines of main text +% here we calculate a space equal to the amount \topskip exceeds the main text height +% we hook in at \@floatboxreset +\def\@IEEEfiguretopskipspace{\ifdim\prevdepth=-1000pt\relax +\setlength{\@IEEEtrantmpdimenA}{1\topskip}\relax +\addtolength{\@IEEEtrantmpdimenA}{-0.7\@IEEEnormalsizeunitybaselineskip}\relax +\vspace*{\@IEEEtrantmpdimenA}\fi} +% V1.8 compensate for \topskip at the top of top tables so caption text is on main text baseline +% use a strut set on the caption baseline within \@makecaption +\def\@IEEEtabletopskipstrut{\ifdim\prevdepth=-1000pt\rule{0pt}{\topskip}\fi} +% the \ifdim\prevdepth checks are always expected to be true for IEEE style float caption ordering +% because top of figure content and top of captions in tables is the first thing on the vertical +% list of these floats +% thanks to Donald Arseneau for his 2000/11/11 post "Re: caption hacking" with info on this topic. + + +\ifCLASSOPTIONcompsoc +% V1.7 compsoc \@makecaption +\ifCLASSOPTIONconference% compsoc conference +\long\def\@makecaption#1#2{% +% test if is a for a figure or table +\ifx\@captype\@IEEEtablestring% +% if a table, do table caption +\footnotesize\bgroup\par\centering\@IEEEtabletopskipstrut{\normalfont\footnotesize {#1.}\nobreakspace\scshape #2}\par\addvspace{0.5\baselineskip}\egroup% +\@IEEEtablecaptionsepspace +% if not a table, format it as a figure +\else +\@IEEEfigurecaptionsepspace +\setbox\@tempboxa\hbox{\normalfont\footnotesize {#1.}\nobreakspace #2}% +\ifdim \wd\@tempboxa >\hsize% +% if caption is longer than a line, let it wrap around +\setbox\@tempboxa\hbox{\normalfont\footnotesize {#1.}\nobreakspace}% +\parbox[t]{\hsize}{\normalfont\footnotesize \noindent\unhbox\@tempboxa#2}% +% if caption is shorter than a line, center +\else% +\hbox to\hsize{\normalfont\footnotesize\hfil\box\@tempboxa\hfil}% +\fi\fi} +% +\else% nonconference compsoc +\long\def\@makecaption#1#2{% +% test if is a for a figure or table +\ifx\@captype\@IEEEtablestring% +% if a table, do table caption +\footnotesize\bgroup\par\centering\@IEEEtabletopskipstrut{\normalfont\sffamily\footnotesize #1}\\{\normalfont\sffamily\footnotesize #2}\par\addvspace{0.5\baselineskip}\egroup% +\@IEEEtablecaptionsepspace +% if not a table, format it as a figure +\else +\@IEEEfigurecaptionsepspace +\setbox\@tempboxa\hbox{\normalfont\sffamily\footnotesize {#1.}\nobreakspace #2}% +\ifdim \wd\@tempboxa >\hsize% +% if caption is longer than a line, let it wrap around +\setbox\@tempboxa\hbox{\normalfont\sffamily\footnotesize {#1.}\nobreakspace}% +\parbox[t]{\hsize}{\normalfont\sffamily\footnotesize \noindent\unhbox\@tempboxa#2}% +% if caption is shorter than a line, left justify +\else% +\hbox to\hsize{\normalfont\sffamily\footnotesize\box\@tempboxa\hfil}% +\fi\fi} +\fi +% +\else% traditional noncompsoc \@makecaption +\long\def\@makecaption#1#2{% +% test if is a for a figure or table +\ifx\@captype\@IEEEtablestring% +% if a table, do table caption +\footnotesize\bgroup\par\centering\@IEEEtabletopskipstrut{\normalfont\footnotesize #1}\\{\normalfont\footnotesize\scshape #2}\par\addvspace{0.5\baselineskip}\egroup% +\@IEEEtablecaptionsepspace +% if not a table, format it as a figure +\else +\@IEEEfigurecaptionsepspace +% 3/2001 use footnotesize, not small; use two nonbreaking spaces, not one +\setbox\@tempboxa\hbox{\normalfont\footnotesize {#1.}\nobreakspace\nobreakspace #2}% +\ifdim \wd\@tempboxa >\hsize% +% if caption is longer than a line, let it wrap around +\setbox\@tempboxa\hbox{\normalfont\footnotesize {#1.}\nobreakspace\nobreakspace}% +\parbox[t]{\hsize}{\normalfont\footnotesize\noindent\unhbox\@tempboxa#2}% +% if caption is shorter than a line, center if conference, left justify otherwise +\else% +\ifCLASSOPTIONconference \hbox to\hsize{\normalfont\footnotesize\hfil\box\@tempboxa\hfil}% +\else \hbox to\hsize{\normalfont\footnotesize\box\@tempboxa\hfil}% +\fi\fi\fi} +\fi + + + +% V1.7 disable captions class option, do so in a way that retains operation of \label +% within \caption +\ifCLASSOPTIONcaptionsoff +\long\def\@makecaption#1#2{\vspace*{2em}\footnotesize\bgroup\par\addvspace{0.5\baselineskip}\centering{\footnotesize #1}\par\addvspace{0.5\baselineskip}\egroup% +\let\@IEEEtemporiglabeldefsave\label +\let\@IEEEtemplabelargsave\relax +\def\label##1{\gdef\@IEEEtemplabelargsave{##1}}% +\setbox\@tempboxa\hbox{#2}% +\let\label\@IEEEtemporiglabeldefsave +\ifx\@IEEEtemplabelargsave\relax\else\label{\@IEEEtemplabelargsave}\fi} +\fi + + +% V1.7 define end environments with \def not \let so as to work OK with +% preview-latex +\newcounter{figure} +\def\thefigure{\@arabic\c@figure} +\def\fps@figure{tbp} +\def\ftype@figure{1} +\def\ext@figure{lof} +\def\fnum@figure{\figurename\nobreakspace\thefigure} +% V1.8 within figures add \@IEEEfiguretopskipspace compensation to LaTeX2e's \@floatboxreset +\def\figure{\def\@floatboxreset{\reset@font\normalsize\@setminipage\@IEEEfiguretopskipspace}\@float{figure}} +\def\endfigure{\end@float} +% V1.8 also add \@IEEEfiguretopskipspace compensation to \figure* +\@namedef{figure*}{\def\@floatboxreset{\reset@font\normalsize\@setminipage\@IEEEfiguretopskipspace}\@dblfloat{figure}} +\@namedef{endfigure*}{\end@dblfloat} + +\newcounter{table} +\ifCLASSOPTIONcompsoc +\def\thetable{\arabic{table}} +\else +\def\thetable{\@Roman\c@table} +\fi +\def\fps@table{tbp} +\def\ftype@table{2} +\def\ext@table{lot} +\def\fnum@table{\tablename\nobreakspace\thetable} +% V1.6 The IEEE uses 8pt text for tables +% within tables alter LaTeX2e's \@floatboxreset to use \footnotesize +\def\table{\def\@floatboxreset{\reset@font\footnotesize\@setminipage}\@float{table}} +\def\endtable{\end@float} +% v1.6b double column tables need to default to footnotesize as well. +\@namedef{table*}{\def\@floatboxreset{\reset@font\footnotesize\@setminipage}\@dblfloat{table}} +\@namedef{endtable*}{\end@dblfloat} + + + + +%% -- Command Argument Scanning Support Functions -- +%% V1.8a + +% usage: \@IEEEstripouterbraces*{} +% \@IEEEstripouterbraces fully expands its argument (which it then stores +% in \@IEEEstripouterbracesarg) via \edef, then removes any outer enclosing +% braces, and finally stores the result in the macro +% \@IEEEstrippedouterbraces. +% +% For example: +% \@IEEEstripouterbraces{{{{ab}c}}} +% results in: +% +% \@IEEEstripouterbracesarg ==> a macro containing {{{ab}c}} +% \@IEEEstrippedouterbraces ==> a macro containing {ab}c +% +% the *-star form,\@IEEEstripouterbraces*, does not expand the argument +% contents during processing +\def\@IEEEstripouterbraces{\@ifstar{\let\@IEEEstripouterbracesdef=\def\@@IEEEstripouterbraces}{\let\@IEEEstripouterbracesdef=\edef\@@IEEEstripouterbraces}} + +\def\@@IEEEstripouterbraces#1{\@IEEEstripouterbracesdef\@IEEEstripouterbracesarg{#1}\relax +% If the macro is unchanged after being acquired as a single delimited +% argument, we know we have one sequence of tokens without any enclosing +% braces. Loop until this is true. +\loop + \expandafter\@@@IEEEstripouterbraces\@IEEEstripouterbracesarg\@IEEEgeneralsequenceDELIMITER +\ifx\@IEEEstrippedouterbraces\@IEEEstripouterbracesarg +\else + \let\@IEEEstripouterbracesarg\@IEEEstrippedouterbraces +\repeat} + +\def\@@@IEEEstripouterbraces#1\@IEEEgeneralsequenceDELIMITER{\def\@IEEEstrippedouterbraces{#1}} + + + +% usage: \@IEEEextractgroup*{} +% \@IEEEextractgroup fully expands its argument (which it then stores in +% \@IEEEextractgrouparg) via \edef and then assigns the first "brace group" +% of tokens to the macro \@IEEEextractedgroup. +% The remaining groups, if any, are stored in the macro +% \@IEEEextractedgroupremain. If the argument does not contain the requisite +% groups, the respective macros will be defined to be empty. +% There is an asymmetry in that \@IEEEextractedgroup is stripped of its first +% outer grouping while \@IEEEextractedgroupremain retains even the outer +% grouping (if present) that originally identified it as a group. +% +% For example: +% \@IEEEextractgroup{{{ab}}{c{de}}} +% results in: +% +% \@IEEEextractgrouparg ==> a macro containing {{ab}}{c{de}} +% \@IEEEextractedgroup ==> a macro containing {ab} +% \@IEEEextractedgroupremain ==> a macro containing {c{de}} +% +% The *-star form, \@IEEEextractgroup*, does not expand its argument +% contents during processing. +\def\@IEEEextractgroup{\@ifstar{\let\@IEEEextractgroupdef=\def\@@IEEEextractgroup}{\let\@IEEEextractgroupdef=\edef\@@IEEEextractgroup}} + +\def\@@IEEEextractgroup#1{\@IEEEextractgroupdef\@IEEEextractgrouparg{#1}\relax +% trap the case of an empty extracted group as this would cause problems with +% \@IEEEextractgroupremain's argument acquisition +\ifx\@IEEEextractgrouparg\@empty + \def\@IEEEextractedgroup{}\relax + \def\@IEEEextractedgroupremain{}\relax +\else + % We have to use some dirty tricks here. We want to insert {} around + % whatever remains after the first group so that TeX's argument scanner + % will preserve any originally enclosing braces as well as provide an + % empty argument to acquire even if there isn't a second group. + % In this first of two dirty tricks, we put a } at the end of the structure + % we are going to extract from. The \ifnum0=`{\fi keeps TeX happy to allow + % what would otherwise be an unbalanced macro definition for + % \@@IEEEextractgroup to be acceptable to it. + \ifnum0=`{\fi\expandafter\@IEEEextractgroupremain\@IEEEextractgrouparg}\relax +\fi} + +% In the second part of the dirty tricks, we insert a leading { right after +% the first group is acquired, but before the remainder is. Again, the +% \ifnum0=`}\fi keeps TeX happy during definition time, but will disappear +% during run time. +\def\@IEEEextractgroupremain#1{\def\@IEEEextractedgroup{#1}\expandafter\@@IEEEextractgroupremain\expandafter{\ifnum0=`}\fi} + +\def\@@IEEEextractgroupremain#1{\def\@IEEEextractedgroupremain{#1}} + + + +% \@IEEEextracttoken relocated at top because margin setting commands rely on it + + + +% usage: \@IEEEextracttokengroups*{} +% \@IEEEextracttokengroups fully expands its argument (which it then stores +% in \@IEEEextracttokengroupsarg) and then assigns the first "brace group" of +% tokens (with the outermost braces removed) to the macro +% \@IEEEextractedfirstgroup. +% The meaning of the first nonbrace (but including the empty group) token +% within this first group is assigned via \let to \@IEEEextractedfirsttoken +% as well as stored in the macro \@IEEEextractedfirsttokenmacro. If a first +% nonbrace token does not exist (or is an empty group), these will be \relax +% and empty, respectively. Tokens that would otherwise be discarded during +% the acquisition of the first token in the first group are stored in +% \@IEEEextractedfirsttokensdiscarded, however their original relative brace +% nesting depths are not guaranteed to be preserved. +% The first group within this first group is stored in the macro +% \@IEEEextractedfirstfirstgroup. +% Likewise for the next group after the first: \@IEEEextractednextgroup, +% \@IEEEextractednextfirstgroup, \@IEEEextractednextgroupfirsttoken, +% \@IEEEextractednextgroupfirsttokenmacro, and +% \@IEEEextractednextfirsttokensdiscarded. +% All tokens/groups after the first group, including any enclosing braces, +% are stored in the macro \@IEEEextractedafterfirstgroupremain which will +% be empty if none exist. +% +% For example: +% \@IEEEextracttokengroups{{{ab}{cd}}{{ef}g}} +% will result in: +% +% \@IEEEextracttokengroupsarg ==> a macro containing {{ab}{cd}}{{ef}g} +% \@IEEEextractedfirstgroup ==> a macro containing {ab}{cd} +% \@IEEEextractedafterfirstgroupremain ==> a macro containing {{ef}g} +% \@IEEEextractedfirsttoken ==> the letter a +% \@IEEEextractedfirsttokenmacro ==> a macro containing a +% \@IEEEextractedfirsttokensdiscarded ==> a macro containing bcd +% \@IEEEextractedfirstfirstgroup ==> a macro containing ab +% \@IEEEextractednextgroup ==> a macro containing {ef}g +% \@IEEEextractednextfirsttoken ==> the letter e +% \@IEEEextractednextfirsttokenmacro ==> a macro containing e +% \@IEEEextractednextfirsttokensdiscarded ==> a macro containing fg +% \@IEEEextractednextfirstgroup ==> a macro containing ef +% +% If given an empty argument, \@IEEEextractedfirsttoken and +% \@IEEEextractednextfirsttoken will be set to \relax +% and all the macros will be empty. +% the *-star form, \@IEEEextracttokengroups*, does not expand its argument +% contents during processing. +% +% Depends on: \@IEEEextractgroup, \@IEEEextracttoken +\def\@IEEEextracttokengroups{\@ifstar{\let\@IEEEextracttokengroupsdef=\def\@@IEEEextracttokengroups}{\let\@IEEEextracttokengroupsdef=\edef\@@IEEEextracttokengroups}} +\def\@@IEEEextracttokengroups#1{\@IEEEextracttokengroupsdef\@IEEEextracttokengroupsarg{#1}\relax +% begin extraction, these functions are safe with empty arguments +% first group +\expandafter\@IEEEextractgroup\expandafter*\expandafter{\@IEEEextracttokengroupsarg}\relax +\let\@IEEEextractedfirstgroup\@IEEEextractedgroup +\let\@IEEEextractedafterfirstgroupremain\@IEEEextractedgroupremain +\expandafter\@IEEEextracttoken\expandafter*\expandafter{\@IEEEextractedfirstgroup}\relax +\let\@IEEEextractedfirsttoken\@IEEEextractedtoken +\let\@IEEEextractedfirsttokenmacro\@IEEEextractedtokenmacro +\let\@IEEEextractedfirsttokensdiscarded\@IEEEextractedtokensdiscarded +% first first group +\expandafter\@IEEEextractgroup\expandafter*\expandafter{\@IEEEextractedfirstgroup}\relax +\let\@IEEEextractedfirstfirstgroup\@IEEEextractedgroup +% next group +\expandafter\@IEEEextractgroup\expandafter*\expandafter{\@IEEEextractedafterfirstgroupremain}\relax +\let\@IEEEextractednextgroup\@IEEEextractedgroup +\expandafter\@IEEEextracttoken\expandafter*\expandafter{\@IEEEextractednextgroup}\relax +\let\@IEEEextractednextfirsttoken\@IEEEextractedtoken +\let\@IEEEextractednextfirsttokenmacro\@IEEEextractedtokenmacro +\let\@IEEEextractednextfirsttokensdiscarded\@IEEEextractedtokensdiscarded +% next first group +\expandafter\@IEEEextractgroup\expandafter*\expandafter{\@IEEEextractednextgroup}\relax +\let\@IEEEextractednextfirstgroup\@IEEEextractedgroup} + + +%% -- End of Command Argument Scanning Support Functions -- + + + + +%% +%% START OF IEEEeqnarray DEFINITIONS +%% +%% Inspired by the concepts, examples, and previous works of LaTeX +%% coders and developers such as Donald Arseneau, Fred Bartlett, +%% David Carlisle, Tony Liu, Frank Mittelbach, Piet van Oostrum, +%% Roland Winkler and Mark Wooding. +%% I don't make the claim that my work here is even near their calibre. ;) + + +\newif\if@IEEEeqnarrayboxnojot% flag to indicate if the environment was called as the star form +\@IEEEeqnarrayboxnojotfalse + +\newif\if@advanceIEEEeqncolcnt% tracks if the environment should advance the col counter +% allows a way to make an \IEEEeqnarraybox that can be used within an \IEEEeqnarray +% used by IEEEeqnarraymulticol so that it can work properly in both +\@advanceIEEEeqncolcnttrue + +\newcount\@IEEEeqnnumcols % tracks how many IEEEeqnarray cols are defined +\newcount\@IEEEeqncolcnt % tracks how many IEEEeqnarray cols the user actually used + + +% The default math style used by the columns +\def\IEEEeqnarraymathstyle{\displaystyle} +% The default text style used by the columns +% default to using the current font +\def\IEEEeqnarraytextstyle{\relax} + +% like the iedlistdecl but for \IEEEeqnarray +\def\IEEEeqnarraydecl{\relax} +\def\IEEEeqnarrayboxdecl{\relax} + + + +% V1.8 flags to indicate that equation numbering is to persist +\newif\if@IEEEeqnumpersist% +\@IEEEeqnumpersistfalse +\newif\if@IEEEsubeqnumpersist% +\@IEEEsubeqnumpersistfalse +% +% V1.8 flags to indicate if (sub)equation number of last line was preadvanced +\newif\if@IEEEeqnumpreadv% +\@IEEEeqnumpreadvfalse +\newif\if@IEEEsubeqnumpreadv% +\@IEEEsubeqnumpreadvfalse + +\newcount\@IEEEsubeqnnumrollback% saves previous value of IEEEsubequation number in case we need to restore it + +% \yesnumber is the opposite of \nonumber +% a novel concept with the same def as the equationarray package +% However, we give IEEE versions too since some LaTeX packages such as +% the MDWtools mathenv.sty redefine \nonumber to something else. +% This command is intended for use in non-IEEEeqnarray math environments +\providecommand{\yesnumber}{\global\@eqnswtrue} + + +% IEEEyes/nonumber +% V1.8 add persistant * forms +% These commands can alter the type of equation an IEEEeqnarray line is. +\def\IEEEyesnumber{\@ifstar{\global\@IEEEeqnumpersisttrue\global\@IEEEsubeqnumpersistfalse\@IEEEyesnumber}{\@IEEEyesnumber}} + +\def\@IEEEyesnumber{\global\@eqnswtrue +\if@IEEEeqnarrayISinner% alter counters and label only inside an IEEEeqnarray +\ifnum\c@IEEEsubequation>0\relax + \stepcounter{equation}\setcounter{IEEEsubequation}{0}\gdef\@currentlabel{\p@equation\theequation}\relax + \gdef\@currentHref{\@IEEEtheHrefequation}% setup hyperref label +\fi +% even if we reached this eqn num via a preadv, it is legit now +\global\@IEEEeqnumpreadvfalse\global\@IEEEsubeqnumpreadvfalse +\fi} + +\def\IEEEnonumber{\@ifstar{\global\@IEEEeqnumpersistfalse\global\@IEEEsubeqnumpersistfalse\global\@eqnswfalse}{\global\@eqnswfalse}} + + +\def\IEEEyessubnumber{\@ifstar{\global\@IEEEsubeqnumpersisttrue\@IEEEyessubnumber}{\@IEEEyessubnumber}} +% +\def\@IEEEyessubnumber{\if@IEEEeqnarrayISinner% alter counters and label only inside an IEEEeqnarray + \ifnum\c@IEEEsubequation>0\relax% if it already is a subequation, we are good to go as-is + \else% if we are a regular equation we have to watch out for two cases + \if@IEEEeqnumpreadv% if this equation is the result of a preadvance, backout and bump the sub eqnnum + \global\advance\c@equation\m@ne\global\c@IEEEsubequation=\@IEEEsubeqnnumrollback\addtocounter{IEEEsubequation}{1}\relax + \else% non-preadvanced equations just need initialization of their sub eqnnum + \setcounter{IEEEsubequation}{1}\relax + \fi + \fi% fi already is subequation + \gdef\@currentlabel{\p@IEEEsubequation\theIEEEsubequation}\relax + \gdef\@currentHref{\@IEEEtheHrefsubequation}% setup hyperref label + \global\@IEEEeqnumpreadvfalse\global\@IEEEsubeqnumpreadvfalse% no longer a preadv anymore + \global\@eqnswtrue +\fi} + + +\def\IEEEnosubnumber{\@ifstar{\global\@IEEEsubeqnumpersistfalse\@IEEEnosubnumber}{\@IEEEnosubnumber}} +% +\def\@IEEEnosubnumber{\if@IEEEeqnarrayISinner% alter counters and label only inside an IEEEeqnarray + \if@eqnsw % we do nothing unless we know we will display because we play with the counters here + % if it currently is a subequation, bump up to the next equation number and turn off the subequation + \ifnum\c@IEEEsubequation>0\relax\addtocounter{equation}{1}\setcounter{IEEEsubequation}{0}\relax + \fi + \global\@IEEEeqnumpreadvfalse\global\@IEEEsubeqnumpreadvfalse% no longer a preadv anymore + \gdef\@currentlabel{\p@equation\theequation}\relax + \gdef\@currentHref{\@IEEEtheHrefequation}% setup hyperref label + \fi +\fi} + + + +% allows users to "push away" equations that get too close to the equation numbers +\def\IEEEeqnarraynumspace{\hphantom{\ifnum\c@IEEEsubequation>0\relax\theIEEEsubequationdis\else\theequationdis\fi}} + +% provides a way to span multiple columns within IEEEeqnarray environments +% will consider \if@advanceIEEEeqncolcnt before globally advancing the +% column counter - so as to work within \IEEEeqnarraybox +% usage: \IEEEeqnarraymulticol{number cols. to span}{col type}{cell text} +\long\def\IEEEeqnarraymulticol#1#2#3{\multispan{#1}\relax +% check if column is defined for the precolumn definition +% We have to be careful here because TeX scans for & even within an \iffalse +% where it does not expand macros. So, if we used only one \ifx and a #3 +% appeared in the false branch and the user inserted another alignment +% structure that uses & in the \IEEEeqnarraymulticol{}, TeX will not see that +% there is an inner alignment in the false branch yet still will see any & +% there and will think that they apply to the outer alignment resulting in an +% incomplete \ifx error. +% So, here we use separate checks for the pre and post parts in order to keep +% the #3 outside of all conditionals. +\relax\expandafter\ifx\csname @IEEEeqnarraycolDEF#2\endcsname\@IEEEeqnarraycolisdefined\relax +\csname @IEEEeqnarraycolPRE#2\endcsname +\else% if not, error and use default type +\@IEEEclspkgerror{Invalid column type "#2" in \string\IEEEeqnarraymulticol.\MessageBreak +Using a default centering column instead}% +{You must define IEEEeqnarray column types before use.}% +\csname @IEEEeqnarraycolPRE@IEEEdefault\endcsname +\fi +% The ten \relax are to help prevent misleading error messages in case a user +% accidently inserted a macro that tries to acquire additional arguments. +#3\relax\relax\relax\relax\relax\relax\relax\relax\relax\relax +% check if column is defined for the postcolumn definition +\expandafter\ifx\csname @IEEEeqnarraycolDEF#2\endcsname\@IEEEeqnarraycolisdefined\relax +\csname @IEEEeqnarraycolPOST#2\endcsname +\else% if not, use the default type +\csname @IEEEeqnarraycolPOST@IEEEdefault\endcsname +\fi +% advance column counter only if the IEEEeqnarray environment wants it +\if@advanceIEEEeqncolcnt\global\advance\@IEEEeqncolcnt by #1\relax\fi} + +% like \omit, but maintains track of the column counter for \IEEEeqnarray +\def\IEEEeqnarrayomit{\omit\if@advanceIEEEeqncolcnt\global\advance\@IEEEeqncolcnt by 1\relax\fi} + + +% provides a way to define a letter referenced column type +% usage: \IEEEeqnarraydefcol{col. type letter/name}{pre insertion text}{post insertion text} +\def\IEEEeqnarraydefcol#1#2#3{\expandafter\def\csname @IEEEeqnarraycolPRE#1\endcsname{#2}% +\expandafter\def\csname @IEEEeqnarraycolPOST#1\endcsname{#3}% +\expandafter\def\csname @IEEEeqnarraycolDEF#1\endcsname{1}} + + +% provides a way to define a numerically referenced inter-column glue types +% usage: \IEEEeqnarraydefcolsep{col. glue number}{glue definition} +\def\IEEEeqnarraydefcolsep#1#2{\expandafter\def\csname @IEEEeqnarraycolSEP\romannumeral #1\endcsname{#2}% +\expandafter\def\csname @IEEEeqnarraycolSEPDEF\romannumeral #1\endcsname{1}} + + +\def\@IEEEeqnarraycolisdefined{1}% just a macro for 1, used for checking undefined column types + + +% expands and appends the given argument to the \@IEEEtrantmptoksA token list +% used to build up the \halign preamble +\def\@IEEEappendtoksA#1{\edef\@@IEEEappendtoksA{\@IEEEtrantmptoksA={\the\@IEEEtrantmptoksA #1}}% +\@@IEEEappendtoksA} + +% also appends to \@IEEEtrantmptoksA, but does not expand the argument +% uses \toks8 as a scratchpad register +\def\@IEEEappendNOEXPANDtoksA#1{\toks8={#1}% +\edef\@@IEEEappendNOEXPANDtoksA{\@IEEEtrantmptoksA={\the\@IEEEtrantmptoksA\the\toks8}}% +\@@IEEEappendNOEXPANDtoksA} + +% define some common column types for the user +% math +\IEEEeqnarraydefcol{l}{$\IEEEeqnarraymathstyle}{$\hfil} +\IEEEeqnarraydefcol{c}{\hfil$\IEEEeqnarraymathstyle}{$\hfil} +\IEEEeqnarraydefcol{r}{\hfil$\IEEEeqnarraymathstyle}{$} +\IEEEeqnarraydefcol{L}{$\IEEEeqnarraymathstyle{}}{{}$\hfil} +\IEEEeqnarraydefcol{C}{\hfil$\IEEEeqnarraymathstyle{}}{{}$\hfil} +\IEEEeqnarraydefcol{R}{\hfil$\IEEEeqnarraymathstyle{}}{{}$} +% text +\IEEEeqnarraydefcol{s}{\IEEEeqnarraytextstyle}{\hfil} +\IEEEeqnarraydefcol{t}{\hfil\IEEEeqnarraytextstyle}{\hfil} +\IEEEeqnarraydefcol{u}{\hfil\IEEEeqnarraytextstyle}{} + +% vertical rules +\IEEEeqnarraydefcol{v}{}{\vrule width\arrayrulewidth} +\IEEEeqnarraydefcol{vv}{\vrule width\arrayrulewidth\hfil}{\hfil\vrule width\arrayrulewidth} +\IEEEeqnarraydefcol{V}{}{\vrule width\arrayrulewidth\hskip\doublerulesep\vrule width\arrayrulewidth} +\IEEEeqnarraydefcol{VV}{\vrule width\arrayrulewidth\hskip\doublerulesep\vrule width\arrayrulewidth\hfil}% +{\hfil\vrule width\arrayrulewidth\hskip\doublerulesep\vrule width\arrayrulewidth} + +% horizontal rules +\IEEEeqnarraydefcol{h}{}{\leaders\hrule height\arrayrulewidth\hfil} +\IEEEeqnarraydefcol{H}{}{\leaders\vbox{\hrule width\arrayrulewidth\vskip\doublerulesep\hrule width\arrayrulewidth}\hfil} + +% plain +\IEEEeqnarraydefcol{x}{}{} +\IEEEeqnarraydefcol{X}{$}{$} + +% the default column type to use in the event a column type is not defined +\IEEEeqnarraydefcol{@IEEEdefault}{\hfil$\IEEEeqnarraymathstyle}{$\hfil} + + +% a zero tabskip (used for "-" col types) +\def\@IEEEeqnarraycolSEPzero{0pt plus 0pt minus 0pt} +% a centering tabskip (used for "+" col types) +\def\@IEEEeqnarraycolSEPcenter{1000pt plus 0pt minus 1000pt} + +% top level default tabskip glues for the start, end, and inter-column +% may be reset within environments not always at the top level, e.g., \IEEEeqnarraybox +\edef\@IEEEeqnarraycolSEPdefaultstart{\@IEEEeqnarraycolSEPcenter}% default start glue +\edef\@IEEEeqnarraycolSEPdefaultend{\@IEEEeqnarraycolSEPcenter}% default end glue +\edef\@IEEEeqnarraycolSEPdefaultmid{\@IEEEeqnarraycolSEPzero}% default inter-column glue + + + +% creates a vertical rule that extends from the bottom to the top a a cell +% Provided in case other packages redefine \vline some other way. +% usage: \IEEEeqnarrayvrule[rule thickness] +% If no argument is provided, \arrayrulewidth will be used for the rule thickness. +\newcommand\IEEEeqnarrayvrule[1][\arrayrulewidth]{\vrule\@width#1\relax} + +% creates a blank separator row +% usage: \IEEEeqnarrayseprow[separation length][font size commands] +% default is \IEEEeqnarrayseprow[0.25\normalbaselineskip][\relax] +% blank arguments inherit the default values +% uses \skip5 as a scratch register - calls \@IEEEeqnarraystrutsize which uses more scratch registers +\def\IEEEeqnarrayseprow{\relax\@ifnextchar[{\@IEEEeqnarrayseprow}{\@IEEEeqnarrayseprow[0.25\normalbaselineskip]}} +\def\@IEEEeqnarrayseprow[#1]{\relax\@ifnextchar[{\@@IEEEeqnarrayseprow[#1]}{\@@IEEEeqnarrayseprow[#1][\relax]}} +\def\@@IEEEeqnarrayseprow[#1][#2]{\def\@IEEEeqnarrayseprowARGONE{#1}% +\ifx\@IEEEeqnarrayseprowARGONE\@empty% +% get the skip value, based on the font commands +% use skip5 because \IEEEeqnarraystrutsize uses \skip0, \skip2, \skip3 +% assign within a bogus box to confine the font changes +{\setbox0=\hbox{#2\relax\global\skip5=0.25\normalbaselineskip}}% +\else% +{\setbox0=\hbox{#2\relax\global\skip5=#1}}% +\fi% +\@IEEEeqnarrayhoptolastcolumn\IEEEeqnarraystrutsize{\skip5}{0pt}[\relax]\relax} + +% creates a blank separator row, but omits all the column templates +% usage: \IEEEeqnarrayseprowcut[separation length][font size commands] +% default is \IEEEeqnarrayseprowcut[0.25\normalbaselineskip][\relax] +% blank arguments inherit the default values +% uses \skip5 as a scratch register - calls \@IEEEeqnarraystrutsize which uses more scratch registers +\def\IEEEeqnarrayseprowcut{\multispan{\@IEEEeqnnumcols}\relax% span all the cols +% advance column counter only if the IEEEeqnarray environment wants it +\if@advanceIEEEeqncolcnt\global\advance\@IEEEeqncolcnt by \@IEEEeqnnumcols\relax\fi% +\@ifnextchar[{\@IEEEeqnarrayseprowcut}{\@IEEEeqnarrayseprowcut[0.25\normalbaselineskip]}} +\def\@IEEEeqnarrayseprowcut[#1]{\relax\@ifnextchar[{\@@IEEEeqnarrayseprowcut[#1]}{\@@IEEEeqnarrayseprowcut[#1][\relax]}} +\def\@@IEEEeqnarrayseprowcut[#1][#2]{\def\@IEEEeqnarrayseprowARGONE{#1}% +\ifx\@IEEEeqnarrayseprowARGONE\@empty% +% get the skip value, based on the font commands +% use skip5 because \IEEEeqnarraystrutsize uses \skip0, \skip2, \skip3 +% assign within a bogus box to confine the font changes +{\setbox0=\hbox{#2\relax\global\skip5=0.25\normalbaselineskip}}% +\else% +{\setbox0=\hbox{#2\relax\global\skip5=#1}}% +\fi% +\IEEEeqnarraystrutsize{\skip5}{0pt}[\relax]\relax} + + + +% draws a single rule across all the columns optional +% argument determines the rule width, \arrayrulewidth is the default +% updates column counter as needed and turns off struts +% usage: \IEEEeqnarrayrulerow[rule line thickness] +\def\IEEEeqnarrayrulerow{\multispan{\@IEEEeqnnumcols}\relax% span all the cols +% advance column counter only if the IEEEeqnarray environment wants it +\if@advanceIEEEeqncolcnt\global\advance\@IEEEeqncolcnt by \@IEEEeqnnumcols\relax\fi% +\@ifnextchar[{\@IEEEeqnarrayrulerow}{\@IEEEeqnarrayrulerow[\arrayrulewidth]}} +\def\@IEEEeqnarrayrulerow[#1]{\leaders\hrule height#1\hfil\relax% put in our rule +% turn off any struts +\IEEEeqnarraystrutsize{0pt}{0pt}[\relax]\relax} + + +% draws a double rule by using a single rule row, a separator row, and then +% another single rule row +% first optional argument determines the rule thicknesses, \arrayrulewidth is the default +% second optional argument determines the rule spacing, \doublerulesep is the default +% usage: \IEEEeqnarraydblrulerow[rule line thickness][rule spacing] +\def\IEEEeqnarraydblrulerow{\multispan{\@IEEEeqnnumcols}\relax% span all the cols +% advance column counter only if the IEEEeqnarray environment wants it +\if@advanceIEEEeqncolcnt\global\advance\@IEEEeqncolcnt by \@IEEEeqnnumcols\relax\fi% +\@ifnextchar[{\@IEEEeqnarraydblrulerow}{\@IEEEeqnarraydblrulerow[\arrayrulewidth]}} +\def\@IEEEeqnarraydblrulerow[#1]{\relax\@ifnextchar[{\@@IEEEeqnarraydblrulerow[#1]}% +{\@@IEEEeqnarraydblrulerow[#1][\doublerulesep]}} +\def\@@IEEEeqnarraydblrulerow[#1][#2]{\def\@IEEEeqnarraydblrulerowARG{#1}% +% we allow the user to say \IEEEeqnarraydblrulerow[][] +\ifx\@IEEEeqnarraydblrulerowARG\@empty% +\@IEEEeqnarrayrulerow[\arrayrulewidth]% +\else% +\@IEEEeqnarrayrulerow[#1]\relax% +\fi% +\def\@IEEEeqnarraydblrulerowARG{#2}% +\ifx\@IEEEeqnarraydblrulerowARG\@empty% +\\\IEEEeqnarrayseprow[\doublerulesep][\relax]% +\else% +\\\IEEEeqnarrayseprow[#2][\relax]% +\fi% +\\\multispan{\@IEEEeqnnumcols}% +% advance column counter only if the IEEEeqnarray environment wants it +\if@advanceIEEEeqncolcnt\global\advance\@IEEEeqncolcnt by \@IEEEeqnnumcols\relax\fi% +\def\@IEEEeqnarraydblrulerowARG{#1}% +\ifx\@IEEEeqnarraydblrulerowARG\@empty% +\@IEEEeqnarrayrulerow[\arrayrulewidth]% +\else% +\@IEEEeqnarrayrulerow[#1]% +\fi% +} + +% draws a double rule by using a single rule row, a separator (cutting) row, and then +% another single rule row +% first optional argument determines the rule thicknesses, \arrayrulewidth is the default +% second optional argument determines the rule spacing, \doublerulesep is the default +% usage: \IEEEeqnarraydblrulerow[rule line thickness][rule spacing] +\def\IEEEeqnarraydblrulerowcut{\multispan{\@IEEEeqnnumcols}\relax% span all the cols +% advance column counter only if the IEEEeqnarray environment wants it +\if@advanceIEEEeqncolcnt\global\advance\@IEEEeqncolcnt by \@IEEEeqnnumcols\relax\fi% +\@ifnextchar[{\@IEEEeqnarraydblrulerowcut}{\@IEEEeqnarraydblrulerowcut[\arrayrulewidth]}} +\def\@IEEEeqnarraydblrulerowcut[#1]{\relax\@ifnextchar[{\@@IEEEeqnarraydblrulerowcut[#1]}% +{\@@IEEEeqnarraydblrulerowcut[#1][\doublerulesep]}} +\def\@@IEEEeqnarraydblrulerowcut[#1][#2]{\def\@IEEEeqnarraydblrulerowARG{#1}% +% we allow the user to say \IEEEeqnarraydblrulerow[][] +\ifx\@IEEEeqnarraydblrulerowARG\@empty% +\@IEEEeqnarrayrulerow[\arrayrulewidth]% +\else% +\@IEEEeqnarrayrulerow[#1]% +\fi% +\def\@IEEEeqnarraydblrulerowARG{#2}% +\ifx\@IEEEeqnarraydblrulerowARG\@empty% +\\\IEEEeqnarrayseprowcut[\doublerulesep][\relax]% +\else% +\\\IEEEeqnarrayseprowcut[#2][\relax]% +\fi% +\\\multispan{\@IEEEeqnnumcols}% +% advance column counter only if the IEEEeqnarray environment wants it +\if@advanceIEEEeqncolcnt\global\advance\@IEEEeqncolcnt by \@IEEEeqnnumcols\relax\fi% +\def\@IEEEeqnarraydblrulerowARG{#1}% +\ifx\@IEEEeqnarraydblrulerowARG\@empty% +\@IEEEeqnarrayrulerow[\arrayrulewidth]% +\else% +\@IEEEeqnarrayrulerow[#1]% +\fi% +} + + + +% inserts a full row's worth of &'s +% relies on \@IEEEeqnnumcols to provide the correct number of columns +% uses \@IEEEtrantmptoksA, \count0 as scratch registers +\def\@IEEEeqnarrayhoptolastcolumn{\@IEEEtrantmptoksA={}\count0=1\relax% +\loop% add cols if the user did not use them all +\ifnum\count0<\@IEEEeqnnumcols\relax% +\@IEEEappendtoksA{&}% +\advance\count0 by 1\relax% update the col count +\repeat% +\the\@IEEEtrantmptoksA%execute the &'s +} + + + +\newif\if@IEEEeqnarrayISinner % flag to indicate if we are within the lines +\@IEEEeqnarrayISinnerfalse % of an IEEEeqnarray - after the IEEEeqnarraydecl + +\edef\@IEEEeqnarrayTHEstrutheight{0pt} % height and depth of IEEEeqnarray struts +\edef\@IEEEeqnarrayTHEstrutdepth{0pt} + +\edef\@IEEEeqnarrayTHEmasterstrutheight{0pt} % default height and depth of +\edef\@IEEEeqnarrayTHEmasterstrutdepth{0pt} % struts within an IEEEeqnarray + +\edef\@IEEEeqnarrayTHEmasterstrutHSAVE{0pt} % saved master strut height +\edef\@IEEEeqnarrayTHEmasterstrutDSAVE{0pt} % and depth + +\newif\if@IEEEeqnarrayusemasterstrut % flag to indicate that the master strut value +\@IEEEeqnarrayusemasterstruttrue % is to be used + + + +% saves the strut height and depth of the master strut +\def\@IEEEeqnarraymasterstrutsave{\relax% +\expandafter\skip0=\@IEEEeqnarrayTHEmasterstrutheight\relax% +\expandafter\skip2=\@IEEEeqnarrayTHEmasterstrutdepth\relax% +% remove stretchability +\dimen0\skip0\relax% +\dimen2\skip2\relax% +% save values +\edef\@IEEEeqnarrayTHEmasterstrutHSAVE{\the\dimen0}% +\edef\@IEEEeqnarrayTHEmasterstrutDSAVE{\the\dimen2}} + +% restores the strut height and depth of the master strut +\def\@IEEEeqnarraymasterstrutrestore{\relax% +\expandafter\skip0=\@IEEEeqnarrayTHEmasterstrutHSAVE\relax% +\expandafter\skip2=\@IEEEeqnarrayTHEmasterstrutDSAVE\relax% +% remove stretchability +\dimen0\skip0\relax% +\dimen2\skip2\relax% +% restore values +\edef\@IEEEeqnarrayTHEmasterstrutheight{\the\dimen0}% +\edef\@IEEEeqnarrayTHEmasterstrutdepth{\the\dimen2}} + + +% globally restores the strut height and depth to the +% master values and sets the master strut flag to true +\def\@IEEEeqnarraystrutreset{\relax% +\expandafter\skip0=\@IEEEeqnarrayTHEmasterstrutheight\relax% +\expandafter\skip2=\@IEEEeqnarrayTHEmasterstrutdepth\relax% +% remove stretchability +\dimen0\skip0\relax% +\dimen2\skip2\relax% +% restore values +\xdef\@IEEEeqnarrayTHEstrutheight{\the\dimen0}% +\xdef\@IEEEeqnarrayTHEstrutdepth{\the\dimen2}% +\global\@IEEEeqnarrayusemasterstruttrue} + + +% if the master strut is not to be used, make the current +% values of \@IEEEeqnarrayTHEstrutheight, \@IEEEeqnarrayTHEstrutdepth +% and the use master strut flag, global +% this allows user strut commands issued in the last column to be carried +% into the isolation/strut column +\def\@IEEEeqnarrayglobalizestrutstatus{\relax% +\if@IEEEeqnarrayusemasterstrut\else% +\xdef\@IEEEeqnarrayTHEstrutheight{\@IEEEeqnarrayTHEstrutheight}% +\xdef\@IEEEeqnarrayTHEstrutdepth{\@IEEEeqnarrayTHEstrutdepth}% +\global\@IEEEeqnarrayusemasterstrutfalse% +\fi} + + + +% usage: \IEEEeqnarraystrutsize{height}{depth}[font size commands] +% If called outside the lines of an IEEEeqnarray, sets the height +% and depth of both the master and local struts. If called inside +% an IEEEeqnarray line, sets the height and depth of the local strut +% only and sets the flag to indicate the use of the local strut +% values. If the height or depth is left blank, 0.7\normalbaselineskip +% and 0.3\normalbaselineskip will be used, respectively. +% The optional argument can be used to evaluate the lengths under +% a different font size and styles. If none is specified, the current +% font is used. +% uses scratch registers \skip0, \skip2, \skip3, \dimen0, \dimen2 +\def\IEEEeqnarraystrutsize#1#2{\relax\@ifnextchar[{\@IEEEeqnarraystrutsize{#1}{#2}}{\@IEEEeqnarraystrutsize{#1}{#2}[\relax]}} +\def\@IEEEeqnarraystrutsize#1#2[#3]{\def\@IEEEeqnarraystrutsizeARG{#1}% +\ifx\@IEEEeqnarraystrutsizeARG\@empty% +{\setbox0=\hbox{#3\relax\global\skip3=0.7\normalbaselineskip}}% +\skip0=\skip3\relax% +\else% arg one present +{\setbox0=\hbox{#3\relax\global\skip3=#1\relax}}% +\skip0=\skip3\relax% +\fi% if null arg +\def\@IEEEeqnarraystrutsizeARG{#2}% +\ifx\@IEEEeqnarraystrutsizeARG\@empty% +{\setbox0=\hbox{#3\relax\global\skip3=0.3\normalbaselineskip}}% +\skip2=\skip3\relax% +\else% arg two present +{\setbox0=\hbox{#3\relax\global\skip3=#2\relax}}% +\skip2=\skip3\relax% +\fi% if null arg +% remove stretchability, just to be safe +\dimen0\skip0\relax% +\dimen2\skip2\relax% +% dimen0 = height, dimen2 = depth +\if@IEEEeqnarrayISinner% inner does not touch master strut size +\edef\@IEEEeqnarrayTHEstrutheight{\the\dimen0}% +\edef\@IEEEeqnarrayTHEstrutdepth{\the\dimen2}% +\@IEEEeqnarrayusemasterstrutfalse% do not use master +\else% outer, have to set master strut too +\edef\@IEEEeqnarrayTHEmasterstrutheight{\the\dimen0}% +\edef\@IEEEeqnarrayTHEmasterstrutdepth{\the\dimen2}% +\edef\@IEEEeqnarrayTHEstrutheight{\the\dimen0}% +\edef\@IEEEeqnarrayTHEstrutdepth{\the\dimen2}% +\@IEEEeqnarrayusemasterstruttrue% use master strut +\fi} + + +% usage: \IEEEeqnarraystrutsizeadd{added height}{added depth}[font size commands] +% If called outside the lines of an IEEEeqnarray, adds the given height +% and depth to both the master and local struts. +% If called inside an IEEEeqnarray line, adds the given height and depth +% to the local strut only and sets the flag to indicate the use +% of the local strut values. +% In both cases, if a height or depth is left blank, 0pt is used instead. +% The optional argument can be used to evaluate the lengths under +% a different font size and styles. If none is specified, the current +% font is used. +% uses scratch registers \skip0, \skip2, \skip3, \dimen0, \dimen2 +\def\IEEEeqnarraystrutsizeadd#1#2{\relax\@ifnextchar[{\@IEEEeqnarraystrutsizeadd{#1}{#2}}{\@IEEEeqnarraystrutsizeadd{#1}{#2}[\relax]}} +\def\@IEEEeqnarraystrutsizeadd#1#2[#3]{\def\@IEEEeqnarraystrutsizearg{#1}% +\ifx\@IEEEeqnarraystrutsizearg\@empty% +\skip0=0pt\relax% +\else% arg one present +{\setbox0=\hbox{#3\relax\global\skip3=#1}}% +\skip0=\skip3\relax% +\fi% if null arg +\def\@IEEEeqnarraystrutsizearg{#2}% +\ifx\@IEEEeqnarraystrutsizearg\@empty% +\skip2=0pt\relax% +\else% arg two present +{\setbox0=\hbox{#3\relax\global\skip3=#2}}% +\skip2=\skip3\relax% +\fi% if null arg +% remove stretchability, just to be safe +\dimen0\skip0\relax% +\dimen2\skip2\relax% +% dimen0 = height, dimen2 = depth +\if@IEEEeqnarrayISinner% inner does not touch master strut size +% get local strut size +\expandafter\skip0=\@IEEEeqnarrayTHEstrutheight\relax% +\expandafter\skip2=\@IEEEeqnarrayTHEstrutdepth\relax% +% add it to the user supplied values +\advance\dimen0 by \skip0\relax% +\advance\dimen2 by \skip2\relax% +% update the local strut size +\edef\@IEEEeqnarrayTHEstrutheight{\the\dimen0}% +\edef\@IEEEeqnarrayTHEstrutdepth{\the\dimen2}% +\@IEEEeqnarrayusemasterstrutfalse% do not use master +\else% outer, have to set master strut too +% get master strut size +\expandafter\skip0=\@IEEEeqnarrayTHEmasterstrutheight\relax% +\expandafter\skip2=\@IEEEeqnarrayTHEmasterstrutdepth\relax% +% add it to the user supplied values +\advance\dimen0 by \skip0\relax% +\advance\dimen2 by \skip2\relax% +% update the local and master strut sizes +\edef\@IEEEeqnarrayTHEmasterstrutheight{\the\dimen0}% +\edef\@IEEEeqnarrayTHEmasterstrutdepth{\the\dimen2}% +\edef\@IEEEeqnarrayTHEstrutheight{\the\dimen0}% +\edef\@IEEEeqnarrayTHEstrutdepth{\the\dimen2}% +\@IEEEeqnarrayusemasterstruttrue% use master strut +\fi} + + +% allow user a way to see the struts +\newif\ifIEEEvisiblestruts +\IEEEvisiblestrutsfalse + +% inserts an invisible strut using the master or local strut values +% uses scratch registers \skip0, \skip2, \dimen0, \dimen2 +\def\@IEEEeqnarrayinsertstrut{\relax% +\if@IEEEeqnarrayusemasterstrut +% get master strut size +\expandafter\skip0=\@IEEEeqnarrayTHEmasterstrutheight\relax% +\expandafter\skip2=\@IEEEeqnarrayTHEmasterstrutdepth\relax% +\else% +% get local strut size +\expandafter\skip0=\@IEEEeqnarrayTHEstrutheight\relax% +\expandafter\skip2=\@IEEEeqnarrayTHEstrutdepth\relax% +\fi% +% remove stretchability, probably not needed +\dimen0\skip0\relax% +\dimen2\skip2\relax% +% dimen0 = height, dimen2 = depth +% allow user to see struts if desired +\ifIEEEvisiblestruts% +\vrule width0.2pt height\dimen0 depth\dimen2\relax% +\else% +\vrule width0pt height\dimen0 depth\dimen2\relax\fi} + + +% creates an invisible strut, useable even outside \IEEEeqnarray +% if \IEEEvisiblestrutstrue, the strut will be visible and 0.2pt wide. +% usage: \IEEEstrut[height][depth][font size commands] +% default is \IEEEstrut[0.7\normalbaselineskip][0.3\normalbaselineskip][\relax] +% blank arguments inherit the default values +% uses \dimen0, \dimen2, \skip0, \skip2 +\def\IEEEstrut{\relax\@ifnextchar[{\@IEEEstrut}{\@IEEEstrut[0.7\normalbaselineskip]}} +\def\@IEEEstrut[#1]{\relax\@ifnextchar[{\@@IEEEstrut[#1]}{\@@IEEEstrut[#1][0.3\normalbaselineskip]}} +\def\@@IEEEstrut[#1][#2]{\relax\@ifnextchar[{\@@@IEEEstrut[#1][#2]}{\@@@IEEEstrut[#1][#2][\relax]}} +\def\@@@IEEEstrut[#1][#2][#3]{\mbox{#3\relax% +\def\@IEEEstrutARG{#1}% +\ifx\@IEEEstrutARG\@empty% +\skip0=0.7\normalbaselineskip\relax% +\else% +\skip0=#1\relax% +\fi% +\def\@IEEEstrutARG{#2}% +\ifx\@IEEEstrutARG\@empty% +\skip2=0.3\normalbaselineskip\relax% +\else% +\skip2=#2\relax% +\fi% +% remove stretchability, probably not needed +\dimen0\skip0\relax% +\dimen2\skip2\relax% +\ifIEEEvisiblestruts% +\vrule width0.2pt height\dimen0 depth\dimen2\relax% +\else% +\vrule width0.0pt height\dimen0 depth\dimen2\relax\fi}} + + +% enables strut mode by setting a default strut size and then zeroing the +% \baselineskip, \lineskip, \lineskiplimit and \jot +\def\IEEEeqnarraystrutmode{\IEEEeqnarraystrutsize{0.7\normalbaselineskip}{0.3\normalbaselineskip}[\relax]% +\baselineskip=0pt\lineskip=0pt\lineskiplimit=0pt\jot=0pt} + + +% equation and subequation forms to use to setup hyperref's \@currentHref +\def\@IEEEtheHrefequation{equation.\theHequation} +\def\@IEEEtheHrefsubequation{equation.\theHequation\alph{IEEEsubequation}} + + +\def\IEEEeqnarray{\@IEEEeqnumpersisttrue\@IEEEsubeqnumpersistfalse\@IEEEeqnarray} +\def\endIEEEeqnarray{\end@IEEEeqnarray} + +\@namedef{IEEEeqnarray*}{\@IEEEeqnumpersistfalse\@IEEEsubeqnumpersistfalse\@IEEEeqnarray} +\@namedef{endIEEEeqnarray*}{\end@IEEEeqnarray} + + +% \IEEEeqnarray is an enhanced \eqnarray. +% The star form defaults to not putting equation numbers at the end of each row. +% usage: \IEEEeqnarray[decl]{cols} +\def\@IEEEeqnarray{\relax\@ifnextchar[{\@@IEEEeqnarray}{\@@IEEEeqnarray[\relax]}} +% We have to be careful here to normalize catcodes just before acquiring the +% cols as that specification may contain punctuation which could be subject +% to document catcode changes. +\def\@@IEEEeqnarray[#1]{\begingroup\IEEEnormalcatcodes\@@@IEEEeqnarray[#1]} +\def\@@@IEEEeqnarray[#1]#2{\endgroup + % default to showing the equation number or not based on whether or not + % the star form was involked + \if@IEEEeqnumpersist\global\@eqnswtrue + \else% not the star form + \global\@eqnswfalse + \fi% if star form + % provide a basic hyperref \theHequation if this has not already been setup (hyperref not loaded, or no section counter) + \@ifundefined{theHequation}{\def\theHequation{\arabic{equation}}}{}\relax + % provide dummy hyperref commands in case hyperref is not loaded + \providecommand{\Hy@raisedlink}[1]{}\relax + \providecommand{\hyper@anchorstart}[1]{}\relax + \providecommand{\hyper@anchorend}{}\relax + \providecommand{\@currentHref}{}\relax + \@IEEEeqnumpreadvfalse% reset eqnpreadv flag + \@IEEEsubeqnumpreadvfalse% reset subeqnpreadv flag + \@IEEEeqnarrayISinnerfalse% not yet within the lines of the halign + \@IEEEeqnarraystrutsize{0pt}{0pt}[\relax]% turn off struts by default + \@IEEEeqnarrayusemasterstruttrue% use master strut till user asks otherwise + \IEEEvisiblestrutsfalse% diagnostic mode defaults to off + % no extra space unless the user specifically requests it + \lineskip=0pt\relax + \lineskiplimit=0pt\relax + \baselineskip=\normalbaselineskip\relax% + \jot=\IEEEnormaljot\relax% + \mathsurround\z@\relax% no extra spacing around math + \@advanceIEEEeqncolcnttrue% advance the col counter for each col the user uses, + % used in \IEEEeqnarraymulticol and in the preamble build + %V1.8 Here we preadvance to the next equation number. + % If the user later wants a continued subequation, we can roll back. + \global\@IEEEsubeqnnumrollback=\c@IEEEsubequation% + \stepcounter{equation}\@IEEEeqnumpreadvtrue% advance equation counter before first line + \setcounter{IEEEsubequation}{0}% no subequation yet + \let\@IEEEcurrentlabelsave\@currentlabel% save current label as we later change it globally + \let\@IEEEcurrentHrefsave\@currentHref% save current href label as we later change it globally + \def\@currentlabel{\p@equation\theequation}% redefine the ref label + \def\@currentHref{\@IEEEtheHrefequation}% setup hyperref label + \IEEEeqnarraydecl\relax% allow a way for the user to make global overrides + #1\relax% allow user to override defaults + \let\\\@IEEEeqnarraycr% replace newline with one that can put in eqn. numbers + \global\@IEEEeqncolcnt\z@% col. count = 0 for first line + \@IEEEbuildpreamble{#2}\relax% build the preamble and put it into \@IEEEtrantmptoksA + % put in the column for the equation number + \ifnum\@IEEEeqnnumcols>0\relax\@IEEEappendtoksA{&}\fi% col separator for those after the first + \toks0={##}% + % advance the \@IEEEeqncolcnt for the isolation col, this helps with error checking + \@IEEEappendtoksA{\global\advance\@IEEEeqncolcnt by 1\relax}% + % add the isolation column + \@IEEEappendtoksA{\tabskip\z@skip\bgroup\the\toks0\egroup}% + % advance the \@IEEEeqncolcnt for the equation number col, this helps with error checking + \@IEEEappendtoksA{&\global\advance\@IEEEeqncolcnt by 1\relax}% + % add the equation number col to the preamble + \@IEEEappendtoksA{\tabskip\z@skip\hb@xt@\z@\bgroup\hss\the\toks0\egroup}% + % note \@IEEEeqnnumcols does not count the equation col or isolation col + % set the starting tabskip glue as determined by the preamble build + \tabskip=\@IEEEBPstartglue\relax + % begin the display alignment + \@IEEEeqnarrayISinnertrue% commands are now within the lines + $$\everycr{}\halign to\displaywidth\bgroup + % "exspand" the preamble + \span\the\@IEEEtrantmptoksA\cr} + +% enter isolation/strut column (or the next column if the user did not use +% every column), record the strut status, complete the columns, do the strut if needed, +% restore counters (to backout any equation setup for a next line that was never used) +% to their correct values and exit +\def\end@IEEEeqnarray{\@IEEEeqnarrayglobalizestrutstatus&\@@IEEEeqnarraycr\egroup +\if@IEEEsubeqnumpreadv\global\advance\c@IEEEsubequation\m@ne\fi +\if@IEEEeqnumpreadv\global\advance\c@equation\m@ne\global\c@IEEEsubequation=\@IEEEsubeqnnumrollback\fi +\global\let\@currentlabel\@IEEEcurrentlabelsave% restore current label +\global\let\@currentHref\@IEEEcurrentHrefsave% restore current href label +$$\@ignoretrue} + + +% IEEEeqnarray uses a modifed \\ instead of the plain \cr to +% end rows. This allows for things like \\*[vskip amount] +% These "cr" macros are modified versions of those for LaTeX2e's eqnarray +% the {\ifnum0=`} braces must be kept away from the last column to avoid +% altering spacing of its math, so we use & to advance to the next column +% as there is an isolation/strut column after the user's columns +\def\@IEEEeqnarraycr{\@IEEEeqnarrayglobalizestrutstatus&% save strut status and advance to next column + {\ifnum0=`}\fi + \@ifstar{% + \global\@eqpen\@M\@IEEEeqnarrayYCR + }{% + \global\@eqpen\interdisplaylinepenalty \@IEEEeqnarrayYCR + }% +} + +\def\@IEEEeqnarrayYCR{\@testopt\@IEEEeqnarrayXCR\z@skip} + +\def\@IEEEeqnarrayXCR[#1]{% + \ifnum0=`{\fi}% + \@@IEEEeqnarraycr + \noalign{\penalty\@eqpen\vskip\jot\vskip #1\relax}}% + +\def\@@IEEEeqnarraycr{\@IEEEtrantmptoksA={}% clear token register + \advance\@IEEEeqncolcnt by -1\relax% adjust col count because of the isolation column + \ifnum\@IEEEeqncolcnt>\@IEEEeqnnumcols\relax + \@IEEEclspkgerror{Too many columns within the IEEEeqnarray\MessageBreak + environment}% + {Use fewer \string &'s or put more columns in the IEEEeqnarray column\MessageBreak + specifications.}\relax% + \else + \loop% add cols if the user did not use them all + \ifnum\@IEEEeqncolcnt<\@IEEEeqnnumcols\relax + \@IEEEappendtoksA{&}% + \advance\@IEEEeqncolcnt by 1\relax% update the col count + \repeat + % this number of &'s will take us the the isolation column + \fi + % execute the &'s + \the\@IEEEtrantmptoksA% + % handle the strut/isolation column + \@IEEEeqnarrayinsertstrut% do the strut if needed + \@IEEEeqnarraystrutreset% reset the strut system for next line or IEEEeqnarray + &% and enter the equation number column + \if@eqnsw% only if we display something + \Hy@raisedlink{\hyper@anchorstart{\@currentHref}}% start a hyperref anchor + \global\@IEEEeqnumpreadvfalse\relax% displaying an equation number means + \global\@IEEEsubeqnumpreadvfalse\relax% the equation counters point to valid equations + % V1.8 Here we setup the counters, currentlabel and status for what would be the *next* + % equation line as would be the case under the current settings. However, there are two problems. + % One problem is that there might not ever be a next line. The second problem is that the user + % may later alter the meaning of a line with commands such as \IEEEyessubnumber. So, to handle + % these cases we have to record the current values of the (sub)equation counters and revert back + % to them if the next line is changed or never comes. The \if@IEEEeqnumpreadv, \if@IEEEsubeqnumpreadv + % and \@IEEEsubeqnnumrollback stuff tracks this. + % The logic to handle all this is surprisingly complex, but a nice feature of the approach here is + % that the equation counters and labels remain valid for what the line would be unless a + % \IEEEyessubnumber et al. later changes it. So, any hyperref links are always correct. + \ifnum\c@IEEEsubequation>0\relax% handle subequation + \theIEEEsubequationdis\relax + \if@IEEEsubeqnumpersist% setup for default type of next line + \stepcounter{IEEEsubequation}\global\@IEEEsubeqnumpreadvtrue\relax + \gdef\@currentlabel{\p@IEEEsubequation\theIEEEsubequation}\relax + \gdef\@currentHref{\@IEEEtheHrefsubequation}% setup hyperref label + \else + % if no subeqnum persist, go ahead and setup for a new equation number + \global\@IEEEsubeqnnumrollback=\c@IEEEsubequation + \stepcounter{equation}\global\@IEEEeqnumpreadvtrue\relax + \setcounter{IEEEsubequation}{0}\gdef\@currentlabel{\p@equation\theequation}\relax + \gdef\@currentHref{\@IEEEtheHrefequation}% setup hyperref label + \fi + \else% display a standard equation number + \theequationdis\relax + \setcounter{IEEEsubequation}{0}\relax% not really needed + \if@IEEEsubeqnumpersist% setup for default type of next line + % subequations that follow plain equations carry the same equation number e.g, 5, 5a rather than 5, 6a + \stepcounter{IEEEsubequation}\global\@IEEEsubeqnumpreadvtrue\relax + \gdef\@currentlabel{\p@IEEEsubequation\theIEEEsubequation}\relax + \gdef\@currentHref{\@IEEEtheHrefsubequation}% setup hyperref label + \else + % if no subeqnum persist, go ahead and setup for a new equation number + \global\@IEEEsubeqnnumrollback=\c@IEEEsubequation + \stepcounter{equation}\global\@IEEEeqnumpreadvtrue\relax + \setcounter{IEEEsubequation}{0}\gdef\@currentlabel{\p@equation\theequation}\relax + \gdef\@currentHref{\@IEEEtheHrefequation}% setup hyperref label + \fi + \fi% + \Hy@raisedlink{\hyper@anchorend}% end hyperref anchor + \fi% fi only if we display something + % reset the flags to indicate the default preferences of the display of equation numbers + \if@IEEEeqnumpersist\global\@eqnswtrue\else\global\@eqnswfalse\fi + \if@IEEEsubeqnumpersist\global\@eqnswtrue\fi% ditto for the subequation flag + % reset the number of columns the user actually used + \global\@IEEEeqncolcnt\z@\relax + % the real end of the line + \cr} + + + + + +% \IEEEeqnarraybox is like \IEEEeqnarray except the box form puts everything +% inside a vtop, vbox, or vcenter box depending on the letter in the second +% optional argument (t,b,c). Vbox is the default. Unlike \IEEEeqnarray, +% equation numbers are not displayed and \IEEEeqnarraybox can be nested. +% \IEEEeqnarrayboxm is for math mode (like \array) and does not put the vbox +% within an hbox. +% \IEEEeqnarrayboxt is for text mode (like \tabular) and puts the vbox within +% a \hbox{$ $} construct. +% \IEEEeqnarraybox will auto detect whether to use \IEEEeqnarrayboxm or +% \IEEEeqnarrayboxt depending on the math mode. +% The third optional argument specifies the width this box is to be set to - +% natural width is the default. +% The * forms do not add \jot line spacing +% usage: \IEEEeqnarraybox[decl][pos][width]{cols} +\def\IEEEeqnarrayboxm{\@IEEEeqnarrayboxnojotfalse\@IEEEeqnarrayboxHBOXSWfalse\@IEEEeqnarraybox} +\def\endIEEEeqnarrayboxm{\end@IEEEeqnarraybox} +\@namedef{IEEEeqnarrayboxm*}{\@IEEEeqnarrayboxnojottrue\@IEEEeqnarrayboxHBOXSWfalse\@IEEEeqnarraybox} +\@namedef{endIEEEeqnarrayboxm*}{\end@IEEEeqnarraybox} + +\def\IEEEeqnarrayboxt{\@IEEEeqnarrayboxnojotfalse\@IEEEeqnarrayboxHBOXSWtrue\@IEEEeqnarraybox} +\def\endIEEEeqnarrayboxt{\end@IEEEeqnarraybox} +\@namedef{IEEEeqnarrayboxt*}{\@IEEEeqnarrayboxnojottrue\@IEEEeqnarrayboxHBOXSWtrue\@IEEEeqnarraybox} +\@namedef{endIEEEeqnarrayboxt*}{\end@IEEEeqnarraybox} + +\def\IEEEeqnarraybox{\@IEEEeqnarrayboxnojotfalse\ifmmode\@IEEEeqnarrayboxHBOXSWfalse\else\@IEEEeqnarrayboxHBOXSWtrue\fi% +\@IEEEeqnarraybox} +\def\endIEEEeqnarraybox{\end@IEEEeqnarraybox} + +\@namedef{IEEEeqnarraybox*}{\@IEEEeqnarrayboxnojottrue\ifmmode\@IEEEeqnarrayboxHBOXSWfalse\else\@IEEEeqnarrayboxHBOXSWtrue\fi% +\@IEEEeqnarraybox} +\@namedef{endIEEEeqnarraybox*}{\end@IEEEeqnarraybox} + +% flag to indicate if the \IEEEeqnarraybox needs to put things into an hbox{$ $} +% for \vcenter in non-math mode +\newif\if@IEEEeqnarrayboxHBOXSW% +\@IEEEeqnarrayboxHBOXSWfalse + +\def\@IEEEeqnarraybox{\relax\@ifnextchar[{\@@IEEEeqnarraybox}{\@@IEEEeqnarraybox[\relax]}} +% We have to be careful here to normalize catcodes just before acquiring the +% cols as that specification may contain punctuation which could be subject +% to document catcode changes. +\def\@@IEEEeqnarraybox[#1]{\relax\begingroup\IEEEnormalcatcodes\@ifnextchar[{\@@@IEEEeqnarraybox[#1]}{\@@@IEEEeqnarraybox[#1][b]}} +\def\@@@IEEEeqnarraybox[#1][#2]{\relax\@ifnextchar[{\@@@@IEEEeqnarraybox[#1][#2]}{\@@@@IEEEeqnarraybox[#1][#2][\relax]}} + +% #1 = decl; #2 = t,b,c; #3 = width, #4 = col specs +\def\@@@@IEEEeqnarraybox[#1][#2][#3]#4{\endgroup\@IEEEeqnarrayISinnerfalse % not yet within the lines of the halign + \@IEEEeqnarraymasterstrutsave% save current master strut values + \@IEEEeqnarraystrutsize{0pt}{0pt}[\relax]% turn off struts by default + \@IEEEeqnarrayusemasterstruttrue% use master strut till user asks otherwise + \IEEEvisiblestrutsfalse% diagnostic mode defaults to off + % no extra space unless the user specifically requests it + \lineskip=0pt\relax% + \lineskiplimit=0pt\relax% + \baselineskip=\normalbaselineskip\relax% + \jot=\IEEEnormaljot\relax% + \mathsurround\z@\relax% no extra spacing around math + % the default end glues are zero for an \IEEEeqnarraybox + \edef\@IEEEeqnarraycolSEPdefaultstart{\@IEEEeqnarraycolSEPzero}% default start glue + \edef\@IEEEeqnarraycolSEPdefaultend{\@IEEEeqnarraycolSEPzero}% default end glue + \edef\@IEEEeqnarraycolSEPdefaultmid{\@IEEEeqnarraycolSEPzero}% default inter-column glue + \@advanceIEEEeqncolcntfalse% do not advance the col counter for each col the user uses, + % used in \IEEEeqnarraymulticol and in the preamble build + \IEEEeqnarrayboxdecl\relax% allow a way for the user to make global overrides + #1\relax% allow user to override defaults + \let\\\@IEEEeqnarrayboxcr% replace newline with one that allows optional spacing + \@IEEEbuildpreamble{#4}\relax% build the preamble and put it into \@IEEEtrantmptoksA + % add an isolation column to the preamble to stop \\'s {} from getting into the last col + \ifnum\@IEEEeqnnumcols>0\relax\@IEEEappendtoksA{&}\fi% col separator for those after the first + \toks0={##}% + % add the isolation column to the preamble + \@IEEEappendtoksA{\tabskip\z@skip\bgroup\the\toks0\egroup}% + % set the starting tabskip glue as determined by the preamble build + \tabskip=\@IEEEBPstartglue\relax + % begin the alignment + \everycr{}% + % use only the very first token to determine the positioning + \@IEEEextracttoken{#2}\relax + \ifx\@IEEEextractedtokensdiscarded\@empty\else + \typeout{** WARNING: IEEEeqnarraybox position specifiers after the first in `\@IEEEextracttokenarg' ignored (line \the\inputlineno).}\relax + \fi + % \@IEEEextractedtoken has the first token, the rest are ignored + % if we need to put things into and hbox and go into math mode, do so now + \if@IEEEeqnarrayboxHBOXSW \leavevmode \hbox \bgroup $\fi% + % use the appropriate vbox type + \if\@IEEEextractedtoken t\relax\vtop\else\if\@IEEEextractedtoken c\relax% + \vcenter\else\vbox\fi\fi\bgroup% + \@IEEEeqnarrayISinnertrue% commands are now within the lines + \ifx#3\relax\halign\else\halign to #3\relax\fi% + \bgroup + % "exspand" the preamble + \span\the\@IEEEtrantmptoksA\cr} + +% carry strut status and enter the isolation/strut column, +% exit from math mode if needed, and exit +\def\end@IEEEeqnarraybox{\@IEEEeqnarrayglobalizestrutstatus% carry strut status +&% enter isolation/strut column +\@IEEEeqnarrayinsertstrut% do strut if needed +\@IEEEeqnarraymasterstrutrestore% restore the previous master strut values +% reset the strut system for next IEEEeqnarray +% (sets local strut values back to previous master strut values) +\@IEEEeqnarraystrutreset% +% ensure last line, exit from halign, close vbox +\crcr\egroup\egroup% +% exit from math mode and close hbox if needed +\if@IEEEeqnarrayboxHBOXSW $\egroup\fi} + + + +% IEEEeqnarraybox uses a modifed \\ instead of the plain \cr to +% end rows. This allows for things like \\[vskip amount] +% This "cr" macros are modified versions those for LaTeX2e's eqnarray +% For IEEEeqnarraybox, \\* is the same as \\ +% the {\ifnum0=`} braces must be kept away from the last column to avoid +% altering spacing of its math, so we use & to advance to the isolation/strut column +% carry strut status into isolation/strut column +\def\@IEEEeqnarrayboxcr{\@IEEEeqnarrayglobalizestrutstatus% carry strut status +&% enter isolation/strut column +\@IEEEeqnarrayinsertstrut% do strut if needed +% reset the strut system for next line or IEEEeqnarray +\@IEEEeqnarraystrutreset% +{\ifnum0=`}\fi% +\@ifstar{\@IEEEeqnarrayboxYCR}{\@IEEEeqnarrayboxYCR}} + +% test and setup the optional argument to \\[] +\def\@IEEEeqnarrayboxYCR{\@testopt\@IEEEeqnarrayboxXCR\z@skip} + +% IEEEeqnarraybox does not automatically increase line spacing by \jot +\def\@IEEEeqnarrayboxXCR[#1]{\ifnum0=`{\fi}% +\cr\noalign{\if@IEEEeqnarrayboxnojot\else\vskip\jot\fi\vskip#1\relax}} + + + +% usage: \@IEEEbuildpreamble{column specifiers} +% starts the halign preamble build +% the assembled preamble is put in \@IEEEtrantmptoksA +\def\@IEEEbuildpreamble#1{\@IEEEtrantmptoksA={}% clear token register +\let\@IEEEBPcurtype=u%current column type is not yet known +\let\@IEEEBPprevtype=s%the previous column type was the start +\let\@IEEEBPnexttype=u%next column type is not yet known +% ensure these are valid +\def\@IEEEBPcurglue={0pt plus 0pt minus 0pt}% +\def\@IEEEBPcurcolname{@IEEEdefault}% name of current column definition +% currently acquired numerically referenced glue +% use a name that is easier to remember +\let\@IEEEBPcurnum=\@IEEEtrantmpcountA% +\@IEEEBPcurnum=0% +% tracks number of columns in the preamble +\@IEEEeqnnumcols=0% +% record the default end glues +\edef\@IEEEBPstartglue{\@IEEEeqnarraycolSEPdefaultstart}% +\edef\@IEEEBPendglue{\@IEEEeqnarraycolSEPdefaultend}% +\edef\@IEEEedefMACRO{#1}\relax% fully expand the preamble to support macro containers +% now parse the user's column specifications +% \ignorespaces is used as a delimiter, need at least one trailing \relax because +% \@@IEEEbuildpreamble looks into the future +\expandafter\@@IEEEbuildpreamble\@IEEEedefMACRO\ignorespaces\relax\relax} + + +% usage: \@@IEEEbuildpreamble{current column}{next column} +% parses and builds the halign preamble +\def\@@IEEEbuildpreamble#1#2{\let\@@nextIEEEbuildpreamble=\@@IEEEbuildpreamble% +% use only the very first token to check the end +\@IEEEextracttokengroups{#1}\relax +\ifx\@IEEEextractedfirsttoken\ignorespaces\let\@@nextIEEEbuildpreamble=\@@IEEEfinishpreamble\else% +% identify current and next token type +\@IEEEgetcoltype{#1}{\@IEEEBPcurtype}{1}% current, error on invalid +\@IEEEgetcoltype{#2}{\@IEEEBPnexttype}{0}% next, no error on invalid next +% if curtype is a glue, get the glue def +\if\@IEEEBPcurtype g\@IEEEgetcurglue{#1}{\@IEEEBPcurglue}\fi% +% if curtype is a column, get the column def and set the current column name +\if\@IEEEBPcurtype c\@IEEEgetcurcol{#1}\fi% +% if curtype is a numeral, acquire the user defined glue +\if\@IEEEBPcurtype n\@IEEEprocessNcol{#1}\fi% +% process the acquired glue +\if\@IEEEBPcurtype g\@IEEEprocessGcol\fi% +% process the acquired col +\if\@IEEEBPcurtype c\@IEEEprocessCcol\fi% +% ready prevtype for next col spec. +\let\@IEEEBPprevtype=\@IEEEBPcurtype% +% be sure and put back the future token(s) as a group +\fi\@@nextIEEEbuildpreamble{#2}} + + +% usage: \@@IEEEfinishpreamble{discarded} +% executed just after preamble build is completed +% warn about zero cols, and if prevtype type = u, put in end tabskip glue +% argument is not used +\def\@@IEEEfinishpreamble#1{\ifnum\@IEEEeqnnumcols<1\relax +\@IEEEclspkgerror{No column specifiers declared for IEEEeqnarray}% +{At least one column type must be declared for each IEEEeqnarray.}% +\fi%num cols less than 1 +%if last type undefined, set default end tabskip glue +\if\@IEEEBPprevtype u\@IEEEappendtoksA{\tabskip=\@IEEEBPendglue}\fi} + + +% usage: \@IEEEgetcoltype{col specifier}{\output}{error more} +% Identify and return the column specifier's type code in the given +% \output macro: +% n = number +% g = glue (any other char in catagory 12) +% c = letter +% e = \ignorespaces (end of sequence) +% u = undefined +% error mode: 0 = no error message, 1 = error on invalid char +\def\@IEEEgetcoltype#1#2#3{% +% use only the very first token to determine the type +\@IEEEextracttoken{#1}\relax +% \@IEEEextractedtoken has the first token, the rest are discarded +\let#2=u\relax% assume invalid until know otherwise +\ifx\@IEEEextractedtoken\ignorespaces\let#2=e\else +\ifcat\@IEEEextractedtoken\relax\else% screen out control sequences +\if0\@IEEEextractedtoken\let#2=n\else +\if1\@IEEEextractedtoken\let#2=n\else +\if2\@IEEEextractedtoken\let#2=n\else +\if3\@IEEEextractedtoken\let#2=n\else +\if4\@IEEEextractedtoken\let#2=n\else +\if5\@IEEEextractedtoken\let#2=n\else +\if6\@IEEEextractedtoken\let#2=n\else +\if7\@IEEEextractedtoken\let#2=n\else +\if8\@IEEEextractedtoken\let#2=n\else +\if9\@IEEEextractedtoken\let#2=n\else +\ifcat,\@IEEEextractedtoken\let#2=g\relax +\else\ifcat a\@IEEEextractedtoken\let#2=c\relax\fi\fi\fi\fi\fi\fi\fi\fi\fi\fi\fi\fi\fi\fi +\if#2u\relax +\if0\noexpand#3\relax\else\@IEEEclspkgerror{Invalid character in column specifications}% +{Only letters, numerals and certain other symbols are allowed \MessageBreak +as IEEEeqnarray column specifiers.}\fi\fi} + + +% usage: \@IEEEgetcurcol{col specifier} +% verify the letter referenced column exists +% and return its name in \@IEEEBPcurcolname +% if column specifier is invalid, use the default column @IEEEdefault +\def\@IEEEgetcurcol#1{\expandafter\ifx\csname @IEEEeqnarraycolDEF#1\endcsname\@IEEEeqnarraycolisdefined% +\def\@IEEEBPcurcolname{#1}\else% invalid column name +\@IEEEclspkgerror{Invalid column type "#1" in column specifications.\MessageBreak +Using a default centering column instead}% +{You must define IEEEeqnarray column types before use.}% +\def\@IEEEBPcurcolname{@IEEEdefault}\fi} + + +% usage: \@IEEEgetcurglue{glue specifier}{\output} +% identify the predefined (punctuation) glue value +% and return it in the given output macro +\def\@IEEEgetcurglue#1#2{% +% ! = \! (neg small) -0.16667em (-3/18 em) +% , = \, (small) 0.16667em ( 3/18 em) +% : = \: (med) 0.22222em ( 4/18 em) +% ; = \; (large) 0.27778em ( 5/18 em) +% ' = \quad 1em +% " = \qquad 2em +% . = 0.5\arraycolsep +% / = \arraycolsep +% ? = 2\arraycolsep +% * = 1fil +% + = \@IEEEeqnarraycolSEPcenter +% - = \@IEEEeqnarraycolSEPzero +% Note that all em values are referenced to the math font (textfont2) fontdimen6 +% value for 1em. +% +% use only the very first token to determine the type +\@IEEEextracttoken{#1}\relax +\ifx\@IEEEextractedtokensdiscarded\@empty\else + \typeout{** WARNING: IEEEeqnarray predefined inter-column glue type specifiers after the first in `\@IEEEextracttokenarg' ignored (line \the\inputlineno).}\relax +\fi +% get the math font 1em value +% LaTeX2e's NFSS2 does not preload the fonts, but \IEEEeqnarray needs +% to gain access to the math (\textfont2) font's spacing parameters. +% So we create a bogus box here that uses the math font to ensure +% that \textfont2 is loaded and ready. If this is not done, +% the \textfont2 stuff here may not work. +% Thanks to Bernd Raichle for his 1997 post on this topic. +{\setbox0=\hbox{$\displaystyle\relax$}}% +% fontdimen6 has the width of 1em (a quad). +\@IEEEtrantmpdimenA=\fontdimen6\textfont2\relax% +% identify the glue value based on the first token +% we discard anything after the first +\if!\@IEEEextractedtoken\@IEEEtrantmpdimenA=-0.16667\@IEEEtrantmpdimenA\edef#2{\the\@IEEEtrantmpdimenA}\else +\if,\@IEEEextractedtoken\@IEEEtrantmpdimenA=0.16667\@IEEEtrantmpdimenA\edef#2{\the\@IEEEtrantmpdimenA}\else +\if:\@IEEEextractedtoken\@IEEEtrantmpdimenA=0.22222\@IEEEtrantmpdimenA\edef#2{\the\@IEEEtrantmpdimenA}\else +\if;\@IEEEextractedtoken\@IEEEtrantmpdimenA=0.27778\@IEEEtrantmpdimenA\edef#2{\the\@IEEEtrantmpdimenA}\else +\if'\@IEEEextractedtoken\@IEEEtrantmpdimenA=1\@IEEEtrantmpdimenA\edef#2{\the\@IEEEtrantmpdimenA}\else +\if"\@IEEEextractedtoken\@IEEEtrantmpdimenA=2\@IEEEtrantmpdimenA\edef#2{\the\@IEEEtrantmpdimenA}\else +\if.\@IEEEextractedtoken\@IEEEtrantmpdimenA=0.5\arraycolsep\edef#2{\the\@IEEEtrantmpdimenA}\else +\if/\@IEEEextractedtoken\edef#2{\the\arraycolsep}\else +\if?\@IEEEextractedtoken\@IEEEtrantmpdimenA=2\arraycolsep\edef#2{\the\@IEEEtrantmpdimenA}\else +\if *\@IEEEextractedtoken\edef#2{0pt plus 1fil minus 0pt}\else +\if+\@IEEEextractedtoken\edef#2{\@IEEEeqnarraycolSEPcenter}\else +\if-\@IEEEextractedtoken\edef#2{\@IEEEeqnarraycolSEPzero}\else +\edef#2{\@IEEEeqnarraycolSEPzero}% +\@IEEEclspkgerror{Invalid predefined inter-column glue type "#1" in\MessageBreak +column specifications. Using a default value of\MessageBreak +0pt instead}% +{Only !,:;'"./?*+ and - are valid predefined glue types in the\MessageBreak +IEEEeqnarray column specifications.}\fi\fi\fi\fi\fi\fi\fi\fi\fi\fi\fi\fi} + + +% usage: \@IEEEprocessNcol{digit} +% process a numerical digit from the column specification +% and look up the corresponding user defined glue value +% can transform current type from n to g or a as the user defined glue is acquired +\def\@IEEEprocessNcol#1{\if\@IEEEBPprevtype g% +\@IEEEclspkgerror{Back-to-back inter-column glue specifiers in column\MessageBreak +specifications. Ignoring consecutive glue specifiers\MessageBreak +after the first}% +{You cannot have two or more glue types next to each other\MessageBreak +in the IEEEeqnarray column specifications.}% +\let\@IEEEBPcurtype=a% abort this glue, future digits will be discarded +\@IEEEBPcurnum=0\relax% +\else% if we previously aborted a glue +\if\@IEEEBPprevtype a\@IEEEBPcurnum=0\let\@IEEEBPcurtype=a%maintain digit abortion +\else%acquire this number +% save the previous type before the numerical digits started +\if\@IEEEBPprevtype n\else\let\@IEEEBPprevsavedtype=\@IEEEBPprevtype\fi% +\multiply\@IEEEBPcurnum by 10\relax% +\advance\@IEEEBPcurnum by #1\relax% add in number, \relax is needed to stop TeX's number scan +\if\@IEEEBPnexttype n\else%close acquisition +\expandafter\ifx\csname @IEEEeqnarraycolSEPDEF\expandafter\romannumeral\number\@IEEEBPcurnum\endcsname\@IEEEeqnarraycolisdefined% +\edef\@IEEEBPcurglue{\csname @IEEEeqnarraycolSEP\expandafter\romannumeral\number\@IEEEBPcurnum\endcsname}% +\else%user glue not defined +\@IEEEclspkgerror{Invalid user defined inter-column glue type "\number\@IEEEBPcurnum" in\MessageBreak +column specifications. Using a default value of\MessageBreak +0pt instead}% +{You must define all IEEEeqnarray numerical inter-column glue types via\MessageBreak +\string\IEEEeqnarraydefcolsep \space before they are used in column specifications.}% +\edef\@IEEEBPcurglue{\@IEEEeqnarraycolSEPzero}% +\fi% glue defined or not +\let\@IEEEBPcurtype=g% change the type to reflect the acquired glue +\let\@IEEEBPprevtype=\@IEEEBPprevsavedtype% restore the prev type before this number glue +\@IEEEBPcurnum=0\relax%ready for next acquisition +\fi%close acquisition, get glue +\fi%discard or acquire number +\fi%prevtype glue or not +} + + +% process an acquired glue +% add any acquired column/glue pair to the preamble +\def\@IEEEprocessGcol{\if\@IEEEBPprevtype a\let\@IEEEBPcurtype=a%maintain previous glue abortions +\else +% if this is the start glue, save it, but do nothing else +% as this is not used in the preamble, but before +\if\@IEEEBPprevtype s\edef\@IEEEBPstartglue{\@IEEEBPcurglue}% +\else%not the start glue +\if\@IEEEBPprevtype g%ignore if back to back glues +\@IEEEclspkgerror{Back-to-back inter-column glue specifiers in column\MessageBreak +specifications. Ignoring consecutive glue specifiers\MessageBreak +after the first}% +{You cannot have two or more glue types next to each other\MessageBreak +in the IEEEeqnarray column specifications.}% +\let\@IEEEBPcurtype=a% abort this glue +\else% not a back to back glue +\if\@IEEEBPprevtype c\relax% if the previoustype was a col, add column/glue pair to preamble +\ifnum\@IEEEeqnnumcols>0\relax\@IEEEappendtoksA{&}\fi +\toks0={##}% +% make preamble advance col counter if this environment needs this +\if@advanceIEEEeqncolcnt\@IEEEappendtoksA{\global\advance\@IEEEeqncolcnt by 1\relax}\fi +% insert the column defintion into the preamble, being careful not to expand +% the column definition +\@IEEEappendtoksA{\tabskip=\@IEEEBPcurglue}% +\@IEEEappendNOEXPANDtoksA{\begingroup\csname @IEEEeqnarraycolPRE}% +\@IEEEappendtoksA{\@IEEEBPcurcolname}% +\@IEEEappendNOEXPANDtoksA{\endcsname}% +\@IEEEappendtoksA{\the\toks0}% +\@IEEEappendNOEXPANDtoksA{\relax\relax\relax\relax\relax% +\relax\relax\relax\relax\relax\csname @IEEEeqnarraycolPOST}% +\@IEEEappendtoksA{\@IEEEBPcurcolname}% +\@IEEEappendNOEXPANDtoksA{\endcsname\relax\relax\relax\relax\relax% +\relax\relax\relax\relax\relax\endgroup}% +\advance\@IEEEeqnnumcols by 1\relax%one more column in the preamble +\else% error: non-start glue with no pending column +\@IEEEclspkgerror{Inter-column glue specifier without a prior column\MessageBreak +type in the column specifications. Ignoring this glue\MessageBreak +specifier}% +{Except for the first and last positions, glue can be placed only\MessageBreak +between column types.}% +\let\@IEEEBPcurtype=a% abort this glue +\fi% previous was a column +\fi% back-to-back glues +\fi% is start column glue +\fi% prev type not a +} + + +% process an acquired letter referenced column and, if necessary, add it to the preamble +\def\@IEEEprocessCcol{\if\@IEEEBPnexttype g\else +\if\@IEEEBPnexttype n\else +% we have a column followed by something other than a glue (or numeral glue) +% so we must add this column to the preamble now +\ifnum\@IEEEeqnnumcols>0\relax\@IEEEappendtoksA{&}\fi%col separator for those after the first +\if\@IEEEBPnexttype e\@IEEEappendtoksA{\tabskip=\@IEEEBPendglue\relax}\else%put in end glue +\@IEEEappendtoksA{\tabskip=\@IEEEeqnarraycolSEPdefaultmid\relax}\fi% or default mid glue +\toks0={##}% +% make preamble advance col counter if this environment needs this +\if@advanceIEEEeqncolcnt\@IEEEappendtoksA{\global\advance\@IEEEeqncolcnt by 1\relax}\fi +% insert the column definition into the preamble, being careful not to expand +% the column definition +\@IEEEappendNOEXPANDtoksA{\begingroup\csname @IEEEeqnarraycolPRE}% +\@IEEEappendtoksA{\@IEEEBPcurcolname}% +\@IEEEappendNOEXPANDtoksA{\endcsname}% +\@IEEEappendtoksA{\the\toks0}% +\@IEEEappendNOEXPANDtoksA{\relax\relax\relax\relax\relax% +\relax\relax\relax\relax\relax\csname @IEEEeqnarraycolPOST}% +\@IEEEappendtoksA{\@IEEEBPcurcolname}% +\@IEEEappendNOEXPANDtoksA{\endcsname\relax\relax\relax\relax\relax% +\relax\relax\relax\relax\relax\endgroup}% +\advance\@IEEEeqnnumcols by 1\relax%one more column in the preamble +\fi%next type not numeral +\fi%next type not glue +} + + +%% +%% END OF IEEEeqnarray DEFINITIONS +%% + + + + + +% set up the running headers and footers +% +% header and footer font and size specifications +\def\@IEEEheaderstyle{\normalfont\scriptsize} +\def\@IEEEfooterstyle{\normalfont\scriptsize} +% +% compsoc uses sans-serif headers and footers +\ifCLASSOPTIONcompsoc + \def\@IEEEheaderstyle{\normalfont\sffamily\scriptsize} + \def\@IEEEfooterstyle{\normalfont\sffamily\scriptsize} +\fi + + +% standard page style, ps@headings +\def\ps@headings{% default to standard twoside headers, no footers +% will change later if the mode requires otherwise +\def\@oddhead{\hbox{}\@IEEEheaderstyle\rightmark\hfil\thepage}\relax +\def\@evenhead{\@IEEEheaderstyle\thepage\hfil\leftmark\hbox{}}\relax +\let\@oddfoot\@empty +\let\@evenfoot\@empty +\ifCLASSOPTIONtechnote + % technote twoside + \def\@oddhead{\hbox{}\@IEEEheaderstyle\leftmark\hfil\thepage}\relax + \def\@evenhead{\@IEEEheaderstyle\thepage\hfil\leftmark\hbox{}}\relax +\fi +\ifCLASSOPTIONdraftcls + % draft footers + \def\@oddfoot{\@IEEEfooterstyle\@date\hfil DRAFT}\relax + \def\@evenfoot{\@IEEEfooterstyle DRAFT\hfil\@date}\relax +\fi +% oneside +\if@twoside\else + % standard one side headers + \def\@oddhead{\hbox{}\@IEEEheaderstyle\leftmark\hfil\thepage}\relax + \let\@evenhead\@empty + \ifCLASSOPTIONdraftcls + % oneside draft footers + \def\@oddfoot{\@IEEEfooterstyle\@date\hfil DRAFT}\relax + \let\@evenfoot\@empty + \fi +\fi +% turn off headers for conferences +\ifCLASSOPTIONconference + \let\@oddhead\@empty + \let\@evenhead\@empty +\fi +% turn off footers for draftclsnofoot +\ifCLASSOPTIONdraftclsnofoot + \let\@oddfoot\@empty + \let\@evenfoot\@empty +\fi} + + +% title page style, ps@IEEEtitlepagestyle +\def\ps@IEEEtitlepagestyle{% default title page headers, no footers +\def\@oddhead{\hbox{}\@IEEEheaderstyle\leftmark\hfil\thepage}\relax +\def\@evenhead{\@IEEEheaderstyle\thepage\hfil\leftmark\hbox{}}\relax +\let\@oddfoot\@empty +\let\@evenfoot\@empty +% will change later if the mode requires otherwise +\ifCLASSOPTIONdraftcls + % draft footers + \ifCLASSOPTIONdraftclsnofoot\else + % but only if not draftclsnofoot + \def\@oddfoot{\@IEEEfooterstyle\@date\hfil DRAFT}\relax + \def\@evenfoot{\@IEEEfooterstyle DRAFT\hfil\@date}\relax + \fi +\else + % all nondraft mode footers + \if@IEEEusingpubid + % for title pages that are using a pubid + % do not repeat pubid on the title page if using a peer review cover page + \ifCLASSOPTIONpeerreview\else + % for noncompsoc papers, the pubid uses footnotesize and + % is at the same vertical position as where the last baseline would normally be + \def\@oddfoot{\hbox{}\hss\@IEEEfooterstyle\footnotesize\raisebox{\footskip}[0pt][0pt]{\@IEEEpubid}\hss\hbox{}}\relax + \def\@evenfoot{\hbox{}\hss\@IEEEfooterstyle\footnotesize\raisebox{\footskip}[0pt][0pt]{\@IEEEpubid}\hss\hbox{}}\relax + \ifCLASSOPTIONcompsoc + % for compsoc papers, the pubid is at the same vertical position as the normal footer + \def\@oddfoot{\hbox{}\hss\@IEEEfooterstyle\raisebox{0pt}[0pt][0pt]{\@IEEEpubid}\hss\hbox{}}\relax + \def\@evenfoot{\hbox{}\hss\@IEEEfooterstyle\raisebox{0pt}[0pt][0pt]{\@IEEEpubid}\hss\hbox{}}\relax + \fi + \fi + \fi +\fi +% turn off headers for conferences +\ifCLASSOPTIONconference + \let\@oddhead\@empty + \let\@evenhead\@empty +\fi} + + +% peer review cover page style, ps@IEEEpeerreviewcoverpagestyle +\def\ps@IEEEpeerreviewcoverpagestyle{% default peer review cover no headers, no footers +\let\@oddhead\@empty +\let\@evenhead\@empty +\let\@oddfoot\@empty +\let\@evenfoot\@empty +% will change later if the mode requires otherwise +\ifCLASSOPTIONdraftcls + % draft footers + \ifCLASSOPTIONdraftclsnofoot\else + % but only if not draftclsnofoot + \def\@oddfoot{\@IEEEfooterstyle\@date\hfil DRAFT}\relax + \def\@evenfoot{\@IEEEfooterstyle DRAFT\hfil\@date}\relax + \fi +\else + % all nondraft mode footers + \if@IEEEusingpubid + % for peer review cover pages that are using a pubid + % for noncompsoc papers, the pubid uses footnotesize and + % is at the same vertical position as where the last baseline would normally be + \def\@oddfoot{\hbox{}\hss\@IEEEfooterstyle\footnotesize\raisebox{\footskip}[0pt][0pt]{\@IEEEpubid}\hss\hbox{}}\relax + \def\@evenfoot{\hbox{}\hss\@IEEEfooterstyle\footnotesize\raisebox{\footskip}[0pt][0pt]{\@IEEEpubid}\hss\hbox{}}\relax + \ifCLASSOPTIONcompsoc + % for compsoc papers, the pubid is at the same vertical position as the normal footer + \def\@oddfoot{\hbox{}\hss\@IEEEfooterstyle\raisebox{0pt}[0pt][0pt]{\@IEEEpubid}\hss\hbox{}}\relax + \def\@evenfoot{\hbox{}\hss\@IEEEfooterstyle\raisebox{0pt}[0pt][0pt]{\@IEEEpubid}\hss\hbox{}}\relax + \fi + \fi +\fi} + + + +%% Defines the command for putting the header. +%% Note that all the text is forced into uppercase, if you have some text +%% that needs to be in lower case, for instance et. al., then either manually +%% set \leftmark and \rightmark or use \MakeLowercase{et. al.} within the +%% arguments to \markboth. +%% V1.7b add \protect to work with Babel +\def\markboth#1#2{\def\leftmark{\MakeUppercase{\protect#1}}% +\def\rightmark{\MakeUppercase{\protect#2}}} + +\def\today{\ifcase\month\or + January\or February\or March\or April\or May\or June\or + July\or August\or September\or October\or November\or December\fi + \space\number\day, \number\year} + + + + +%% CITATION AND BIBLIOGRAPHY COMMANDS +%% +%% V1.6 no longer supports the older, nonstandard \shortcite and \citename setup stuff +% +% +% Modify Latex2e \@citex to separate citations with "], [" +\def\@citex[#1]#2{% + \let\@citea\@empty + \@cite{\@for\@citeb:=#2\do + {\@citea\def\@citea{], [}% + \edef\@citeb{\expandafter\@firstofone\@citeb\@empty}% + \if@filesw\immediate\write\@auxout{\string\citation{\@citeb}}\fi + \@ifundefined{b@\@citeb}{\mbox{\reset@font\bfseries ?}% + \G@refundefinedtrue + \@latex@warning + {Citation `\@citeb' on page \thepage \space undefined}}% + {\hbox{\csname b@\@citeb\endcsname}}}}{#1}} + +% V1.6 we create hooks for the optional use of Donald Arseneau's +% cite.sty package. cite.sty is "smart" and will notice that the +% following format controls are already defined and will not +% redefine them. The result will be the proper sorting of the +% citation numbers and auto detection of 3 or more entry "ranges" - +% all in IEEE style: [1], [2], [5]--[7], [12] +% This also allows for an optional note, i.e., \cite[mynote]{..}. +% If the \cite with note has more than one reference, the note will +% be applied to the last of the listed references. It is generally +% desired that if a note is given, only one reference is listed in +% that \cite. +% Thanks to Mr. Arseneau for providing the required format arguments +% to produce the IEEE style. +\def\citepunct{], [} +\def\citedash{]--[} + +% V1.7 default to using same font for urls made by url.sty +\AtBeginDocument{\csname url@samestyle\endcsname} + +% V1.6 class files should always provide these +\def\newblock{\hskip .11em\@plus.33em\@minus.07em} +\let\@openbib@code\@empty +% V1.8b article.cls is now providing these too +% we do not use \@mkboth, nor alter the page style +\newenvironment{theindex} + {\if@twocolumn + \@restonecolfalse + \else + \@restonecoltrue + \fi + \twocolumn[\section*{\indexname}]% + \parindent\z@ + \parskip\z@ \@plus .3\p@\relax + \columnseprule \z@ + \columnsep 35\p@ + \let\item\@idxitem} + {\if@restonecol\onecolumn\else\clearpage\fi} +\newcommand\@idxitem{\par\hangindent 40\p@} +\newcommand\subitem{\@idxitem \hspace*{20\p@}} +\newcommand\subsubitem{\@idxitem \hspace*{30\p@}} +\newcommand\indexspace{\par \vskip 10\p@ \@plus5\p@ \@minus3\p@\relax} + + + +% Provide support for the control entries of IEEEtran.bst V1.00 and later. +% V1.7 optional argument allows for a different aux file to be specified in +% order to handle multiple bibliographies. For example, with multibib.sty: +% \newcites{sec}{Secondary Literature} +% \bstctlcite[@auxoutsec]{BSTcontrolhak} +\def\bstctlcite{\@ifnextchar[{\@bstctlcite}{\@bstctlcite[@auxout]}} +\def\@bstctlcite[#1]#2{\@bsphack + \@for\@citeb:=#2\do{% + \edef\@citeb{\expandafter\@firstofone\@citeb}% + \if@filesw\immediate\write\csname #1\endcsname{\string\citation{\@citeb}}\fi}% + \@esphack} + +% \IEEEnoauxwrite{} allows for citations that do not add to or affect +% the order of the existing citation list. Can be useful for \cite +% within \thanks{}. +\DeclareRobustCommand{\IEEEnoauxwrite}[1]{\relax +\if@filesw +\@fileswfalse +#1\relax\relax\relax\relax\relax +\@fileswtrue +\else +#1\relax\relax\relax\relax\relax +\fi} + +% V1.6 provide a way for a user to execute a command just before +% a given reference number - used to insert a \newpage to balance +% the columns on the last page +\edef\@IEEEtriggerrefnum{0} % the default of zero means that + % the command is not executed +\def\@IEEEtriggercmd{\newpage} + +% allow the user to alter the triggered command +\long\def\IEEEtriggercmd#1{\long\def\@IEEEtriggercmd{#1}} + +% allow user a way to specify the reference number just before the +% command is executed +\def\IEEEtriggeratref#1{\@IEEEtrantmpcountA=#1% +\edef\@IEEEtriggerrefnum{\the\@IEEEtrantmpcountA}}% + +% trigger command at the given reference +\def\@IEEEbibitemprefix{\@IEEEtrantmpcountA=\@IEEEtriggerrefnum\relax% +\advance\@IEEEtrantmpcountA by -1\relax% +\ifnum\c@enumiv=\@IEEEtrantmpcountA\relax\@IEEEtriggercmd\relax\fi} + + +\def\@biblabel#1{[#1]} + +% compsoc journals and conferences left align the reference numbers +\@IEEEcompsoconly{\def\@biblabel#1{[#1]\hfill}} + +% controls bib item spacing +\def\IEEEbibitemsep{0pt plus .5pt} + +\@IEEEcompsocconfonly{\def\IEEEbibitemsep{0.5\baselineskip plus 0.25\baselineskip minus 0.25\baselineskip}} + + +\def\thebibliography#1{\section*{\refname}% + \addcontentsline{toc}{section}{\refname}% + % V1.6 add some rubber space here and provide a command trigger + \footnotesize\vskip 0.3\baselineskip plus 0.1\baselineskip minus 0.1\baselineskip% + \list{\@biblabel{\@arabic\c@enumiv}}% + {\settowidth\labelwidth{\@biblabel{#1}}% + \leftmargin\labelwidth + \advance\leftmargin\labelsep\relax + \itemsep \IEEEbibitemsep\relax + \usecounter{enumiv}% + \let\p@enumiv\@empty + \renewcommand\theenumiv{\@arabic\c@enumiv}}% + \let\@IEEElatexbibitem\bibitem% + \def\bibitem{\@IEEEbibitemprefix\@IEEElatexbibitem}% +\def\newblock{\hskip .11em plus .33em minus .07em}% +% originally: +% \sloppy\clubpenalty4000\widowpenalty4000% +% by adding the \interlinepenalty here, we make it more +% difficult, but not impossible, for LaTeX to break within a reference. +% The IEEE almost never breaks a reference (but they do it more often with +% technotes). You may get an underfull vbox warning around the bibliography, +% but the final result will be much more like what the IEEE will publish. +% MDS 11/2000 +\ifCLASSOPTIONtechnote\sloppy\clubpenalty4000\widowpenalty4000\interlinepenalty100% +\else\sloppy\clubpenalty4000\widowpenalty4000\interlinepenalty500\fi% + \sfcode`\.=1000\relax} +\let\endthebibliography=\endlist + + + + +% TITLE PAGE COMMANDS +% +% +% \IEEEmembership is used to produce the sublargesize italic font used to indicate author +% IEEE membership. compsoc uses a large size sans slant font +\def\IEEEmembership#1{{\@IEEEnotcompsoconly{\sublargesize}\normalfont\@IEEEcompsoconly{\sffamily}\textit{#1}}} + + +% \IEEEauthorrefmark{} produces a footnote type symbol to indicate author affiliation. +% When given an argument of 1 to 9, \IEEEauthorrefmark{} follows the standard LaTeX footnote +% symbol sequence convention. However, for arguments 10 and above, \IEEEauthorrefmark{} +% reverts to using lower case roman numerals, so it cannot overflow. Do note that you +% cannot use \footnotemark[] in place of \IEEEauthorrefmark{} within \author as the footnote +% symbols will have been turned off to prevent \thanks from creating footnote marks. +% \IEEEauthorrefmark{} produces a symbol that appears to LaTeX as having zero vertical +% height - this allows for a more compact line packing, but the user must ensure that +% the interline spacing is large enough to prevent \IEEEauthorrefmark{} from colliding +% with the text above. +% V1.7 make this a robust command +% V1.8 transmag uses an arabic author affiliation symbol +\ifCLASSOPTIONtransmag +\DeclareRobustCommand*{\IEEEauthorrefmark}[1]{\raisebox{0pt}[0pt][0pt]{\textsuperscript{\footnotesize #1}}} +\else +\DeclareRobustCommand*{\IEEEauthorrefmark}[1]{\raisebox{0pt}[0pt][0pt]{\textsuperscript{\footnotesize\ensuremath{\ifcase#1\or *\or \dagger\or \ddagger\or% + \mathsection\or \mathparagraph\or \|\or **\or \dagger\dagger% + \or \ddagger\ddagger \else\textsuperscript{\expandafter\romannumeral#1}\fi}}}} +\fi + + +% FONT CONTROLS AND SPACINGS FOR CONFERENCE MODE AUTHOR NAME AND AFFILIATION BLOCKS +% +% The default font styles for the author name and affiliation blocks (confmode) +\def\@IEEEauthorblockNstyle{\normalfont\@IEEEcompsocnotconfonly{\sffamily}\sublargesize} +\def\@IEEEauthorblockAstyle{\normalfont\@IEEEcompsocnotconfonly{\sffamily}\@IEEEcompsocconfonly{\itshape}\normalsize} +% The default if the user does not use an author block +\def\@IEEEauthordefaulttextstyle{\normalfont\@IEEEcompsocnotconfonly{\sffamily}\sublargesize} + +% adjustment spacing from title (or special paper notice) to author name blocks (confmode) +% can be negative +\def\@IEEEauthorblockconfadjspace{-0.25em} +% compsoc conferences need more space here +\@IEEEcompsocconfonly{\def\@IEEEauthorblockconfadjspace{0.75\@IEEEnormalsizeunitybaselineskip}} + +% spacing between name and affiliation blocks (confmode) +% This can be negative. +% The IEEE doesn't want any added spacing here, but I will leave these +% controls in place in case they ever change their mind. +% Personally, I like 0.75ex. +%\def\@IEEEauthorblockNtopspace{0.75ex} +%\def\@IEEEauthorblockAtopspace{0.75ex} +\def\@IEEEauthorblockNtopspace{0.0ex} +\def\@IEEEauthorblockAtopspace{0.0ex} +\ifCLASSOPTIONtransmag +% transmag uses one line of space above first affiliation block +\def\@IEEEauthorblockAtopspace{1\@IEEEnormalsizeunitybaselineskip} +\fi + +% baseline spacing within name and affiliation blocks (confmode) +% must be positive, spacings below certain values will make +% the position of line of text sensitive to the contents of the +% line above it i.e., whether or not the prior line has descenders, +% subscripts, etc. For this reason it is a good idea to keep +% these above 2.6ex +\def\@IEEEauthorblockNinterlinespace{2.6ex} +\def\@IEEEauthorblockAinterlinespace{2.75ex} + +% This tracks the required strut size. +% See the \@IEEEauthorhalign command for the actual default value used. +\def\@IEEEauthorblockXinterlinespace{2.7ex} + +% variables to retain font size and style across groups +% values given here have no effect as they will be overwritten later +\gdef\@IEEESAVESTATEfontsize{10} +\gdef\@IEEESAVESTATEfontbaselineskip{12} +\gdef\@IEEESAVESTATEfontencoding{OT1} +\gdef\@IEEESAVESTATEfontfamily{ptm} +\gdef\@IEEESAVESTATEfontseries{m} +\gdef\@IEEESAVESTATEfontshape{n} + +% saves the current font attributes +\def\@IEEEcurfontSAVE{\global\let\@IEEESAVESTATEfontsize\f@size% +\global\let\@IEEESAVESTATEfontbaselineskip\f@baselineskip% +\global\let\@IEEESAVESTATEfontencoding\f@encoding% +\global\let\@IEEESAVESTATEfontfamily\f@family% +\global\let\@IEEESAVESTATEfontseries\f@series% +\global\let\@IEEESAVESTATEfontshape\f@shape} + +% restores the saved font attributes +\def\@IEEEcurfontRESTORE{\fontsize{\@IEEESAVESTATEfontsize}{\@IEEESAVESTATEfontbaselineskip}% +\fontencoding{\@IEEESAVESTATEfontencoding}% +\fontfamily{\@IEEESAVESTATEfontfamily}% +\fontseries{\@IEEESAVESTATEfontseries}% +\fontshape{\@IEEESAVESTATEfontshape}% +\selectfont} + + +% variable to indicate if the current block is the first block in the column +\newif\if@IEEEprevauthorblockincol \@IEEEprevauthorblockincolfalse + + +% the command places a strut with height and depth = \@IEEEauthorblockXinterlinespace +% we use this technique to have complete manual control over the spacing of the lines +% within the halign environment. +% We set the below baseline portion at 30%, the above +% baseline portion at 70% of the total length. +% Responds to changes in the document's \baselinestretch +\def\@IEEEauthorstrutrule{\@IEEEtrantmpdimenA\@IEEEauthorblockXinterlinespace% +\@IEEEtrantmpdimenA=\baselinestretch\@IEEEtrantmpdimenA% +\rule[-0.3\@IEEEtrantmpdimenA]{0pt}{\@IEEEtrantmpdimenA}} + + +% blocks to hold the authors' names and affilations. +% Makes formatting easy for conferences +% +% use real definitions in conference mode +% name block +\def\IEEEauthorblockN#1{\relax\@IEEEauthorblockNstyle% set the default text style +\gdef\@IEEEauthorblockXinterlinespace{0pt}% disable strut for spacer row +% the \expandafter hides the \cr in conditional tex, see the array.sty docs +% for details, probably not needed here as the \cr is in a macro +% do a spacer row if needed +\if@IEEEprevauthorblockincol\expandafter\@IEEEauthorblockNtopspaceline\fi +\global\@IEEEprevauthorblockincoltrue% we now have a block in this column +%restore the correct strut value +\gdef\@IEEEauthorblockXinterlinespace{\@IEEEauthorblockNinterlinespace}% +% input the author names +#1% +% end the row if the user did not already +\crcr} +% spacer row for names +\def\@IEEEauthorblockNtopspaceline{\cr\noalign{\vskip\@IEEEauthorblockNtopspace}} +% +% affiliation block +\def\IEEEauthorblockA#1{\relax\@IEEEauthorblockAstyle% set the default text style +\gdef\@IEEEauthorblockXinterlinespace{0pt}%disable strut for spacer row +% the \expandafter hides the \cr in conditional tex, see the array.sty docs +% for details, probably not needed here as the \cr is in a macro +% do a spacer row if needed +\if@IEEEprevauthorblockincol\expandafter\@IEEEauthorblockAtopspaceline\fi +\global\@IEEEprevauthorblockincoltrue% we now have a block in this column +%restore the correct strut value +\gdef\@IEEEauthorblockXinterlinespace{\@IEEEauthorblockAinterlinespace}% +% input the author affiliations +#1% +% end the row if the user did not already +\crcr +% V1.8 transmag does not use any additional affiliation spacing after the first author +\ifCLASSOPTIONtransmag\gdef\@IEEEauthorblockAtopspace{0pt}\fi} + +% spacer row for affiliations +\def\@IEEEauthorblockAtopspaceline{\cr\noalign{\vskip\@IEEEauthorblockAtopspace}} + + +% allow papers to compile even if author blocks are used in modes other +% than conference or peerreviewca. For such cases, we provide dummy blocks. +\ifCLASSOPTIONconference +\else + \ifCLASSOPTIONpeerreviewca\else + % not conference, peerreviewca or transmag mode + \ifCLASSOPTIONtransmag\else + \def\IEEEauthorblockN#1{#1}% + \def\IEEEauthorblockA#1{#1}% + \fi + \fi +\fi + + + +% we provide our own halign so as not to have to depend on tabular +\def\@IEEEauthorhalign{\@IEEEauthordefaulttextstyle% default text style + \lineskip=0pt\relax% disable line spacing + \lineskiplimit=0pt\relax% + \baselineskip=0pt\relax% + \@IEEEcurfontSAVE% save the current font + \mathsurround\z@\relax% no extra spacing around math + \let\\\@IEEEauthorhaligncr% replace newline with halign friendly one + \tabskip=0pt\relax% no column spacing + \everycr{}% ensure no problems here + \@IEEEprevauthorblockincolfalse% no author blocks yet + \def\@IEEEauthorblockXinterlinespace{2.7ex}% default interline space + \vtop\bgroup%vtop box + \halign\bgroup&\relax\hfil\@IEEEcurfontRESTORE\relax ##\relax + \hfil\@IEEEcurfontSAVE\@IEEEauthorstrutrule\cr} + +% ensure last line, exit from halign, close vbox +\def\end@IEEEauthorhalign{\crcr\egroup\egroup} + +% handle bogus star form +\def\@IEEEauthorhaligncr{{\ifnum0=`}\fi\@ifstar{\@@IEEEauthorhaligncr}{\@@IEEEauthorhaligncr}} + +% test and setup the optional argument to \\[] +\def\@@IEEEauthorhaligncr{\@testopt\@@@IEEEauthorhaligncr\z@skip} + +% end the line and do the optional spacer +\def\@@@IEEEauthorhaligncr[#1]{\ifnum0=`{\fi}\cr\noalign{\vskip#1\relax}} + + + +% flag to prevent multiple \and warning messages +\newif\if@IEEEWARNand +\@IEEEWARNandtrue + +% if in conference or peerreviewca modes, we support the use of \and as \author is a +% tabular environment, otherwise we warn the user that \and is invalid +% outside of conference or peerreviewca modes. +\def\and{\relax} % provide a bogus \and that we will then override + +\renewcommand{\and}[1][\relax]{\if@IEEEWARNand\typeout{** WARNING: \noexpand\and is valid only + when in conference or peerreviewca}\typeout{modes (line \the\inputlineno).}\fi\global\@IEEEWARNandfalse} + +\ifCLASSOPTIONconference% +\renewcommand{\and}[1][\hfill]{\end{@IEEEauthorhalign}#1\begin{@IEEEauthorhalign}}% +\fi +\ifCLASSOPTIONpeerreviewca +\renewcommand{\and}[1][\hfill]{\end{@IEEEauthorhalign}#1\begin{@IEEEauthorhalign}}% +\fi +% V1.8 transmag uses conference author format +\ifCLASSOPTIONtransmag +\renewcommand{\and}[1][\hfill]{\end{@IEEEauthorhalign}#1\begin{@IEEEauthorhalign}}% +\fi + +% page clearing command +% based on LaTeX2e's \cleardoublepage, but allows different page styles +% for the inserted blank pages +\def\@IEEEcleardoublepage#1{\clearpage\if@twoside\ifodd\c@page\else +\hbox{}\thispagestyle{#1}\newpage\if@twocolumn\hbox{}\thispagestyle{#1}\newpage\fi\fi\fi} + +% V1.8b hooks to allow adjustment of space above title +\def\IEEEtitletopspace{0.5\baselineskip} +% an added extra amount to allow for adjustment/offset +\def\IEEEtitletopspaceextra{0pt} + +% user command to invoke the title page +\def\maketitle{\par% + \begingroup% + \normalfont% + \def\thefootnote{}% the \thanks{} mark type is empty + \def\footnotemark{}% and kill space from \thanks within author + \let\@makefnmark\relax% V1.7, must *really* kill footnotemark to remove all \textsuperscript spacing as well. + \footnotesize% equal spacing between thanks lines + \footnotesep 0.7\baselineskip%see global setting of \footnotesep for more info + % V1.7 disable \thanks note indention for compsoc + \@IEEEcompsoconly{\long\def\@makefntext##1{\parindent 1em\noindent\hbox{\@makefnmark}##1}}% + \normalsize% + \ifCLASSOPTIONpeerreview + \newpage\global\@topnum\z@ \@maketitle\@IEEEstatictitlevskip\@IEEEaftertitletext% + \thispagestyle{IEEEpeerreviewcoverpagestyle}\@thanks% + \else + \if@twocolumn% + \ifCLASSOPTIONtechnote% + \newpage\global\@topnum\z@ \@maketitle\@IEEEstatictitlevskip\@IEEEaftertitletext% + \else + \twocolumn[{\IEEEquantizevspace{\@maketitle}[\IEEEquantizedisabletitlecmds]{0pt}[-\topskip]{\baselineskip}{\@IEEENORMtitlevspace}{\@IEEEMINtitlevspace}\@IEEEaftertitletext}]% + \fi + \else + \newpage\global\@topnum\z@ \@maketitle\@IEEEstatictitlevskip\@IEEEaftertitletext% + \fi + \thispagestyle{IEEEtitlepagestyle}\@thanks% + \fi + % pullup page for pubid if used. + \if@IEEEusingpubid + \enlargethispage{-\@IEEEpubidpullup}% + \fi + \endgroup + \setcounter{footnote}{0}\let\maketitle\relax\let\@maketitle\relax + \gdef\@thanks{}% + % v1.6b do not clear these as we will need the title again for peer review papers + % \gdef\@author{}\gdef\@title{}% + \let\thanks\relax} + + +% V1.8 parbox to format \@IEEEtitleabstractindextext +\long\def\@IEEEtitleabstractindextextbox#1{\parbox{1\textwidth}{#1}} +% V1.8 compsoc is partial width +\ifCLASSOPTIONcompsoc +% comparison with proofs suggests it's in the range of 92.1-92.3% +\long\def\@IEEEtitleabstractindextextbox#1{\parbox{0.922\textwidth}{\@IEEEcompsocnotconfonly{\rightskip\@flushglue\leftskip\z@skip}#1}} +\fi + +% formats the Title, authors names, affiliations and special paper notice +% THIS IS A CONTROLLED SPACING COMMAND! Do not allow blank lines or unintentional +% spaces to enter the definition - use % at the end of each line +\def\@maketitle{\newpage +\bgroup\par\vskip\IEEEtitletopspace\vskip\IEEEtitletopspaceextra\centering% +\ifCLASSOPTIONtechnote% technotes, V1.8a abstract and index terms are not treated differently for compsoc technotes + {\bfseries\large\@IEEEcompsoconly{\Large\sffamily}\@title\par}\vskip 1.3em{\lineskip .5em\@IEEEcompsoconly{\large\sffamily}\@author + \@IEEEspecialpapernotice\par}\relax +\else% not a technote + \vskip0.2em{\Huge\ifCLASSOPTIONtransmag\bfseries\LARGE\fi\@IEEEcompsoconly{\sffamily}\@IEEEcompsocconfonly{\normalfont\normalsize\vskip 2\@IEEEnormalsizeunitybaselineskip + \bfseries\Large}\@IEEEcompsocnotconfonly{\vskip 0.75\@IEEEnormalsizeunitybaselineskip}\@title\par}\relax + \@IEEEcompsocnotconfonly{\vskip 0.5\@IEEEnormalsizeunitybaselineskip}\vskip1.0em\par% + % V1.6 handle \author differently if in conference mode + \ifCLASSOPTIONconference% + {\@IEEEspecialpapernotice\mbox{}\vskip\@IEEEauthorblockconfadjspace% + \mbox{}\hfill\begin{@IEEEauthorhalign}\@author\end{@IEEEauthorhalign}\hfill\mbox{}\par}\relax + \else% peerreviewca, peerreview or journal + \ifCLASSOPTIONpeerreviewca + % peerreviewca handles author names just like conference mode + {\@IEEEcompsoconly{\sffamily}\@IEEEspecialpapernotice\mbox{}\vskip\@IEEEauthorblockconfadjspace% + \mbox{}\hfill\begin{@IEEEauthorhalign}\@author\end{@IEEEauthorhalign}\hfill\mbox{}\par + {\@IEEEcompsoconly{\vskip 1.5em\relax + \@IEEEtitleabstractindextextbox{\@IEEEtitleabstractindextext}\par\noindent\hfill + \IEEEcompsocdiamondline\hfill\hbox{}\par}}}\relax + \else% journal, peerreview or transmag + \ifCLASSOPTIONtransmag + % transmag also handles author names just like conference mode + % it also uses \@IEEEtitleabstractindextex, but with one line less + % space above, and one more below + {\@IEEEspecialpapernotice\mbox{}\vskip\@IEEEauthorblockconfadjspace% + \mbox{}\hfill\begin{@IEEEauthorhalign}\@author\end{@IEEEauthorhalign}\hfill\mbox{}\par + {\vspace{0.5\baselineskip}\relax\@IEEEtitleabstractindextextbox{\@IEEEtitleabstractindextext}\vspace{-1\baselineskip}\par}}\relax + \else% journal or peerreview + {\lineskip.5em\@IEEEcompsoconly{\sffamily}\sublargesize\@author\@IEEEspecialpapernotice\par + {\@IEEEcompsoconly{\vskip 1.5em\relax + \@IEEEtitleabstractindextextbox{\@IEEEtitleabstractindextext}\par\noindent\hfill + \IEEEcompsocdiamondline\hfill\hbox{}\par}}}\relax + \fi + \fi + \fi +\fi\par\addvspace{0.5\baselineskip}\egroup} + + +% V1.7 Computer Society "diamond line" which follows index terms for nonconference papers +% V1.8a full width diamond line for single column use +\def\@IEEEcompsocdiamondlinei{\vrule depth 0pt height 0.5pt width 4cm\nobreak\hspace{7.5pt}\nobreak +\raisebox{-3.5pt}{\fontfamily{pzd}\fontencoding{U}\fontseries{m}\fontshape{n}\fontsize{11}{12}\selectfont\char70}\nobreak +\hspace{7.5pt}\nobreak\vrule depth 0pt height 0.5pt width 4cm\relax} +% V1.8a narrower width diamond line for double column use +\def\@IEEEcompsocdiamondlineii{\vrule depth 0pt height 0.5pt width 2.5cm\nobreak\hspace{7.5pt}\nobreak +\raisebox{-3.5pt}{\fontfamily{pzd}\fontencoding{U}\fontseries{m}\fontshape{n}\fontsize{11}{12}\selectfont\char70}\nobreak +\hspace{7.5pt}\nobreak\vrule depth 0pt height 0.5pt width 2.5cm\relax} +% V1.8a bare core without rules to base a last resort on for very narrow linewidths +\def\@IEEEcompsocdiamondlineiii{\mbox{}\nobreak\hspace{7.5pt}\nobreak +\raisebox{-3.5pt}{\fontfamily{pzd}\fontencoding{U}\fontseries{m}\fontshape{n}\fontsize{11}{12}\selectfont\char70}\nobreak +\hspace{7.5pt}\nobreak\mbox{}\relax} + +% V1.8a allow \IEEEcompsocdiamondline to adjust for different linewidths. +% Use \@IEEEcompsocdiamondlinei if its width is less than 0.66\linewidth (0.487 nominal for single column) +% if not, fall back to \@IEEEcompsocdiamondlineii if its width is less than 0.75\linewidth (0.659 nominal for double column) +% if all else fails, try to make a custom diamondline based on the abnormally narrow linewidth +\def\IEEEcompsocdiamondline{\settowidth{\@IEEEtrantmpdimenA}{\@IEEEcompsocdiamondlinei}\relax +\ifdim\@IEEEtrantmpdimenA<0.66\linewidth\relax\@IEEEcompsocdiamondlinei\relax +\else +\settowidth{\@IEEEtrantmpdimenA}{\@IEEEcompsocdiamondlineii}\relax +\ifdim\@IEEEtrantmpdimenA<0.75\linewidth\relax\@IEEEcompsocdiamondlineii\relax +\else +\settowidth{\@IEEEtrantmpdimenA}{\@IEEEcompsocdiamondlineiii}\relax +\@IEEEtrantmpdimenB=\linewidth\relax +\addtolength{\@IEEEtrantmpdimenB}{-1\@IEEEtrantmpdimenA}\relax +\vrule depth 0pt height 0.5pt width 0.33\@IEEEtrantmpdimenB\@IEEEcompsocdiamondlineiii\vrule depth 0pt height 0.5pt width 0.33\@IEEEtrantmpdimenB\relax +\fi\fi} + + +% V1.7 standard LateX2e \thanks, but with \itshape under compsoc. Also make it a \long\def +% We also need to trigger the one-shot footnote rule +\def\@IEEEtriggeroneshotfootnoterule{\global\@IEEEenableoneshotfootnoteruletrue} + + +\long\def\thanks#1{\footnotemark + \protected@xdef\@thanks{\@thanks + \protect\footnotetext[\the\c@footnote]{\@IEEEcompsoconly{\itshape + \protect\@IEEEtriggeroneshotfootnoterule\relax}\ignorespaces#1}}} +\let\@thanks\@empty + + +% V1.7 allow \author to contain \par's. This is needed to allow \thanks to contain \par. +\long\def\author#1{\gdef\@author{#1}} + + +% in addition to setting up IEEEitemize, we need to remove a baselineskip space above and +% below it because \list's \pars introduce blank lines because of the footnote struts. +\def\@IEEEsetupcompsocitemizelist{\def\labelitemi{$\bullet$}% +\setlength{\IEEElabelindent}{0pt}\setlength{\labelsep}{1.2em}\setlength{\parskip}{0pt}% +\setlength{\partopsep}{0pt}\setlength{\topsep}{0.5\baselineskip}\vspace{-1\baselineskip}\relax} + + +% flag for fake non-compsoc \IEEEcompsocthanksitem - prevents line break on very first item +\newif\if@IEEEbreakcompsocthanksitem \@IEEEbreakcompsocthanksitemfalse + +\ifCLASSOPTIONcompsoc +% V1.7 compsoc bullet item \thanks +% also, we need to redefine this to destroy the argument in \IEEEquantizevspace +\long\def\IEEEcompsocitemizethanks#1{\relax\@IEEEbreakcompsocthanksitemfalse\footnotemark + \protected@xdef\@thanks{\@thanks + \protect\footnotetext[\the\c@footnote]{\itshape\protect\@IEEEtriggeroneshotfootnoterule + {\let\IEEEiedlistdecl\relax\protect\begin{IEEEitemize}[\protect\@IEEEsetupcompsocitemizelist]\ignorespaces#1\relax + \protect\end{IEEEitemize}}\protect\vspace{-1\baselineskip}}}} +\DeclareRobustCommand*{\IEEEcompsocthanksitem}{\item} +\else +% non-compsoc, allow for dual compilation via rerouting to normal \thanks +\long\def\IEEEcompsocitemizethanks#1{\thanks{#1}} +% redirect to "pseudo-par" \hfil\break\indent after swallowing [] from \IEEEcompsocthanksitem[] +\DeclareRobustCommand{\IEEEcompsocthanksitem}{\@ifnextchar [{\@IEEEthanksswallowoptionalarg}% +{\@IEEEthanksswallowoptionalarg[\relax]}} +% be sure and break only after first item, be sure and ignore spaces after optional argument +\def\@IEEEthanksswallowoptionalarg[#1]{\relax\if@IEEEbreakcompsocthanksitem\hfil\break +\indent\fi\@IEEEbreakcompsocthanksitemtrue\ignorespaces} +\fi + + +% V1.6b define the \IEEEpeerreviewmaketitle as needed +\ifCLASSOPTIONpeerreview +\def\IEEEpeerreviewmaketitle{\@IEEEcleardoublepage{empty}% +\ifCLASSOPTIONtwocolumn +\twocolumn[{\IEEEquantizevspace{\@IEEEpeerreviewmaketitle}[\IEEEquantizedisabletitlecmds]{0pt}[-\topskip]{\baselineskip}{\@IEEENORMtitlevspace}{\@IEEEMINtitlevspace}}] +\else +\newpage\@IEEEpeerreviewmaketitle\@IEEEstatictitlevskip +\fi +\thispagestyle{IEEEtitlepagestyle}} +\else +% \IEEEpeerreviewmaketitle does nothing if peer review option has not been selected +\def\IEEEpeerreviewmaketitle{\relax} +\fi + +% peerreview formats the repeated title like the title in journal papers. +\def\@IEEEpeerreviewmaketitle{\bgroup\par\addvspace{0.5\baselineskip}\centering\@IEEEcompsoconly{\sffamily}% +\normalfont\normalsize\vskip0.2em{\Huge\@title\par}\vskip1.0em\par +\par\addvspace{0.5\baselineskip}\egroup} + + + +% V1.6 +% this is a static rubber spacer between the title/authors and the main text +% used for single column text, or when the title appears in the first column +% of two column text (technotes). +\def\@IEEEstatictitlevskip{{\normalfont\normalsize +% adjust spacing to next text +% v1.6b handle peer review papers +\ifCLASSOPTIONpeerreview +% for peer review papers, the same value is used for both title pages +% regardless of the other paper modes + \vskip 1\baselineskip plus 0.375\baselineskip minus 0.1875\baselineskip +\else + \ifCLASSOPTIONconference% conference + \vskip 1\baselineskip plus 0.375\baselineskip minus 0.1875\baselineskip% + \else% + \ifCLASSOPTIONtechnote% technote + \vskip 1\baselineskip plus 0.375\baselineskip minus 0.1875\baselineskip% + \else% journal uses more space + \vskip 2.5\baselineskip plus 0.75\baselineskip minus 0.375\baselineskip% + \fi + \fi +\fi}} + + +% set the nominal and minimum values for the quantized title spacer +% the quantization algorithm will not allow the spacer size to +% become less than \@IEEEMINtitlevspace - instead it will be lengthened +% default to journal values +\def\@IEEENORMtitlevspace{2.5\baselineskip} +\def\@IEEEMINtitlevspace{2\baselineskip} +% conferences and technotes need tighter spacing +\ifCLASSOPTIONconference% conference + \def\@IEEENORMtitlevspace{1\baselineskip} + \def\@IEEEMINtitlevspace{0.75\baselineskip} +\fi +\ifCLASSOPTIONtechnote% technote + \def\@IEEENORMtitlevspace{1\baselineskip} + \def\@IEEEMINtitlevspace{0.75\baselineskip} +\fi + + +% V1.8a +\def\IEEEquantizevspace{\begingroup\@ifstar{\@IEEEquantizevspacestarformtrue\@IEEEquantizevspace}{\@IEEEquantizevspacestarformfalse\@IEEEquantizevspace}} +% \IEEEquantizevspace[output dimen register]{object}[object decl] +% {top baselineskip} +% [offset][prevdepth][lineskip limit][lineskip] +% {unit height}{nominal vspace}{minimum vspace} +% +% Calculates and creates the vspace needed to make the combined height with +% the given object an integer multiple of the given unit height. This command +% is more general than the older \@IEEEdynamictitlevspace it replaces. +% +% The star form has no effect at present, but is reserved for future use. +% +% If the optional argument [output dimen register] is given, the calculated +% vspace height is stored in the given output dimen (or skip) register +% and no other action is taken, otherwise the object followed by a vspace* +% of the appropriate height is evaluated/output. +% +% The optional object decl (declarations) is code that is evaluated just +% before the object's height is evaluated. Its intented purpose is to allow +% for the alteration or disabling of code within the object during internal +% height evaluation (e.g., \long\def\thanks#1{\relax} ). +% This special code is not invoked if/when the object is rendered at the end. +% +% The nominal vspace is the target value of the added vspace and the minimum +% vspace is the lower allowed limit. The vspacer will be the value that achieves +% integral overall height, in terms of the given unit height, that is closest +% to the nominal vspace and that is not less than the specified minimum vspace. +% +% The line spacing algorithm of TeX is somewhat involved and requires special +% care with regard to the first line of a vertical list (which is indicated +% when \prevdepth is -1000pt or less). top baselineskip specifies the +% baselineskip or topskip used prior to the object. If the height of the +% first line of the object is greater than the given top baselineskip, then +% the top baselineskip is subtracted from the height of the first line and +% that difference is considered along with the rest of the object height +% (because the object will be shifted down by an amount = +% top line height - top baselineskip). Otherwise, the height of the first line +% of the object is ignored as far as the calculations are concerned. +% This algorithm is adequate for objects that appear at the top of a page +% (e.g., titles) where \topskip spacing is used. +% +% However, as explained on page 78 of the TeXbook, interline spacing is more +% complex when \baselineskip is being used (indicated by \prevdepth > +% -1000pt). The four optional parameters offset, prevdepth, lineskip limit and +% lineskip are assumed to be equal to be 0pt, \prevdepth, \lineskiplimit and +% \lineskip, respectively, if they are omitted. +% +% The prevdepth is the depth of the line before the object, the lineskip limit +% specifies how close the top of the object can come to the bottom of the +% previous line before \baselineskip is ignored and \lineskip is inserted +% between the object and the line above it. Lineskip does not come into +% play unless the first line of the object is high enough to "get too close" +% (as specified by lineskiplimit) to the line before it. The the prevdepth, +% lineskip limit, and lineskip optional parameters are not needed for the +% first object/line on a page (i.e., prevdepth <= -1000pt) where the simplier +% \topskip spacing rules are in effect. +% +% Offset is a manual adjustment that is added to the height calculations of +% object irrespective of the value of \prevdepth. It is useful when the top +% baselineskip will result in a noninteger unit height object placement even +% if the object itself has integral height. e.g., a footnotesize baselineskip +% is used before the object, thus an offset of, say -3pt, can be given as a +% correction. + +% Common combinations of these parameters include: +% +% top baselineskip: (and default values for offset, prevdepth, etc.) +% \topskip % for objects that appear at the top of a page +% \maxdimen % always ignore the height of the top line +% 0pt % always consider any positive height of the top line +% +% for objects to appear inline in normal text: +% top baselineskip = \baselineskip +% +% set prevdepth = -1000pt and top baselineskip = 0pt to consider the +% overall height of the object without any other external skip +% consideration + +\newif\if@IEEEquantizevspacestarform % flag to indicate star form +\newif\if@IEEEquantizevspaceuseoutdimenreg % flag to indicate output dimen register is to be used +% Use our own private registers because the object could contain a +% structure that uses the existing tmp scratch pad registers +\newdimen\@IEEEquantizeheightA +\newdimen\@IEEEquantizeheightB +\newdimen\@IEEEquantizeheightC +\newdimen\@IEEEquantizeprevdepth % need to save this early as can change +\newcount\@IEEEquantizemultiple +\newbox\@IEEEquantizeboxA + + +\def\@IEEEquantizevspace{\@ifnextchar [{\@IEEEquantizevspaceuseoutdimenregtrue\@@IEEEquantizevspace}{\@IEEEquantizevspaceuseoutdimenregfalse\@@IEEEquantizevspace[]}} + + +\long\def\@@IEEEquantizevspace[#1]#2{\relax +% acquire and store +% #1 optional output dimen register +% #2 object +\edef\@IEEEquantizeoutdimenreg{#1}\relax +% allow for object specifications that contain parameters +\@IEEEtrantmptoksA={#2}\relax +\long\edef\@IEEEquantizeobject{\the\@IEEEtrantmptoksA}\relax +\@ifnextchar [{\@@@IEEEquantizevspace}{\@@@IEEEquantizevspace[\relax]}} + +\long\def\@@@IEEEquantizevspace[#1]#2{\relax +% acquire and store +% [#1] optional object decl, is \relax if not given by user +% #2 top baselineskip +% allow for object decl specifications that have parameters +\@IEEEtrantmptoksA={#1}\relax +\long\edef\@IEEEquantizeobjectdecl{\the\@IEEEtrantmptoksA}\relax +\edef\@IEEEquantizetopbaselineskip{#2}\ivIEEEquantizevspace} + +% acquire optional argument set and store +% [offset][prevdepth][lineskip limit][lineskip] +\def\ivIEEEquantizevspace{\@ifnextchar [{\@vIEEEquantizevspace}{\@vIEEEquantizevspace[0pt]}} +\def\@vIEEEquantizevspace[#1]{\edef\@IEEEquantizeoffset{#1}\@ifnextchar [{\@viIEEEquantizevspace}{\@viIEEEquantizevspace[\prevdepth]}} +\def\@viIEEEquantizevspace[#1]{\@IEEEquantizeprevdepth=#1\relax\@ifnextchar [{\@viiIEEEquantizevspace}{\@viiIEEEquantizevspace[\lineskiplimit]}} +\def\@viiIEEEquantizevspace[#1]{\edef\@IEEEquantizelineskiplimit{#1}\@ifnextchar [{\@viiiIEEEquantizevspace}{\@viiiIEEEquantizevspace[\lineskip]}} +\def\@viiiIEEEquantizevspace[#1]{\edef\@IEEEquantizelineskip{#1}\@ixIEEEquantizevspace} + +% main routine +\def\@ixIEEEquantizevspace#1#2#3{\relax +\edef\@IEEEquantizeunitheight{#1}\relax +\edef\@IEEEquantizenomvspace{#2}\relax +\edef\@IEEEquantizeminvspace{#3}\relax +% \@IEEEquantizeoutdimenreg +% \@IEEEquantizeobject +% \@IEEEquantizeobjectdecl +% \@IEEEquantizetopbaselineskip +% \@IEEEquantizeoffset +% \@IEEEquantizeprevdepth +% \@IEEEquantizelineskiplimit +% \@IEEEquantizelineskip +% \@IEEEquantizeunitheight +% \@IEEEquantizenomvspace +% \@IEEEquantizeminvspace +% get overall height of object +\setbox\@IEEEquantizeboxA\vbox{\begingroup\@IEEEquantizeobjectdecl\@IEEEquantizeobject\relax\endgroup}\relax +\@IEEEquantizeheightA\ht\@IEEEquantizeboxA\relax +% get height of first line of object +\setbox\@IEEEquantizeboxA\vtop{\begingroup\@IEEEquantizeobjectdecl\@IEEEquantizeobject\relax\endgroup}\relax +\@IEEEquantizeheightB\ht\@IEEEquantizeboxA\relax +\ifdim\@IEEEquantizeprevdepth>-1000pt\relax % prevdepth > -1000pf means full baselineskip\lineskip rules in effect +% lineskip spacing rule takes effect if height of top line > baselineskip - prevdepth - lineskiplimit, +% otherwise the baselineskip rule is in effect and the height of the first line does not matter at all. +\@IEEEquantizeheightC=\@IEEEquantizetopbaselineskip\relax +\advance\@IEEEquantizeheightC-\@IEEEquantizeprevdepth\relax +\advance\@IEEEquantizeheightC-\@IEEEquantizelineskiplimit\relax % this works even though \@IEEEquantizelineskiplimit is a macro because TeX allows --10pt notation +\ifdim\@IEEEquantizeheightB>\@IEEEquantizeheightC\relax +% lineskip spacing rule is in effect i.e., the object is going to be shifted down relative to the +% baselineskip set position by its top line height (already a part of the total height) + prevdepth + lineskip - baselineskip +\advance\@IEEEquantizeheightA\@IEEEquantizeprevdepth\relax +\advance\@IEEEquantizeheightA\@IEEEquantizelineskip\relax +\advance\@IEEEquantizeheightA-\@IEEEquantizetopbaselineskip\relax +\else +% height of first line <= \@IEEEquantizetopbaselineskip - \@IEEEquantizeprevdepth - \@IEEEquantizelineskiplimit +% standard baselineskip rules are in effect, so don't consider height of first line +\advance\@IEEEquantizeheightA-\@IEEEquantizeheightB\relax +\fi +% +\else % prevdepth <= -1000pt, simplier \topskip type rules in effect +\ifdim\@IEEEquantizeheightB>\@IEEEquantizetopbaselineskip +% height of top line (already included in the total height) in excess of +% baselineskip is the amount it will be downshifted +\advance\@IEEEquantizeheightA-\@IEEEquantizetopbaselineskip\relax +\else +% height of first line is irrelevant, remove it +\advance\@IEEEquantizeheightA-\@IEEEquantizeheightB\relax +\fi +\fi % prevdepth <= -1000pt +% +% adjust height for any manual offset +\advance\@IEEEquantizeheightA\@IEEEquantizeoffset\relax +% add in nominal spacer +\advance\@IEEEquantizeheightA\@IEEEquantizenomvspace\relax +% check for nonzero unitheight +\@IEEEquantizeheightB=\@IEEEquantizeunitheight\relax +\ifnum\@IEEEquantizeheightB=0\relax +\@IEEEclspkgerror{IEEEquantizevspace unit height cannot be zero. Assuming 10pt.}% +{Division by zero is not allowed.} +\@IEEEquantizeheightB=10pt\relax +\fi +% get integer number of lines +\@IEEEquantizemultiple=\@IEEEquantizeheightA\relax +\divide\@IEEEquantizemultiple\@IEEEquantizeheightB\relax +% set A to contain the excess height over the \@IEEEquantizemultiple of lines +% A = height - multiple*unitheight +\@IEEEquantizeheightC\@IEEEquantizeheightB\relax +\multiply\@IEEEquantizeheightC\@IEEEquantizemultiple\relax +\advance\@IEEEquantizeheightA-\@IEEEquantizeheightC\relax +% set B to contain the height short of \@IEEEquantizemultiple+1 of lines +% B = unitheight - A +\advance\@IEEEquantizeheightB-\@IEEEquantizeheightA\relax +% choose A or B based on which is closer +\@IEEEquantizeheightC\@IEEEquantizenomvspace\relax +\ifdim\@IEEEquantizeheightA<\@IEEEquantizeheightB\relax +% C = nomvspace - A, go with lower +\advance\@IEEEquantizeheightC-\@IEEEquantizeheightA\relax +\else +% C = nomvspace + B, go with upper +\advance\@IEEEquantizeheightC\@IEEEquantizeheightB\relax +\fi +% if violate lower bound, use next integer bound +\ifdim\@IEEEquantizeheightC<\@IEEEquantizeminvspace\relax +% A + B = unitheight +\advance\@IEEEquantizeheightC\@IEEEquantizeheightA\relax +\advance\@IEEEquantizeheightC\@IEEEquantizeheightB\relax +\fi +% export object and spacer outside of group +\global\let\@IEEEquantizeobjectout\@IEEEquantizeobject\relax +\global\@IEEEquantizeheightC\@IEEEquantizeheightC\relax +\endgroup +\if@IEEEquantizevspaceuseoutdimenreg +\@IEEEquantizeoutdimenreg=\@IEEEquantizeheightC\relax +\else +\@IEEEquantizeobjectout\relax +\vskip\@IEEEquantizeheightC\relax +\fi} + + +% user command to disable all global assignments, possible use within object decl +\def\IEEEquantizedisableglobal{\let\global\relax +\let\gdef\def +\let\xdef\edef} +% user command to allow for the disabling of \thanks and other commands, possible use within object decl +\def\IEEEquantizedisabletitlecmds{\long\def\thanks##1{\relax}\relax +\long\def\IEEEcompsocitemizethanks##1{\relax}\def\newpage{\relax}} + + + + + +% V1.6 +% we allow the user access to the last part of the title area +% useful in emergencies such as when a different spacing is needed +% This text is NOT compensated for in the dynamic sizer. +\let\@IEEEaftertitletext=\relax +\long\def\IEEEaftertitletext#1{\def\@IEEEaftertitletext{#1}} + + +% V1.7 provide a way for users to enter abstract and keywords +% into the onecolumn title are. This text is compensated for +% in the dynamic sizer. +\let\@IEEEtitleabstractindextext=\relax +\long\def\IEEEtitleabstractindextext#1{\def\@IEEEtitleabstractindextext{#1}} + +% V1.7 provide a way for users to get the \@IEEEtitleabstractindextext if +% not in compsoc or transmag journal mode - this way abstract and keywords +% can still be placed in their conventional position if not in those modes. +\def\IEEEdisplaynontitleabstractindextext{% +% display for all conference formats +\ifCLASSOPTIONconference\@IEEEtitleabstractindextext\relax +\else% non-conferences + % V1.8a display for all technotes + \ifCLASSOPTIONtechnote\@IEEEtitleabstractindextext\relax + % V1.8a add diamond line after abstract and index terms for compsoc technotes + \@IEEEcompsoconly{\noindent\hfill\IEEEcompsocdiamondline\hfill\hbox{}\par}\relax + \else % non-conferences and non-technotes + \ifCLASSOPTIONcompsoc% display if not compsoc and not transmag + \else + \ifCLASSOPTIONtransmag + \else% not compsoc journal nor transmag journal + \@IEEEtitleabstractindextext\relax + \fi + \fi + \fi +\fi} + + +% command to allow alteration of baselinestretch, but only if the current +% baselineskip is unity. Used to tweak the compsoc abstract and keywords line spacing. +\def\@IEEEtweakunitybaselinestretch#1{{\def\baselinestretch{1}\selectfont +\global\@tempskipa\baselineskip}\ifnum\@tempskipa=\baselineskip% +\def\baselinestretch{#1}\selectfont\fi\relax} + + +% abstract and keywords are in \small, except +% for 9pt docs in which they are in \footnotesize +% Because 9pt docs use an 8pt footnotesize, \small +% becomes a rather awkward 8.5pt +\def\@IEEEabskeysecsize{\small} +\ifx\CLASSOPTIONpt\@IEEEptsizenine + \def\@IEEEabskeysecsize{\footnotesize} +\fi + +% compsoc journals use \footnotesize, compsoc conferences use normalsize +\@IEEEcompsoconly{\def\@IEEEabskeysecsize{\footnotesize}} +\@IEEEcompsocconfonly{\def\@IEEEabskeysecsize{\small}} + + +% V1.6 have abstract and keywords strip leading spaces, pars and newlines +% so that spacing is more tightly controlled. +\def\abstract{\normalfont + \if@twocolumn + \@IEEEabskeysecsize\bfseries\textit{\abstractname}---\relax + \else + \bgroup\par\addvspace{0.5\baselineskip}\centering\vspace{-1.78ex}\@IEEEabskeysecsize\textbf{\abstractname}\par\addvspace{0.5\baselineskip}\egroup\quotation\@IEEEabskeysecsize + \fi\@IEEEgobbleleadPARNLSP} +% V1.6 The IEEE wants only 1 pica from end of abstract to introduction heading when in +% conference mode (the heading already has this much above it) +\def\endabstract{\relax\ifCLASSOPTIONconference\vspace{0ex}\else\vspace{1.34ex}\fi\par\if@twocolumn\else\endquotation\fi + \normalfont\normalsize} + +\def\IEEEkeywords{\normalfont + \if@twocolumn + \@IEEEabskeysecsize\bfseries\textit{\IEEEkeywordsname}---\relax + \else + \bgroup\par\addvspace{0.5\baselineskip}\centering\@IEEEabskeysecsize\textbf{\IEEEkeywordsname}\par\addvspace{0.5\baselineskip}\egroup\quotation\@IEEEabskeysecsize + \fi\@IEEEgobbleleadPARNLSP} +\def\endIEEEkeywords{\relax\ifCLASSOPTIONtechnote\vspace{1.34ex}\else\vspace{0.67ex}\fi + \par\if@twocolumn\else\endquotation\fi% + \normalfont\normalsize} + +% V1.7 compsoc keywords index terms +\ifCLASSOPTIONcompsoc + \ifCLASSOPTIONconference% compsoc conference +\def\abstract{\normalfont\@IEEEtweakunitybaselinestretch{1.15}\bfseries + \if@twocolumn + \@IEEEabskeysecsize\noindent\textit{\abstractname}---\relax + \else + \bgroup\par\addvspace{0.5\baselineskip}\centering\vspace{-1.78ex}\@IEEEabskeysecsize\textbf{\abstractname}\par\addvspace{0.5\baselineskip}\egroup\quotation\@IEEEabskeysecsize% + \fi\@IEEEgobbleleadPARNLSP} +\def\IEEEkeywords{\normalfont\@IEEEtweakunitybaselinestretch{1.15}\bfseries + \if@twocolumn + \@IEEEabskeysecsize\vskip 0.5\baselineskip plus 0.25\baselineskip minus 0.25\baselineskip\noindent + \textit{\IEEEkeywordsname}---\relax + \else + \bgroup\par\addvspace{0.5\baselineskip}\centering\@IEEEabskeysecsize\textbf{\IEEEkeywordsname}\par\addvspace{0.5\baselineskip}\egroup\quotation\@IEEEabskeysecsize% + \fi\@IEEEgobbleleadPARNLSP} + \else% compsoc not conference +\def\abstract{\normalfont\@IEEEtweakunitybaselinestretch{1.15}\sffamily + \if@twocolumn + \@IEEEabskeysecsize\noindent\textbf{\abstractname}---\relax + \else + \bgroup\par\addvspace{0.5\baselineskip}\centering\vspace{-1.78ex}\@IEEEabskeysecsize\textbf{\abstractname}\par\addvspace{0.5\baselineskip}\egroup\quotation\@IEEEabskeysecsize% + \fi\@IEEEgobbleleadPARNLSP} +\def\IEEEkeywords{\normalfont\@IEEEtweakunitybaselinestretch{1.15}\sffamily + \if@twocolumn + \@IEEEabskeysecsize\vskip 0.5\baselineskip plus 0.25\baselineskip minus 0.25\baselineskip\noindent + \textbf{\IEEEkeywordsname}---\relax + \else + \bgroup\par\addvspace{0.5\baselineskip}\centering\@IEEEabskeysecsize\textbf{\IEEEkeywordsname}\par\addvspace{0.5\baselineskip}\egroup\quotation\@IEEEabskeysecsize% + \fi\@IEEEgobbleleadPARNLSP} + \fi +\fi + +% V1.8 transmag keywords index terms +% no abstract name, use indentation +\ifCLASSOPTIONtransmag +\def\abstract{\normalfont\parindent 1em\relax + \if@twocolumn + \@IEEEabskeysecsize\bfseries\indent + \else + \bgroup\par\addvspace{0.5\baselineskip}\centering\vspace{-1.78ex}\@IEEEabskeysecsize + \textbf{\abstractname}\par\addvspace{0.5\baselineskip}\egroup\quotation\@IEEEabskeysecsize + \fi\@IEEEgobbleleadPARNLSP} + +\def\IEEEkeywords{\normalfont\parindent 1em\relax + \if@twocolumn + \@IEEEabskeysecsize\vspace{1\baselineskip}\bfseries\indent\textit{\IEEEkeywordsname}---\relax + \else + \bgroup\par\vspace{1\baselineskip}\centering\@IEEEabskeysecsize + \textbf{\IEEEkeywordsname}\par\addvspace{0.5\baselineskip}\egroup\quotation\@IEEEabskeysecsize + \fi\@IEEEgobbleleadPARNLSP} +\fi + + + +% gobbles all leading \, \\ and \par, upon finding first token that +% is not a \ , \\ or a \par, it ceases and returns that token +% +% used to strip leading \, \\ and \par from the input +% so that such things in the beginning of an environment will not +% affect the formatting of the text +\long\def\@IEEEgobbleleadPARNLSP#1{\let\@IEEEswallowthistoken=0% +\let\@IEEEgobbleleadPARNLSPtoken#1% +\let\@IEEEgobbleleadPARtoken=\par% +\let\@IEEEgobbleleadNLtoken=\\% +\let\@IEEEgobbleleadSPtoken=\ % +\def\@IEEEgobbleleadSPMACRO{\ }% +\ifx\@IEEEgobbleleadPARNLSPtoken\@IEEEgobbleleadPARtoken% +\let\@IEEEswallowthistoken=1% +\fi% +\ifx\@IEEEgobbleleadPARNLSPtoken\@IEEEgobbleleadNLtoken% +\let\@IEEEswallowthistoken=1% +\fi% +\ifx\@IEEEgobbleleadPARNLSPtoken\@IEEEgobbleleadSPtoken% +\let\@IEEEswallowthistoken=1% +\fi% +% a control space will come in as a macro +% when it is the last one on a line +\ifx\@IEEEgobbleleadPARNLSPtoken\@IEEEgobbleleadSPMACRO% +\let\@IEEEswallowthistoken=1% +\fi% +% if we have to swallow this token, do so and taste the next one +% else spit it out and stop gobbling +\ifx\@IEEEswallowthistoken 1\let\@IEEEnextgobbleleadPARNLSP=\@IEEEgobbleleadPARNLSP\else% +\let\@IEEEnextgobbleleadPARNLSP=#1\fi% +\@IEEEnextgobbleleadPARNLSP}% + + + + +% TITLING OF SECTIONS +\def\@IEEEsectpunct{:\ \,} % Punctuation after run-in section heading (headings which are + % part of the paragraphs), need little bit more than a single space + % spacing from section number to title +% compsoc conferences use regular period/space punctuation +\ifCLASSOPTIONcompsoc +\ifCLASSOPTIONconference +\def\@IEEEsectpunct{.\ } +\fi\fi + + +\def\@seccntformat#1{\csname the#1dis\endcsname\hskip 0.5em\relax} + +\ifCLASSOPTIONcompsoc +% compsoc journals need extra spacing +\ifCLASSOPTIONconference\else +\def\@seccntformat#1{\csname the#1dis\endcsname\hskip 1em\relax} +\fi\fi + +%v1.7 put {} after #6 to allow for some types of user font control +%and use \@@par rather than \par +\def\@sect#1#2#3#4#5#6[#7]#8{% + \ifnum #2>\c@secnumdepth + \let\@svsec\@empty + \else + \refstepcounter{#1}% + % load section label and spacer into \@svsec + \protected@edef\@svsec{\@seccntformat{#1}\relax}% + \fi% + \@tempskipa #5\relax + \ifdim \@tempskipa>\z@% tempskipa determines whether is treated as a high + \begingroup #6{\relax% or low level heading + \noindent % subsections are NOT indented + % print top level headings. \@svsec is label, #8 is heading title + % The IEEE does not block indent the section title text, it flows like normal + {\hskip #3\relax\@svsec}{\interlinepenalty \@M #8\@@par}}% + \endgroup + \addcontentsline{toc}{#1}{\ifnum #2>\c@secnumdepth\relax\else + \protect\numberline{\csname the#1\endcsname}\fi#7}% + \else % printout low level headings + % svsechd seems to swallow the trailing space, protect it with \mbox{} + % got rid of sectionmark stuff + \def\@svsechd{#6{\hskip #3\relax\@svsec #8\@IEEEsectpunct\mbox{}}% + \addcontentsline{toc}{#1}{\ifnum #2>\c@secnumdepth\relax\else + \protect\numberline{\csname the#1\endcsname}\fi#7}}% + \fi%skip down + \@xsect{#5}} + + +% section* handler +%v1.7 put {} after #4 to allow for some types of user font control +%and use \@@par rather than \par +\def\@ssect#1#2#3#4#5{\@tempskipa #3\relax + \ifdim \@tempskipa>\z@ + %\begingroup #4\@hangfrom{\hskip #1}{\interlinepenalty \@M #5\par}\endgroup + % The IEEE does not block indent the section title text, it flows like normal + \begingroup \noindent #4{\relax{\hskip #1}{\interlinepenalty \@M #5\@@par}}\endgroup + % svsechd swallows the trailing space, protect it with \mbox{} + \else \def\@svsechd{#4{\hskip #1\relax #5\@IEEEsectpunct\mbox{}}}\fi + \@xsect{#3}} + + +%% SECTION heading spacing and font +%% +% arguments are: #1 - sectiontype name +% (for \@sect) #2 - section level +% #3 - section heading indent +% #4 - top separation (absolute value used, neg indicates not to indent main text) +% If negative, make stretch parts negative too! +% #5 - (absolute value used) positive: bottom separation after heading, +% negative: amount to indent main text after heading +% Both #4 and #5 negative means to indent main text and use negative top separation +% #6 - font control +% You've got to have \normalfont\normalsize in the font specs below to prevent +% trouble when you do something like: +% \section{Note}{\ttfamily TT-TEXT} is known to ... +% The IEEE sometimes REALLY stretches the area before a section +% heading by up to about 0.5in. However, it may not be a good +% idea to let LaTeX have quite this much rubber. +\ifCLASSOPTIONconference% +% The IEEE wants section heading spacing to decrease for conference mode +\def\section{\@startsection{section}{1}{\z@}{1.5ex plus 1.5ex minus 0.5ex}% +{0.7ex plus 1ex minus 0ex}{\normalfont\normalsize\centering\scshape}}% +\def\subsection{\@startsection{subsection}{2}{\z@}{1.5ex plus 1.5ex minus 0.5ex}% +{0.7ex plus .5ex minus 0ex}{\normalfont\normalsize\itshape}}% +\else % for journals +\def\section{\@startsection{section}{1}{\z@}{3.0ex plus 1.5ex minus 1.5ex}% V1.6 3.0ex from 3.5ex +{0.7ex plus 1ex minus 0ex}{\normalfont\normalsize\centering\scshape}}% +\def\subsection{\@startsection{subsection}{2}{\z@}{3.5ex plus 1.5ex minus 1.5ex}% +{0.7ex plus .5ex minus 0ex}{\normalfont\normalsize\itshape}}% +\fi + +% for both journals and conferences +% decided to put in a little rubber above the section, might help somebody +\def\subsubsection{\@startsection{subsubsection}{3}{\parindent}{0ex plus 0.1ex minus 0.1ex}% +{0ex}{\normalfont\normalsize\itshape}}% +\def\paragraph{\@startsection{paragraph}{4}{2\parindent}{0ex plus 0.1ex minus 0.1ex}% +{0ex}{\normalfont\normalsize\itshape}}% + + +% compsoc +\ifCLASSOPTIONcompsoc +\ifCLASSOPTIONconference +% compsoc conference +\def\section{\@startsection{section}{1}{\z@}{1\baselineskip plus 0.25\baselineskip minus 0.25\baselineskip}% +{1\baselineskip plus 0.25\baselineskip minus 0.25\baselineskip}{\normalfont\large\bfseries}}% +\def\subsection{\@startsection{subsection}{2}{\z@}{1\baselineskip plus 0.25\baselineskip minus 0.25\baselineskip}% +{1\baselineskip plus 0.25\baselineskip minus 0.25\baselineskip}{\normalfont\sublargesize\bfseries}}% +\def\subsubsection{\@startsection{subsubsection}{3}{\z@}{1\baselineskip plus 0.25\baselineskip minus 0.25\baselineskip}% +{0ex}{\normalfont\normalsize\bfseries}}% +\def\paragraph{\@startsection{paragraph}{4}{2\parindent}{0ex plus 0.1ex minus 0.1ex}% +{0ex}{\normalfont\normalsize}}% +\else% compsoc journals +% use negative top separation as compsoc journals do not indent paragraphs after section titles +\def\section{\@startsection{section}{1}{\z@}{-3.5ex plus -2ex minus -1.5ex}% +{0.7ex plus 1ex minus 0ex}{\normalfont\sublargesize\sffamily\bfseries\scshape}}% +% Note that subsection and smaller may not be correct for the Computer Society, +% I have to look up an example. +\def\subsection{\@startsection{subsection}{2}{\z@}{-3.5ex plus -1.5ex minus -1.5ex}% +{0.7ex plus .5ex minus 0ex}{\normalfont\normalsize\sffamily\bfseries}}% +\def\subsubsection{\@startsection{subsubsection}{3}{\z@}{-2.5ex plus -1ex minus -1ex}% +{0.5ex plus 0.5ex minus 0ex}{\normalfont\normalsize\sffamily\itshape}}% +\def\paragraph{\@startsection{paragraph}{4}{2\parindent}{-0ex plus -0.1ex minus -0.1ex}% +{0ex}{\normalfont\normalsize}}% +\fi\fi + +% transmag +\ifCLASSOPTIONtransmag +\def\subsection{\@startsection{subsection}{2}{0.75\parindent}{3.5ex plus 1.5ex minus 1.5ex}% +{0.7ex plus .5ex minus 0ex}{\normalfont\normalsize\itshape}}% +\def\subsubsection{\@startsection{subsubsection}{3}{1.25\parindent}{0.1ex plus 0.1ex minus 0.1ex}% +{0.1ex}{\normalfont\normalsize\itshape}}% +\fi + + +% V1.8a provide for a raised line Introduction section for use with Computer +% Society papers. We have to remove any spacing glue after the section +% heading and then remove the blank line for the new paragraph after it. +% LaTeX's section handler alters \everypar and we need to propogate those +% changes outside of the \parbox lest there be spacing problems at the top +% of the next section. +\def\IEEEraisesectionheading#1{\noindent\raisebox{1.5\baselineskip}[0pt][0pt]{\parbox[b]{\columnwidth}{#1\unskip\global\everypar=\everypar}}\vspace{-1\baselineskip}\vspace{-\parskip}\par} + + + +%% ENVIRONMENTS +% "box" symbols at end of proofs +\def\IEEEQEDclosed{\mbox{\rule[0pt]{1.3ex}{1.3ex}}} % for a filled box +% V1.6 some journals use an open box instead that will just fit around a closed one +\def\IEEEQEDopen{{\setlength{\fboxsep}{0pt}\setlength{\fboxrule}{0.2pt}\fbox{\rule[0pt]{0pt}{1.3ex}\rule[0pt]{1.3ex}{0pt}}}} +\ifCLASSOPTIONcompsoc +\def\IEEEQED{\IEEEQEDopen} % default to open for compsoc +\else +\def\IEEEQED{\IEEEQEDclosed} % otherwise default to closed +\fi + +%V1.8 flag to indicate if QED symbol is to be shown +\newif\if@IEEEQEDshow \@IEEEQEDshowtrue +\def\IEEEproofindentspace{2\parindent}% V1.8 allow user to change indentation amount if desired +% v1.7 name change to avoid namespace collision with amsthm. Also add support +% for an optional argument. +\def\IEEEproof{\@ifnextchar[{\@IEEEproof}{\@IEEEproof[\IEEEproofname]}} +\def\@IEEEproof[#1]{\@IEEEQEDshowtrue\par\noindent\hspace{\IEEEproofindentspace}{\itshape #1: }} +\def\endIEEEproof{\if@IEEEQEDshow\hspace*{\fill}\nobreakspace\IEEEQED\fi\par} +% qedhere for equation environments, similar to AMS \qedhere +\def\IEEEQEDhereeqn{\global\@IEEEQEDshowfalse\eqno\let\eqno\relax\let\leqno\relax + \let\veqno\relax\hbox{\IEEEQED}} +% IEEE style qedhere for IEEEeqnarray and other environments +\def\IEEEQEDhere{\global\@IEEEQEDshowfalse\IEEEQED} +% command to disable QED at end of IEEEproof +\def\IEEEQEDoff{\global\@IEEEQEDshowfalse} + + +%\itemindent is set to \z@ by list, so define new temporary variable +\newdimen\@IEEEtmpitemindent + +\ifCLASSOPTIONcompsoc +% V1.8a compsoc uses bold theorem titles, a period instead of a colon, vertical spacing, and hanging indentation +% V1.8 allow long theorem names to break across lines. +% Thanks to Miquel Payaro for reporting this. +\def\@begintheorem#1#2{\@IEEEtmpitemindent\itemindent\relax + \topsep 0.2\@IEEEnormalsizeunitybaselineskip plus 0.26\@IEEEnormalsizeunitybaselineskip minus 0.05\@IEEEnormalsizeunitybaselineskip + \rmfamily\trivlist\hangindent\parindent% + \item[]\textit{\bfseries\noindent #1\ #2.} \itemindent\@IEEEtmpitemindent\relax} +\def\@opargbegintheorem#1#2#3{\@IEEEtmpitemindent\itemindent\relax +\topsep 0.2\@IEEEnormalsizeunitybaselineskip plus 0.26\@IEEEnormalsizeunitybaselineskip minus 0.05\@IEEEnormalsizeunitybaselineskip +\rmfamily\trivlist\hangindent\parindent% +% V1.6 The IEEE is back to using () around theorem names which are also in italics +% Thanks to Christian Peel for reporting this. + \item[]\textit{\bfseries\noindent #1\ #2\ (#3).} \itemindent\@IEEEtmpitemindent\relax} +% V1.7 remove bogus \unskip that caused equations in theorems to collide with +% lines below. +\def\@endtheorem{\endtrivlist\vskip 0.25\@IEEEnormalsizeunitybaselineskip plus 0.26\@IEEEnormalsizeunitybaselineskip minus 0.05\@IEEEnormalsizeunitybaselineskip} +\else +% +% noncompsoc +% +% V1.8 allow long theorem names to break across lines. +% Thanks to Miquel Payaro for reporting this. +\def\@begintheorem#1#2{\@IEEEtmpitemindent\itemindent\relax\topsep 0pt\rmfamily\trivlist% + \item[]\textit{\indent #1\ #2:} \itemindent\@IEEEtmpitemindent\relax} +\def\@opargbegintheorem#1#2#3{\@IEEEtmpitemindent\itemindent\relax\topsep 0pt\rmfamily \trivlist% +% V1.6 The IEEE is back to using () around theorem names which are also in italics +% Thanks to Christian Peel for reporting this. + \item[]\textit{\indent #1\ #2\ (#3):} \itemindent\@IEEEtmpitemindent\relax} +% V1.7 remove bogus \unskip that caused equations in theorems to collide with +% lines below. +\def\@endtheorem{\endtrivlist} +\fi + + + +% V1.6 +% display command for the section the theorem is in - so that \thesection +% is not used as this will be in Roman numerals when we want arabic. +% LaTeX2e uses \def\@thmcounter#1{\noexpand\arabic{#1}} for the theorem number +% (second part) display and \def\@thmcountersep{.} as a separator. +% V1.7 intercept calls to the section counter and reroute to \@IEEEthmcounterinsection +% to allow \appendix(ices} to override as needed. +% +% special handler for sections, allows appendix(ices) to override +\gdef\@IEEEthmcounterinsection#1{\arabic{#1}} +% string macro +\edef\@IEEEstringsection{section} + +% redefine the #1#2[#3] form of newtheorem to use a hook to \@IEEEthmcounterinsection +% if section in_counter is used +\def\@xnthm#1#2[#3]{% + \expandafter\@ifdefinable\csname #1\endcsname + {\@definecounter{#1}\@newctr{#1}[#3]% + \edef\@IEEEstringtmp{#3} + \ifx\@IEEEstringtmp\@IEEEstringsection + \expandafter\xdef\csname the#1\endcsname{% + \noexpand\@IEEEthmcounterinsection{#3}\@thmcountersep + \@thmcounter{#1}}% + \else + \expandafter\xdef\csname the#1\endcsname{% + \expandafter\noexpand\csname the#3\endcsname \@thmcountersep + \@thmcounter{#1}}% + \fi + \global\@namedef{#1}{\@thm{#1}{#2}}% + \global\@namedef{end#1}{\@endtheorem}}} + + + +%% SET UP THE DEFAULT PAGESTYLE +\pagestyle{headings} +\pagenumbering{arabic} + +% normally the page counter starts at 1 +\setcounter{page}{1} +% however, for peerreview the cover sheet is page 0 or page -1 +% (for duplex printing) +\ifCLASSOPTIONpeerreview + \if@twoside + \setcounter{page}{-1} + \else + \setcounter{page}{0} + \fi +\fi + +% standard book class behavior - let bottom line float up and down as +% needed when single sided +\ifCLASSOPTIONtwoside\else\raggedbottom\fi +% if two column - turn on twocolumn, allow word spacings to stretch more and +% enforce a rigid position for the last lines +\ifCLASSOPTIONtwocolumn +% the peer review option delays invoking twocolumn + \ifCLASSOPTIONpeerreview\else + \twocolumn + \fi +\sloppy +\flushbottom +\fi + + + + +% \APPENDIX and \APPENDICES definitions + +% This is the \@ifmtarg command from the LaTeX ifmtarg package +% by Peter Wilson (CUA) and Donald Arseneau +% \@ifmtarg is used to determine if an argument to a command +% is present or not. +% For instance: +% \@ifmtarg{#1}{\typeout{empty}}{\typeout{has something}} +% \@ifmtarg is used with our redefined \section command if +% \appendices is invoked. +% The command \section will behave slightly differently depending +% on whether the user specifies a title: +% \section{My appendix title} +% or not: +% \section{} +% This way, we can eliminate the blank lines where the title +% would be, and the unneeded : after Appendix in the table of +% contents +\begingroup +\catcode`\Q=3 +\long\gdef\@ifmtarg#1{\@xifmtarg#1QQ\@secondoftwo\@firstoftwo\@nil} +\long\gdef\@xifmtarg#1#2Q#3#4#5\@nil{#4} +\endgroup +% end of \@ifmtarg defs + + +% V1.7 +% command that allows the one time saving of the original definition +% of section to \@IEEEappendixsavesection for \appendix or \appendices +% we don't save \section here as it may be redefined later by other +% packages (hyperref.sty, etc.) +\def\@IEEEsaveoriginalsectiononce{\let\@IEEEappendixsavesection\section +\let\@IEEEsaveoriginalsectiononce\relax} + +% neat trick to grab and process the argument from \section{argument} +% we process differently if the user invoked \section{} with no +% argument (title) +% note we reroute the call to the old \section* +\def\@IEEEprocessthesectionargument#1{% +\@ifmtarg{#1}{% +\@IEEEappendixsavesection*{\appendixname\nobreakspace\thesectiondis}% +\addcontentsline{toc}{section}{\appendixname\nobreakspace\thesection}}{% +\@IEEEappendixsavesection*{\appendixname\nobreakspace\thesectiondis\\* #1}% +\addcontentsline{toc}{section}{\appendixname\nobreakspace\thesection: #1}}} + +% we use this if the user calls \section{} after +% \appendix-- which has no meaning. So, we ignore the +% command and its argument. Then, warn the user. +\def\@IEEEdestroythesectionargument#1{\typeout{** WARNING: Ignoring useless +\protect\section\space in Appendix (line \the\inputlineno).}} + + +% remember \thesection forms will be displayed in \ref calls +% and in the Table of Contents. +% The \sectiondis form is used in the actual heading itself + +% appendix command for one single appendix +% normally has no heading. However, if you want a +% heading, you can do so via the optional argument: +% \appendix[Optional Heading] +\def\appendix{\relax} +\renewcommand{\appendix}[1][]{\@IEEEsaveoriginalsectiononce\par + % v1.6 keep hyperref's identifiers unique + \gdef\theHsection{Appendix.A}% + % v1.6 adjust hyperref's string name for the section + \xdef\Hy@chapapp{appendix}% + \setcounter{section}{0}% + \setcounter{subsection}{0}% + \setcounter{subsubsection}{0}% + \setcounter{paragraph}{0}% + \gdef\thesection{A}% + \gdef\thesectiondis{}% + \gdef\thesubsection{\Alph{subsection}}% + \gdef\@IEEEthmcounterinsection##1{A} + \refstepcounter{section}% update the \ref counter + \@ifmtarg{#1}{\@IEEEappendixsavesection*{\appendixname}% + \addcontentsline{toc}{section}{\appendixname}}{% + \@IEEEappendixsavesection*{\appendixname\nobreakspace\\* #1}% + \addcontentsline{toc}{section}{\appendixname: #1}}% + % redefine \section command for appendix + % leave \section* as is + \def\section{\@ifstar{\@IEEEappendixsavesection*}{% + \@IEEEdestroythesectionargument}}% throw out the argument + % of the normal form +} + + + +% appendices command for multiple appendices +% user then calls \section with an argument (possibly empty) to +% declare the individual appendices +\def\appendices{\@IEEEsaveoriginalsectiononce\par + % v1.6 keep hyperref's identifiers unique + \gdef\theHsection{Appendix.\Alph{section}}% + % v1.6 adjust hyperref's string name for the section + \xdef\Hy@chapapp{appendix}% + \setcounter{section}{-1}% we want \refstepcounter to use section 0 + \setcounter{subsection}{0}% + \setcounter{subsubsection}{0}% + \setcounter{paragraph}{0}% + \ifCLASSOPTIONromanappendices% + \gdef\thesection{\Roman{section}}% + \gdef\thesectiondis{\Roman{section}}% + \@IEEEcompsocconfonly{\gdef\thesectiondis{\Roman{section}.}}% + \gdef\@IEEEthmcounterinsection##1{A\arabic{##1}} + \else% + \gdef\thesection{\Alph{section}}% + \gdef\thesectiondis{\Alph{section}}% + \@IEEEcompsocconfonly{\gdef\thesectiondis{\Alph{section}.}}% + \gdef\@IEEEthmcounterinsection##1{\Alph{##1}} + \fi% + \refstepcounter{section}% update the \ref counter + \setcounter{section}{0}% NEXT \section will be the FIRST appendix + % redefine \section command for appendices + % leave \section* as is + \def\section{\@ifstar{\@IEEEappendixsavesection*}{% process the *-form + \refstepcounter{section}% or is a new section so, + \@IEEEprocessthesectionargument}}% process the argument + % of the normal form +} + + + +% V1.7 compoc uses nonbold drop cap and small caps word style +\ifCLASSOPTIONcompsoc + \def\IEEEPARstartFONTSTYLE{\mdseries} + \def\IEEEPARstartWORDFONTSTYLE{\scshape} + \def\IEEEPARstartWORDCAPSTYLE{\relax} +\fi +% +% +% \IEEEPARstart +% Definition for the big two line drop cap letter at the beginning of the +% first paragraph of journal papers. The first argument is the first letter +% of the first word, the second argument is the remaining letters of the +% first word which will be rendered in upper case. +% In V1.6 this has been completely rewritten to: +% +% 1. no longer have problems when the user begins an environment +% within the paragraph that uses \IEEEPARstart. +% 2. auto-detect and use the current font family +% 3. revise handling of the space at the end of the first word so that +% interword glue will now work as normal. +% 4. produce correctly aligned edges for the (two) indented lines. +% +% We generalize things via control macros - playing with these is fun too. +% +% V1.7 added more control macros to make it easy for IEEEtrantools.sty users +% to change the font style. +% +% the number of lines that are indented to clear it +% may need to increase if using decenders +\providecommand{\IEEEPARstartDROPLINES}{2} +% minimum number of lines left on a page to allow a \@IEEEPARstart +% Does not take into consideration rubber shrink, so it tends to +% be overly cautious +\providecommand{\IEEEPARstartMINPAGELINES}{2} +% V1.7 the height of the drop cap is adjusted to match the height of this text +% in the current font (when \IEEEPARstart is called). +\providecommand{\IEEEPARstartHEIGHTTEXT}{T} +% the depth the letter is lowered below the baseline +% the height (and size) of the letter is determined by the sum +% of this value and the height of the \IEEEPARstartHEIGHTTEXT in the current +% font. It is a good idea to set this value in terms of the baselineskip +% so that it can respond to changes therein. +\providecommand{\IEEEPARstartDROPDEPTH}{1.1\baselineskip} +% V1.7 the font the drop cap will be rendered in, +% can take zero or one argument. +\providecommand{\IEEEPARstartFONTSTYLE}{\bfseries} +% V1.7 any additional, non-font related commands needed to modify +% the drop cap letter, can take zero or one argument. +\providecommand{\IEEEPARstartCAPSTYLE}{\MakeUppercase} +% V1.7 the font that will be used to render the rest of the word, +% can take zero or one argument. +\providecommand{\IEEEPARstartWORDFONTSTYLE}{\relax} +% V1.7 any additional, non-font related commands needed to modify +% the rest of the word, can take zero or one argument. +\providecommand{\IEEEPARstartWORDCAPSTYLE}{\MakeUppercase} +% This is the horizontal separation distance from the drop letter to the main text. +% Lengths that depend on the font (e.g., ex, em, etc.) will be referenced +% to the font that is active when \IEEEPARstart is called. +\providecommand{\IEEEPARstartSEP}{0.15em} +% V1.7 horizontal offset applied to the left of the drop cap. +\providecommand{\IEEEPARstartHOFFSET}{0em} +% V1.7 Italic correction command applied at the end of the drop cap. +\providecommand{\IEEEPARstartITLCORRECT}{\/} + +% width of the letter output, set globally. Can be used in \IEEEPARstartSEP +% or \IEEEPARstartHOFFSET, but not the height lengths. +\newdimen\IEEEPARstartletwidth +\IEEEPARstartletwidth 0pt\relax + +% definition of \IEEEPARstart +% THIS IS A CONTROLLED SPACING AREA, DO NOT ALLOW SPACES WITHIN THESE LINES +% +% The token \@IEEEPARstartfont will be globally defined after the first use +% of \IEEEPARstart and will be a font command which creates the big letter +% The first argument is the first letter of the first word and the second +% argument is the rest of the first word(s). +\def\IEEEPARstart#1#2{\par{% +% if this page does not have enough space, break it and lets start +% on a new one +\@IEEEtranneedspace{\IEEEPARstartMINPAGELINES\baselineskip}{\relax}% +% V1.7 move this up here in case user uses \textbf for \IEEEPARstartFONTSTYLE +% which uses command \leavevmode which causes an unwanted \indent to be issued +\noindent +% calculate the desired height of the big letter +% it extends from the top of \IEEEPARstartHEIGHTTEXT in the current font +% down to \IEEEPARstartDROPDEPTH below the current baseline +\settoheight{\@IEEEtrantmpdimenA}{\IEEEPARstartHEIGHTTEXT}% +\addtolength{\@IEEEtrantmpdimenA}{\IEEEPARstartDROPDEPTH}% +% extract the name of the current font in bold +% and place it in \@IEEEPARstartFONTNAME +\def\@IEEEPARstartGETFIRSTWORD##1 ##2\relax{##1}% +{\IEEEPARstartFONTSTYLE{\selectfont\edef\@IEEEPARstartFONTNAMESPACE{\fontname\font\space}% +\xdef\@IEEEPARstartFONTNAME{\expandafter\@IEEEPARstartGETFIRSTWORD\@IEEEPARstartFONTNAMESPACE\relax}}}% +% define a font based on this name with a point size equal to the desired +% height of the drop letter +\font\@IEEEPARstartsubfont\@IEEEPARstartFONTNAME\space at \@IEEEtrantmpdimenA\relax% +% save this value as a counter (integer) value (sp points) +\@IEEEtrantmpcountA=\@IEEEtrantmpdimenA% +% now get the height of the actual letter produced by this font size +\settoheight{\@IEEEtrantmpdimenB}{\@IEEEPARstartsubfont\IEEEPARstartCAPSTYLE{#1}}% +% If something bogus happens like the first argument is empty or the +% current font is strange, do not allow a zero height. +\ifdim\@IEEEtrantmpdimenB=0pt\relax% +\typeout{** WARNING: IEEEPARstart drop letter has zero height! (line \the\inputlineno)}% +\typeout{ Forcing the drop letter font size to 10pt.}% +\@IEEEtrantmpdimenB=10pt% +\fi% +% and store it as a counter +\@IEEEtrantmpcountB=\@IEEEtrantmpdimenB% +% Since a font size doesn't exactly correspond to the height of the capital +% letters in that font, the actual height of the letter, \@IEEEtrantmpcountB, +% will be less than that desired, \@IEEEtrantmpcountA +% we need to raise the font size, \@IEEEtrantmpdimenA +% by \@IEEEtrantmpcountA / \@IEEEtrantmpcountB +% But, TeX doesn't have floating point division, so we have to use integer +% division. Hence the use of the counters. +% We need to reduce the denominator so that the loss of the remainder will +% have minimal affect on the accuracy of the result +\divide\@IEEEtrantmpcountB by 200% +\divide\@IEEEtrantmpcountA by \@IEEEtrantmpcountB% +% Then reequalize things when we use TeX's ability to multiply by +% floating point values +\@IEEEtrantmpdimenB=0.005\@IEEEtrantmpdimenA% +\multiply\@IEEEtrantmpdimenB by \@IEEEtrantmpcountA% +% \@IEEEPARstartfont is globaly set to the calculated font of the big letter +% We need to carry this out of the local calculation area to to create the +% big letter. +\global\font\@IEEEPARstartfont\@IEEEPARstartFONTNAME\space at \@IEEEtrantmpdimenB% +% Now set \@IEEEtrantmpdimenA to the width of the big letter +% We need to carry this out of the local calculation area to set the +% hanging indent +\settowidth{\global\@IEEEtrantmpdimenA}{\@IEEEPARstartfont +\IEEEPARstartCAPSTYLE{#1\IEEEPARstartITLCORRECT}}}% +% end of the isolated calculation environment +\global\IEEEPARstartletwidth\@IEEEtrantmpdimenA\relax% +% add in the extra clearance we want +\advance\@IEEEtrantmpdimenA by \IEEEPARstartSEP\relax% +% add in the optional offset +\advance\@IEEEtrantmpdimenA by \IEEEPARstartHOFFSET\relax% +% V1.7 don't allow negative offsets to produce negative hanging indents +\@IEEEtrantmpdimenB\@IEEEtrantmpdimenA +\ifnum\@IEEEtrantmpdimenB < 0 \@IEEEtrantmpdimenB 0pt\fi +% \@IEEEtrantmpdimenA has the width of the big letter plus the +% separation space and \@IEEEPARstartfont is the font we need to use +% Now, we make the letter and issue the hanging indent command +% The letter is placed in a box of zero width and height so that other +% text won't be displaced by it. +\hangindent\@IEEEtrantmpdimenB\hangafter=-\IEEEPARstartDROPLINES% +\makebox[0pt][l]{\hspace{-\@IEEEtrantmpdimenA}% +\raisebox{-\IEEEPARstartDROPDEPTH}[0pt][0pt]{\hspace{\IEEEPARstartHOFFSET}% +\@IEEEPARstartfont\IEEEPARstartCAPSTYLE{#1\IEEEPARstartITLCORRECT}% +\hspace{\IEEEPARstartSEP}}}% +{\IEEEPARstartWORDFONTSTYLE{\IEEEPARstartWORDCAPSTYLE{\selectfont#2}}}} + + + + +% determines if the space remaining on a given page is equal to or greater +% than the specified space of argument one +% if not, execute argument two (only if the remaining space is greater than zero) +% and issue a \newpage +% +% example: \@IEEEtranneedspace{2in}{\vfill} +% +% Does not take into consideration rubber shrinkage, so it tends to +% be overly cautious +% Based on an example posted by Donald Arseneau +% Note this macro uses \@IEEEtrantmpdimenB internally for calculations, +% so DO NOT PASS \@IEEEtrantmpdimenB to this routine +% if you need a dimen register, import with \@IEEEtrantmpdimenA instead +\def\@IEEEtranneedspace#1#2{\penalty-100\begingroup%shield temp variable +\@IEEEtrantmpdimenB\pagegoal\advance\@IEEEtrantmpdimenB-\pagetotal% space left +\ifdim #1>\@IEEEtrantmpdimenB\relax% not enough space left +\ifdim\@IEEEtrantmpdimenB>\z@\relax #2\fi% +\newpage% +\fi\endgroup} + + + +% IEEEbiography ENVIRONMENT +% Allows user to enter biography leaving place for picture (adapts to font size) +% As of V1.5, a new optional argument allows you to have a real graphic! +% V1.5 and later also fixes the "colliding biographies" which could happen when a +% biography's text was shorter than the space for the photo. +% MDS 7/2001 +% V1.6 prevent multiple biographies from making multiple TOC entries +\newif\if@IEEEbiographyTOCentrynotmade +\global\@IEEEbiographyTOCentrynotmadetrue + +% biography counter so hyperref can jump directly to the biographies +% and not just the previous section +\newcounter{IEEEbiography} +\setcounter{IEEEbiography}{0} + +% photo area size +\def\@IEEEBIOphotowidth{1.0in} % width of the biography photo area +\def\@IEEEBIOphotodepth{1.25in} % depth (height) of the biography photo area +% area cleared for photo +\def\@IEEEBIOhangwidth{1.14in} % width cleared for the biography photo area +\def\@IEEEBIOhangdepth{1.25in} % depth cleared for the biography photo area + % actual depth will be a multiple of + % \baselineskip, rounded up +\def\@IEEEBIOskipN{4\baselineskip}% nominal value of the vskip above the biography + +\newenvironment{IEEEbiography}[2][]{\normalfont\@IEEEcompsoconly{\sffamily}\footnotesize% +\unitlength 1in\parskip=0pt\par\parindent 1em\interlinepenalty500% +% we need enough space to support the hanging indent +% the nominal value of the spacer +% and one extra line for good measure +\@IEEEtrantmpdimenA=\@IEEEBIOhangdepth% +\advance\@IEEEtrantmpdimenA by \@IEEEBIOskipN% +\advance\@IEEEtrantmpdimenA by 1\baselineskip% +% if this page does not have enough space, break it and lets start +% with a new one +\@IEEEtranneedspace{\@IEEEtrantmpdimenA}{\relax}% +% nominal spacer can strech, not shrink use 1fil so user can out stretch with \vfill +\vskip \@IEEEBIOskipN plus 1fil minus 0\baselineskip% +% the default box for where the photo goes +\def\@IEEEtempbiographybox{{\setlength{\fboxsep}{0pt}\framebox{% +\begin{minipage}[b][\@IEEEBIOphotodepth][c]{\@IEEEBIOphotowidth}\centering PLACE\\ PHOTO\\ HERE \end{minipage}}}}% +% +% detect if the optional argument was supplied, this requires the +% \@ifmtarg command as defined in the appendix section above +% and if so, override the default box with what they want +\@ifmtarg{#1}{\relax}{\def\@IEEEtempbiographybox{\mbox{\begin{minipage}[b][\@IEEEBIOphotodepth][c]{\@IEEEBIOphotowidth}% +\centering% +#1% +\end{minipage}}}}% end if optional argument supplied +% Make an entry into the table of contents only if we have not done so before +\if@IEEEbiographyTOCentrynotmade% +% link labels to the biography counter so hyperref will jump +% to the biography, not the previous section +\setcounter{IEEEbiography}{-1}% +\refstepcounter{IEEEbiography}% +\addcontentsline{toc}{section}{Biographies}% +\global\@IEEEbiographyTOCentrynotmadefalse% +\fi% +% one more biography +\refstepcounter{IEEEbiography}% +% Make an entry for this name into the table of contents +\addcontentsline{toc}{subsection}{#2}% +% V1.6 properly handle if a new paragraph should occur while the +% hanging indent is still active. Do this by redefining \par so +% that it will not start a new paragraph. (But it will appear to the +% user as if it did.) Also, strip any leading pars, newlines, or spaces. +\let\@IEEEBIOORGparCMD=\par% save the original \par command +\edef\par{\hfil\break\indent}% the new \par will not be a "real" \par +\settoheight{\@IEEEtrantmpdimenA}{\@IEEEtempbiographybox}% get height of biography box +\@IEEEtrantmpdimenB=\@IEEEBIOhangdepth% +\@IEEEtrantmpcountA=\@IEEEtrantmpdimenB% countA has the hang depth +\divide\@IEEEtrantmpcountA by \baselineskip% calculates lines needed to produce the hang depth +\advance\@IEEEtrantmpcountA by 1% ensure we overestimate +% set the hanging indent +\hangindent\@IEEEBIOhangwidth% +\hangafter-\@IEEEtrantmpcountA% +% reference the top of the photo area to the top of a capital T +\settoheight{\@IEEEtrantmpdimenB}{\mbox{T}}% +% set the photo box, give it zero width and height so as not to disturb anything +\noindent\makebox[0pt][l]{\hspace{-\@IEEEBIOhangwidth}\raisebox{\@IEEEtrantmpdimenB}[0pt][0pt]{% +\raisebox{-\@IEEEBIOphotodepth}[0pt][0pt]{\@IEEEtempbiographybox}}}% +% now place the author name and begin the bio text +\noindent\textbf{#2\ }\@IEEEgobbleleadPARNLSP}{\relax\let\par=\@IEEEBIOORGparCMD\par% +% 7/2001 V1.5 detect when the biography text is shorter than the photo area +% and pad the unused area - preventing a collision from the next biography entry +% MDS +\ifnum \prevgraf <\@IEEEtrantmpcountA\relax% detect when the biography text is shorter than the photo + \advance\@IEEEtrantmpcountA by -\prevgraf% calculate how many lines we need to pad + \advance\@IEEEtrantmpcountA by -1\relax% we compensate for the fact that we indented an extra line + \@IEEEtrantmpdimenA=\baselineskip% calculate the length of the padding + \multiply\@IEEEtrantmpdimenA by \@IEEEtrantmpcountA% + \noindent\rule{0pt}{\@IEEEtrantmpdimenA}% insert an invisible support strut +\fi% +\par\normalfont} + + + +% V1.6 +% added biography without a photo environment +\newenvironment{IEEEbiographynophoto}[1]{% +% Make an entry into the table of contents only if we have not done so before +\if@IEEEbiographyTOCentrynotmade% +% link labels to the biography counter so hyperref will jump +% to the biography, not the previous section +\setcounter{IEEEbiography}{-1}% +\refstepcounter{IEEEbiography}% +\addcontentsline{toc}{section}{Biographies}% +\global\@IEEEbiographyTOCentrynotmadefalse% +\fi% +% one more biography +\refstepcounter{IEEEbiography}% +% Make an entry for this name into the table of contents +\addcontentsline{toc}{subsection}{#1}% +\normalfont\@IEEEcompsoconly{\sffamily}\footnotesize\interlinepenalty500% +\vskip 4\baselineskip plus 1fil minus 0\baselineskip% +\parskip=0pt\par% +\noindent\textbf{#1\ }\@IEEEgobbleleadPARNLSP}{\relax\par\normalfont} + + +% provide the user with some old font commands +% got this from article.cls +\DeclareOldFontCommand{\rm}{\normalfont\rmfamily}{\mathrm} +\DeclareOldFontCommand{\sf}{\normalfont\sffamily}{\mathsf} +\DeclareOldFontCommand{\tt}{\normalfont\ttfamily}{\mathtt} +\DeclareOldFontCommand{\bf}{\normalfont\bfseries}{\mathbf} +\DeclareOldFontCommand{\it}{\normalfont\itshape}{\mathit} +\DeclareOldFontCommand{\sl}{\normalfont\slshape}{\@nomath\sl} +\DeclareOldFontCommand{\sc}{\normalfont\scshape}{\@nomath\sc} +\DeclareRobustCommand*\cal{\@fontswitch\relax\mathcal} +\DeclareRobustCommand*\mit{\@fontswitch\relax\mathnormal} + + +% SPECIAL PAPER NOTICE COMMANDS +% +% holds the special notice text +\def\@IEEEspecialpapernotice{\relax} + +% for special papers, like invited papers, the user can do: +% \IEEEspecialpapernotice{(Invited Paper)} before \maketitle +\def\IEEEspecialpapernotice#1{\ifCLASSOPTIONconference% +\def\@IEEEspecialpapernotice{{\sublargesize\textit{#1}\vspace*{1em}}}% +\else% +\def\@IEEEspecialpapernotice{{\\*[1.5ex]\sublargesize\textit{#1}}\vspace*{-2ex}}% +\fi} + + + + +% PUBLISHER ID COMMANDS +% to insert a publisher's ID footer +% V1.6 \IEEEpubid has been changed so that the change in page size and style +% occurs in \maketitle. \IEEEpubid must now be issued prior to \maketitle +% use \IEEEpubidadjcol as before - in the second column of the title page +% These changes allow \maketitle to take the reduced page height into +% consideration when dynamically setting the space between the author +% names and the maintext. +% +% the amount the main text is pulled up to make room for the +% publisher's ID footer +% The IEEE uses about 1.3\baselineskip for journals, +% dynamic title spacing will clean up the fraction +\def\@IEEEpubidpullup{1.3\baselineskip} +\ifCLASSOPTIONtechnote +% for technotes it must be an integer of baselineskip as there can be no +% dynamic title spacing for two column mode technotes (the title is in the +% in first column) and we should maintain an integer number of lines in the +% second column +% There are some examples (such as older issues of "Transactions on +% Information Theory") in which the IEEE really pulls the text off the ID for +% technotes - about 0.55in (or 4\baselineskip). We'll use 2\baselineskip +% and call it even. +\def\@IEEEpubidpullup{2\baselineskip} +\fi + +% V1.7 compsoc does not use a pullup +\ifCLASSOPTIONcompsoc +\def\@IEEEpubidpullup{0pt} +\fi + +% holds the ID text +\def\@IEEEpubid{\relax} + +% flag so \maketitle can tell if \IEEEpubid was called +\newif\if@IEEEusingpubid +\global\@IEEEusingpubidfalse +% issue this command in the page to have the ID at the bottom +% V1.6 use before \maketitle +\def\IEEEpubid#1{\def\@IEEEpubid{#1}\global\@IEEEusingpubidtrue} + + +% command which will pull up (shorten) the column it is executed in +% to make room for the publisher ID. Place in the second column of +% the title page when using \IEEEpubid +% Is smart enough not to do anything when in single column text or +% if the user hasn't called \IEEEpubid +% currently needed in for the second column of a page with the +% publisher ID. If not needed in future releases, please provide this +% command and define it as \relax for backward compatibility +% v1.6b do not allow command to operate if the peer review option has been +% selected because \IEEEpubidadjcol will not be on the cover page. +% V1.7 do nothing if compsoc +\def\IEEEpubidadjcol{\ifCLASSOPTIONcompsoc\else\ifCLASSOPTIONpeerreview\else +\if@twocolumn\if@IEEEusingpubid\enlargethispage{-\@IEEEpubidpullup}\fi\fi\fi\fi} + +% Special thanks to Peter Wilson, Daniel Luecking, and the other +% gurus at comp.text.tex, for helping me to understand how best to +% implement the IEEEpubid command in LaTeX. + + + +%% Lockout some commands under various conditions + +% general purpose bit bucket +\newsavebox{\@IEEEtranrubishbin} + +% flags to prevent multiple warning messages +\newif\if@IEEEWARNthanks +\newif\if@IEEEWARNIEEEPARstart +\newif\if@IEEEWARNIEEEbiography +\newif\if@IEEEWARNIEEEbiographynophoto +\newif\if@IEEEWARNIEEEpubid +\newif\if@IEEEWARNIEEEpubidadjcol +\newif\if@IEEEWARNIEEEmembership +\newif\if@IEEEWARNIEEEaftertitletext +\@IEEEWARNthankstrue +\@IEEEWARNIEEEPARstarttrue +\@IEEEWARNIEEEbiographytrue +\@IEEEWARNIEEEbiographynophototrue +\@IEEEWARNIEEEpubidtrue +\@IEEEWARNIEEEpubidadjcoltrue +\@IEEEWARNIEEEmembershiptrue +\@IEEEWARNIEEEaftertitletexttrue + + +%% Lockout some commands when in various modes, but allow them to be restored if needed +%% +% save commands which might be locked out +% so that the user can later restore them if needed +\let\@IEEESAVECMDthanks\thanks +\let\@IEEESAVECMDIEEEPARstart\IEEEPARstart +\let\@IEEESAVECMDIEEEbiography\IEEEbiography +\let\@IEEESAVECMDendIEEEbiography\endIEEEbiography +\let\@IEEESAVECMDIEEEbiographynophoto\IEEEbiographynophoto +\let\@IEEESAVECMDendIEEEbiographynophoto\endIEEEbiographynophoto +\let\@IEEESAVECMDIEEEpubid\IEEEpubid +\let\@IEEESAVECMDIEEEpubidadjcol\IEEEpubidadjcol +\let\@IEEESAVECMDIEEEmembership\IEEEmembership +\let\@IEEESAVECMDIEEEaftertitletext\IEEEaftertitletext + + +% disable \IEEEPARstart when in draft mode +% This may have originally been done because the pre-V1.6 drop letter +% algorithm had problems with a non-unity baselinestretch +% At any rate, it seems too formal to have a drop letter in a draft +% paper. +\ifCLASSOPTIONdraftcls +\def\IEEEPARstart#1#2{#1#2\if@IEEEWARNIEEEPARstart\typeout{** ATTENTION: \noexpand\IEEEPARstart + is disabled in draft mode (line \the\inputlineno).}\fi\global\@IEEEWARNIEEEPARstartfalse} +\fi +% and for technotes +\ifCLASSOPTIONtechnote +\def\IEEEPARstart#1#2{#1#2\if@IEEEWARNIEEEPARstart\typeout{** WARNING: \noexpand\IEEEPARstart + is locked out for technotes (line \the\inputlineno).}\fi\global\@IEEEWARNIEEEPARstartfalse} +\fi + + +% lockout unneeded commands when in conference mode +\ifCLASSOPTIONconference +% when locked out, \thanks, \IEEEbiography, \IEEEbiographynophoto, \IEEEpubid, +% \IEEEmembership and \IEEEaftertitletext will all swallow their given text. +% \IEEEPARstart will output a normal character instead +% warn the user about these commands only once to prevent the console screen +% from filling up with redundant messages +\def\thanks#1{\if@IEEEWARNthanks\typeout{** WARNING: \noexpand\thanks + is locked out when in conference mode (line \the\inputlineno).}\fi\global\@IEEEWARNthanksfalse} +\def\IEEEPARstart#1#2{#1#2\if@IEEEWARNIEEEPARstart\typeout{** WARNING: \noexpand\IEEEPARstart + is locked out when in conference mode (line \the\inputlineno).}\fi\global\@IEEEWARNIEEEPARstartfalse} + + +% LaTeX treats environments and commands with optional arguments differently. +% the actual ("internal") command is stored as \\commandname +% (accessed via \csname\string\commandname\endcsname ) +% the "external" command \commandname is a macro with code to determine +% whether or not the optional argument is presented and to provide the +% default if it is absent. So, in order to save and restore such a command +% we would have to save and restore \\commandname as well. But, if LaTeX +% ever changes the way it names the internal names, the trick would break. +% Instead let us just define a new environment so that the internal +% name can be left undisturbed. +\newenvironment{@IEEEbogusbiography}[2][]{\if@IEEEWARNIEEEbiography\typeout{** WARNING: \noexpand\IEEEbiography + is locked out when in conference mode (line \the\inputlineno).}\fi\global\@IEEEWARNIEEEbiographyfalse% +\setbox\@IEEEtranrubishbin\vbox\bgroup}{\egroup\relax} +% and make biography point to our bogus biography +\let\IEEEbiography=\@IEEEbogusbiography +\let\endIEEEbiography=\end@IEEEbogusbiography + +\renewenvironment{IEEEbiographynophoto}[1]{\if@IEEEWARNIEEEbiographynophoto\typeout{** WARNING: \noexpand\IEEEbiographynophoto + is locked out when in conference mode (line \the\inputlineno).}\fi\global\@IEEEWARNIEEEbiographynophotofalse% +\setbox\@IEEEtranrubishbin\vbox\bgroup}{\egroup\relax} + +\def\IEEEpubid#1{\if@IEEEWARNIEEEpubid\typeout{** WARNING: \noexpand\IEEEpubid + is locked out when in conference mode (line \the\inputlineno).}\fi\global\@IEEEWARNIEEEpubidfalse} +\def\IEEEpubidadjcol{\if@IEEEWARNIEEEpubidadjcol\typeout{** WARNING: \noexpand\IEEEpubidadjcol + is locked out when in conference mode (line \the\inputlineno).}\fi\global\@IEEEWARNIEEEpubidadjcolfalse} +\def\IEEEmembership#1{\if@IEEEWARNIEEEmembership\typeout{** WARNING: \noexpand\IEEEmembership + is locked out when in conference mode (line \the\inputlineno).}\fi\global\@IEEEWARNIEEEmembershipfalse} +\def\IEEEaftertitletext#1{\if@IEEEWARNIEEEaftertitletext\typeout{** WARNING: \noexpand\IEEEaftertitletext + is locked out when in conference mode (line \the\inputlineno).}\fi\global\@IEEEWARNIEEEaftertitletextfalse} +\fi + + +% provide a way to restore the commands that are locked out +\def\IEEEoverridecommandlockouts{% +\typeout{** ATTENTION: Overriding command lockouts (line \the\inputlineno).}% +\let\thanks\@IEEESAVECMDthanks% +\let\IEEEPARstart\@IEEESAVECMDIEEEPARstart% +\let\IEEEbiography\@IEEESAVECMDIEEEbiography% +\let\endIEEEbiography\@IEEESAVECMDendIEEEbiography% +\let\IEEEbiographynophoto\@IEEESAVECMDIEEEbiographynophoto% +\let\endIEEEbiographynophoto\@IEEESAVECMDendIEEEbiographynophoto% +\let\IEEEpubid\@IEEESAVECMDIEEEpubid% +\let\IEEEpubidadjcol\@IEEESAVECMDIEEEpubidadjcol% +\let\IEEEmembership\@IEEESAVECMDIEEEmembership% +\let\IEEEaftertitletext\@IEEESAVECMDIEEEaftertitletext} + + + +% need a backslash character for typeout output +{\catcode`\|=0 \catcode`\\=12 +|xdef|@IEEEbackslash{\}} + + +% hook to allow easy disabling of all legacy warnings +\def\@IEEElegacywarn#1#2{\typeout{** ATTENTION: \@IEEEbackslash #1 is deprecated (line \the\inputlineno). +Use \@IEEEbackslash #2 instead.}} + + +% provide some legacy IEEEtran commands +\def\IEEEcompsoctitleabstractindextext{\@IEEElegacywarn{IEEEcompsoctitleabstractindextext}{IEEEtitleabstractindextext}\IEEEtitleabstractindextext} +\def\IEEEdisplaynotcompsoctitleabstractindextext{\@IEEElegacywarn{IEEEdisplaynotcompsoctitleabstractindextext}{IEEEdisplaynontitleabstractindextext}\IEEEdisplaynontitleabstractindextext} +% provide some legacy IEEEtran environments + + +% V1.8a no more support for these legacy commands +%\def\authorblockA{\@IEEElegacywarn{authorblockA}{IEEEauthorblockA}\IEEEauthorblockA} +%\def\authorblockN{\@IEEElegacywarn{authorblockN}{IEEEauthorblockN}\IEEEauthorblockN} +%\def\authorrefmark{\@IEEElegacywarn{authorrefmark}{IEEEauthorrefmark}\IEEEauthorrefmark} +%\def\PARstart{\@IEEElegacywarn{PARstart}{IEEEPARstart}\IEEEPARstart} +%\def\pubid{\@IEEElegacywarn{pubid}{IEEEpubid}\IEEEpubid} +%\def\pubidadjcol{\@IEEElegacywarn{pubidadjcol}{IEEEpubidadjcol}\IEEEpubidadjcol} +%\def\specialpapernotice{\@IEEElegacywarn{specialpapernotice}{IEEEspecialpapernotice}\IEEEspecialpapernotice} +% and environments +%\def\keywords{\@IEEElegacywarn{keywords}{IEEEkeywords}\IEEEkeywords} +%\def\endkeywords{\endIEEEkeywords} +% V1.8 no more support for legacy IED list commands +%\let\labelindent\IEEElabelindent +%\def\calcleftmargin{\@IEEElegacywarn{calcleftmargin}{IEEEcalcleftmargin}\IEEEcalcleftmargin} +%\def\setlabelwidth{\@IEEElegacywarn{setlabelwidth}{IEEEsetlabelwidth}\IEEEsetlabelwidth} +%\def\usemathlabelsep{\@IEEElegacywarn{usemathlabelsep}{IEEEusemathlabelsep}\IEEEusemathlabelsep} +%\def\iedlabeljustifyc{\@IEEElegacywarn{iedlabeljustifyc}{IEEEiedlabeljustifyc}\IEEEiedlabeljustifyc} +%\def\iedlabeljustifyl{\@IEEElegacywarn{iedlabeljustifyl}{IEEEiedlabeljustifyl}\IEEEiedlabeljustifyl} +%\def\iedlabeljustifyr{\@IEEElegacywarn{iedlabeljustifyr}{IEEEiedlabeljustifyr}\IEEEiedlabeljustifyr} +% V1.8 no more support for QED and proof stuff +%\def\QED{\@IEEElegacywarn{QED}{IEEEQED}\IEEEQED} +%\def\QEDclosed{\@IEEElegacywarn{QEDclosed}{IEEEQEDclosed}\IEEEQEDclosed} +%\def\QEDopen{\@IEEElegacywarn{QEDopen}{IEEEQEDopen}\IEEEQEDopen} +%\AtBeginDocument{\def\proof{\@IEEElegacywarn{proof}{IEEEproof}\IEEEproof}\def\endproof{\endIEEEproof}} +% V1.8 no longer support biography or biographynophoto +%\def\biography{\@IEEElegacywarn{biography}{IEEEbiography}\IEEEbiography} +%\def\biographynophoto{\@IEEElegacywarn{biographynophoto}{IEEEbiographynophoto}\IEEEbiographynophoto} +%\def\endbiography{\endIEEEbiography} +%\def\endbiographynophoto{\endIEEEbiographynophoto} +% V1.7 and later no longer supports \overrideIEEEmargins +%\def\overrideIEEEmargins{% +%\typeout{** WARNING: \string\overrideIEEEmargins \space no longer supported (line \the\inputlineno).}% +%\typeout{** Use the \string\CLASSINPUTinnersidemargin, \string\CLASSINPUToutersidemargin \space controls instead.}} + +\endinput + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%% End of IEEEtran.cls %%%%%%%%%%%%%%%%%%%%%%%%%%%% +% That's all folks! + diff --git a/SAT_package_paper/Conference-LaTeX-template_10-17-19/bibliography.bib b/SAT_package_paper/Conference-LaTeX-template_10-17-19/bibliography.bib new file mode 100644 index 0000000..acfcb17 --- /dev/null +++ b/SAT_package_paper/Conference-LaTeX-template_10-17-19/bibliography.bib @@ -0,0 +1,76 @@ +@article{convexjl, + title = {Convex Optimization in {J}ulia}, + author = {Udell, Madeleine and Mohan, Karanveer and Zeng, David and Hong, Jenny and Diamond, Steven and Boyd, Stephen}, + year = {2014}, + journal = {SC14 Workshop on High Performance Technical Computing in Dynamic Languages}, + archivePrefix = "arXiv", + eprint = {1410.4821}, + primaryClass = "math-oc", +} + +@article{Lubin2023, + author = {Miles Lubin and Oscar Dowson and Joaquim Dias Garcia and Joey Huchette and Beno{\^i}t Legat and Juan Pablo Vielma}, + title = {JuMP 1.0: Recent improvements to a modeling language for mathematical optimization}, + journal = {Mathematical Programming Computation}, + year = {2023}, + doi = {10.1007/s12532-023-00239-3} +} + +@inproceedings{pysmt2015, + title={PySMT: a solver-agnostic library for fast prototyping of SMT-based algorithms}, + author={Gario, Marco and Micheli, Andrea}, + booktitle={SMT Workshop 2015}, + year={2015} +} + +@inproceedings{z3, + title={Z3: An Efficient SMT Solver}, + author={Leonardo Mendonça de Moura and Nikolaj S. Bj{\o}rner}, + booktitle={International Conference on Tools and Algorithms for Construction and Analysis of Systems}, + year={2008} +} + +@inproceedings{cvc5, + author = {Haniel Barbosa and + Clark W. Barrett and + Martin Brain and + Gereon Kremer and + Hanna Lachnitt and + Makai Mann and + Abdalrhman Mohamed and + Mudathir Mohamed and + Aina Niemetz and + Andres N{\"{o}}tzli and + Alex Ozdemir and + Mathias Preiner and + Andrew Reynolds and + Ying Sheng and + Cesare Tinelli and + Yoni Zohar}, + editor = {Dana Fisman and + Grigore Rosu}, + title = {cvc5: {A} Versatile and Industrial-Strength {SMT} Solver}, + booktitle = {Tools and Algorithms for the Construction and Analysis of Systems + - 28th International Conference, {TACAS} 2022, Held as Part of the + European Joint Conferences on Theory and Practice of Software, {ETAPS} + 2022, Munich, Germany, April 2-7, 2022, Proceedings, Part {I}}, + series = {Lecture Notes in Computer Science}, + volume = {13243}, + pages = {415--442}, + publisher = {Springer}, + year = {2022}, + url = {https://doi.org/10.1007/978-3-030-99524-9\_24}, + doi = {10.1007/978-3-030-99524-9\_24}, + timestamp = {Fri, 01 Apr 2022 15:49:27 +0200}, + biburl = {https://dblp.org/rec/conf/tacas/BarbosaBBKLMMMN22.bib}, + bibsource = {dblp computer science bibliography, https://dblp.org}, +} + +@TECHREPORT{smtlib2, + author = {Clark Barrett and Pascal Fontaine and Cesare Tinelli}, + title = {{The SMT-LIB Standard: Version 2.6}}, + institution = {Department of Computer Science, The University of Iowa}, + year = 2017, + note = {Available at {\tt www.SMT-LIB.org}} +} + diff --git a/SAT_package_paper/Conference-LaTeX-template_10-17-19/conference_101719.tex b/SAT_package_paper/Conference-LaTeX-template_10-17-19/conference_101719.tex new file mode 100644 index 0000000..09d7398 --- /dev/null +++ b/SAT_package_paper/Conference-LaTeX-template_10-17-19/conference_101719.tex @@ -0,0 +1,288 @@ +\documentclass[conference]{IEEEtran} +\IEEEoverridecommandlockouts +% The preceding line is only needed to identify funding in the first footnote. If that is unneeded, please comment it out. +\usepackage{cite} +\usepackage{amsmath,amssymb,amsfonts} +\usepackage{algorithmic} +\usepackage{graphicx} +\usepackage{textcomp} +\usepackage{xcolor} +\def\BibTeX{{\rm B\kern-.05em{\sc i\kern-.025em b}\kern-.08em + T\kern-.1667em\lower.7ex\hbox{E}\kern-.125emX}} +\begin{document} + +\title{Conference Paper Title*\\ +{\footnotesize \textsuperscript{*}Note: Sub-titles are not captured in Xplore and +should not be used} +\thanks{Identify applicable funding agency here. If none, delete this.} +} + +\author{\IEEEauthorblockN{1\textsuperscript{st} Given Name Surname} +\IEEEauthorblockA{\textit{dept. name of organization (of Aff.)} \\ +\textit{name of organization (of Aff.)}\\ +City, Country \\ +email address or ORCID} +\and +\IEEEauthorblockN{2\textsuperscript{nd} Given Name Surname} +\IEEEauthorblockA{\textit{dept. name of organization (of Aff.)} \\ +\textit{name of organization (of Aff.)}\\ +City, Country \\ +email address or ORCID} +\and +\IEEEauthorblockN{3\textsuperscript{rd} Given Name Surname} +\IEEEauthorblockA{\textit{dept. name of organization (of Aff.)} \\ +\textit{name of organization (of Aff.)}\\ +City, Country \\ +email address or ORCID} +\and +\IEEEauthorblockN{4\textsuperscript{th} Given Name Surname} +\IEEEauthorblockA{\textit{dept. name of organization (of Aff.)} \\ +\textit{name of organization (of Aff.)}\\ +City, Country \\ +email address or ORCID} +\and +\IEEEauthorblockN{5\textsuperscript{th} Given Name Surname} +\IEEEauthorblockA{\textit{dept. name of organization (of Aff.)} \\ +\textit{name of organization (of Aff.)}\\ +City, Country \\ +email address or ORCID} +\and +\IEEEauthorblockN{6\textsuperscript{th} Given Name Surname} +\IEEEauthorblockA{\textit{dept. name of organization (of Aff.)} \\ +\textit{name of organization (of Aff.)}\\ +City, Country \\ +email address or ORCID} +} + +\maketitle + +\begin{abstract} +This document is a model and instructions for \LaTeX. +This and the IEEEtran.cls file define the components of your paper [title, text, heads, etc.]. *CRITICAL: Do Not Use Symbols, Special Characters, Footnotes, +or Math in Paper Title or Abstract. +\end{abstract} + +\begin{IEEEkeywords} +component, formatting, style, styling, insert +\end{IEEEkeywords} + +\section{Introduction} +This document is a model and instructions for \LaTeX. +Please observe the conference page limits. + +\section{Ease of Use} + +\subsection{Maintaining the Integrity of the Specifications} + +The IEEEtran class file is used to format your paper and style the text. All margins, +column widths, line spaces, and text fonts are prescribed; please do not +alter them. You may note peculiarities. For example, the head margin +measures proportionately more than is customary. This measurement +and others are deliberate, using specifications that anticipate your paper +as one part of the entire proceedings, and not as an independent document. +Please do not revise any of the current designations. + +\section{Prepare Your Paper Before Styling} +Before you begin to format your paper, first write and save the content as a +separate text file. Complete all content and organizational editing before +formatting. Please note sections \ref{AA}--\ref{SCM} below for more information on +proofreading, spelling and grammar. + +Keep your text and graphic files separate until after the text has been +formatted and styled. Do not number text heads---{\LaTeX} will do that +for you. + +\subsection{Abbreviations and Acronyms}\label{AA} +Define abbreviations and acronyms the first time they are used in the text, +even after they have been defined in the abstract. Abbreviations such as +IEEE, SI, MKS, CGS, ac, dc, and rms do not have to be defined. Do not use +abbreviations in the title or heads unless they are unavoidable. + +\subsection{Units} +\begin{itemize} +\item Use either SI (MKS) or CGS as primary units. (SI units are encouraged.) English units may be used as secondary units (in parentheses). An exception would be the use of English units as identifiers in trade, such as ``3.5-inch disk drive''. +\item Avoid combining SI and CGS units, such as current in amperes and magnetic field in oersteds. This often leads to confusion because equations do not balance dimensionally. If you must use mixed units, clearly state the units for each quantity that you use in an equation. +\item Do not mix complete spellings and abbreviations of units: ``Wb/m\textsuperscript{2}'' or ``webers per square meter'', not ``webers/m\textsuperscript{2}''. Spell out units when they appear in text: ``. . . a few henries'', not ``. . . a few H''. +\item Use a zero before decimal points: ``0.25'', not ``.25''. Use ``cm\textsuperscript{3}'', not ``cc''.) +\end{itemize} + +\subsection{Equations} +Number equations consecutively. To make your +equations more compact, you may use the solidus (~/~), the exp function, or +appropriate exponents. Italicize Roman symbols for quantities and variables, +but not Greek symbols. Use a long dash rather than a hyphen for a minus +sign. Punctuate equations with commas or periods when they are part of a +sentence, as in: +\begin{equation} +a+b=\gamma\label{eq} +\end{equation} + +Be sure that the +symbols in your equation have been defined before or immediately following +the equation. Use ``\eqref{eq}'', not ``Eq.~\eqref{eq}'' or ``equation \eqref{eq}'', except at +the beginning of a sentence: ``Equation \eqref{eq} is . . .'' + +\subsection{\LaTeX-Specific Advice} + +Please use ``soft'' (e.g., \verb|\eqref{Eq}|) cross references instead +of ``hard'' references (e.g., \verb|(1)|). That will make it possible +to combine sections, add equations, or change the order of figures or +citations without having to go through the file line by line. + +Please don't use the \verb|{eqnarray}| equation environment. Use +\verb|{align}| or \verb|{IEEEeqnarray}| instead. The \verb|{eqnarray}| +environment leaves unsightly spaces around relation symbols. + +Please note that the \verb|{subequations}| environment in {\LaTeX} +will increment the main equation counter even when there are no +equation numbers displayed. If you forget that, you might write an +article in which the equation numbers skip from (17) to (20), causing +the copy editors to wonder if you've discovered a new method of +counting. + +{\BibTeX} does not work by magic. It doesn't get the bibliographic +data from thin air but from .bib files. If you use {\BibTeX} to produce a +bibliography you must send the .bib files. + +{\LaTeX} can't read your mind. If you assign the same label to a +subsubsection and a table, you might find that Table I has been cross +referenced as Table IV-B3. + +{\LaTeX} does not have precognitive abilities. If you put a +\verb|\label| command before the command that updates the counter it's +supposed to be using, the label will pick up the last counter to be +cross referenced instead. In particular, a \verb|\label| command +should not go before the caption of a figure or a table. + +Do not use \verb|\nonumber| inside the \verb|{array}| environment. It +will not stop equation numbers inside \verb|{array}| (there won't be +any anyway) and it might stop a wanted equation number in the +surrounding equation. + +\subsection{Some Common Mistakes}\label{SCM} +\begin{itemize} +\item The word ``data'' is plural, not singular. +\item The subscript for the permeability of vacuum $\mu_{0}$, and other common scientific constants, is zero with subscript formatting, not a lowercase letter ``o''. +\item In American English, commas, semicolons, periods, question and exclamation marks are located within quotation marks only when a complete thought or name is cited, such as a title or full quotation. When quotation marks are used, instead of a bold or italic typeface, to highlight a word or phrase, punctuation should appear outside of the quotation marks. A parenthetical phrase or statement at the end of a sentence is punctuated outside of the closing parenthesis (like this). (A parenthetical sentence is punctuated within the parentheses.) +\item A graph within a graph is an ``inset'', not an ``insert''. The word alternatively is preferred to the word ``alternately'' (unless you really mean something that alternates). +\item Do not use the word ``essentially'' to mean ``approximately'' or ``effectively''. +\item In your paper title, if the words ``that uses'' can accurately replace the word ``using'', capitalize the ``u''; if not, keep using lower-cased. +\item Be aware of the different meanings of the homophones ``affect'' and ``effect'', ``complement'' and ``compliment'', ``discreet'' and ``discrete'', ``principal'' and ``principle''. +\item Do not confuse ``imply'' and ``infer''. +\item The prefix ``non'' is not a word; it should be joined to the word it modifies, usually without a hyphen. +\item There is no period after the ``et'' in the Latin abbreviation ``et al.''. +\item The abbreviation ``i.e.'' means ``that is'', and the abbreviation ``e.g.'' means ``for example''. +\end{itemize} +An excellent style manual for science writers is \cite{b7}. + +\subsection{Authors and Affiliations} +\textbf{The class file is designed for, but not limited to, six authors.} A +minimum of one author is required for all conference articles. Author names +should be listed starting from left to right and then moving down to the +next line. This is the author sequence that will be used in future citations +and by indexing services. Names should not be listed in columns nor group by +affiliation. Please keep your affiliations as succinct as possible (for +example, do not differentiate among departments of the same organization). + +\subsection{Identify the Headings} +Headings, or heads, are organizational devices that guide the reader through +your paper. There are two types: component heads and text heads. + +Component heads identify the different components of your paper and are not +topically subordinate to each other. Examples include Acknowledgments and +References and, for these, the correct style to use is ``Heading 5''. Use +``figure caption'' for your Figure captions, and ``table head'' for your +table title. Run-in heads, such as ``Abstract'', will require you to apply a +style (in this case, italic) in addition to the style provided by the drop +down menu to differentiate the head from the text. + +Text heads organize the topics on a relational, hierarchical basis. For +example, the paper title is the primary text head because all subsequent +material relates and elaborates on this one topic. If there are two or more +sub-topics, the next level head (uppercase Roman numerals) should be used +and, conversely, if there are not at least two sub-topics, then no subheads +should be introduced. + +\subsection{Figures and Tables} +\paragraph{Positioning Figures and Tables} Place figures and tables at the top and +bottom of columns. Avoid placing them in the middle of columns. Large +figures and tables may span across both columns. Figure captions should be +below the figures; table heads should appear above the tables. Insert +figures and tables after they are cited in the text. Use the abbreviation +``Fig.~\ref{fig}'', even at the beginning of a sentence. + +\begin{table}[htbp] +\caption{Table Type Styles} +\begin{center} +\begin{tabular}{|c|c|c|c|} +\hline +\textbf{Table}&\multicolumn{3}{|c|}{\textbf{Table Column Head}} \\ +\cline{2-4} +\textbf{Head} & \textbf{\textit{Table column subhead}}& \textbf{\textit{Subhead}}& \textbf{\textit{Subhead}} \\ +\hline +copy& More table copy$^{\mathrm{a}}$& & \\ +\hline +\multicolumn{4}{l}{$^{\mathrm{a}}$Sample of a Table footnote.} +\end{tabular} +\label{tab1} +\end{center} +\end{table} + +\begin{figure}[htbp] +\centerline{\includegraphics{fig1.png}} +\caption{Example of a figure caption.} +\label{fig} +\end{figure} + +Figure Labels: Use 8 point Times New Roman for Figure labels. Use words +rather than symbols or abbreviations when writing Figure axis labels to +avoid confusing the reader. As an example, write the quantity +``Magnetization'', or ``Magnetization, M'', not just ``M''. If including +units in the label, present them within parentheses. Do not label axes only +with units. In the example, write ``Magnetization (A/m)'' or ``Magnetization +\{A[m(1)]\}'', not just ``A/m''. Do not label axes with a ratio of +quantities and units. For example, write ``Temperature (K)'', not +``Temperature/K''. + +\section*{Acknowledgment} + +The preferred spelling of the word ``acknowledgment'' in America is without +an ``e'' after the ``g''. Avoid the stilted expression ``one of us (R. B. +G.) thanks $\ldots$''. Instead, try ``R. B. G. thanks$\ldots$''. Put sponsor +acknowledgments in the unnumbered footnote on the first page. + +\section*{References} + +Please number citations consecutively within brackets \cite{b1}. The +sentence punctuation follows the bracket \cite{b2}. Refer simply to the reference +number, as in \cite{b3}---do not use ``Ref. \cite{b3}'' or ``reference \cite{b3}'' except at +the beginning of a sentence: ``Reference \cite{b3} was the first $\ldots$'' + +Number footnotes separately in superscripts. Place the actual footnote at +the bottom of the column in which it was cited. Do not put footnotes in the +abstract or reference list. Use letters for table footnotes. + +Unless there are six authors or more give all authors' names; do not use +``et al.''. Papers that have not been published, even if they have been +submitted for publication, should be cited as ``unpublished'' \cite{b4}. Papers +that have been accepted for publication should be cited as ``in press'' \cite{b5}. +Capitalize only the first word in a paper title, except for proper nouns and +element symbols. + +For papers published in translation journals, please give the English +citation first, followed by the original foreign-language citation \cite{b6}. + +\begin{thebibliography}{00} +\bibitem{b1} G. Eason, B. Noble, and I. N. Sneddon, ``On certain integrals of Lipschitz-Hankel type involving products of Bessel functions,'' Phil. Trans. Roy. Soc. London, vol. A247, pp. 529--551, April 1955. +\bibitem{b2} J. Clerk Maxwell, A Treatise on Electricity and Magnetism, 3rd ed., vol. 2. Oxford: Clarendon, 1892, pp.68--73. +\bibitem{b3} I. S. Jacobs and C. P. Bean, ``Fine particles, thin films and exchange anisotropy,'' in Magnetism, vol. III, G. T. Rado and H. Suhl, Eds. New York: Academic, 1963, pp. 271--350. +\bibitem{b4} K. Elissa, ``Title of paper if known,'' unpublished. +\bibitem{b5} R. Nicole, ``Title of paper with only first word capitalized,'' J. Name Stand. Abbrev., in press. +\bibitem{b6} Y. Yorozu, M. Hirano, K. Oka, and Y. Tagawa, ``Electron spectroscopy studies on magneto-optical media and plastic substrate interface,'' IEEE Transl. J. Magn. Japan, vol. 2, pp. 740--741, August 1987 [Digests 9th Annual Conf. Magnetics Japan, p. 301, 1982]. +\bibitem{b7} M. Young, The Technical Writer's Handbook. Mill Valley, CA: University Science, 1989. +\end{thebibliography} +\vspace{12pt} +\color{red} +IEEE conference templates contain guidance text for composing and formatting conference papers. Please ensure that all template text is removed from your conference paper prior to submission to the conference. Failure to remove the template text from your paper may result in your paper not being published. + +\end{document} diff --git a/SAT_package_paper/Conference-LaTeX-template_10-17-19/paper-blx.bib b/SAT_package_paper/Conference-LaTeX-template_10-17-19/paper-blx.bib new file mode 100644 index 0000000..880a27d --- /dev/null +++ b/SAT_package_paper/Conference-LaTeX-template_10-17-19/paper-blx.bib @@ -0,0 +1,11 @@ +@Comment{$ biblatex control file $} +@Comment{$ biblatex version 2.9 $} +Do not modify this file! + +This is an auxiliary file used by the 'biblatex' package. +This file may safely be deleted. It will be recreated as +required. + +@Control{biblatex-control, + options = {2.9:0:0:1:0:1:1:0:0:0:0:0:3:3:79:+:none}, +} diff --git a/SAT_package_paper/Conference-LaTeX-template_10-17-19/paper.tex b/SAT_package_paper/Conference-LaTeX-template_10-17-19/paper.tex new file mode 100644 index 0000000..a48e3b9 --- /dev/null +++ b/SAT_package_paper/Conference-LaTeX-template_10-17-19/paper.tex @@ -0,0 +1,292 @@ +\documentclass[conference]{IEEEtran} +\IEEEoverridecommandlockouts +% The preceding line is only needed to identify funding in the first footnote. If that is unneeded, please comment it out. +%\usepackage{cite} +\usepackage{amsmath,amssymb,amsfonts} +\usepackage{algorithmic} +\usepackage{graphicx} +\usepackage{textcomp} +\usepackage{xcolor} +%\def\BibTeX{{\rm B\kern-.05em{\sc i\kern-.025em b}\kern-.08em +% T\kern-.1667em\lower.7ex\hbox{E}\kern-.125emX}} +\usepackage[ +backend=bibtex, +style=ieee, +]{biblatex} +\bibliography{bibliography.bib} + +\begin{document} + +\title{BooleanSatisfiability.jl: Satisfiability Modulo Theories in Julia\\ +\thanks{This work was supported by a grant from Ford Motor Company.} %TODO grant #? +} + +\author{\IEEEauthorblockN{1\textsuperscript{st} Emiko Soroka} +\IEEEauthorblockA{\textit{Aeronautics and Astronautics} \\ +\textit{Stanford University}\\ +Stanford, USA \\ +esoroka@stanford.edu} +\and +\IEEEauthorblockN{2\textsuperscript{nd} Sanjay Lall} +\IEEEauthorblockA{\textit{Electrical Engineering} \\ +\textit{Stanford University}\\ +Stanford, USA \\ +lall@stanford.edu} +\and +\IEEEauthorblockN{3\textsuperscript{rd} Mykel Kochenderfer} +\IEEEauthorblockA{\textit{Aeronautics and Astronautics} \\ + \textit{Stanford University}\\ + Stanford, USA \\ + mykel@stanford.edu} +} + +\maketitle + +\begin{abstract} +Automated theorem provers such as Z3 and CVC5 can check the satisfiability or validity of a logical formula stated in one or more theories. Theorem provers have applications in formal verification including practical tasks such as proving the security of firewall configurations or the correctness of safety-critical software. While the SMTLIB2 format can be used to interface with theorem proving software, its limited syntax hampers the specification of complex statements. In this paper we present a high-level Julia interface to specify problems in several common theories. +\end{abstract} + +\begin{IEEEkeywords} +automated reasoning, theorem prover, satisfiability modulo theories, julia package, smtlib +\end{IEEEkeywords} + +\section{Introduction} +Satisfiability modulo theories (SMT) is a general framework for computational theorem proving, in which the goal is to algorithmically find a satisfying assignment of variables such that one or more logical statements hold true. SMT encompasses a broad class of problems including the theories of propositional logic, integer arithmetic, floating-point arithmetic, and data structures. SMT formulae are used in formal verification and model checking to prove or disprove the correctness of a system. + +A decision procedure for an SMT problem is an algorithm that either finds such an assignment or determines that the given formula is unsatisfiable. Theorem proving software such as Z3 or CVC5 \cite{z3, cvc5} +implements these procedures, allowing users to check SMT formulae and find satisfying assignments where possible. However, theorem provers themselves are low-level tools intended to be integrated into other software. + +In this paper we introduce \verb|BooleanSatisfiability.jl|, a Julia package that provides a high-level representation of SMT theories including propositional logic, integer and real-valued arithmetic, and IEEE floating-point numbers. \verb|BooleanSatisfiability.jl| is the first Julia package to provide this functionality. + +\section{Prior Work} +Two popular theorem provers are Z3, developed by Microsoft Research, and the open-source prover CVC5. Both provers including bindings for multiple programming languages, allowing access to some or all functionality with varying levels of abstraction. Additionally, both Z3 and CVC5 accept commands in the SMTLIB2 specification language \cite{smtlib2}. + +Similar packages are available in other languages; for example, \verb|PySMT| provides a high-level SAT interface using the same strategy of translation to SMTLIB2 commands \cite{pysmt2015}. +To our knowledge, \verb|BooleanSatisfiability.jl| is the first Julia package to use the SMTLIB2 format for interactions with solvers, allowing compatibility with any theorem prover that supports SMTLIB2. + +\subsection{The SMTLIB language} +SMTLIB is a low-level specification language designed to standardize interactions with theorem provers. At time of writing, the current SMTLIB standard is V2.6; we used this version of the language specification when implementing our software. + +SMTLIB uses a Lisp-like syntax designed to simplify input parsing. It is intended to provide an interactive interface, similar to Julia's REPL. The language supports declarations (for example, of variables or functions), assertions (requiring that a Boolean formula be true), and various solver commands. + +Figure ?%TODO figure +shows a simple example of a solver moving between modes as statements are received. Note that many commands are only valid in specific solver modes. +For example, the command \verb|(get-model)| retrieves the satisfying assignment for a formula and is only valid in \verb|sat| mode, while \verb|(get-unsat-core)| is only valid in \verb|unsat| mode. Issuing a command in the wrong mode yields an error. + +For a complete description of the SMTLIB language, readers are referred to \cite{smtlib2}. + + +\section{Package Design} +%TODO diagram +The basic unit of an SMT formula is the expression (Figure ?). %TODO) +Expressions may represent single variables or operators and implements a tree structure capable of representing arbitrarily complex formulae. Julia's type system prevents expressions from being incorrectly combined. For example, $\neg\verb|x|$ is only valid if \verb|x| is of type \verb|BoolExpr|. + +Output types of operations follow type compatibility and promotion rules; for example, if \verb|x| is a \verb|BoolExpr| and \verb|a| is an \verb|IntExpr|, \verb|x + a| is an \verb|IntExpr|. + +\subsection{Working with formulae}. +The function \verb|smt(e::AbstractExpr)| returns the SMTLIB representation of expression \verb|e| as a string. + +The function \verb|sat!(e::BoolExpr, prover::Prover)| calls the given prover on \verb|e| and returns either \verb|:SAT|, \verb|:UNSAT|, or \verb|:ERROR|. If \verb|e| is \verb|:SAT|, the values of all nested expressions in \verb|e| are updated to allow easy retrieval of the satisfying assignment. If \verb|e| is \verb|:UNSAT|, the values of all nested expressions are set to \verb|nothing|. + +Note that \verb|sat!| can only be called on Boolean expressions, because the purpose of a theorem prover is to determine whether a Boolean statement is \verb|true| or \verb|false|. In comparison, one can generate the SMT representation of any \verb|AbstractExpr|, including non-Boolean expressions that do not represent valid SMT problems. + +Internally, our package uses Julia's \verb|Process| library to interact with a prover via input and output pipes. This supports the interactive nature of SMTLIB; for example, the command \verb|(get-model)| is required to retrieve a satisfying assignment, but cannot be issued if the formula is unsatisfiable. + +\subsection{Interface} +New variables are declared using the \verb|@satvariable| macro, which behaves similarly to the \verb|@variable| macro in JuMP \cite{Lubin2023}. +The \verb|@satvariable| macro takes two arguments: a variable name with optional size and shape (for creating vector-valued and matrix-valued variables), and a symbol representing the variable type. +\begin{itemize} +\item \verb|@satvariable(x, :Bool)| declares a single \verb|BoolExpr| \verb|x|. +\item \verb|@satvariable(y[1:n], :Bool)| declares an $n$-vector of \verb|BoolExpr|s \verb|y|. +\item \verb|@satvariable(z[1:n], :Int)| declares an $m\times n$ matrix of \verb|IntExpr|s \verb|z|. +\end{itemize} + +Variables may be combined using operations, which we distinguish by return type. +Boolean operations \verb|and|, \verb|or|, \verb|not|, \verb|xor|, \verb|implies|, \verb|iff|, and \verb|ite| (if-then-else) return Boolean expressions. + +The integer or real-valued operations \verb|+|, \verb|-|, \verb|*| return integer or real expressions (using Julia type promotion rules). Division (\verb|/|) is only valid over real-valued expressions. + +\section{Examples} + +\subsection*{Custom solver interactions} +We expose the low-level interface, allowing advanced users to send SMT commands and receive prover responses. Users are responsible for ensuring the correctness of these commands, as well as interpreting the results. In this use case, \verb|BooleanSatisfiability.jl| can be used to automate generation of the SMT problem and programmatically interact with solvers, extending the usability of the SMT interface. + +\section{Acknowledgements} +The software architecture of \verb|BooleanSatisfiability.jl| was inspired by \verb|Convex.jl|, \verb|JuMP|, and \verb|PySMT| \cite{convexjl, Lubin2023, pysmt2015}. + +\section{Future Work} + +\printbibliography + + +%\subsection{Maintaining the Integrity of the Specifications} + +%\subsection{Abbreviations and Acronyms}\label{AA} +%Define abbreviations and acronyms the first time they are used in the text, +%even after they have been defined in the abstract. Abbreviations such as +%IEEE, SI, MKS, CGS, ac, dc, and rms do not have to be defined. Do not use +%abbreviations in the title or heads unless they are unavoidable. + +%\subsection{Equations} +%Number equations consecutively. To make your +%equations more compact, you may use the solidus (~/~), the exp function, or +%appropriate exponents. Italicize Roman symbols for quantities and variables, +%but not Greek symbols. Use a long dash rather than a hyphen for a minus +%sign. Punctuate equations with commas or periods when they are part of a +%sentence, as in: +%\begin{equation} +%a+b=\gamma\label{eq} +%\end{equation} + +%Be sure that the +%symbols in your equation have been defined before or immediately following +%the equation. Use ``\eqref{eq}'', not ``Eq.~\eqref{eq}'' or ``equation \eqref{eq}'', except at +%the beginning of a sentence: ``Equation \eqref{eq} is . . .'' + +%\subsection{\LaTeX-Specific Advice} + +%Please note that the \verb|{subequations}| environment in {\LaTeX} +%will increment the main equation counter even when there are no +%equation numbers displayed. If you forget that, you might write an +%article in which the equation numbers skip from (17) to (20), causing +%the copy editors to wonder if you've discovered a new method of +%counting. + +%{\BibTeX} does not work by magic. It doesn't get the bibliographic +%data from thin air but from .bib files. If you use {\BibTeX} to produce a +%bibliography you must send the .bib files. + +%{\LaTeX} can't read your mind. If you assign the same label to a +%subsubsection and a table, you might find that Table I has been cross +%referenced as Table IV-B3. + +%{\LaTeX} does not have precognitive abilities. If you put a +%\verb|\label| command before the command that updates the counter it's +%supposed to be using, the label will pick up the last counter to be +%cross referenced instead. In particular, a \verb|\label| command +%should not go before the caption of a figure or a table. + +%Do not use \verb|\nonumber| inside the \verb|{array}| environment. It +%will not stop equation numbers inside \verb|{array}| (there won't be +%any anyway) and it might stop a wanted equation number in the +%surrounding equation. + +%\subsection{Some Common Mistakes}\label{SCM} +%\begin{itemize} +%\item The word ``data'' is plural, not singular. +%\item The subscript for the permeability of vacuum $\mu_{0}$, and other common scientific constants, is zero with subscript formatting, not a lowercase letter ``o''. +%\item In American English, commas, semicolons, periods, question and exclamation marks are located within quotation marks only when a complete thought or name is cited, such as a title or full quotation. When quotation marks are used, instead of a bold or italic typeface, to highlight a word or phrase, punctuation should appear outside of the quotation marks. A parenthetical phrase or statement at the end of a sentence is punctuated outside of the closing parenthesis (like this). (A parenthetical sentence is punctuated within the parentheses.) +%\item A graph within a graph is an ``inset'', not an ``insert''. The word alternatively is preferred to the word ``alternately'' (unless you really mean something that alternates). +%\item Do not use the word ``essentially'' to mean ``approximately'' or ``effectively''. +%\item In your paper title, if the words ``that uses'' can accurately replace the word ``using'', capitalize the ``u''; if not, keep using lower-cased. +%\item Be aware of the different meanings of the homophones ``affect'' and ``effect'', ``complement'' and ``compliment'', ``discreet'' and ``discrete'', ``principal'' and ``principle''. +%\item Do not confuse ``imply'' and ``infer''. +%\item The prefix ``non'' is not a word; it should be joined to the word it modifies, usually without a hyphen. +%\item There is no period after the ``et'' in the Latin abbreviation ``et al.''. +%\item The abbreviation ``i.e.'' means ``that is'', and the abbreviation ``e.g.'' means ``for example''. +%\end{itemize} +%An excellent style manual for science writers is \cite{b7}. + + +%\subsection{Identify the Headings} +%Headings, or heads, are organizational devices that guide the reader through +%your paper. There are two types: component heads and text heads. +% +%Component heads identify the different components of your paper and are not +%topically subordinate to each other. Examples include Acknowledgments and +%References and, for these, the correct style to use is ``Heading 5''. Use +%``figure caption'' for your Figure captions, and ``table head'' for your +%table title. Run-in heads, such as ``Abstract'', will require you to apply a +%style (in this case, italic) in addition to the style provided by the drop +%down menu to differentiate the head from the text. +% +%Text heads organize the topics on a relational, hierarchical basis. For +%example, the paper title is the primary text head because all subsequent +%material relates and elaborates on this one topic. If there are two or more +%sub-topics, the next level head (uppercase Roman numerals) should be used +%and, conversely, if there are not at least two sub-topics, then no subheads +%should be introduced. +% +%\subsection{Figures and Tables} +%\paragraph{Positioning Figures and Tables} Place figures and tables at the top and +%bottom of columns. Avoid placing them in the middle of columns. Large +%figures and tables may span across both columns. Figure captions should be +%below the figures; table heads should appear above the tables. Insert +%figures and tables after they are cited in the text. Use the abbreviation +%``Fig.~\ref{fig}'', even at the beginning of a sentence. +% +%\begin{table}[htbp] +%\caption{Table Type Styles} +%\begin{center} +%\begin{tabular}{|c|c|c|c|} +%\hline +%\textbf{Table}&\multicolumn{3}{|c|}{\textbf{Table Column Head}} \\ +%\cline{2-4} +%\textbf{Head} & \textbf{\textit{Table column subhead}}& \textbf{\textit{Subhead}}& \textbf{\textit{Subhead}} \\ +%\hline +%copy& More table copy$^{\mathrm{a}}$& & \\ +%\hline +%\multicolumn{4}{l}{$^{\mathrm{a}}$Sample of a Table footnote.} +%\end{tabular} +%\label{tab1} +%\end{center} +%\end{table} +% +%\begin{figure}[htbp] +%\centerline{\includegraphics{fig1.png}} +%\caption{Example of a figure caption.} +%\label{fig} +%\end{figure} +% +%Figure Labels: Use 8 point Times New Roman for Figure labels. Use words +%rather than symbols or abbreviations when writing Figure axis labels to +%avoid confusing the reader. As an example, write the quantity +%``Magnetization'', or ``Magnetization, M'', not just ``M''. If including +%units in the label, present them within parentheses. Do not label axes only +%with units. In the example, write ``Magnetization (A/m)'' or ``Magnetization +%\{A[m(1)]\}'', not just ``A/m''. Do not label axes with a ratio of +%quantities and units. For example, write ``Temperature (K)'', not +%``Temperature/K''. +% +%\section*{Acknowledgment} +% +%The preferred spelling of the word ``acknowledgment'' in America is without +%an ``e'' after the ``g''. Avoid the stilted expression ``one of us (R. B. +%G.) thanks $\ldots$''. Instead, try ``R. B. G. thanks$\ldots$''. Put sponsor +%acknowledgments in the unnumbered footnote on the first page. +% +%\section*{References} +% +%Please number citations consecutively within brackets \cite{b1}. The +%sentence punctuation follows the bracket \cite{b2}. Refer simply to the reference +%number, as in \cite{b3}---do not use ``Ref. \cite{b3}'' or ``reference \cite{b3}'' except at +%the beginning of a sentence: ``Reference \cite{b3} was the first $\ldots$'' +% +%Number footnotes separately in superscripts. Place the actual footnote at +%the bottom of the column in which it was cited. Do not put footnotes in the +%abstract or reference list. Use letters for table footnotes. +% +%Unless there are six authors or more give all authors' names; do not use +%``et al.''. Papers that have not been published, even if they have been +%submitted for publication, should be cited as ``unpublished'' \cite{b4}. Papers +%that have been accepted for publication should be cited as ``in press'' \cite{b5}. +%Capitalize only the first word in a paper title, except for proper nouns and +%element symbols. +% +%For papers published in translation journals, please give the English +%citation first, followed by the original foreign-language citation \cite{b6}. +% +%\begin{thebibliography}{00} +%\bibitem{b1} G. Eason, B. Noble, and I. N. Sneddon, ``On certain integrals of Lipschitz-Hankel type involving products of Bessel functions,'' Phil. Trans. Roy. Soc. London, vol. A247, pp. 529--551, April 1955. +%\bibitem{b2} J. Clerk Maxwell, A Treatise on Electricity and Magnetism, 3rd ed., vol. 2. Oxford: Clarendon, 1892, pp.68--73. +%\bibitem{b3} I. S. Jacobs and C. P. Bean, ``Fine particles, thin films and exchange anisotropy,'' in Magnetism, vol. III, G. T. Rado and H. Suhl, Eds. New York: Academic, 1963, pp. 271--350. +%\bibitem{b4} K. Elissa, ``Title of paper if known,'' unpublished. +%\bibitem{b5} R. Nicole, ``Title of paper with only first word capitalized,'' J. Name Stand. Abbrev., in press. +%\bibitem{b6} Y. Yorozu, M. Hirano, K. Oka, and Y. Tagawa, ``Electron spectroscopy studies on magneto-optical media and plastic substrate interface,'' IEEE Transl. J. Magn. Japan, vol. 2, pp. 740--741, August 1987 [Digests 9th Annual Conf. Magnetics Japan, p. 301, 1982]. +%\bibitem{b7} M. Young, The Technical Writer's Handbook. Mill Valley, CA: University Science, 1989. +%\end{thebibliography} +%\vspace{12pt} +%\color{red} +%IEEE conference templates contain guidance text for composing and formatting conference papers. Please ensure that all template text is removed from your conference paper prior to submission to the conference. Failure to remove the template text from your paper may result in your paper not being published. + +\end{document} diff --git a/TODOS.txt b/TODOS.txt index 28df337..e315d0d 100644 --- a/TODOS.txt +++ b/TODOS.txt @@ -74,7 +74,7 @@ Update call_solver.jl to expose a function send_command(cmd::String; is_valid=ne # TODO 7/8/23 Make final API change of @satvariable to mirror JuMP @variable - done 7/8/23 -Update documentation and examples for variable macro. +Update documentation and examples for variable macro. - done 7/12/23 Use repo2docker to publish examples https://repo2docker.readthedocs.io/en/latest/usage.html # TODO 7/25/23 From cc3637d37180208403d78691208df11c06a273e1 Mon Sep 17 00:00:00 2001 From: Emiko Soroka Date: Sat, 29 Jul 2023 14:37:39 -0700 Subject: [PATCH 05/36] update gitignore for latex files --- .gitignore | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/.gitignore b/.gitignore index 29126e4..312b302 100644 --- a/.gitignore +++ b/.gitignore @@ -5,6 +5,13 @@ # Files generated by invoking Julia with --track-allocation *.jl.mem +# smt files generated by code +*.smt + +# checkpoints +*/.ipynb_checkpoints/* +*.vscode/* + # System-specific files and directories generated by the BinaryProvider and BinDeps packages # They contain absolute paths specific to the host computer, and so should not be committed deps/deps.jl @@ -22,3 +29,38 @@ docs/site/ # committed for packages, but should be committed for applications that require a static # environment. Manifest.toml + +## Core latex/pdflatex auxiliary files: +*.aux +*.lof +*.log +*.lot +*.fls +*.out +*.toc +*.fmt +*.fot +*.cb +*.cb2 +.*.lb +*.synctex.gz + +## Intermediate documents: +*.dvi +*.xdv +*-converted-to.* +# these rules might exclude image files for figures etc. +# *.ps +# *.eps +# *.pdf + +## Generated if empty string is given at "Please type another file name for output:" +# .pdf + +## Bibliography auxiliary files (bibtex/biblatex/biber): +*.bbl +*.bcf +*.blg +*-blx.aux +*-blx.bib +*.run.xml \ No newline at end of file From 6ad16a00e232b38e7895b3d0d35ac6bda89315df Mon Sep 17 00:00:00 2001 From: Emiko Soroka Date: Mon, 31 Jul 2023 12:06:57 -0700 Subject: [PATCH 06/36] working on paper! --- .../paper.tex | 190 +++++++++++++++--- TODOS.txt | 5 +- 2 files changed, 170 insertions(+), 25 deletions(-) diff --git a/SAT_package_paper/Conference-LaTeX-template_10-17-19/paper.tex b/SAT_package_paper/Conference-LaTeX-template_10-17-19/paper.tex index a48e3b9..081cb96 100644 --- a/SAT_package_paper/Conference-LaTeX-template_10-17-19/paper.tex +++ b/SAT_package_paper/Conference-LaTeX-template_10-17-19/paper.tex @@ -2,10 +2,14 @@ \IEEEoverridecommandlockouts % The preceding line is only needed to identify funding in the first footnote. If that is unneeded, please comment it out. %\usepackage{cite} +\usepackage[utf8]{inputenc} \usepackage{amsmath,amssymb,amsfonts} \usepackage{algorithmic} \usepackage{graphicx} \usepackage{textcomp} +\usepackage{fontspec} +\setmonofont{FreeMono} % has unicode symbols https://tex.stackexchange.com/questions/581407/how-can-i-get-both-greek-and-unicode-characters-to-render-in-a-verbatim-environm +% \setmonofont{DejaVu Mono} \usepackage{xcolor} %\def\BibTeX{{\rm B\kern-.05em{\sc i\kern-.025em b}\kern-.08em % T\kern-.1667em\lower.7ex\hbox{E}\kern-.125emX}} @@ -43,7 +47,7 @@ \maketitle \begin{abstract} -Automated theorem provers such as Z3 and CVC5 can check the satisfiability or validity of a logical formula stated in one or more theories. Theorem provers have applications in formal verification including practical tasks such as proving the security of firewall configurations or the correctness of safety-critical software. While the SMTLIB2 format can be used to interface with theorem proving software, its limited syntax hampers the specification of complex statements. In this paper we present a high-level Julia interface to specify problems in several common theories. +Automated theorem provers such as Z3 and CVC5 can check the satisfiability or validity of a logical formula stated in one or more theories. These provers, and the satisfiability modulo theories (SMT) problems they solve, have applications in formal verification including practical tasks such as proving the security of firewall configurations or the correctness of safety-critical software. While the SMT-LIB specification language can be used to interact with theorem proving software, a high-level interface allows for faster and easier specifications of complex SMT formulae. In this paper we present such an interface for the Julia programming language. \end{abstract} \begin{IEEEkeywords} @@ -59,54 +63,192 @@ \section{Introduction} In this paper we introduce \verb|BooleanSatisfiability.jl|, a Julia package that provides a high-level representation of SMT theories including propositional logic, integer and real-valued arithmetic, and IEEE floating-point numbers. \verb|BooleanSatisfiability.jl| is the first Julia package to provide this functionality. \section{Prior Work} -Two popular theorem provers are Z3, developed by Microsoft Research, and the open-source prover CVC5. Both provers including bindings for multiple programming languages, allowing access to some or all functionality with varying levels of abstraction. Additionally, both Z3 and CVC5 accept commands in the SMTLIB2 specification language \cite{smtlib2}. +Two popular theorem provers are Z3, developed by Microsoft Research, and the open-source prover CVC5. Both provers including bindings for multiple programming languages, allowing access to some or all functionality with varying levels of abstraction. Additionally, both Z3 and CVC5 accept commands in the SMT-LIB specification language \cite{smtlib2}. -Similar packages are available in other languages; for example, \verb|PySMT| provides a high-level SAT interface using the same strategy of translation to SMTLIB2 commands \cite{pysmt2015}. -To our knowledge, \verb|BooleanSatisfiability.jl| is the first Julia package to use the SMTLIB2 format for interactions with solvers, allowing compatibility with any theorem prover that supports SMTLIB2. +Similar packages are available in other languages; for example, \verb|PySMT| provides a high-level SAT interface using the same strategy of translation to SMT-LIB commands \cite{pysmt2015}. +To our knowledge, \verb|BooleanSatisfiability.jl| is the first Julia package to use the SMT-LIB format for interactions with solvers, allowing compatibility with any theorem prover that supports SMT-LIB. -\subsection{The SMTLIB language} -SMTLIB is a low-level specification language designed to standardize interactions with theorem provers. At time of writing, the current SMTLIB standard is V2.6; we used this version of the language specification when implementing our software. +\subsection{The SMT-LIB specification language} +SMT-LIB is low-level specification language designed to standardize interactions with theorem provers. At time of writing, the current SMT-LIB standard is V2.6; we used this version of the language specification when implementing our software. To disambiguate between SMT (satisfiability modulo theories) and this specification language, we always refer to the language as SMT-LIB. -SMTLIB uses a Lisp-like syntax designed to simplify input parsing. It is intended to provide an interactive interface, similar to Julia's REPL. The language supports declarations (for example, of variables or functions), assertions (requiring that a Boolean formula be true), and various solver commands. +SMT-LIB uses a Lisp-like syntax designed to simplify input parsing. It is intended to provide an interactive interface, similar to Julia's REPL. The language supports declarations (for example, of variables or functions), assertions (requiring that a Boolean formula be true), and various solver commands. -Figure ?%TODO figure +(TO DO should we discuss it more here?) %TODO + +Figure ? %TODO figure shows a simple example of a solver moving between modes as statements are received. Note that many commands are only valid in specific solver modes. For example, the command \verb|(get-model)| retrieves the satisfying assignment for a formula and is only valid in \verb|sat| mode, while \verb|(get-unsat-core)| is only valid in \verb|unsat| mode. Issuing a command in the wrong mode yields an error. -For a complete description of the SMTLIB language, readers are referred to \cite{smtlib2}. - +For a full description of SMT-LIB, readers are referred to \cite{smtlib2}. As the purpose of our software is to provide an abstraction on top of SMT-LIB, we refrain from describing the language. Knowledge of SMT-LIB is not required to understand and use the basic functionality of \verb|BooleanSatisfiability.jl|. \section{Package Design} %TODO diagram -The basic unit of an SMT formula is the expression (Figure ?). %TODO) -Expressions may represent single variables or operators and implements a tree structure capable of representing arbitrarily complex formulae. Julia's type system prevents expressions from being incorrectly combined. For example, $\neg\verb|x|$ is only valid if \verb|x| is of type \verb|BoolExpr|. +Our software facilitates the construction and SMT-LIB representation of SMT formulae, along with providing a simple interface to SMT-LIB compliant theorem provers. + +The basic unit of a formula in our software is the expression (Figure ?). %TODO) +Expressions may represent single variables or operators. An abstract type \verb|AbstractExpr| is provided. Concrete types inheriting from \verb|AbstractExpr| implement a tree structure capable of representing arbitrarily complex nested expressions. Julia's type system prevents expressions from being incorrectly combined using operators. For example, $\neg\verb|x|$ is only valid if \verb|x| is of type \verb|BoolExpr|. Output types of operations follow type compatibility and promotion rules; for example, if \verb|x| is a \verb|BoolExpr| and \verb|a| is an \verb|IntExpr|, \verb|x + a| is an \verb|IntExpr|. +\subsection{Expressions} +Variables are declared using \verb|@satvariable|. Vector- and matrix-valued variables are arrays of single-valued expressions, allowing them to inherit Julia's built in array functionality. The elements of said arrays are assigned human-readable names of the form \verb|name_i_j|. +\begin{verbatim} +@satvariable(x[1:2], Bool) +# x is an array of BoolExprs +# with names x_1, x_2 + +@satvariable(y[1:2, 1:3], Bool) +# y is an array of BoolExprs +# with names y_1_1, y_1_2, ... y_2_3 +\end{verbatim} + +Expressions constructed from operators and variables take names of the format \verb|OP_HASH| where \verb|OP| is the operator name and \verb|HASH| is computed from the names of child expressions using Julia's deterministic hash function. This ensures all expressions have unique names and allows components of nested expressions to be re-used when generating the SMT-LIB representation of an expression. In future versions of the software, this could also allow for optimization by memoizing large expressions with repeated smaller components. + +\subsection{SMT-LIB representation} + +While SMT-LIB permits expressions of arbitrary complexity, our software limits the depth of nested expressions by generating sub-expressions using SMT-LIB's \verb|(define-fun)|. This command defines a function over previously defined expressions. % TODO clean up this part + +\subsection{Interacting with Solvers} +Internally, our package uses Julia's \verb|Process| library to interact with a prover via input and output pipes. This supports the interactive nature of SMT2; for example, the command \verb|(get-model)| is required to retrieve a satisfying assignment, but cannot be issued if the formula is unsatisfiable. + +\section{Using The Package} \subsection{Working with formulae}. -The function \verb|smt(e::AbstractExpr)| returns the SMTLIB representation of expression \verb|e| as a string. +The function \verb|smt(e::AbstractExpr)| returns the SMT2 representation of expression \verb|e| as a string. The function \verb|sat!(e::BoolExpr, prover::Prover)| calls the given prover on \verb|e| and returns either \verb|:SAT|, \verb|:UNSAT|, or \verb|:ERROR|. If \verb|e| is \verb|:SAT|, the values of all nested expressions in \verb|e| are updated to allow easy retrieval of the satisfying assignment. If \verb|e| is \verb|:UNSAT|, the values of all nested expressions are set to \verb|nothing|. -Note that \verb|sat!| can only be called on Boolean expressions, because the purpose of a theorem prover is to determine whether a Boolean statement is \verb|true| or \verb|false|. In comparison, one can generate the SMT representation of any \verb|AbstractExpr|, including non-Boolean expressions that do not represent valid SMT problems. +Note that \verb|sat!| can only be called on Boolean expressions, because the purpose of a theorem prover is to determine whether a Boolean statement is \verb|true| or \verb|false|. In comparison, one can generate the SMT2 representation of any \verb|AbstractExpr|, including non-Boolean expressions that do not represent valid SMT problems. -Internally, our package uses Julia's \verb|Process| library to interact with a prover via input and output pipes. This supports the interactive nature of SMTLIB; for example, the command \verb|(get-model)| is required to retrieve a satisfying assignment, but cannot be issued if the formula is unsatisfiable. - -\subsection{Interface} +\section{Specifying an SMT Problem} +\subsection{Variables} New variables are declared using the \verb|@satvariable| macro, which behaves similarly to the \verb|@variable| macro in JuMP \cite{Lubin2023}. -The \verb|@satvariable| macro takes two arguments: a variable name with optional size and shape (for creating vector-valued and matrix-valued variables), and a symbol representing the variable type. -\begin{itemize} -\item \verb|@satvariable(x, :Bool)| declares a single \verb|BoolExpr| \verb|x|. -\item \verb|@satvariable(y[1:n], :Bool)| declares an $n$-vector of \verb|BoolExpr|s \verb|y|. -\item \verb|@satvariable(z[1:n], :Int)| declares an $m\times n$ matrix of \verb|IntExpr|s \verb|z|. -\end{itemize} +The \verb|@satvariable| macro takes two arguments: a variable name with optional size and shape (for creating vector-valued and matrix-valued variables), and the variable type. + +\begin{verbatim} +# Single BoolExpr +@satvariable(x, Bool) + +# n-vector of BoolExpr +@satvariable(y[1:n], Bool) + +# m x n vector of IntExpr +@satvariable(z[1:n], Int) +\end{verbatim} Variables may be combined using operations, which we distinguish by return type. Boolean operations \verb|and|, \verb|or|, \verb|not|, \verb|xor|, \verb|implies|, \verb|iff|, and \verb|ite| (if-then-else) return Boolean expressions. -The integer or real-valued operations \verb|+|, \verb|-|, \verb|*| return integer or real expressions (using Julia type promotion rules). Division (\verb|/|) is only valid over real-valued expressions. + +\subsection{Type Promotion} +Integer or real-valued operations \verb|+|, \verb|-|, \verb|*| return integer or real expressions using Julia type promotion rules. Division (\verb|/|) is only valid over real-valued expressions. +\begin{verbatim} +@satvariable(a, Bool) +@satvariable(b, Int) +@satvariable(c, Real) + +a + b # returns IntExpr +b + c # returns RealExpr +a + b > 1 # returns BoolExpr +\end{verbatim} + +Type promotion also applies to constants, which are automatically wrapped when nested in expressions. Continuing the above example: +\begin{verbatim} +b + true # IntExpr + Bool returns IntExpr +b + 1.0 # IntExpr + Real returns RealExpr +c + 1 # RealExpr + Int returns RealExpr +\end{verbatim} + +\subsection{Operators} +We define the following operators. +\begin{table}[h!] + \centering + \begin{tabular}{|c|c|c|c|c|} + %\hline + %\multicolumn{5}{1}{Boolean Operators}\\ + \hline + Operator & \# Inputs & Input Type(s) & Return Type & Symbol\\ + \hline + \verb|or| & $n\geq 2$ & \verb|BoolExpr| & \verb|BoolExpr| & \verb|any|, \verb|∨|\\ + \hline + \verb|and| & $n\geq 2$ & \verb|BoolExpr| & \verb|BoolExpr| & \verb|all|, \verb|∧|\\ + \hline + \verb|not| & 1 & \verb|BoolExpr| & \verb|BoolExpr| & \verb|¬|\\ + \hline + \verb|implies| & 2 & \verb|BoolExpr| & \verb|BoolExpr| & \verb|⟹|\\ + \hline + \verb|xor| & $n\geq 2$ & \verb|BoolExpr| & \verb|BoolExpr| & \verb|⊻|\\ + \hline + \verb|iff| & 2 & \verb|BoolExpr| & \verb|BoolExpr| & \verb|⟺|\\ + \hline + \verb|ite|\footnote{The operator \texttt{ite} refers to ``if-then-else". \texttt{ite(x, y, z)} is equivalent to \texttt{(x ⟹ y) ∧ (¬x ⟹ z)}.} + & 3 & \verb|BoolExpr| & \verb|BoolExpr| & ~\\ + \hline + \end{tabular} +\label{tab:bool_ops} +\caption{Boolean operators} +\end{table} + +\begin{table}[h!] + \centering + \begin{tabular}{|c|c|c|c|} + %\hline + %\multicolumn{5}{|1|}{Arithmetic Operators}\\ + \hline + Operator & Input Type(s) & Return Type\\ + \hline + \verb|>| & \verb|BoolExpr|, \verb|IntExpr|, \verb|RealExpr|& \verb|BoolExpr| \\ + \hline + \verb|>=| & \verb|BoolExpr|, \verb|IntExpr|, \verb|RealExpr|& \verb|BoolExpr| \\ + \hline + \verb|<| & \verb|BoolExpr|, \verb|IntExpr|, \verb|RealExpr|& \verb|BoolExpr| \\ + \hline + \verb|<=| & \verb|BoolExpr|, \verb|IntExpr|, \verb|RealExpr|& \verb|BoolExpr| \\ + \hline + \verb|==|\footnote{To check whether two \texttt{AbstractExpr} are equivalent, use \texttt{isequal}.} + & \verb|BoolExpr|, \verb|IntExpr|, \verb|RealExpr|& \verb|BoolExpr| \\ + \hline + \verb|-| (unary) & \verb|IntExpr|, \verb|RealExpr| & \verb|IntExpr|, \verb|RealExpr|\\ + \hline + \verb|+| & \verb|BoolExpr|, \verb|IntExpr|, \verb|RealExpr|& \verb|IntExpr|, \verb|RealExpr| \\ + \hline + \verb|-| & \verb|BoolExpr|, \verb|IntExpr|, \verb|RealExpr|& \verb|IntExpr|, \verb|RealExpr| \\ + \hline + \verb|*| & \verb|BoolExpr|, \verb|IntExpr|, \verb|RealExpr|& \verb|IntExpr|, \verb|RealExpr| \\ + \hline + \verb|/| & \verb|RealExpr|& \verb|RealExpr| \\ + \hline +\end{tabular} +\label{tab:arithmetic_ops} +\caption{Comparison and arithmetic operators} +\end{table} + +\subsection{Operator Precedence} +Julia defines the operator precedence and associativity for all symbolic operators defined in this package. +For the most up-to-date description of Julia's operator precedence rules, see. %TODO cite https://docs.julialang.org/en/v1/manual/mathematical-operations/#Operator-Precedence-and-Associativity +One can also determine operator precedence using the call \verb|Base.operator_precedence(s)| where \verb|s| is a symbol (e.g. \verb|:+| or \verb|:*|). Higher numbers indicate greater precedence. + +Precedence and associativity rules can yield misleading expressions or unexpected type errors. Readers are encouraged to parenthesize expressions, avoiding potential sources of confusion. The following illustrative examples are provided. + +\begin{verbatim} +@satvariable(x, Bool) +@satvariable(y, Bool) +@satvariable(z, Bool) + +x⟹y ∧ y⟹z +# this is implies(x, implies(and(y, y), z)) +# it is not (x⟹y) ∧ (y⟹z) + +x ∧ y + z # equivalent to (x ∧ y) + z + +@satvariable(a, Int) +@satvariable(b, Int) + +a >= 1 ∨ b >= 1 # yields a type error +(a >= 1) ∨ (b >= 1) # valid expression +\end{verbatim} \section{Examples} +% TODO \subsection*{Custom solver interactions} We expose the low-level interface, allowing advanced users to send SMT commands and receive prover responses. Users are responsible for ensuring the correctness of these commands, as well as interpreting the results. In this use case, \verb|BooleanSatisfiability.jl| can be used to automate generation of the SMT problem and programmatically interact with solvers, extending the usability of the SMT interface. diff --git a/TODOS.txt b/TODOS.txt index e315d0d..cbdcae7 100644 --- a/TODOS.txt +++ b/TODOS.txt @@ -79,4 +79,7 @@ Use repo2docker to publish examples https://repo2docker.readthedocs.io/en/latest # TODO 7/25/23 Change @satvariable to use Bool instead of :Bool, etc. - done 7/25/23 -Use system newline in smt() - done 7/25/23 \ No newline at end of file +Use system newline in smt() - done 7/25/23 + +# TODO 7/29/23 +and() and or() accept IntExpr type which is not permitted and doesn't match the SMT2 behavior. The operators \wedge and \vee correctly reject them. \ No newline at end of file From df832bfa0c886a5b5a8655edf88904f4f33fb3c8 Mon Sep 17 00:00:00 2001 From: Emiko Soroka Date: Mon, 31 Jul 2023 17:51:44 -0700 Subject: [PATCH 07/36] continuing work on paper --- .../paper.tex | 98 +++++++++++++------ TODOS.txt | 3 +- 2 files changed, 70 insertions(+), 31 deletions(-) diff --git a/SAT_package_paper/Conference-LaTeX-template_10-17-19/paper.tex b/SAT_package_paper/Conference-LaTeX-template_10-17-19/paper.tex index 081cb96..1798cb7 100644 --- a/SAT_package_paper/Conference-LaTeX-template_10-17-19/paper.tex +++ b/SAT_package_paper/Conference-LaTeX-template_10-17-19/paper.tex @@ -6,6 +6,7 @@ \usepackage{amsmath,amssymb,amsfonts} \usepackage{algorithmic} \usepackage{graphicx} +\usepackage{tablefootnote} \usepackage{textcomp} \usepackage{fontspec} \setmonofont{FreeMono} % has unicode symbols https://tex.stackexchange.com/questions/581407/how-can-i-get-both-greek-and-unicode-characters-to-render-in-a-verbatim-environm @@ -58,9 +59,10 @@ \section{Introduction} Satisfiability modulo theories (SMT) is a general framework for computational theorem proving, in which the goal is to algorithmically find a satisfying assignment of variables such that one or more logical statements hold true. SMT encompasses a broad class of problems including the theories of propositional logic, integer arithmetic, floating-point arithmetic, and data structures. SMT formulae are used in formal verification and model checking to prove or disprove the correctness of a system. A decision procedure for an SMT problem is an algorithm that either finds such an assignment or determines that the given formula is unsatisfiable. Theorem proving software such as Z3 or CVC5 \cite{z3, cvc5} -implements these procedures, allowing users to check SMT formulae and find satisfying assignments where possible. However, theorem provers themselves are low-level tools intended to be integrated into other software. +uses decision procedures to check SMT formulae and find satisfying assignments where possible. However, theorem provers themselves are low-level tools intended to be integrated into other software. -In this paper we introduce \verb|BooleanSatisfiability.jl|, a Julia package that provides a high-level representation of SMT theories including propositional logic, integer and real-valued arithmetic, and IEEE floating-point numbers. \verb|BooleanSatisfiability.jl| is the first Julia package to provide this functionality. +In this paper we introduce \verb|BooleanSatisfiability.jl|, a Julia package providing a high-level representation for SMT formulae including propositional logic, integer and real-valued arithmetic.% TODO, and IEEE floating-point numbers. +\verb|BooleanSatisfiability.jl| is the first Julia package to provide this functionality. \section{Prior Work} Two popular theorem provers are Z3, developed by Microsoft Research, and the open-source prover CVC5. Both provers including bindings for multiple programming languages, allowing access to some or all functionality with varying levels of abstraction. Additionally, both Z3 and CVC5 accept commands in the SMT-LIB specification language \cite{smtlib2}. @@ -68,30 +70,36 @@ \section{Prior Work} Similar packages are available in other languages; for example, \verb|PySMT| provides a high-level SAT interface using the same strategy of translation to SMT-LIB commands \cite{pysmt2015}. To our knowledge, \verb|BooleanSatisfiability.jl| is the first Julia package to use the SMT-LIB format for interactions with solvers, allowing compatibility with any theorem prover that supports SMT-LIB. -\subsection{The SMT-LIB specification language} +\section{The SMT-LIB specification language} SMT-LIB is low-level specification language designed to standardize interactions with theorem provers. At time of writing, the current SMT-LIB standard is V2.6; we used this version of the language specification when implementing our software. To disambiguate between SMT (satisfiability modulo theories) and this specification language, we always refer to the language as SMT-LIB. -SMT-LIB uses a Lisp-like syntax designed to simplify input parsing. It is intended to provide an interactive interface, similar to Julia's REPL. The language supports declarations (for example, of variables or functions), assertions (requiring that a Boolean formula be true), and various solver commands. +SMT-LIB uses a Lisp-like syntax designed to simplify input parsing. It is intended to provide an interactive interface for theorem proving similar to Julia's REPL. SMT-LIB supports declaring variables, defining functions, making assertions (e.g. requiring that a Boolean formula be true), and issuing solver commands. Figure ? % TODO \ref{fig:smtbasic} +provides an example of an SMT solver moving between modes. -(TO DO should we discuss it more here?) %TODO +SMT expressions have an associated \textit{sort}, which constrains what functions or operations are valid for a given expression. For example, the SMT-LIB variable declaration \verb|(declare-const a Int)| declares a symbol \verb|a| with sort \verb|Int|, and the function definition \verb|(define-fun f () Bool (> a 1))| defines a function \verb|a > 1| with sort \verb|Bool|. The concept of SMT sorts maps cleanly onto Julia's type system. -Figure ? %TODO figure -shows a simple example of a solver moving between modes as statements are received. Note that many commands are only valid in specific solver modes. -For example, the command \verb|(get-model)| retrieves the satisfying assignment for a formula and is only valid in \verb|sat| mode, while \verb|(get-unsat-core)| is only valid in \verb|unsat| mode. Issuing a command in the wrong mode yields an error. +%(TO DO should we discuss SMT-LIB more here?) %TODO -For a full description of SMT-LIB, readers are referred to \cite{smtlib2}. As the purpose of our software is to provide an abstraction on top of SMT-LIB, we refrain from describing the language. Knowledge of SMT-LIB is not required to understand and use the basic functionality of \verb|BooleanSatisfiability.jl|. +%Figure ? %TODO figure +%shows a simple example of a solver moving between modes as statements are received. +One limitation of SMT-LIB is that many commands are only valid in specific solver modes. +For example, the command \verb|(get-model)| retrieves the satisfying assignment for a formula and is only valid in \verb|sat| mode, while \verb|(get-unsat-core)| is only valid in \verb|unsat| mode. Issuing a command in the wrong mode yields an error, thus many useful sequences of SMT-LIB commands cannot be scripted in advance. + +For a full description of SMT-LIB, readers are referred to \cite{smtlib2}. As the purpose of our software is to provide an abstraction on top of SMT-LIB, we refrain from an in-depth description of the language. Knowledge of SMT-LIB is not required to understand and use the basic functionality of \verb|BooleanSatisfiability.jl|. \section{Package Design} %TODO diagram Our software facilitates the construction and SMT-LIB representation of SMT formulae, along with providing a simple interface to SMT-LIB compliant theorem provers. The basic unit of a formula in our software is the expression (Figure ?). %TODO) -Expressions may represent single variables or operators. An abstract type \verb|AbstractExpr| is provided. Concrete types inheriting from \verb|AbstractExpr| implement a tree structure capable of representing arbitrarily complex nested expressions. Julia's type system prevents expressions from being incorrectly combined using operators. For example, $\neg\verb|x|$ is only valid if \verb|x| is of type \verb|BoolExpr|. +Expressions may represent single variables or operators combining expressions. An abstract type \verb|AbstractExpr| is provided. Concrete types inheriting from \verb|AbstractExpr| implement a tree structure capable of representing arbitrarily complex nested expressions. Julia's type system prevents expressions from being incorrectly combined operators. For example, $\neg\verb|x|$ is only valid if \verb|x| is of type \verb|BoolExpr|. Output types of operations follow type compatibility and promotion rules; for example, if \verb|x| is a \verb|BoolExpr| and \verb|a| is an \verb|IntExpr|, \verb|x + a| is an \verb|IntExpr|. \subsection{Expressions} -Variables are declared using \verb|@satvariable|. Vector- and matrix-valued variables are arrays of single-valued expressions, allowing them to inherit Julia's built in array functionality. The elements of said arrays are assigned human-readable names of the form \verb|name_i_j|. +Variables are declared using \verb|@satvariable|. Vector- and matrix-valued variables are arrays of single-valued expressions; thus, Julia's built in array functionality allows operators to be broadcast across said variables. + +Elements of vector and matrix expressions are assigned human-readable names of the form \verb|name_i_j|. \begin{verbatim} @satvariable(x[1:2], Bool) # x is an array of BoolExprs @@ -102,22 +110,52 @@ \subsection{Expressions} # with names y_1_1, y_1_2, ... y_2_3 \end{verbatim} -Expressions constructed from operators and variables take names of the format \verb|OP_HASH| where \verb|OP| is the operator name and \verb|HASH| is computed from the names of child expressions using Julia's deterministic hash function. This ensures all expressions have unique names and allows components of nested expressions to be re-used when generating the SMT-LIB representation of an expression. In future versions of the software, this could also allow for optimization by memoizing large expressions with repeated smaller components. +Expressions constructed from operators and variables take names of the format \verb|OP_HASH| where \verb|OP| is the operator name and \verb|HASH| is computed from the names of child expressions using Julia's deterministic hash function. This ensures all expressions have unique names and allows components of nested expressions to be re-used when generating the SMT-LIB representation of an expression. In future versions of our software, this could also allow for optimization by memoizing large expressions with repeated smaller components. + +Expressions are simplified where possible: specifically, \verb|not(not(expr))| simplifies to \verb|expr|, and nested conjunctions or disjunctions are flattened. + +\subsection{Constants} +Constants are automatically wrapped. Julia's native \verb|Bool|, \verb|Int|, and \verb|Float64| types interoperate with our \verb|BoolExpr|, \verb|IntExpr| and \verb|RealExpr| types as expected, following type promotion rules. + +Numeric constants are combined when possible: for example, \verb|true + 2| will be stored as integer \verb|3| and \verb|1 + 2.5| is promoted to \verb|3.5|. Logical expressions involving constants can often be simplified. The following examples are provided. +\begin{verbatim} +@satvariable(z, Bool) +and(false, z) # returns false +implies(false, z) # returns true +iff(z, false) # returns not(z) +\end{verbatim} \subsection{SMT-LIB representation} -While SMT-LIB permits expressions of arbitrary complexity, our software limits the depth of nested expressions by generating sub-expressions using SMT-LIB's \verb|(define-fun)|. This command defines a function over previously defined expressions. % TODO clean up this part +While SMT-LIB permits expressions of arbitrary complexity, our software limits the depth of nested expressions by generating sub-expressions using SMT-LIB's \verb|(define-fun)| to define sub-expressions without \verb|assert|ing them. % TODO clean up this part +A representative example is provided below. +\begin{verbatim} +@satvariable(x, Bool) +@satvariable(y, Bool) +expr = or(¬x, and(¬x, y)) +print(smt(expr)) +>>> (declare-const x Bool) +>>> (declare-const y Bool) +>>> (define-fun NOT_53b20e3050918288 () Bool + (not x)) +>>> (define-fun AND_eb3b71ab55532084 () Bool + (and NOT_53b20e3050918288 y)) +>>> (define-fun OR_90de3d1a32047990 () Bool + (or AND_eb3b71ab55532084 NOT_53b20e3050918288)) +>>> (assert OR_90de3d1a32047990) +\end{verbatim} +Although \verb|¬x| appears twice in \verb|expr|, it is defined once and reused. \subsection{Interacting with Solvers} -Internally, our package uses Julia's \verb|Process| library to interact with a prover via input and output pipes. This supports the interactive nature of SMT2; for example, the command \verb|(get-model)| is required to retrieve a satisfying assignment, but cannot be issued if the formula is unsatisfiable. +Internally, our package uses Julia's \verb|Process| library to interact with a prover via input and output pipes. This supports the interactive nature of SMT-LIB.%; for example, the command \verb|(get-model)| is required to retrieve a satisfying assignment, but cannot be issued if the formula is unsatisfiable. \section{Using The Package} \subsection{Working with formulae}. -The function \verb|smt(e::AbstractExpr)| returns the SMT2 representation of expression \verb|e| as a string. +The function \verb|smt(e::AbstractExpr)| returns the SMT-LIB representation of expression \verb|e| as a string. If \verb|e| is a Boolean expression, \verb|smt| will assert \verb|e|; otherwise \verb|smt| will simply generate the SMT-LIB statements defining \verb|e|. This behavior can be controlled using the optional keyword argument \texttt{assert=true|false}. The related function \verb|save(e::AbstractExpr, filename="out")| writes the output of \verb|smt(e)| to the text file \verb|out.smt|. -The function \verb|sat!(e::BoolExpr, prover::Prover)| calls the given prover on \verb|e| and returns either \verb|:SAT|, \verb|:UNSAT|, or \verb|:ERROR|. If \verb|e| is \verb|:SAT|, the values of all nested expressions in \verb|e| are updated to allow easy retrieval of the satisfying assignment. If \verb|e| is \verb|:UNSAT|, the values of all nested expressions are set to \verb|nothing|. +The function \verb|sat!(e::BoolExpr, solver::solver)| calls the given solver on \verb|e| and returns either \verb|:SAT|, \verb|:UNSAT|, or \verb|:ERROR|. If \verb|e| is \verb|:SAT|, the values of all nested expressions in \verb|e| are updated to allow easy retrieval of the satisfying assignment. If \verb|e| is \verb|:UNSAT|, the values of all nested expressions are set to \verb|nothing|. -Note that \verb|sat!| can only be called on Boolean expressions, because the purpose of a theorem prover is to determine whether a Boolean statement is \verb|true| or \verb|false|. In comparison, one can generate the SMT2 representation of any \verb|AbstractExpr|, including non-Boolean expressions that do not represent valid SMT problems. +Note that \verb|sat!| can only be called on Boolean expressions, because the purpose of a theorem prover is to determine whether a Boolean statement is \verb|true| or \verb|false|. In comparison, one can generate the SMT-LIB representation of any \verb|AbstractExpr|, including non-Boolean expressions that do not represent valid SMT problems. Tables \ref{tab:bool_ops} and \ref{tab:arithmetic_ops} provide an overview of which operators return Boolean expressions. \section{Specifying an SMT Problem} \subsection{Variables} @@ -151,7 +189,7 @@ \subsection{Type Promotion} a + b > 1 # returns BoolExpr \end{verbatim} -Type promotion also applies to constants, which are automatically wrapped when nested in expressions. Continuing the above example: +Type promotion also applies to constants. Continuing the above example: \begin{verbatim} b + true # IntExpr + Bool returns IntExpr b + 1.0 # IntExpr + Real returns RealExpr @@ -180,12 +218,12 @@ \subsection{Operators} \hline \verb|iff| & 2 & \verb|BoolExpr| & \verb|BoolExpr| & \verb|⟺|\\ \hline - \verb|ite|\footnote{The operator \texttt{ite} refers to ``if-then-else". \texttt{ite(x, y, z)} is equivalent to \texttt{(x ⟹ y) ∧ (¬x ⟹ z)}.} + \verb|ite|\tablefootnote{The operator \texttt{ite} refers to ``if-then-else". \texttt{ite(x, y, z)} is equivalent to \texttt{(x ⟹ y) ∧ (¬x ⟹ z)}.} & 3 & \verb|BoolExpr| & \verb|BoolExpr| & ~\\ \hline \end{tabular} +\caption{Boolean operators.} \label{tab:bool_ops} -\caption{Boolean operators} \end{table} \begin{table}[h!] @@ -196,30 +234,30 @@ \subsection{Operators} \hline Operator & Input Type(s) & Return Type\\ \hline - \verb|>| & \verb|BoolExpr|, \verb|IntExpr|, \verb|RealExpr|& \verb|BoolExpr| \\ + \verb|>| & Any numeric expr. & \verb|BoolExpr| \\ \hline - \verb|>=| & \verb|BoolExpr|, \verb|IntExpr|, \verb|RealExpr|& \verb|BoolExpr| \\ + \verb|>=| & Any numeric expr. & \verb|BoolExpr| \\ \hline - \verb|<| & \verb|BoolExpr|, \verb|IntExpr|, \verb|RealExpr|& \verb|BoolExpr| \\ + \verb|<| & Any numeric expr. & \verb|BoolExpr| \\ \hline - \verb|<=| & \verb|BoolExpr|, \verb|IntExpr|, \verb|RealExpr|& \verb|BoolExpr| \\ + \verb|<=| & Any numeric expr. & \verb|BoolExpr| \\ \hline - \verb|==|\footnote{To check whether two \texttt{AbstractExpr} are equivalent, use \texttt{isequal}.} - & \verb|BoolExpr|, \verb|IntExpr|, \verb|RealExpr|& \verb|BoolExpr| \\ + \verb|==|\tablefootnote{To check whether two \texttt{AbstractExpr} are equivalent, use \texttt{isequal}.} + & Any numeric expr. & \verb|BoolExpr| \\ \hline \verb|-| (unary) & \verb|IntExpr|, \verb|RealExpr| & \verb|IntExpr|, \verb|RealExpr|\\ \hline - \verb|+| & \verb|BoolExpr|, \verb|IntExpr|, \verb|RealExpr|& \verb|IntExpr|, \verb|RealExpr| \\ + \verb|+| & Any numeric expr. & \verb|IntExpr|, \verb|RealExpr| \\ \hline - \verb|-| & \verb|BoolExpr|, \verb|IntExpr|, \verb|RealExpr|& \verb|IntExpr|, \verb|RealExpr| \\ + \verb|-| & Any numeric expr.& \verb|IntExpr|, \verb|RealExpr| \\ \hline - \verb|*| & \verb|BoolExpr|, \verb|IntExpr|, \verb|RealExpr|& \verb|IntExpr|, \verb|RealExpr| \\ + \verb|*| & Any numeric expr. & \verb|IntExpr|, \verb|RealExpr| \\ \hline \verb|/| & \verb|RealExpr|& \verb|RealExpr| \\ \hline \end{tabular} +\caption{Comparison and arithmetic operators. Where ``Any numeric expr" is listed, this refers to \texttt{BoolExpr}, \texttt{IntExpr}, \texttt{RealExpr}, or a \texttt{Bool}, \texttt{Int}, or \texttt{Float} constant. The return type of an arithmetic operator is determined by Julia's \texttt{Int} and \texttt{Float} type promotion rules.} \label{tab:arithmetic_ops} -\caption{Comparison and arithmetic operators} \end{table} \subsection{Operator Precedence} diff --git a/TODOS.txt b/TODOS.txt index cbdcae7..aec8553 100644 --- a/TODOS.txt +++ b/TODOS.txt @@ -82,4 +82,5 @@ Change @satvariable to use Bool instead of :Bool, etc. - done 7/25/23 Use system newline in smt() - done 7/25/23 # TODO 7/29/23 -and() and or() accept IntExpr type which is not permitted and doesn't match the SMT2 behavior. The operators \wedge and \vee correctly reject them. \ No newline at end of file +and() and or() accept IntExpr type which is not permitted and doesn't match the SMT2 behavior. The operators \wedge and \vee correctly reject them. +add an option assert=false to smt() which controls whether assert is generated \ No newline at end of file From 4e385575c97b8561750a82b2a5d1dc907174a8ea Mon Sep 17 00:00:00 2001 From: Emiko Soroka Date: Mon, 31 Jul 2023 23:37:36 -0700 Subject: [PATCH 08/36] Added Windows compatibility. Tested and it works on a Windows machine with z3. --- src/call_solver.jl | 10 +++++++--- test/solver_interface_tests.jl | 11 +++++++---- 2 files changed, 14 insertions(+), 7 deletions(-) diff --git a/src/call_solver.jl b/src/call_solver.jl index cd63b68..25bdbc4 100644 --- a/src/call_solver.jl +++ b/src/call_solver.jl @@ -7,9 +7,13 @@ end # some instantiation options Solver(name::String, cmd::Cmd) = Solver(name, cmd, Dict{String, Any}()) -Z3() = Solver("Z3", `z3 -smt2 -in`, Dict{String, Any}()) -CVC5() = Solver("CVC5", `cvc5 --interactive --produce-models`, Dict{String, Any}()) - +if Sys.iswindows() + Z3() = Solver("Z3", `z3.exe -smt2 -in`, Dict{String, Any}()) + CVC5() = Solver("CVC5", `cvc5.exe --interactive --produce-models`, Dict{String, Any}()) +else + Z3() = Solver("Z3", `z3 -smt2 -in`, Dict{String, Any}()) + CVC5() = Solver("CVC5", `cvc5 --interactive --produce-models`, Dict{String, Any}()) +end ##### INVOKE AND TALK TO SOLVER ##### diff --git a/test/solver_interface_tests.jl b/test/solver_interface_tests.jl index 5c962a7..ba7cffb 100644 --- a/test/solver_interface_tests.jl +++ b/test/solver_interface_tests.jl @@ -120,14 +120,17 @@ end all(x[1:2] .∨ y), all(¬y), ] - input = smt(exprs...)*"(check-sat)\n" + line_ending = Sys.iswindows() ? "\r\n" : "\n" + input = smt(exprs...)*"(check-sat)$line_ending" # Set up a custom solver that doesn't work (it should be z3) - solver = Solver("Z3", `Z3 -smt2 -in`) - @test_throws Base.IOError open_solver(solver) + if !Sys.iswindows() # this test doesn't work on Windows, probably because Windows cmd sucks + solver = Solver("Z3", `Z3 -smt2 -in`) + @test_throws Base.IOError open_solver(solver) + end # Interact using send_command proc, pstdin, pstdout, pstderr = open_solver(Z3()) output = send_command(pstdin, pstdout, input, is_done=nested_parens_match) - @test output == "sat\n" + @test output == "sat$line_ending" end \ No newline at end of file From 31814ccaa0b17235152f3234bfe2e15e7e317410 Mon Sep 17 00:00:00 2001 From: Emiko Soroka Date: Tue, 1 Aug 2023 11:29:32 -0700 Subject: [PATCH 09/36] 1. Added Windows installation instructions 2. Fixed (?) CI and docs build badges in README, including link to docs --- README.md | 4 +--- docs/src/installation.md | 13 ++++++++++++- 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 05c67bf..21d7fe4 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,6 @@ # [BooleanSatisfiability](https://elsoroka.github.io/BooleanSatisfiability.jl) -![example workflow](https://github.com/github/docs/actions/workflows/ci.yml/badge.svg) [![codecov](https://codecov.io/gh/elsoroka/BooleanSatisfiability.jl/branch/main/graph/badge.svg?token=84BIREQL46)](https://codecov.io/gh/elsoroka/BooleanSatisfiability.jl) - -[![Build Status](https://github.com/elsoroka/BooleanSatisfiability.jl/actions/workflows/CI.yml/badge.svg?branch=main)](https://github.com/elsoroka/BooleanSatisfiability.jl/actions/workflows/CI.yml?query=branch%3Amain) +[![build status](https://github.com/elsoroka/BooleanSatisfiability.jl/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/elsoroka/BooleanSatisfiability.jl/actions/workflows/CI.yml?query=branch%3Amain) [![docs](https://github.com/elsoroka/BooleanSatisfiability.jl/actions/workflows/docs.yml/badge.svg)](https://elsoroka.github.io/BooleanSatisfiability.jl/) [![codecov](https://codecov.io/gh/elsoroka/BooleanSatisfiability.jl/branch/main/graph/badge.svg?token=84BIREQL46)](https://codecov.io/gh/elsoroka/BooleanSatisfiability.jl) BooleanSatisfiability.jl is a package for representing Boolean satisfiability (SAT) and selected other satisfiability modulo theories (SMT) problems in Julia. This package provides a simple front-end interface to common SMT solvers, including full support for vector-valued and matrix-valued expressions. diff --git a/docs/src/installation.md b/docs/src/installation.md index 9a2430d..bd5addd 100644 --- a/docs/src/installation.md +++ b/docs/src/installation.md @@ -28,4 +28,15 @@ If you can launch cvc5 from the command line by typing `cvc5 --interactive --pro (TODO) ### Windows -(TODO) \ No newline at end of file +**To install Z3** +* Download the appropriate zip file for the [latest Z3 release](https://github.com/Z3Prover/z3/releases). +* Unzip the file and put it in your applications folder. +* Find z3.exe. Typically this will be in a bin file in your unzipped folder. Don't move it, but make a note of this file path. +* Add the z3.exe file path to your PATH environment variable ([here's how to do this](https://helpdeskgeek.com/windows-10/add-windows-path-environment-variable/)). +If you can open the WIndows command line and launch z3 by typing `z3.exe -smt2 -in`, your installation is correct. + +**To install cvc5** +* Download the [latest release](https://github.com/cvc5/cvc5/releases/) of cvc5. Make sure you save the exe file as `cvc5.exe`, not `cvc5-Win64.exe` or anything else. +* Make a note of the file path where you put cvc5.exe. +* Add the cvc5.exe file path to your PATH environment variable ([here's how to do this](https://helpdeskgeek.com/windows-10/add-windows-path-environment-variable/)). +If you can open the Windows command line and launch cvc5 by typing `cvc5 --interactive --produce-models`, your installation is correct. From b6e8674e1425cd693cf71f2079a7bfb8764ebe63 Mon Sep 17 00:00:00 2001 From: Emiko Soroka Date: Tue, 1 Aug 2023 11:37:04 -0700 Subject: [PATCH 10/36] changed workflow names so they aren't so long, they should be ci and docs --- .github/workflows/ci.yml | 2 +- .github/workflows/docs.yml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1a3bd99..bc78fb8 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,4 +1,4 @@ -name: Workflow for Codecov example-julia +name: CI on: push: branches: diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index b546215..6cb2175 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -1,4 +1,4 @@ -name: Build and Deploy Documentation +name: docs # https://github.com/julia-actions/julia-docdeploy on: push: From fefb06ef52e6ccda368a1d274bcc3760f98c1787 Mon Sep 17 00:00:00 2001 From: Emiko Soroka Date: Tue, 1 Aug 2023 21:33:09 -0700 Subject: [PATCH 11/36] Fixed behavior of smt() to: 1. control whether (assert name) is generated based on an optional argument, smt(expr, assert=true|false) (default is true). 2. correctly assert single variables when assert=true. --- TODOS.txt | 7 +++- docs/src/installation.md | 2 +- src/smt_representation.jl | 67 +++++++++++++++++++------------- test/smt_representation_tests.jl | 31 ++++++++------- 4 files changed, 61 insertions(+), 46 deletions(-) diff --git a/TODOS.txt b/TODOS.txt index aec8553..da9fe6c 100644 --- a/TODOS.txt +++ b/TODOS.txt @@ -82,5 +82,8 @@ Change @satvariable to use Bool instead of :Bool, etc. - done 7/25/23 Use system newline in smt() - done 7/25/23 # TODO 7/29/23 -and() and or() accept IntExpr type which is not permitted and doesn't match the SMT2 behavior. The operators \wedge and \vee correctly reject them. -add an option assert=false to smt() which controls whether assert is generated \ No newline at end of file +and() and or() accept IntExpr type which is not permitted and doesn't match the SMT-LIB behavior. The operators \wedge and \vee correctly reject them. +add an option assert=false to smt() which controls whether assert is generated +Add README link to documentation and fix badges - fixed 8/1/23 +Fix to use z3.exe and cvc5.exe in Windows - done 7/31/23 +Fix the custom solver interactions test to use z3.exe and run on Windows - done 7/31/23 diff --git a/docs/src/installation.md b/docs/src/installation.md index bd5addd..52bfbe4 100644 --- a/docs/src/installation.md +++ b/docs/src/installation.md @@ -12,7 +12,7 @@ You can install the latest version of BooleanSatisfiability with the command (TODO) Add official way when package is published. ## Installing a Solver -BooleanSatisfiability uses Julia's Base.Process library to interact with solvers. Thus to successfully install a solver for this package, all you need to do is make sure the appropriate command (listed below) works in your machine's terminal. +BooleanSatisfiability uses Julia's Base.Process library to interact with solvers. Thus to successfully install a solver for this package, all you need to do is make sure the appropriate command works in your machine's terminal. ### Debian Linux **To install Z3**, use `sudo apt-get install z3`. diff --git a/src/smt_representation.jl b/src/smt_representation.jl index 8a042a4..6497d93 100644 --- a/src/smt_representation.jl +++ b/src/smt_representation.jl @@ -77,13 +77,17 @@ end cache is a Dict where each value is an SMT statement and its key is the hash of the statement. This allows us to avoid two things: 1. Redeclaring SMT statements, which causes the solver to emit errors. 2. Re-using named functions. For example if we \"(define-fun FUNC_NAME or(z1, z2))\" and then the expression or(z1, z2) re-appears later in the expression \"and(or(z1, z2), z3)\", we can write and(FUNC_NAME, z3)." -function __define_n_op!(zs::Array{T}, op::Symbol, cache::Dict{UInt64, String}, depth::Int, line_ending='\n') where T <: AbstractExpr - if length(zs) == 0 +function __define_n_op!(zs::Array{T}, op::Symbol, cache::Dict{UInt64, String}, depth::Int; assert=true, line_ending='\n') where T <: AbstractExpr + if length(zs) == 0 # silly case but we should handle it return "" - - elseif length(zs) == 1 - return depth == 0 ? "(assert ($(zs[1].name)))$line_ending" : "" - + end + if assert && depth == 0 && !isa(zs[1], BoolExpr) + @warn("Cannot assert non-Boolean expression $op($zs)") + end + + # done error checking + if length(zs) == 1 + return assert && depth == 0 ? "(assert ($(zs[1].name)))$line_ending" : "" else fname = __get_hash_name(op, zs) # if the expr is a :CONST it will have a value (e.g. 2 or 1.5), otherwise use its name @@ -99,7 +103,7 @@ function __define_n_op!(zs::Array{T}, op::Symbol, cache::Dict{UInt64, String}, d if cache_key in keys(cache) prop = depth == 0 ? cache[cache_key] : "" else - if op ∈ __boolean_ops && depth == 0 + if assert && op ∈ __boolean_ops && depth == 0 prop = declaration*"(assert $fname)$line_ending" # the proposition is generated and cached now. cache[cache_key] = "(assert $fname)$line_ending" @@ -112,15 +116,15 @@ function __define_n_op!(zs::Array{T}, op::Symbol, cache::Dict{UInt64, String}, d end -function __define_1_op!(z::AbstractExpr, op::Symbol, cache::Dict{UInt64, String}, depth::Int, line_ending='\n') +function __define_1_op!(z::AbstractExpr, op::Symbol, cache::Dict{UInt64, String}, depth::Int; assert=true, line_ending='\n') fname = __get_hash_name(op, z.children) outname = __return_type(op, [z]) prop = "" declaration = "(define-fun $fname () $outname ($(__smt_1_opnames[op]) $(__get_smt_name(z.children[1]))))$line_ending" cache_key = hash(declaration) - if depth == 0 && !isa(z, BoolEx) - @warn("Cannot assert non-Boolean expression $z") + if assert && depth == 0 && !isa(z, BoolExpr) + @warn("Cannot assert non-Boolean expression $op($z)") end if cache_key in keys(cache) && depth == 0 @@ -128,7 +132,7 @@ function __define_1_op!(z::AbstractExpr, op::Symbol, cache::Dict{UInt64, String} else # if depth = 0 that means we are at the top-level of a nested expression. # thus, if the expr is Boolean we should assert it. - if op ∈ __boolean_ops && depth == 0 + if assert && op ∈ __boolean_ops && depth == 0 prop = declaration*"(assert $fname)$line_ending" # the proposition is generated and cached now. cache[cache_key] = "(assert $fname)$line_ending" @@ -144,20 +148,25 @@ end "smt!(prob, declarations, propositions) is an INTERNAL version of smt(prob). We use it to iteratively build a list of declarations and propositions. Users should call smt(prob, line_ending)." -function smt!(z::AbstractExpr, declarations::Array{T}, propositions::Array{T}, cache::Dict{UInt64, String}, depth::Int, line_ending) :: Tuple{Array{T}, Array{T}} where T <: String - if z.op == :IDENTITY +function smt!(z::AbstractExpr, declarations::Array{T}, propositions::Array{T}, cache::Dict{UInt64, String}, depth::Int; assert=true, line_ending='\n') :: Tuple{Array{T}, Array{T}} where T <: String + if z.op == :IDENTITY # a single variable n = length(declarations) push_unique!(declarations, declare(z; line_ending=line_ending)) + if assert && depth == 0 + push_unique!(propositions, "(assert $(z.name))$line_ending") + end + elseif z.op == :CONST - ; - else - map( (c) -> smt!(c, declarations, propositions, cache, depth+1, line_ending) , z.children) + ; # do nothing, constants don't need declarations + + else # an expression with operators and children + map( (c) -> smt!(c, declarations, propositions, cache, depth+1, assert=assert, line_ending=line_ending) , z.children) if z.op ∈ keys(__smt_1_opnames) - props = [__define_1_op!(z, z.op, cache, depth, line_ending),] + props = [__define_1_op!(z, z.op, cache, depth, assert=assert, line_ending=line_ending),] elseif z.op ∈ keys(__smt_n_opnames) # all n-ary ops where n >= 2 - props = broadcast((zs::Vararg{AbstractExpr}) -> __define_n_op!(collect(zs), z.op, cache, depth, line_ending), z.children...) + props = broadcast((zs::Vararg{AbstractExpr}) -> __define_n_op!(collect(zs), z.op, cache, depth, assert=assert, line_ending=line_ending), z.children...) #n = length(propositions) props = collect(props) else @@ -181,7 +190,7 @@ Generate the SMT representation of `z` or `and(z1,...,zn)`. When calling `smt([z1,...,zn])`, the array must have type `Array{AbstractExpr}`. Note that list comprehensions do not preserve array typing. For example, if `z` is an array of `BoolExpr`, `[z[i] for i=1:n]` will be an array of type `Any`. To preserve the correct type, use `BoolExpr[z[i] for i=1:n]`. """ -function smt(zs::Array{T}; line_ending=nothing) where T <: AbstractExpr +function smt(zs::Array{T}; assert=true, line_ending=nothing) where T <: AbstractExpr if isnothing(line_ending) line_ending = Sys.iswindows() ? "\r\n" : '\n' end @@ -190,16 +199,16 @@ function smt(zs::Array{T}; line_ending=nothing) where T <: AbstractExpr propositions = String[] cache = Dict{UInt64, String}() if length(zs) == 1 - declarations, propositions = smt!(zs[1], declarations, propositions, cache, 0, line_ending) + declarations, propositions = smt!(zs[1], declarations, propositions, cache, 0, assert=assert, line_ending=line_ending) else - map((z) -> smt!(z, declarations, propositions, cache, 0, line_ending), zs) + map((z) -> smt!(z, declarations, propositions, cache, 0, assert=assert, line_ending=line_ending), zs) end # this expression concatenates all the strings in row 1, then all the strings in row 2, etc. return reduce(*, declarations)*reduce(*,propositions) end -smt(zs::Vararg{Union{Array{T}, T}}; line_ending=nothing) where T <: AbstractExpr = smt(collect(zs), line_ending=line_ending) +smt(zs::Vararg{Union{Array{T}, T}}; assert=true, line_ending=nothing) where T <: AbstractExpr = smt(collect(zs), assert=assert, line_ending=line_ending) ##### WRITE TO FILE ##### @@ -210,22 +219,24 @@ smt(zs::Vararg{Union{Array{T}, T}}; line_ending=nothing) where T <: AbstractExpr Write the SMT representation of `z` or `and(z1,...,zn)` to filename.smt. """ -function save(prob::AbstractExpr, filename="out"; line_ending=nothing) +function save(prob::AbstractExpr, filename="out"; assert=true, check_sat=true, line_ending=nothing) if isnothing(line_ending) line_ending = Sys.iswindows() ? "\r\n" : '\n' end - if !isa(prob, BoolExpr) + if assert && !isa(prob, BoolExpr) @warn "Top-level expression must be Boolean to produce a valid SMT program." end open("$filename.smt", "w") do io - write(io, smt(prob, line_ending=line_ending)) - write(io, "(check-sat)$line_ending") + write(io, smt(prob, assert=assert, line_ending=line_ending)) + if check_sat + write(io, "(check-sat)$line_ending") + end end end # this is the version that accepts a list of exprs, for example save(z1, z2, z3). This is necessary because if z1::BoolExpr and z2::Array{BoolExpr}, etc, then the typing is too difficult to make an array. -save(zs::Vararg{Union{Array{T}, T}}; filename="out", line_ending=nothing) where T <: AbstractExpr = save(__flatten_nested_exprs(all, zs...), filename, line_ending=line_ending) +save(zs::Vararg{Union{Array{T}, T}}; filename="out", assert=true, check_sat=true, line_ending=nothing) where T <: AbstractExpr = save(__flatten_nested_exprs(all, zs...), filename, assert=assert, check_sat=check_sat, line_ending=line_ending) # array version for convenience. THIS DOES NOT ACCEPT ARRAYS OF MIXED AbstractExpr and Array{AbstractExpr}. -save(zs::Array{T}, filename="out"; line_ending=nothing) where T <: AbstractExpr = save(all(zs), filename, line_ending=line_ending) +save(zs::Array{T}, filename="out"; assert=true, check_sat=true, line_ending=nothing) where T <: AbstractExpr = save(all(zs), filename, assert=assert, check_sat=check_sat, line_ending=line_ending) diff --git a/test/smt_representation_tests.jl b/test/smt_representation_tests.jl index 182f716..e95bafe 100644 --- a/test/smt_representation_tests.jl +++ b/test/smt_representation_tests.jl @@ -1,3 +1,4 @@ +push!(LOAD_PATH, "../src") using BooleanSatisfiability using Test @@ -7,28 +8,28 @@ using Test @satvariable(z12[1:1, 1:2], Bool) # indexed expression correctly declared - @test smt(z12[1,2]) == "(declare-const z12_1_2 Bool)\n" - #1d and 2d expression - @test smt(z2) == "(declare-const z2_1 Bool)\n" - @test smt(z12) == "(declare-const z12_1_1 Bool)\n(declare-const z12_1_2 Bool)\n" + @test smt(z12[1,2]) == "(declare-const z12_1_2 Bool)\n(assert z12_1_2)\n" + #1d and 2d expression, with and without assert + @test smt(z2) == "(declare-const z2_1 Bool)\n(assert z2_1)\n" + @test smt(z12, assert=false) == "(declare-const z12_1_1 Bool)\n(declare-const z12_1_2 Bool)\n" # idea from https://microsoft.github.io/z3guide/docs/logic/propositional-logic # broadcast expression correctly generated hashname = BooleanSatisfiability.__get_hash_name(:AND, [z1, z2[1]]) - @test smt(z1 .∧ z2) == smt(z1)*smt(z2)*"(define-fun $hashname () Bool (and z1 z2_1))\n(assert $hashname)\n" + @test smt(z1 .∧ z2) == smt(z1, assert=false)*smt(z2, assert=false)*"(define-fun $hashname () Bool (and z1 z2_1))\n(assert $hashname)\n" # indexing creates a 1d expression hashname = BooleanSatisfiability.__get_hash_name(:AND, [z1, z12[1,2]]) - @test smt(z1 ∧ z12[1,2]) == smt(z1)*smt(z12[1,2])*"(define-fun $hashname () Bool (and z1 z12_1_2))\n(assert $hashname)\n" + @test smt(z1 ∧ z12[1,2]) == smt(z1, assert=false)*smt(z12[1,2], assert=false)*"(define-fun $hashname () Bool (and z1 z12_1_2))\n(assert $hashname)\n" hashname = BooleanSatisfiability.__get_hash_name(:AND, z12) - @test smt(z12[1,1] ∧ z12[1,2]) == smt(z12[1,1])*smt(z12[1,2])*"(define-fun $hashname () Bool (and z12_1_1 z12_1_2))\n(assert $hashname)\n" + @test smt(z12[1,1] ∧ z12[1,2]) == smt(z12[1,1], assert=false)*smt(z12[1,2], assert=false)*"(define-fun $hashname () Bool (and z12_1_1 z12_1_2))\n(assert $hashname)\n" # all() and any() work hashname = BooleanSatisfiability.__get_hash_name(:OR, [z1 z12]) - @test smt(any(z1 .∨ z12)) == smt(z1)*smt(z12)*"(define-fun $hashname () Bool (or z1 z12_1_1 z12_1_2))\n(assert $hashname)\n" + @test smt(any(z1 .∨ z12)) == smt(z1, assert=false)*smt(z12, assert=false)*"(define-fun $hashname () Bool (or z1 z12_1_1 z12_1_2))\n(assert $hashname)\n" hashname = BooleanSatisfiability.__get_hash_name(:AND, [z1 z12]) - @test smt(all(z1 .∧ z12)) == smt(z1)*smt(z12)*"(define-fun $hashname () Bool (and z1 z12_1_1 z12_1_2))\n(assert $hashname)\n" + @test smt(all(z1 .∧ z12)) == smt(z1, assert=false)*smt(z12, assert=false)*"(define-fun $hashname () Bool (and z1 z12_1_1 z12_1_2))\n(assert $hashname)\n" # cross all() and any() terms # TESTS DO NOT WORK @@ -51,18 +52,18 @@ end # iff, also tests \r\n hashname = BooleanSatisfiability.__get_hash_name(:IFF, [z1, z12[1,2]]) - @test smt(z1 ⟺ z12[1,2], line_ending="\r\n") == smt(z1, line_ending="\r\n")*smt(z12[1,2], line_ending="\r\n")*"(define-fun $hashname () Bool (= z1 z12_1_2))\r\n(assert $hashname)\r\n" + @test smt(z1 ⟺ z12[1,2], line_ending="\r\n") == smt(z1, assert=false, line_ending="\r\n")*smt(z12[1,2], assert=false, line_ending="\r\n")*"(define-fun $hashname () Bool (= z1 z12_1_2))\r\n(assert $hashname)\r\n" # xor hashname = BooleanSatisfiability.__get_hash_name(:XOR, z12) - @test smt(xor(z12[1,1], z12[1,2])) == smt(z12[1,1])*smt(z12[1,2])*"(define-fun $hashname () Bool (xor z12_1_1 z12_1_2))\n(assert $hashname)\n" + @test smt(xor(z12[1,1], z12[1,2])) == smt(z12[1,1], assert=false)*smt(z12[1,2], assert=false)*"(define-fun $hashname () Bool (xor z12_1_1 z12_1_2))\n(assert $hashname)\n" # if-then-else @satvariable(x, Bool) @satvariable(y, Bool) @satvariable(z, Bool) hashname = BooleanSatisfiability.__get_hash_name(:ITE, [x,y,z]) - @test smt(ite(x,y,z)) == smt(x)*smt(y)*smt(z)*"(define-fun $hashname () Bool (ite x y z))\n(assert $hashname)\n" + @test smt(ite(x,y,z)) == smt(x, assert=false)*smt(y, assert=false)*smt(z, assert=false)*"(define-fun $hashname () Bool (ite x y z))\n(assert $hashname)\n" end @testset "Generate nested expr without duplications" begin @@ -73,7 +74,7 @@ end xy = and(x,y) yx = and(y,x) topname = BooleanSatisfiability.__get_hash_name(:OR, [xy, yx]) - @test smt(or(xy, yx)) == smt(x)*smt(y)* + @test smt(or(xy, yx)) == smt(x, assert=false)*smt(y, assert=false)* "(define-fun $xyname () Bool (and x y)) (define-fun $topname () Bool (or $xyname $xyname)) (assert $topname)\n" @@ -82,7 +83,7 @@ end xname = BooleanSatisfiability.__get_hash_name(:NOT, [x]) nx = ¬x xyname = BooleanSatisfiability.__get_hash_name(:AND, [nx, nx]) - @test smt(and(¬x, ¬x)) == smt(x)* + @test smt(and(¬x, ¬x)) == smt(x, assert=false)* "(define-fun $xname () Bool (not x)) (define-fun $xyname () Bool (and $xname $xname)) (assert $xyname)\n" @@ -96,5 +97,5 @@ end text = read(open("outfile.smt", "r"), String) @test text == smt(all(z1 .∧ z12))*"(check-sat)\n" a = Int("a") - @test_logs (:warn, "Top-level expression must be Boolean to produce a valid SMT program.") save(a+1) + @test_logs (:warn, "Top-level expression must be Boolean to produce a valid SMT program.") save(a) end \ No newline at end of file From 6ce6f5e6e7bbb518d7e057bb6e841075a267ecf3 Mon Sep 17 00:00:00 2001 From: Emiko Soroka Date: Tue, 1 Aug 2023 22:05:53 -0700 Subject: [PATCH 12/36] Fixed and() and or() to only accept BoolExpr types. Cleaned up and() vs all() and any() vs or() (they're the same now). --- TODOS.txt | 5 ++-- src/BooleanOperations.jl | 42 ++++++++++++++-------------------- src/utilities.jl | 2 +- test/solver_interface_tests.jl | 5 +++- 4 files changed, 25 insertions(+), 29 deletions(-) diff --git a/TODOS.txt b/TODOS.txt index da9fe6c..99444ce 100644 --- a/TODOS.txt +++ b/TODOS.txt @@ -82,8 +82,9 @@ Change @satvariable to use Bool instead of :Bool, etc. - done 7/25/23 Use system newline in smt() - done 7/25/23 # TODO 7/29/23 -and() and or() accept IntExpr type which is not permitted and doesn't match the SMT-LIB behavior. The operators \wedge and \vee correctly reject them. -add an option assert=false to smt() which controls whether assert is generated +and() and or() accept IntExpr type which is not permitted and doesn't match the SMT-LIB behavior. The operators \wedge and \vee correctly reject them. - fixed 8/1/23 +add an option assert=false to smt() which controls whether assert is generated - done 8/1/23 Add README link to documentation and fix badges - fixed 8/1/23 Fix to use z3.exe and cvc5.exe in Windows - done 7/31/23 Fix the custom solver interactions test to use z3.exe and run on Windows - done 7/31/23 +clean up: all() should call and() and any() should call or() - done 8/1/23 \ No newline at end of file diff --git a/src/BooleanOperations.jl b/src/BooleanOperations.jl index 0c3d28a..aa32c8f 100644 --- a/src/BooleanOperations.jl +++ b/src/BooleanOperations.jl @@ -62,7 +62,7 @@ not(zs::Array{T}) where T <: BoolExpr = map(not, zs) function and(zs_mixed::Array{T}; broadcast_type=:Elementwise) where T - zs, literals = __check_inputs_nary_op(zs_mixed) + zs, literals = __check_inputs_nary_op(zs_mixed, expr_type=BoolExpr) if length(literals) > 0 if !all(literals) # if any literal is 0 @@ -79,9 +79,10 @@ function and(zs_mixed::Array{T}; broadcast_type=:Elementwise) where T end # now the remaining are BoolExpr - child_values = getproperty.(zs, :value) - value = any(isnothing.(child_values)) ? nothing : reduce(&, child_values) - return BoolExpr(:AND, zs, value, __get_hash_name(:AND, zs)) + expr = __combine(zs, :AND) + values = getproperty.(expr.children, :value) + expr.value = length(values) > 0 && !any(isnothing.(values)) ? reduce(&, values) : nothing + return expr end """ @@ -107,7 +108,7 @@ and(zs::Vararg{Union{T, Bool}}; broadcast_type=:Elementwise) where T <: Abstract # We need this declaration to enable the syntax and.([z1, z2,...,zn]) where z1, z2,...,zn are broadcast-compatible function or(zs_mixed::Array{T}; broadcast_type=:Elementwise) where T - zs, literals = __check_inputs_nary_op(zs_mixed) + zs, literals = __check_inputs_nary_op(zs_mixed, expr_type=BoolExpr) if length(literals) > 0 if any(literals) # if any literal is 1 @@ -123,9 +124,10 @@ function or(zs_mixed::Array{T}; broadcast_type=:Elementwise) where T return zs[1] end - child_values = getproperty.(zs, :value) - value = any(isnothing.(child_values)) ? nothing : reduce(|, child_values) - return BoolExpr(:OR, zs, value, __get_hash_name(:OR, zs)) + expr = __combine(zs, :OR) + values = getproperty.(expr.children, :value) + expr.value = length(values) > 0 && !any(isnothing.(values)) ? reduce(|, values) : nothing + return expr end """ @@ -167,7 +169,7 @@ Special cases: * `xor(true, true, z)` returns `false`. """ function xor(zs_mixed::Array{T}; broadcast_type=:Elementwise) where T - zs, literals = __check_inputs_nary_op(zs_mixed) + zs, literals = __check_inputs_nary_op(zs_mixed, expr_type=BoolExpr) if length(literals) > 0 if sum(literals)>1 # more than one literal is true, so xor automatically is false @@ -186,9 +188,10 @@ function xor(zs_mixed::Array{T}; broadcast_type=:Elementwise) where T return zs[1] end + expr = __combine(zs, :XOR) child_values = getproperty.(zs, :value) - value = any(isnothing.(child_values)) ? nothing : reduce(xor, child_values) - return BoolExpr(:XOR, zs, value, __get_hash_name(:XOR, zs)) + expr.value = any(isnothing.(child_values)) ? nothing : reduce(xor, child_values) + return expr end # We need this extra line to enable the syntax xor.([z1, z2,...,zn]) where z1, z2,...,z are broadcast-compatible @@ -271,7 +274,7 @@ iff(z1::Bool, z2::Bool) = z1 == z2 ##### ADDITIONAL OPERATIONS ##### -"combine is used for both all() and any() since those are fundamentally the same with different operations." +"combine is used for both and() and or() since those are fundamentally the same with different operations." function __combine(zs::Array{T}, op::Symbol) where T <: BoolExpr if length(zs) == 0 error("Cannot iterate over zero-length array.") @@ -310,12 +313,7 @@ Examples: * `and([and(z1, z2), and(z3, z4)]) == and(z1, z2, z3, z4)` * `and([or(z1, z3), z3, z4]) == and(or(z1, z3), z3, z4)` """ -function all(zs::Array{T}) where T <: BoolExpr - expr = __combine(zs, :AND) - values = getproperty.(expr.children, :value) - expr.value = length(values) > 0 && !any(isnothing.(values)) ? reduce(&, values) : nothing - return expr -end +all(zs::Array{T}) where T <: BoolExpr = and(zs) """ any([z1,...,zn]) @@ -325,13 +323,7 @@ Examples: * `any([or(z1, z2), or(z3, z4)]) == or(z1, z2, z3, z4)` * `any([and(z1, z3), z3, z4]) == or(and(z1, z3), z3, z4)` """ -function any(zs::Array{T}) where T <: BoolExpr - expr = __combine(zs, :OR) - values = getproperty.(expr.children, :value) - expr.value = length(values) > 0 && !any(isnothing.(values)) ? reduce(|, values) : nothing - return expr -end - +any(zs::Array{T}) where T <: BoolExpr = or(zs) """ value(z::BoolExpr) diff --git a/src/utilities.jl b/src/utilities.jl index 04830e1..64691ad 100644 --- a/src/utilities.jl +++ b/src/utilities.jl @@ -19,7 +19,7 @@ function __check_inputs_nary_op(zs_mixed::Array{T}; const_type=Bool, expr_type=A end # separate literals and const_type literals = filter((z) -> isa(z, const_type), zs_mixed) - zs = Array{AbstractExpr}(filter((z) -> isa(z, expr_type), zs_mixed)) + zs = Array{expr_type}(filter((z) -> isa(z, expr_type), zs_mixed)) return zs, literals end diff --git a/test/solver_interface_tests.jl b/test/solver_interface_tests.jl index ba7cffb..61d49ec 100644 --- a/test/solver_interface_tests.jl +++ b/test/solver_interface_tests.jl @@ -17,12 +17,15 @@ using Test, Logging "y_1" => 0, "y_2" => 0,) BooleanSatisfiability.__assign!(prob, values) @test ismissing(value(z)) + z.value = 0 + @test all(value(x) .== [1, 1 ,1]) @test all(value(y) .== [0, 0]) - # Creating a new expression where all children have assigned values also yields assigned values @test all(value(x .∨ [y; z]) .== 1) + @test all(value(xor.(x, [y; z])) .== 1) + @test all(value(x .∧ [y; z]) .== 0) @test value(and(prob.children[1], prob.children[2])) == 1 From d70e9cb256efb50c36de7e03f3348418f445f4fc Mon Sep 17 00:00:00 2001 From: Emiko Soroka Date: Wed, 2 Aug 2023 10:46:51 -0700 Subject: [PATCH 13/36] fix the bug introduced last night --- src/BooleanOperations.jl | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/BooleanOperations.jl b/src/BooleanOperations.jl index aa32c8f..b0897cf 100644 --- a/src/BooleanOperations.jl +++ b/src/BooleanOperations.jl @@ -188,10 +188,10 @@ function xor(zs_mixed::Array{T}; broadcast_type=:Elementwise) where T return zs[1] end - expr = __combine(zs, :XOR) + name = __get_hash_name(:XOR, zs) child_values = getproperty.(zs, :value) - expr.value = any(isnothing.(child_values)) ? nothing : reduce(xor, child_values) - return expr + value = any(isnothing.(child_values)) ? nothing : reduce(xor, child_values) + return BoolExpr(:XOR, zs, value, name) end # We need this extra line to enable the syntax xor.([z1, z2,...,zn]) where z1, z2,...,z are broadcast-compatible From 23b4b40849f85d4b9a2371e4f944e954a695f723 Mon Sep 17 00:00:00 2001 From: Emiko Soroka Date: Wed, 2 Aug 2023 12:47:23 -0700 Subject: [PATCH 14/36] paper figures, additions to paper, more citations. --- .../bibliography.bib | 74 +++++++++++++++++ .../figures/expr-tree.tex | 16 ++++ .../figures/smt-lib.tex | 21 +++++ .../paper.tex | 79 +++++++++++++------ 4 files changed, 165 insertions(+), 25 deletions(-) create mode 100644 SAT_package_paper/Conference-LaTeX-template_10-17-19/figures/expr-tree.tex create mode 100644 SAT_package_paper/Conference-LaTeX-template_10-17-19/figures/smt-lib.tex diff --git a/SAT_package_paper/Conference-LaTeX-template_10-17-19/bibliography.bib b/SAT_package_paper/Conference-LaTeX-template_10-17-19/bibliography.bib index acfcb17..f077ef7 100644 --- a/SAT_package_paper/Conference-LaTeX-template_10-17-19/bibliography.bib +++ b/SAT_package_paper/Conference-LaTeX-template_10-17-19/bibliography.bib @@ -16,6 +16,31 @@ @article{Lubin2023 doi = {10.1007/s12532-023-00239-3} } +@book{bradley2007calculus, + title={The calculus of computation: decision procedures with applications to verification}, + author={Bradley, Aaron R and Manna, Zohar}, + year={2007}, + publisher={Springer Science \& Business Media} +} + +@book{kroening2016decision, + title={Decision procedures}, + author={Kroening, Daniel and Strichman, Ofer}, + year={2016}, + publisher={Springer} +} + +@article{de2011satisfiabilityintro, + title={Satisfiability modulo theories: introduction and applications}, + author={De Moura, Leonardo and Bj{\o}rner, Nikolaj}, + journal={Communications of the ACM}, + volume={54}, + number={9}, + pages={69--77}, + year={2011}, + publisher={ACM New York, NY, USA} +} + @inproceedings{pysmt2015, title={PySMT: a solver-agnostic library for fast prototyping of SMT-based algorithms}, author={Gario, Marco and Micheli, Andrea}, @@ -23,6 +48,7 @@ @inproceedings{pysmt2015 year={2015} } + @inproceedings{z3, title={Z3: An Efficient SMT Solver}, author={Leonardo Mendonça de Moura and Nikolaj S. Bj{\o}rner}, @@ -74,3 +100,51 @@ @TECHREPORT{smtlib2 note = {Available at {\tt www.SMT-LIB.org}} } +@article{bezanson2017julia, + title={Julia: A fresh approach to numerical computing}, + author={Bezanson, Jeff and Edelman, Alan and Karpinski, Stefan and Shah, Viral B}, + journal={SIAM review}, + volume={59}, + number={1}, + pages={65--98}, + year={2017}, + publisher={SIAM}, + url={https://doi.org/10.1137/141000671} +} + +@article{perkel2019juliaspeed, + title={Julia: come for the syntax, stay for the speed}, + author={Perkel, Jeffrey M and others}, + journal={Nature}, + volume={572}, + number={7767}, + pages={141--142}, + year={2019}, + publisher={Springer Science and Business Media LLC} +} + +@article{besard2018juliagpu, + title={Effective extensible programming: unleashing Julia on GPUs}, + author={Besard, Tim and Foket, Christophe and De Sutter, Bjorn}, + journal={IEEE Transactions on Parallel and Distributed Systems}, + volume={30}, + number={4}, + pages={827--841}, + year={2018}, + publisher={IEEE} +} +@article{GAO2020juliaml, + title = {Julia language in machine learning: Algorithms, applications, and open issues}, + journal = {Computer Science Review}, + volume = {37}, + pages = {100254}, + year = {2020}, + issn = {1574-0137}, + doi = {https://doi.org/10.1016/j.cosrev.2020.100254}, + url = {https://www.sciencedirect.com/science/article/pii/S157401372030071X}, + author = {Kaifeng Gao and Gang Mei and Francesco Piccialli and Salvatore Cuomo and Jingzhi Tu and Zenan Huo}, + keywords = {Julia language, Machine learning, Supervised learning, Unsupervised learning, Deep learning, Artificial neural networks}, + abstract = {Machine learning is driving development across many fields in science and engineering. A simple and efficient programming language could accelerate applications of machine learning in various fields. Currently, the programming languages most commonly used to develop machine learning algorithms include Python, MATLAB, and C/C ++. However, none of these languages well balance both efficiency and simplicity. The Julia language is a fast, easy-to-use, and open-source programming language that was originally designed for high-performance computing, which can well balance the efficiency and simplicity. This paper summarizes the related research work and developments in the applications of the Julia language in machine learning. It first surveys the popular machine learning algorithms that are developed in the Julia language. Then, it investigates applications of the machine learning algorithms implemented with the Julia language. Finally, it discusses the open issues and the potential future directions that arise in the use of the Julia language in machine learning.} +} + +@misc{Julia_documentation_2023, url={https://docs.julialang.org/en/v1/manual/mathematical-operations/#Operator-Precedence-and-Associativity}, journal={Julia documentation}, publisher={julialang.org}, year={2023}, month={Jul}} \ No newline at end of file diff --git a/SAT_package_paper/Conference-LaTeX-template_10-17-19/figures/expr-tree.tex b/SAT_package_paper/Conference-LaTeX-template_10-17-19/figures/expr-tree.tex new file mode 100644 index 0000000..520861a --- /dev/null +++ b/SAT_package_paper/Conference-LaTeX-template_10-17-19/figures/expr-tree.tex @@ -0,0 +1,16 @@ + \begin{tikzpicture}[level distance=3em, + level 1/.style={sibling distance=6em}, + level 2/.style={sibling distance=3em}] + \node[rectangle, draw] {and} + child {node[rectangle, draw] {>} + child{node[rectangle, draw] {a}} + child{node[rectangle, draw] {+} + child{node[rectangle, draw] {1}} + child{node[rectangle, draw] {b}} + } + } + child {node[rectangle, draw] {>=} + child {node[rectangle, draw] {b}} + child {node[rectangle, draw] {0}} + }; + \end{tikzpicture} \ No newline at end of file diff --git a/SAT_package_paper/Conference-LaTeX-template_10-17-19/figures/smt-lib.tex b/SAT_package_paper/Conference-LaTeX-template_10-17-19/figures/smt-lib.tex new file mode 100644 index 0000000..0e5d2a4 --- /dev/null +++ b/SAT_package_paper/Conference-LaTeX-template_10-17-19/figures/smt-lib.tex @@ -0,0 +1,21 @@ +\begin{tikzpicture} +\node[rectangle, draw, align=center, text width=2cm] (a) {Solver\\(start mode)}; +\node[align=left, above=4.5mm of a.north east] (in1) {(set-logic ...)}; + +\node[rectangle, draw, align=center, text width=2.6cm] (b) [right=5mm of a] {Solver\\(assert mode)}; +\node at (b) [align=left, above right = 14mm and -10mm] (in2) {(declare-const ...)\\(define-fun ...)\\(assert ...)}; + +\node at (b) [align=left, above right=9mm and 6mm] (in2) {(check-sat)}; + +\node[rectangle, draw, align=center, text width=2cm, ] (c) [right=5mm of b] {Solver\\(sat mode)}; +\node at (c) [align=left, above right=13mm and -8mm] (in2) {(get-model)}; +% https://tikz.dev/tikz-arrows#sec-16.3.3 +\draw [draw = blue, thick, +arrows={ + -> [bend,]}] +(a) edge [bend left=45] (b) +(b) edge [in=70, out=110,looseness=8] (b) +(b) edge [bend left=45] (c) +(c) edge [in=70, out=110,looseness=8] (c); + +\end{tikzpicture} \ No newline at end of file diff --git a/SAT_package_paper/Conference-LaTeX-template_10-17-19/paper.tex b/SAT_package_paper/Conference-LaTeX-template_10-17-19/paper.tex index 1798cb7..53aff3d 100644 --- a/SAT_package_paper/Conference-LaTeX-template_10-17-19/paper.tex +++ b/SAT_package_paper/Conference-LaTeX-template_10-17-19/paper.tex @@ -8,6 +8,8 @@ \usepackage{graphicx} \usepackage{tablefootnote} \usepackage{textcomp} +\usepackage{tikz} +\usetikzlibrary {positioning, bending} \usepackage{fontspec} \setmonofont{FreeMono} % has unicode symbols https://tex.stackexchange.com/questions/581407/how-can-i-get-both-greek-and-unicode-characters-to-render-in-a-verbatim-environm % \setmonofont{DejaVu Mono} @@ -56,13 +58,13 @@ \end{IEEEkeywords} \section{Introduction} -Satisfiability modulo theories (SMT) is a general framework for computational theorem proving, in which the goal is to algorithmically find a satisfying assignment of variables such that one or more logical statements hold true. SMT encompasses a broad class of problems including the theories of propositional logic, integer arithmetic, floating-point arithmetic, and data structures. SMT formulae are used in formal verification and model checking to prove or disprove the correctness of a system. +Satisfiability modulo theories (SMT) is a general framework for computational theorem proving, in which the goal is to algorithmically find a satisfying assignment of variables such that one or more logical statements hold true. SMT encompasses a broad class of problems including the theories of propositional logic, integer arithmetic, floating-point arithmetic, and data structures. SMT formulae are used in formal verification and model checking to prove or disprove the correctness of a system \cite{de2011satisfiabilityintro}. -A decision procedure for an SMT problem is an algorithm that either finds such an assignment or determines that the given formula is unsatisfiable. Theorem proving software such as Z3 or CVC5 \cite{z3, cvc5} -uses decision procedures to check SMT formulae and find satisfying assignments where possible. However, theorem provers themselves are low-level tools intended to be integrated into other software. +A decision procedure for an SMT problem is an algorithm that either finds such an assignment or determines that the given formula is unsatisfiable. Theorem proving software such as Z3 or CVC5 \cite{z3, cvc5} uses decision procedures to check SMT formulae and find satisfying assignments where possible. However, theorem provers themselves are low-level tools intended to be integrated into other software. -In this paper we introduce \verb|BooleanSatisfiability.jl|, a Julia package providing a high-level representation for SMT formulae including propositional logic, integer and real-valued arithmetic.% TODO, and IEEE floating-point numbers. -\verb|BooleanSatisfiability.jl| is the first Julia package to provide this functionality. +This paper introduces \verb|BooleanSatisfiability.jl|, a Julia package providing a high-level representation for SMT formulae including propositional logic, integer and real-valued arithmetic.% TODO, and IEEE floating-point numbers. +The Julia programming language is ideal for scientific computing due to its use of type inference, multiple dispatch, and just-in-time compilation to improve performance \cite{bezanson2017julia, perkel2019juliaspeed}. Although Julia has a smaller software ecosystem compared to Matlab or scientific Python, it has successfully been used in high-performance applications including machine learning \cite{GAO2020juliaml} and GPU programming \cite{besard2018juliagpu}. +\verb|BooleanSatisfiability.jl| is the first package to provide an interface for SMT solving in Julia. \section{Prior Work} Two popular theorem provers are Z3, developed by Microsoft Research, and the open-source prover CVC5. Both provers including bindings for multiple programming languages, allowing access to some or all functionality with varying levels of abstraction. Additionally, both Z3 and CVC5 accept commands in the SMT-LIB specification language \cite{smtlib2}. @@ -70,8 +72,14 @@ \section{Prior Work} Similar packages are available in other languages; for example, \verb|PySMT| provides a high-level SAT interface using the same strategy of translation to SMT-LIB commands \cite{pysmt2015}. To our knowledge, \verb|BooleanSatisfiability.jl| is the first Julia package to use the SMT-LIB format for interactions with solvers, allowing compatibility with any theorem prover that supports SMT-LIB. +\section{Introduction to SMT} +(TO DO) + +For an in-depth treatment of computational logic and the associated decision procedures, readers are referred to \cite{bradley2007calculus, kroening2016decision}. A shorter overview of SMT is available in \cite{de2011satisfiabilityintro}. +% TODO a section on SMT here? + \section{The SMT-LIB specification language} -SMT-LIB is low-level specification language designed to standardize interactions with theorem provers. At time of writing, the current SMT-LIB standard is V2.6; we used this version of the language specification when implementing our software. To disambiguate between SMT (satisfiability modulo theories) and this specification language, we always refer to the language as SMT-LIB. +SMT-LIB is a low-level specification language designed to standardize interactions with theorem provers. At time of writing, the current SMT-LIB standard is V2.6; we used this version of the language specification when implementing our software. To disambiguate between SMT (satisfiability modulo theories) and this specification language, we always refer to the language as SMT-LIB. SMT-LIB uses a Lisp-like syntax designed to simplify input parsing. It is intended to provide an interactive interface for theorem proving similar to Julia's REPL. SMT-LIB supports declaring variables, defining functions, making assertions (e.g. requiring that a Boolean formula be true), and issuing solver commands. Figure ? % TODO \ref{fig:smtbasic} provides an example of an SMT solver moving between modes. @@ -80,18 +88,34 @@ \section{The SMT-LIB specification language} %(TO DO should we discuss SMT-LIB more here?) %TODO -%Figure ? %TODO figure -%shows a simple example of a solver moving between modes as statements are received. +Figure \ref{fig:smt-lib} shows a simple example of a solver moving between modes as statements are received. One limitation of SMT-LIB is that many commands are only valid in specific solver modes. For example, the command \verb|(get-model)| retrieves the satisfying assignment for a formula and is only valid in \verb|sat| mode, while \verb|(get-unsat-core)| is only valid in \verb|unsat| mode. Issuing a command in the wrong mode yields an error, thus many useful sequences of SMT-LIB commands cannot be scripted in advance. +\begin{figure}[h] + \centering + \input{figures/smt-lib.tex} + \caption{A simple interaction with an SMT-LIB standard solver. If the formula \texttt{assert}ed in assert mode was unsatisfiable, the solver would instead enter unsat mode and a different set of commands would be valid.} + \label{fig:smt-lib} +\end{figure} + For a full description of SMT-LIB, readers are referred to \cite{smtlib2}. As the purpose of our software is to provide an abstraction on top of SMT-LIB, we refrain from an in-depth description of the language. Knowledge of SMT-LIB is not required to understand and use the basic functionality of \verb|BooleanSatisfiability.jl|. +In this section we make use of Julia's type notation \verb|f(x::Type)| to disambiguate the types of function arguments when necessary. + \section{Package Design} -%TODO diagram + Our software facilitates the construction and SMT-LIB representation of SMT formulae, along with providing a simple interface to SMT-LIB compliant theorem provers. -The basic unit of a formula in our software is the expression (Figure ?). %TODO) +The basic unit of a formula in our software is the expression (Figure \ref{fig:expr-tree}). + +\begin{figure}[h] + \centering + \input{figures/expr-tree.tex} + \caption{The expression \texttt{and(a > b + 1, b >= 0)}.} + \label{fig:expr-tree} +\end{figure} + Expressions may represent single variables or operators combining expressions. An abstract type \verb|AbstractExpr| is provided. Concrete types inheriting from \verb|AbstractExpr| implement a tree structure capable of representing arbitrarily complex nested expressions. Julia's type system prevents expressions from being incorrectly combined operators. For example, $\neg\verb|x|$ is only valid if \verb|x| is of type \verb|BoolExpr|. Output types of operations follow type compatibility and promotion rules; for example, if \verb|x| is a \verb|BoolExpr| and \verb|a| is an \verb|IntExpr|, \verb|x + a| is an \verb|IntExpr|. @@ -128,26 +152,27 @@ \subsection{Constants} \subsection{SMT-LIB representation} While SMT-LIB permits expressions of arbitrary complexity, our software limits the depth of nested expressions by generating sub-expressions using SMT-LIB's \verb|(define-fun)| to define sub-expressions without \verb|assert|ing them. % TODO clean up this part -A representative example is provided below. +A representative example is provided below, with hashed names shortened for readability. \begin{verbatim} @satvariable(x, Bool) @satvariable(y, Bool) expr = or(¬x, and(¬x, y)) print(smt(expr)) ->>> (declare-const x Bool) ->>> (declare-const y Bool) ->>> (define-fun NOT_53b20e3050918288 () Bool - (not x)) ->>> (define-fun AND_eb3b71ab55532084 () Bool - (and NOT_53b20e3050918288 y)) ->>> (define-fun OR_90de3d1a32047990 () Bool - (or AND_eb3b71ab55532084 NOT_53b20e3050918288)) ->>> (assert OR_90de3d1a32047990) +> (declare-const x Bool) +> (declare-const y Bool) +> (define-fun NOT_53b20e () Bool (not x)) +> (define-fun AND_eb3b71 () Bool + (and NOT_53b20e y)) +> (define-fun OR_90de3d + () Bool (or AND_eb3b71 NOT_53b20e)) +> (assert OR_90de3d) \end{verbatim} -Although \verb|¬x| appears twice in \verb|expr|, it is defined once and reused. +Note that although \verb|not(x)| appears twice in \verb|expr|, it is defined once and reused. \subsection{Interacting with Solvers} -Internally, our package uses Julia's \verb|Process| library to interact with a prover via input and output pipes. This supports the interactive nature of SMT-LIB.%; for example, the command \verb|(get-model)| is required to retrieve a satisfying assignment, but cannot be issued if the formula is unsatisfiable. +Internally, our package uses Julia's \verb|Process| library to interact with a solver via input and output pipes. This supports the interactive nature of SMT-LIB, which necessitates a two-way connection with the solver. +%TODO diagram of this process thing +This design provides several benefits. By transparently documenting how our software manages sessions with solvers, we eliminate many of the difficulties that arise when calling software dependencies. The process to make solvers available for \verb|BooleanSatisfiability.jl| on any system is fundamentally the same: the user must install the solver and ensure it can be invoked from their machine's command line. Users can customize the command used to invoke a solver. This provides a single mechanism for interacting with SMT-LIB compatible solvers that aren't explicitly supported; customizing options using command line flags; and working around machine-specific issues such as a solver being available under a different name or at a specific path. \section{Using The Package} \subsection{Working with formulae}. @@ -178,7 +203,8 @@ \subsection{Variables} \subsection{Type Promotion} -Integer or real-valued operations \verb|+|, \verb|-|, \verb|*| return integer or real expressions using Julia type promotion rules. Division (\verb|/|) is only valid over real-valued expressions. +Integer or real-valued operations \verb|+|, \verb|-|, \verb|*| return integer or real expressions using Julia type promotion rules. Division (\verb|/|) is only valid over real-valued expressions\footnote{Readers familiar with gradient-based or iterative optimization over real-valued variables should be aware that although SMT provides mechanisms to represent arithmetic over real values, decision procedures for the theory of real arithmetic are incomplete and often require an impractical amount of computation time. SMT is primarily used for representing problems involving discrete-valued variables and logical statements over said variables. +}. \begin{verbatim} @satvariable(a, Bool) @satvariable(b, Int) @@ -262,7 +288,7 @@ \subsection{Operators} \subsection{Operator Precedence} Julia defines the operator precedence and associativity for all symbolic operators defined in this package. -For the most up-to-date description of Julia's operator precedence rules, see. %TODO cite https://docs.julialang.org/en/v1/manual/mathematical-operations/#Operator-Precedence-and-Associativity +For the most up-to-date description of Julia's operator precedence rules, see \cite{Julia_documentation_2023}. One can also determine operator precedence using the call \verb|Base.operator_precedence(s)| where \verb|s| is a symbol (e.g. \verb|:+| or \verb|:*|). Higher numbers indicate greater precedence. Precedence and associativity rules can yield misleading expressions or unexpected type errors. Readers are encouraged to parenthesize expressions, avoiding potential sources of confusion. The following illustrative examples are provided. @@ -291,8 +317,11 @@ \section{Examples} \subsection*{Custom solver interactions} We expose the low-level interface, allowing advanced users to send SMT commands and receive prover responses. Users are responsible for ensuring the correctness of these commands, as well as interpreting the results. In this use case, \verb|BooleanSatisfiability.jl| can be used to automate generation of the SMT problem and programmatically interact with solvers, extending the usability of the SMT interface. +\section{Conclusions} +We have successfully developed a Julia package providing a simple, high-level interface to SMT-LIB compatible solvers. Our package takes advantage of Julia's functionality to construct a simple and extensible interface; we use multiple dispatch to optimize and simplify operations over constants, the type system to enforce the correctness of SMT expressions, and \verb|Base.Process| to interact with SMT-LIB solvers. + \section{Acknowledgements} -The software architecture of \verb|BooleanSatisfiability.jl| was inspired by \verb|Convex.jl|, \verb|JuMP|, and \verb|PySMT| \cite{convexjl, Lubin2023, pysmt2015}. +The software architecture of \verb|BooleanSatisfiability.jl| was inspired by \verb|Convex.jl|, \verb|JuMP|, and \verb|PySMT| \cite{convexjl, Lubin2023, pysmt2015}. Ideas, suggestions and feedback on the package's user interface were provided by Prof. Mykel Kochenderfer. \section{Future Work} From 94f46759732c29eb06e3a104aa5337eae029c125 Mon Sep 17 00:00:00 2001 From: Emiko Soroka Date: Fri, 4 Aug 2023 15:20:27 -0700 Subject: [PATCH 15/36] moved paper to its own repository for cleanliness --- .../IEEEtran.cls | 6347 ----------------- .../bibliography.bib | 150 - .../conference_101719.tex | 288 - .../figures/expr-tree.tex | 16 - .../figures/smt-lib.tex | 21 - .../paper-blx.bib | 11 - .../paper.tex | 501 -- 7 files changed, 7334 deletions(-) delete mode 100644 SAT_package_paper/Conference-LaTeX-template_10-17-19/IEEEtran.cls delete mode 100644 SAT_package_paper/Conference-LaTeX-template_10-17-19/bibliography.bib delete mode 100644 SAT_package_paper/Conference-LaTeX-template_10-17-19/conference_101719.tex delete mode 100644 SAT_package_paper/Conference-LaTeX-template_10-17-19/figures/expr-tree.tex delete mode 100644 SAT_package_paper/Conference-LaTeX-template_10-17-19/figures/smt-lib.tex delete mode 100644 SAT_package_paper/Conference-LaTeX-template_10-17-19/paper-blx.bib delete mode 100644 SAT_package_paper/Conference-LaTeX-template_10-17-19/paper.tex diff --git a/SAT_package_paper/Conference-LaTeX-template_10-17-19/IEEEtran.cls b/SAT_package_paper/Conference-LaTeX-template_10-17-19/IEEEtran.cls deleted file mode 100644 index 905a10c..0000000 --- a/SAT_package_paper/Conference-LaTeX-template_10-17-19/IEEEtran.cls +++ /dev/null @@ -1,6347 +0,0 @@ -%% -%% IEEEtran.cls 2015/08/26 version V1.8b -%% -%% This is the IEEEtran LaTeX class for authors of the Institute of -%% Electrical and Electronics Engineers (IEEE) Transactions journals and -%% conferences. -%% -%% Support sites: -%% http://www.michaelshell.org/tex/ieeetran/ -%% http://www.ctan.org/pkg/ieeetran -%% and -%% http://www.ieee.org/ -%% -%% Based on the original 1993 IEEEtran.cls, but with many bug fixes -%% and enhancements (from both JVH and MDS) over the 1996/7 version. -%% -%% -%% Contributors: -%% Gerry Murray (1993), Silvano Balemi (1993), -%% Jon Dixon (1996), Peter N"uchter (1996), -%% Juergen von Hagen (2000), and Michael Shell (2001-2014) -%% -%% -%% Copyright (c) 1993-2000 by Gerry Murray, Silvano Balemi, -%% Jon Dixon, Peter N"uchter, -%% Juergen von Hagen -%% and -%% Copyright (c) 2001-2015 by Michael Shell -%% -%% Current maintainer (V1.3 to V1.8b): Michael Shell -%% See: -%% http://www.michaelshell.org/ -%% for current contact information. -%% -%% Special thanks to Peter Wilson (CUA) and Donald Arseneau -%% for allowing the inclusion of the \@ifmtarg command -%% from their ifmtarg LaTeX package. -%% -%%************************************************************************* -%% Legal Notice: -%% This code is offered as-is without any warranty either expressed or -%% implied; without even the implied warranty of MERCHANTABILITY or -%% FITNESS FOR A PARTICULAR PURPOSE! -%% User assumes all risk. -%% In no event shall the IEEE or any contributor to this code be liable for -%% any damages or losses, including, but not limited to, incidental, -%% consequential, or any other damages, resulting from the use or misuse -%% of any information contained here. -%% -%% All comments are the opinions of their respective authors and are not -%% necessarily endorsed by the IEEE. -%% -%% This work is distributed under the LaTeX Project Public License (LPPL) -%% ( http://www.latex-project.org/ ) version 1.3, and may be freely used, -%% distributed and modified. A copy of the LPPL, version 1.3, is included -%% in the base LaTeX documentation of all distributions of LaTeX released -%% 2003/12/01 or later. -%% Retain all contribution notices and credits. -%% ** Modified files should be clearly indicated as such, including ** -%% ** renaming them and changing author support contact information. ** -%% -%% File list of work: IEEEtran.cls, IEEEtran_HOWTO.pdf, bare_adv.tex, -%% bare_conf.tex, bare_jrnl.tex, bare_conf_compsoc.tex, -%% bare_jrnl_compsoc.tex -%% -%% Major changes to the user interface should be indicated by an -%% increase in the version numbers. If a version is a beta, it will -%% be indicated with a BETA suffix, i.e., 1.4 BETA. -%% Small changes can be indicated by appending letters to the version -%% such as "IEEEtran_v14a.cls". -%% In all cases, \Providesclass, any \typeout messages to the user, -%% \IEEEtransversionmajor and \IEEEtransversionminor must reflect the -%% correct version information. -%% The changes should also be documented via source comments. -%%************************************************************************* -%% -% -% Available class options -% e.g., \documentclass[10pt,conference]{IEEEtran} -% -% *** choose only one from each category *** -% -% 9pt, 10pt, 11pt, 12pt -% Sets normal font size. The default is 10pt. -% -% conference, journal, technote, peerreview, peerreviewca -% determines format mode - conference papers, journal papers, -% correspondence papers (technotes), or peer review papers. The user -% should also select 9pt when using technote. peerreview is like -% journal mode, but provides for a single-column "cover" title page for -% anonymous peer review. The paper title (without the author names) is -% repeated at the top of the page after the cover page. For peer review -% papers, the \IEEEpeerreviewmaketitle command must be executed (will -% automatically be ignored for non-peerreview modes) at the place the -% cover page is to end, usually just after the abstract (keywords are -% not normally used with peer review papers). peerreviewca is like -% peerreview, but allows the author names to be entered and formatted -% as with conference mode so that author affiliation and contact -% information can be easily seen on the cover page. -% The default is journal. -% -% draft, draftcls, draftclsnofoot, final -% determines if paper is formatted as a widely spaced draft (for -% handwritten editor comments) or as a properly typeset final version. -% draftcls restricts draft mode to the class file while all other LaTeX -% packages (i.e., \usepackage{graphicx}) will behave as final - allows -% for a draft paper with visible figures, etc. draftclsnofoot is like -% draftcls, but does not display the date and the word "DRAFT" at the foot -% of the pages. If using one of the draft modes, the user will probably -% also want to select onecolumn. -% The default is final. -% -% letterpaper, a4paper, cspaper -% determines paper size: 8.5in X 11in, 210mm X 297mm or 7.875in X 10.75in. -% Changing the paper size in the standard journal and conference modes -% will not alter the typesetting of the document - only the margins will -% be affected. In particular, documents using the a4paper option will -% have reduced side margins (A4 is narrower than US letter) and a longer -% bottom margin (A4 is longer than US letter). For both cases, the top -% margins will be the same and the text will be horizontally centered. -% For the compsoc conference and draft modes, it is the margins that will -% remain constant, and thus the text area size will vary, with changes in -% the paper size. -% The cspaper option is the special ``trim'' paper size (7.875in x 10.75in) -% used in the actual publication of Computer Society journals. Under -% compsoc journal mode, this option does not alter the typesetting of the -% document. Authors should invoke the cspaper option only if requested to -% do so by the editors of the specific journal they are submitting to. -% For final submission to the IEEE, authors should generally use US letter -% (8.5 X 11in) paper unless otherwise instructed. Note that authors should -% ensure that all post-processing (ps, pdf, etc.) uses the same paper -% specificiation as the .tex document. Problems here are by far the number -% one reason for incorrect margins. IEEEtran will automatically set the -% default paper size under pdflatex (without requiring any change to -% pdftex.cfg), so this issue is more important to dvips users. Fix -% config.ps, config.pdf, or ~/.dvipsrc for dvips, or use the -% dvips -t papersize option instead as needed. For the cspaper option, -% the corresponding dvips paper name is "ieeecs". -% See the testflow documentation -% http://www.ctan.org/tex-archive/macros/latex/contrib/IEEEtran/testflow -% for more details on dvips paper size configuration. -% The default is letterpaper. -% -% oneside, twoside -% determines if layout follows single sided or two sided (duplex) -% printing. The only notable change is with the headings at the top of -% the pages. -% The default is oneside. -% -% onecolumn, twocolumn -% determines if text is organized into one or two columns per page. One -% column mode is usually used only with draft papers. -% The default is twocolumn. -% -% comsoc, compsoc, transmag -% Use the format of the IEEE Communications Society, IEEE Computer Society -% or IEEE Transactions on Magnetics, respectively. -% -% romanappendices -% Use the "Appendix I" convention when numbering appendices. IEEEtran.cls -% now defaults to Alpha "Appendix A" convention - the opposite of what -% v1.6b and earlier did. -% -% captionsoff -% disables the display of the figure/table captions. Some IEEE journals -% request that captions be removed and figures/tables be put on pages -% of their own at the end of an initial paper submission. The endfloat -% package can be used with this class option to achieve this format. -% -% nofonttune -% turns off tuning of the font interword spacing. Maybe useful to those -% not using the standard Times fonts or for those who have already "tuned" -% their fonts. -% The default is to enable IEEEtran to tune font parameters. -% -% -%---------- -% Available CLASSINPUTs provided (all are macros unless otherwise noted): -% \CLASSINPUTbaselinestretch -% \CLASSINPUTinnersidemargin -% \CLASSINPUToutersidemargin -% \CLASSINPUTtoptextmargin -% \CLASSINPUTbottomtextmargin -% -% Available CLASSINFOs provided: -% \ifCLASSINFOpdf (TeX if conditional) -% \CLASSINFOpaperwidth (macro) -% \CLASSINFOpaperheight (macro) -% \CLASSINFOnormalsizebaselineskip (length) -% \CLASSINFOnormalsizeunitybaselineskip (length) -% -% Available CLASSOPTIONs provided: -% all class option flags (TeX if conditionals) unless otherwise noted, -% e.g., \ifCLASSOPTIONcaptionsoff -% point size options provided as a single macro: -% \CLASSOPTIONpt -% which will be defined as 9, 10, 11, or 12 depending on the document's -% normalsize point size. -% also, class option peerreviewca implies the use of class option peerreview -% and classoption draft implies the use of class option draftcls - - - - - -\ProvidesClass{IEEEtran}[2015/08/26 V1.8b by Michael Shell] -\typeout{-- See the "IEEEtran_HOWTO" manual for usage information.} -\typeout{-- http://www.michaelshell.org/tex/ieeetran/} -\NeedsTeXFormat{LaTeX2e} - -% IEEEtran.cls version numbers, provided as of V1.3 -% These values serve as a way a .tex file can -% determine if the new features are provided. -% The version number of this IEEEtrans.cls can be obtained from -% these values. i.e., V1.4 -% KEEP THESE AS INTEGERS! i.e., NO {4a} or anything like that- -% (no need to enumerate "a" minor changes here) -\def\IEEEtransversionmajor{1} -\def\IEEEtransversionminor{8} - - -% hook to allow easy changeover to IEEEtran.cls/tools.sty error reporting -\def\@IEEEclspkgerror{\ClassError{IEEEtran}} - - -% These do nothing, but provide them like in article.cls -\newif\if@restonecol -\newif\if@titlepage - - -% class option conditionals -\newif\ifCLASSOPTIONonecolumn \CLASSOPTIONonecolumnfalse -\newif\ifCLASSOPTIONtwocolumn \CLASSOPTIONtwocolumntrue - -\newif\ifCLASSOPTIONoneside \CLASSOPTIONonesidetrue -\newif\ifCLASSOPTIONtwoside \CLASSOPTIONtwosidefalse - -\newif\ifCLASSOPTIONfinal \CLASSOPTIONfinaltrue -\newif\ifCLASSOPTIONdraft \CLASSOPTIONdraftfalse -\newif\ifCLASSOPTIONdraftcls \CLASSOPTIONdraftclsfalse -\newif\ifCLASSOPTIONdraftclsnofoot \CLASSOPTIONdraftclsnofootfalse - -\newif\ifCLASSOPTIONpeerreview \CLASSOPTIONpeerreviewfalse -\newif\ifCLASSOPTIONpeerreviewca \CLASSOPTIONpeerreviewcafalse - -\newif\ifCLASSOPTIONjournal \CLASSOPTIONjournaltrue -\newif\ifCLASSOPTIONconference \CLASSOPTIONconferencefalse -\newif\ifCLASSOPTIONtechnote \CLASSOPTIONtechnotefalse - -\newif\ifCLASSOPTIONnofonttune \CLASSOPTIONnofonttunefalse - -\newif\ifCLASSOPTIONcaptionsoff \CLASSOPTIONcaptionsofffalse - -\newif\ifCLASSOPTIONcomsoc \CLASSOPTIONcomsocfalse -\newif\ifCLASSOPTIONcompsoc \CLASSOPTIONcompsocfalse -\newif\ifCLASSOPTIONtransmag \CLASSOPTIONtransmagfalse - -\newif\ifCLASSOPTIONromanappendices \CLASSOPTIONromanappendicesfalse - - -% class info conditionals - -% indicates if pdf (via pdflatex) output -\newif\ifCLASSINFOpdf \CLASSINFOpdffalse - - -% V1.6b internal flag to show if using a4paper -\newif\if@IEEEusingAfourpaper \@IEEEusingAfourpaperfalse -% V1.6b internal flag to show if using cspaper -\newif\if@IEEEusingcspaper \@IEEEusingcspaperfalse - - -% IEEEtran class scratch pad registers -% dimen -\newdimen\@IEEEtrantmpdimenA -\newdimen\@IEEEtrantmpdimenB -\newdimen\@IEEEtrantmpdimenC -% count -\newcount\@IEEEtrantmpcountA -\newcount\@IEEEtrantmpcountB -\newcount\@IEEEtrantmpcountC -% token list -\newtoks\@IEEEtrantmptoksA - -% we use \CLASSOPTIONpt so that we can ID the point size (even for 9pt docs) -% as well as LaTeX's \@ptsize to retain some compatability with some -% external packages -\def\@ptsize{0} -% LaTeX does not support 9pt, so we set \@ptsize to 0 - same as that of 10pt -\DeclareOption{9pt}{\def\CLASSOPTIONpt{9}\def\@ptsize{0}} -\DeclareOption{10pt}{\def\CLASSOPTIONpt{10}\def\@ptsize{0}} -\DeclareOption{11pt}{\def\CLASSOPTIONpt{11}\def\@ptsize{1}} -\DeclareOption{12pt}{\def\CLASSOPTIONpt{12}\def\@ptsize{2}} - - - -\DeclareOption{letterpaper}{\setlength{\paperwidth}{8.5in}% - \setlength{\paperheight}{11in}% - \@IEEEusingAfourpaperfalse - \@IEEEusingcspaperfalse - \def\CLASSOPTIONpaper{letter}% - \def\CLASSINFOpaperwidth{8.5in}% - \def\CLASSINFOpaperheight{11in}} - - -\DeclareOption{a4paper}{\setlength{\paperwidth}{210mm}% - \setlength{\paperheight}{297mm}% - \@IEEEusingAfourpapertrue - \@IEEEusingcspaperfalse - \def\CLASSOPTIONpaper{a4}% - \def\CLASSINFOpaperwidth{210mm}% - \def\CLASSINFOpaperheight{297mm}} - -% special paper option for compsoc journals -\DeclareOption{cspaper}{\setlength{\paperwidth}{7.875in}% - \setlength{\paperheight}{10.75in}% - \@IEEEusingcspapertrue - \@IEEEusingAfourpaperfalse - \def\CLASSOPTIONpaper{ieeecs}% - \def\CLASSINFOpaperwidth{7.875in}% - \def\CLASSINFOpaperheight{10.75in}} - -\DeclareOption{oneside}{\@twosidefalse\@mparswitchfalse - \CLASSOPTIONonesidetrue\CLASSOPTIONtwosidefalse} -\DeclareOption{twoside}{\@twosidetrue\@mparswitchtrue - \CLASSOPTIONtwosidetrue\CLASSOPTIONonesidefalse} - -\DeclareOption{onecolumn}{\CLASSOPTIONonecolumntrue\CLASSOPTIONtwocolumnfalse} -\DeclareOption{twocolumn}{\CLASSOPTIONtwocolumntrue\CLASSOPTIONonecolumnfalse} - -% If the user selects draft, then this class AND any packages -% will go into draft mode. -\DeclareOption{draft}{\CLASSOPTIONdrafttrue\CLASSOPTIONdraftclstrue - \CLASSOPTIONdraftclsnofootfalse} -% draftcls is for a draft mode which will not affect any packages -% used by the document. -\DeclareOption{draftcls}{\CLASSOPTIONdraftfalse\CLASSOPTIONdraftclstrue - \CLASSOPTIONdraftclsnofootfalse} -% draftclsnofoot is like draftcls, but without the footer. -\DeclareOption{draftclsnofoot}{\CLASSOPTIONdraftfalse\CLASSOPTIONdraftclstrue - \CLASSOPTIONdraftclsnofoottrue} -\DeclareOption{final}{\CLASSOPTIONdraftfalse\CLASSOPTIONdraftclsfalse - \CLASSOPTIONdraftclsnofootfalse} - -\DeclareOption{journal}{\CLASSOPTIONpeerreviewfalse\CLASSOPTIONpeerreviewcafalse - \CLASSOPTIONjournaltrue\CLASSOPTIONconferencefalse\CLASSOPTIONtechnotefalse} - -\DeclareOption{conference}{\CLASSOPTIONpeerreviewfalse\CLASSOPTIONpeerreviewcafalse - \CLASSOPTIONjournalfalse\CLASSOPTIONconferencetrue\CLASSOPTIONtechnotefalse} - -\DeclareOption{technote}{\CLASSOPTIONpeerreviewfalse\CLASSOPTIONpeerreviewcafalse - \CLASSOPTIONjournalfalse\CLASSOPTIONconferencefalse\CLASSOPTIONtechnotetrue} - -\DeclareOption{peerreview}{\CLASSOPTIONpeerreviewtrue\CLASSOPTIONpeerreviewcafalse - \CLASSOPTIONjournalfalse\CLASSOPTIONconferencefalse\CLASSOPTIONtechnotefalse} - -\DeclareOption{peerreviewca}{\CLASSOPTIONpeerreviewtrue\CLASSOPTIONpeerreviewcatrue - \CLASSOPTIONjournalfalse\CLASSOPTIONconferencefalse\CLASSOPTIONtechnotefalse} - -\DeclareOption{nofonttune}{\CLASSOPTIONnofonttunetrue} - -\DeclareOption{captionsoff}{\CLASSOPTIONcaptionsofftrue} - -\DeclareOption{comsoc}{\CLASSOPTIONcomsoctrue\CLASSOPTIONcompsocfalse\CLASSOPTIONtransmagfalse} - -\DeclareOption{compsoc}{\CLASSOPTIONcomsocfalse\CLASSOPTIONcompsoctrue\CLASSOPTIONtransmagfalse} - -\DeclareOption{transmag}{\CLASSOPTIONtransmagtrue\CLASSOPTIONcomsocfalse\CLASSOPTIONcompsocfalse} - -\DeclareOption{romanappendices}{\CLASSOPTIONromanappendicestrue} - - -% default to US letter paper, 10pt, twocolumn, one sided, final, journal -\ExecuteOptions{letterpaper,10pt,twocolumn,oneside,final,journal} -% overrride these defaults per user requests -\ProcessOptions - - - -%% -- Command Argument Scanning Support Functions -- - -% Sets the category codes for punctuation to their normal values. -% For local use with argument scanning. -\def\IEEEnormalcatcodespunct{\catcode`\!=12 \catcode`\,=12 \catcode`\:=12 -\catcode`\;=12 \catcode`\`=12 \catcode`\'=12 \catcode`\"=12 \catcode`\.=12 -\catcode`\/=12 \catcode`\?=12 \catcode`\*=12 \catcode`\+=12 \catcode`\-=12 -\catcode`\<=12 \catcode`\>=12 \catcode`\(=12 \catcode`\)=12 \catcode`\[=12 -\catcode`\]=12 \catcode`\==12 \catcode`\|=12} -% Sets the category codes for numbers to their normal values. -% For local use with argument scanning. -\def\IEEEnormalcatcodesnum{\catcode`\0=12 \catcode`\1=12 \catcode`\2=12 -\catcode`\3=12 \catcode`\4=12 \catcode`\5=12 \catcode`\6=12 \catcode`\7=12 -\catcode`\8=12 \catcode`\9=12} -% combined action of \IEEEnormalcatcodespunct and \IEEEnormalcatcodesnum -\def\IEEEnormalcatcodes{\IEEEnormalcatcodespunct\IEEEnormalcatcodesnum} - - -% usage: \@IEEEextracttoken*{} -% \@IEEEextracttoken fully expands its argument (which it then stores in -% \@IEEEextracttokenarg) via \edef and then the meaning of the first -% nonbrace (but including the empty group) token found is assigned via \let -% to \@IEEEextractedtoken as well as stored in the macro -% \@IEEEextractedtokenmacro. Tokens that would otherwise be discarded during -% the acquisition of the first are stored in \@IEEEextractedtokensdiscarded, -% however their original relative brace nesting depths are not guaranteed to -% be preserved. -% If the argument is empty, or if a first nonbrace token does not exist (or -% is an empty group), \@IEEEextractedtoken will be \relax and -% \@IEEEextractedtokenmacro and \@IEEEextractedtokensdiscarded will be empty. -% -% For example: -% \@IEEEextracttoken{{{ab}{cd}}{{ef}g}} -% results in: -% -% \@IEEEextracttokenarg ==> a macro containing {{ab}{cd}}{{ef}g} -% \@IEEEextractedtoken ==> the letter a -% \@IEEEextractedtokenmacro ==> a macro containing a -% \@IEEEextractedtokensdiscarded ==> a macro containing bcd{ef}g -% -% the *-star form, \@IEEEextracttoken*, does not expand its argument -% contents during processing. -\def\@IEEEextracttoken{\@ifstar{\let\@IEEEextracttokendef=\def\@@IEEEextracttoken}{\let\@IEEEextracttokendef=\edef\@@IEEEextracttoken}} - -\def\@@IEEEextracttoken#1{\@IEEEextracttokendef\@IEEEextracttokenarg{#1}\relax -\def\@IEEEextractedtokensdiscarded{}\relax % initialize to empty -% if the macro is unchanged after being acquired as a single undelimited argument -% with anything after it being stripped off as a delimited argument -% we know we have one token without any enclosing braces. loop until this is true. -\let\@IEEEextracttokencurgroup\@IEEEextracttokenarg -\loop - % trap case of an empty argument as this would cause a problem with - % \@@@IEEEextracttoken's first (nondelimited) argument acquisition - \ifx\@IEEEextracttokencurgroup\@empty - \def\@IEEEextractedtokenmacro{}\relax - \else - \expandafter\@@@IEEEextracttoken\@IEEEextracttokencurgroup\@IEEEgeneralsequenceDELIMITER\relax - \fi - \ifx\@IEEEextractedtokenmacro\@IEEEextracttokencurgroup - \else - \let\@IEEEextracttokencurgroup=\@IEEEextractedtokenmacro -\repeat -% we can safely do a \let= here because there should be at most one token -% the relax is needed to handle the case of no token found -\expandafter\let\expandafter\@IEEEextractedtoken\@IEEEextractedtokenmacro\relax} - -\def\@@@IEEEextracttoken#1#2\@IEEEgeneralsequenceDELIMITER{\def\@IEEEextractedtokenmacro{#1}\relax -\def\@@IEEEextractedtokensdiscarded{#2}\expandafter\expandafter\expandafter\def\expandafter\expandafter\expandafter -\@IEEEextractedtokensdiscarded\expandafter\expandafter\expandafter -{\expandafter\@@IEEEextractedtokensdiscarded\@IEEEextractedtokensdiscarded}} -%% -%% -- End of Command Argument Scanning Support Functions -- - - - -% Computer Society conditional execution command -\long\def\@IEEEcompsoconly#1{\relax\ifCLASSOPTIONcompsoc\relax#1\relax\fi\relax} -% inverse -\long\def\@IEEEnotcompsoconly#1{\relax\ifCLASSOPTIONcompsoc\else\relax#1\relax\fi\relax} -% compsoc conference -\long\def\@IEEEcompsocconfonly#1{\relax\ifCLASSOPTIONcompsoc\ifCLASSOPTIONconference\relax#1\relax\fi\fi\relax} -% compsoc not conference -\long\def\@IEEEcompsocnotconfonly#1{\relax\ifCLASSOPTIONcompsoc\ifCLASSOPTIONconference\else\relax#1\relax\fi\fi\relax} - - -% comsoc verify that newtxmath, mtpro2, mt11p or mathtime has been loaded -\def\@IEEEcomsocverifymathfont{\typeout{-- Verifying Times compatible math font.}\relax - \@ifpackageloaded{newtxmath}{\typeout{-- newtxmath loaded, OK.}}{\@@IEEEcomsocverifymathfont}} -\def\@@IEEEcomsocverifymathfont{\@ifpackageloaded{mtpro2}{\typeout{-- mtpro2 loaded, OK.}}{\@@@IEEEcomsocverifymathfont}} -\def\@@@IEEEcomsocverifymathfont{\@ifpackageloaded{mt11p}{\typeout{-- mt11p2 loaded, OK.}}{\@@@@IEEEcomsocverifymathfont}} -\def\@@@@IEEEcomsocverifymathfont{\@ifpackageloaded{mathtime}{\typeout{-- mathtime loaded, OK.}}{\@IEEEcomsocenforcemathfont}} - -% comsoc, if a Times math font was not loaded by user, enforce it -\def\@IEEEcomsocenforcemathfont{\typeout{** Times compatible math font not found, forcing.}\relax -\IfFileExists{newtxmath.sty}{\typeout{-- Found newtxmath, loading.}\RequirePackage{newtxmath}}{\@@IEEEcomsocenforcemathfont}} -\def\@@IEEEcomsocenforcemathfont{\IfFileExists{mtpro2.sty}{\typeout{-- Found mtpro2, loading.}\RequirePackage{mtpro2}}{\@@@IEEEcomsocenforcemathfont}} -\def\@@@IEEEcomsocenforcemathfont{\IfFileExists{mt11p.sty}{\typeout{-- Found mt11p, loading.}\RequirePackage{mt11p}}{\@@@@IEEEcomsocenforcemathfont}} -\def\@@@@IEEEcomsocenforcemathfont{\IfFileExists{mathtime.sty}{\typeout{-- Found mathtime, loading.}\RequirePackage{mathtime}}{\@@@@@IEEEcomsocenforcemathfont}} -% if no acceptable Times math font package found, error with newtxmath requirement -\def\@@@@@IEEEcomsocenforcemathfont{\typeout{** No Times compatible math font package found. newtxmath is required.}\RequirePackage{newtxmath}} - - -\ifCLASSOPTIONcomsoc - % ensure that if newtxmath is used, the cmintegrals option is also invoked - \PassOptionsToPackage{cmintegrals}{newtxmath} - % comsoc requires a Times like math font - % ensure this requirement is satisfied at document start - \AtBeginDocument{\@IEEEcomsocverifymathfont} -\fi - - - -% The IEEE uses Times Roman font, so we'll default to Times. -% These three commands make up the entire times.sty package. -\renewcommand{\sfdefault}{phv} -\renewcommand{\rmdefault}{ptm} -\renewcommand{\ttdefault}{pcr} - -% V1.7 compsoc nonconference papers, use Palatino/Palladio as the main text font, -% not Times Roman. -\@IEEEcompsocnotconfonly{\renewcommand{\rmdefault}{ppl}} - -% enable the selected main text font -\normalfont\selectfont - - -\ifCLASSOPTIONcomsoc - \typeout{-- Using IEEE Communications Society mode.} -\fi - -\ifCLASSOPTIONcompsoc - \typeout{-- Using IEEE Computer Society mode.} -\fi - - -% V1.7 conference notice message hook -\def\@IEEEconsolenoticeconference{\typeout{}% -\typeout{** Conference Paper **}% -\typeout{Before submitting the final camera ready copy, remember to:}% -\typeout{}% -\typeout{ 1. Manually equalize the lengths of two columns on the last page}% -\typeout{ of your paper;}% -\typeout{}% -\typeout{ 2. Ensure that any PostScript and/or PDF output post-processing}% -\typeout{ uses only Type 1 fonts and that every step in the generation}% -\typeout{ process uses the appropriate paper size.}% -\typeout{}} - - -% we can send console reminder messages to the user here -\AtEndDocument{\ifCLASSOPTIONconference\@IEEEconsolenoticeconference\fi} - - -% warn about the use of single column other than for draft mode -\ifCLASSOPTIONtwocolumn\else% - \ifCLASSOPTIONdraftcls\else% - \typeout{** ATTENTION: Single column mode is not typically used with IEEE publications.}% - \fi% -\fi - - -% V1.7 improved paper size setting code. -% Set pdfpage and dvips paper sizes. Conditional tests are similar to that -% of ifpdf.sty. Retain within {} to ensure tested macros are never altered, -% even if only effect is to set them to \relax. -% if \pdfoutput is undefined or equal to relax, output a dvips special -{\@ifundefined{pdfoutput}{\AtBeginDvi{\special{papersize=\CLASSINFOpaperwidth,\CLASSINFOpaperheight}}}{% -% pdfoutput is defined and not equal to \relax -% check for pdfpageheight existence just in case someone sets pdfoutput -% under non-pdflatex. If exists, set them regardless of value of \pdfoutput. -\@ifundefined{pdfpageheight}{\relax}{\global\pdfpagewidth\paperwidth -\global\pdfpageheight\paperheight}% -% if using \pdfoutput=0 under pdflatex, send dvips papersize special -\ifcase\pdfoutput -\AtBeginDvi{\special{papersize=\CLASSINFOpaperwidth,\CLASSINFOpaperheight}}% -\else -% we are using pdf output, set CLASSINFOpdf flag -\global\CLASSINFOpdftrue -\fi}} - -% let the user know the selected papersize -\typeout{-- Using \CLASSINFOpaperwidth\space x \CLASSINFOpaperheight\space -(\CLASSOPTIONpaper)\space paper.} - -\ifCLASSINFOpdf -\typeout{-- Using PDF output.} -\else -\typeout{-- Using DVI output.} -\fi - - -% The idea hinted here is for LaTeX to generate markleft{} and markright{} -% automatically for you after you enter \author{}, \journal{}, -% \journaldate{}, journalvol{}, \journalnum{}, etc. -% However, there may be some backward compatibility issues here as -% well as some special applications for IEEEtran.cls and special issues -% that may require the flexible \markleft{}, \markright{} and/or \markboth{}. -% We'll leave this as an open future suggestion. -%\newcommand{\journal}[1]{\def\@journal{#1}} -%\def\@journal{} - - - -% pointsize values -% used with ifx to determine the document's normal size -\def\@IEEEptsizenine{9} -\def\@IEEEptsizeten{10} -\def\@IEEEptsizeeleven{11} -\def\@IEEEptsizetwelve{12} - - - -% FONT DEFINITIONS (No sizexx.clo file needed) -% V1.6 revised font sizes, displayskip values and -% revised normalsize baselineskip to reduce underfull vbox problems -% on the 58pc = 696pt = 9.5in text height we want -% normalsize #lines/column baselineskip (aka leading) -% 9pt 63 11.0476pt (truncated down) -% 10pt 58 12pt (exact) -% 11pt 52 13.3846pt (truncated down) -% 12pt 50 13.92pt (exact) -% - -% we need to store the nominal baselineskip for the given font size -% in case baselinestretch ever changes. -% this is a dimen, so it will not hold stretch or shrink -\newdimen\@IEEEnormalsizeunitybaselineskip -\@IEEEnormalsizeunitybaselineskip\baselineskip - - - -%% ******* WARNING! ******* -%% -%% Authors should not alter font sizes, baselineskip ("leading"), -%% margins or other spacing values in an attempt to squeeze more -%% material on each page. -%% -%% The IEEE's own typesetting software will restore the correct -%% values when re-typesetting/proofing the submitted document, -%% possibly resulting in unexpected article over length charges. -%% -%% ******* WARNING! ******* - - -% 9pt option defaults -\ifx\CLASSOPTIONpt\@IEEEptsizenine -\typeout{-- This is a 9 point document.} -\def\normalsize{\@setfontsize{\normalsize}{9}{11.0476pt}} -\setlength{\@IEEEnormalsizeunitybaselineskip}{11.0476pt} -\normalsize -\abovedisplayskip 1.5ex plus 3pt minus 1pt -\belowdisplayskip \abovedisplayskip -\abovedisplayshortskip 0pt plus 3pt -\belowdisplayshortskip 1.5ex plus 3pt minus 1pt -\def\small{\@setfontsize{\small}{8.5}{10pt}} -\def\footnotesize{\@setfontsize{\footnotesize}{8}{9pt}} -\def\scriptsize{\@setfontsize{\scriptsize}{7}{8pt}} -\def\tiny{\@setfontsize{\tiny}{5}{6pt}} -% sublargesize is the same as large - 10pt -\def\sublargesize{\@setfontsize{\sublargesize}{10}{12pt}} -\def\large{\@setfontsize{\large}{10}{12pt}} -\def\Large{\@setfontsize{\Large}{12}{14pt}} -\def\LARGE{\@setfontsize{\LARGE}{14}{17pt}} -\def\huge{\@setfontsize{\huge}{17}{20pt}} -\def\Huge{\@setfontsize{\Huge}{20}{24pt}} -\fi -% -% 10pt option defaults -\ifx\CLASSOPTIONpt\@IEEEptsizeten -\typeout{-- This is a 10 point document.} -\def\normalsize{\@setfontsize{\normalsize}{10}{12.00pt}} -\setlength{\@IEEEnormalsizeunitybaselineskip}{12pt} -\normalsize -\abovedisplayskip 1.5ex plus 4pt minus 2pt -\belowdisplayskip \abovedisplayskip -\abovedisplayshortskip 0pt plus 4pt -\belowdisplayshortskip 1.5ex plus 4pt minus 2pt -\def\small{\@setfontsize{\small}{9}{10pt}} -\def\footnotesize{\@setfontsize{\footnotesize}{8}{9pt}} -\def\scriptsize{\@setfontsize{\scriptsize}{7}{8pt}} -\def\tiny{\@setfontsize{\tiny}{5}{6pt}} -% sublargesize is a tad smaller than large - 11pt -\def\sublargesize{\@setfontsize{\sublargesize}{11}{13.4pt}} -\def\large{\@setfontsize{\large}{12}{14pt}} -\def\Large{\@setfontsize{\Large}{14}{17pt}} -\def\LARGE{\@setfontsize{\LARGE}{17}{20pt}} -\def\huge{\@setfontsize{\huge}{20}{24pt}} -\def\Huge{\@setfontsize{\Huge}{24}{28pt}} -\fi -% -% 11pt option defaults -\ifx\CLASSOPTIONpt\@IEEEptsizeeleven -\typeout{-- This is an 11 point document.} -\def\normalsize{\@setfontsize{\normalsize}{11}{13.3846pt}} -\setlength{\@IEEEnormalsizeunitybaselineskip}{13.3846pt} -\normalsize -\abovedisplayskip 1.5ex plus 5pt minus 3pt -\belowdisplayskip \abovedisplayskip -\abovedisplayshortskip 0pt plus 5pt -\belowdisplayshortskip 1.5ex plus 5pt minus 3pt -\def\small{\@setfontsize{\small}{10}{12pt}} -\def\footnotesize{\@setfontsize{\footnotesize}{9}{10.5pt}} -\def\scriptsize{\@setfontsize{\scriptsize}{8}{9pt}} -\def\tiny{\@setfontsize{\tiny}{6}{7pt}} -% sublargesize is the same as large - 12pt -\def\sublargesize{\@setfontsize{\sublargesize}{12}{14pt}} -\def\large{\@setfontsize{\large}{12}{14pt}} -\def\Large{\@setfontsize{\Large}{14}{17pt}} -\def\LARGE{\@setfontsize{\LARGE}{17}{20pt}} -\def\huge{\@setfontsize{\huge}{20}{24pt}} -\def\Huge{\@setfontsize{\Huge}{24}{28pt}} -\fi -% -% 12pt option defaults -\ifx\CLASSOPTIONpt\@IEEEptsizetwelve -\typeout{-- This is a 12 point document.} -\def\normalsize{\@setfontsize{\normalsize}{12}{13.92pt}} -\setlength{\@IEEEnormalsizeunitybaselineskip}{13.92pt} -\normalsize -\abovedisplayskip 1.5ex plus 6pt minus 4pt -\belowdisplayskip \abovedisplayskip -\abovedisplayshortskip 0pt plus 6pt -\belowdisplayshortskip 1.5ex plus 6pt minus 4pt -\def\small{\@setfontsize{\small}{10}{12pt}} -\def\footnotesize{\@setfontsize{\footnotesize}{9}{10.5pt}} -\def\scriptsize{\@setfontsize{\scriptsize}{8}{9pt}} -\def\tiny{\@setfontsize{\tiny}{6}{7pt}} -% sublargesize is the same as large - 14pt -\def\sublargesize{\@setfontsize{\sublargesize}{14}{17pt}} -\def\large{\@setfontsize{\large}{14}{17pt}} -\def\Large{\@setfontsize{\Large}{17}{20pt}} -\def\LARGE{\@setfontsize{\LARGE}{20}{24pt}} -\def\huge{\@setfontsize{\huge}{22}{26pt}} -\def\Huge{\@setfontsize{\Huge}{24}{28pt}} -\fi - - - -% V1.8a compsoc font sizes -% compsoc font sizes use bp "Postscript" point units (1/72in) -% rather than the traditional pt (1/72.27) -\ifCLASSOPTIONcompsoc -% -- compsoc defaults -- -% ** will override some of these values later ** -% 9pt -\ifx\CLASSOPTIONpt\@IEEEptsizenine -\def\normalsize{\@setfontsize{\normalsize}{9bp}{11bp}} -\setlength{\@IEEEnormalsizeunitybaselineskip}{11bp} -\normalsize -\abovedisplayskip 1.5ex plus 3bp minus 1bp -\belowdisplayskip \abovedisplayskip -\abovedisplayshortskip 0bp plus 3bp -\belowdisplayshortskip 1.5ex plus 3bp minus 1bp -\def\small{\@setfontsize{\small}{8.5bp}{10bp}} -\def\footnotesize{\@setfontsize{\footnotesize}{8bp}{9bp}} -\def\scriptsize{\@setfontsize{\scriptsize}{7bp}{8bp}} -\def\tiny{\@setfontsize{\tiny}{5bp}{6bp}} -% sublargesize is the same as large - 10bp -\def\sublargesize{\@setfontsize{\sublargesize}{10bp}{12bp}} -\def\large{\@setfontsize{\large}{10bp}{12bp}} -\def\Large{\@setfontsize{\Large}{12bp}{14bp}} -\def\LARGE{\@setfontsize{\LARGE}{14bp}{17bp}} -\def\huge{\@setfontsize{\huge}{17bp}{20bp}} -\def\Huge{\@setfontsize{\Huge}{20bp}{24bp}} -\fi -% -% 10pt -\ifx\CLASSOPTIONpt\@IEEEptsizeten -\def\normalsize{\@setfontsize{\normalsize}{10bp}{12bp}} -\setlength{\@IEEEnormalsizeunitybaselineskip}{12bp} -\normalsize -\abovedisplayskip 1.5ex plus 4bp minus 2bp -\belowdisplayskip \abovedisplayskip -\abovedisplayshortskip 0pt plus 4bp -\belowdisplayshortskip 1.5ex plus 4bp minus 2bp -\def\small{\@setfontsize{\small}{9bp}{10bp}} -\def\footnotesize{\@setfontsize{\footnotesize}{8bp}{9bp}} -\def\scriptsize{\@setfontsize{\scriptsize}{7bp}{8bp}} -\def\tiny{\@setfontsize{\tiny}{5bp}{6bp}} -% sublargesize is a tad smaller than large - 11bp -\def\sublargesize{\@setfontsize{\sublargesize}{11bp}{13.5bp}} -\def\large{\@setfontsize{\large}{12bp}{14bp}} -\def\Large{\@setfontsize{\Large}{14bp}{17bp}} -\def\LARGE{\@setfontsize{\LARGE}{17bp}{20bp}} -\def\huge{\@setfontsize{\huge}{20bp}{24bp}} -\def\Huge{\@setfontsize{\Huge}{24bp}{28bp}} -\fi -% -% 11pt -\ifx\CLASSOPTIONpt\@IEEEptsizeeleven -\def\normalsize{\@setfontsize{\normalsize}{11bp}{13.5bp}} -\setlength{\@IEEEnormalsizeunitybaselineskip}{13.5bp} -\normalsize -\abovedisplayskip 1.5ex plus 5bp minus 3bp -\belowdisplayskip \abovedisplayskip -\abovedisplayshortskip 0pt plus 5bp -\belowdisplayshortskip 1.5ex plus 5bp minus 3bp -\def\small{\@setfontsize{\small}{10bp}{12bp}} -\def\footnotesize{\@setfontsize{\footnotesize}{9bp}{10.5bp}} -\def\scriptsize{\@setfontsize{\scriptsize}{8bp}{9bp}} -\def\tiny{\@setfontsize{\tiny}{6bp}{7bp}} -% sublargesize is the same as large - 12bp -\def\sublargesize{\@setfontsize{\sublargesize}{12bp}{14bp}} -\def\large{\@setfontsize{\large}{12bp}{14bp}} -\def\Large{\@setfontsize{\Large}{14bp}{17bp}} -\def\LARGE{\@setfontsize{\LARGE}{17bp}{20bp}} -\def\huge{\@setfontsize{\huge}{20bp}{24bp}} -\def\Huge{\@setfontsize{\Huge}{24bp}{28bp}} -\fi -% -% 12pt -\ifx\CLASSOPTIONpt\@IEEEptsizetwelve -\def\normalsize{\@setfontsize{\normalsize}{12bp}{14bp}}% -\setlength{\@IEEEnormalsizeunitybaselineskip}{14bp}% -\normalsize -\abovedisplayskip 1.5ex plus 6bp minus 4bp -\belowdisplayskip \abovedisplayskip -\abovedisplayshortskip 0pt plus 6bp -\belowdisplayshortskip 1.5ex plus 6bp minus 4bp -\def\small{\@setfontsize{\small}{10bp}{12bp}} -\def\footnotesize{\@setfontsize{\footnotesize}{9bp}{10.5bp}} -\def\scriptsize{\@setfontsize{\scriptsize}{8bp}{9bp}} -\def\tiny{\@setfontsize{\tiny}{6bp}{7bp}} -% sublargesize is the same as large - 14bp -\def\sublargesize{\@setfontsize{\sublargesize}{14bp}{17bp}} -\def\large{\@setfontsize{\large}{14bp}{17bp}} -\def\Large{\@setfontsize{\Large}{17bp}{20bp}} -\def\LARGE{\@setfontsize{\LARGE}{20bp}{24bp}} -\def\huge{\@setfontsize{\huge}{22bp}{26bp}} -\def\Huge{\@setfontsize{\Huge}{24bp}{28bp}} -\fi -% -% -- override defaults: compsoc journals use special normalsizes -- -\ifCLASSOPTIONconference -% -% compsoc conferences -% 9pt -\ifx\CLASSOPTIONpt\@IEEEptsizenine -\def\normalsize{\@setfontsize{\normalsize}{9bp}{10.8bp}} -\setlength{\@IEEEnormalsizeunitybaselineskip}{10.8bp} -\normalsize -\abovedisplayskip 1.5ex plus 3bp minus 1bp -\belowdisplayskip \abovedisplayskip -\abovedisplayshortskip 0bp plus 3bp -\belowdisplayshortskip 1.5ex plus 3bp minus 1bp -\fi -% 10pt -\ifx\CLASSOPTIONpt\@IEEEptsizeten -\def\normalsize{\@setfontsize{\normalsize}{10bp}{11.2bp}} -\setlength{\@IEEEnormalsizeunitybaselineskip}{11.2bp} -\normalsize -\abovedisplayskip 1.5ex plus 4bp minus 2bp -\belowdisplayskip \abovedisplayskip -\abovedisplayshortskip 0pt plus 4bp -\belowdisplayshortskip 1.5ex plus 4bp minus 2bp -\fi -% 11pt -\ifx\CLASSOPTIONpt\@IEEEptsizeeleven -\def\normalsize{\@setfontsize{\normalsize}{11bp}{13.2bp}} -\setlength{\@IEEEnormalsizeunitybaselineskip}{13.2bp} -\normalsize -\abovedisplayskip 1.5ex plus 5bp minus 3bp -\belowdisplayskip \abovedisplayskip -\abovedisplayshortskip 0pt plus 5bp -\belowdisplayshortskip 1.5ex plus 5bp minus 3bp -\fi -% 12pt -\ifx\CLASSOPTIONpt\@IEEEptsizetwelve -\def\normalsize{\@setfontsize{\normalsize}{12bp}{14.4bp}} -\setlength{\@IEEEnormalsizeunitybaselineskip}{14.4bp} -\normalsize -\abovedisplayskip 1.5ex plus 6bp minus 4bp -\belowdisplayskip \abovedisplayskip -\abovedisplayshortskip 0pt plus 6bp -\belowdisplayshortskip 1.5ex plus 6bp minus 4bp -\fi -% -% compsoc nonconferences -\else -% 9pt -\ifx\CLASSOPTIONpt\@IEEEptsizenine -\def\normalsize{\@setfontsize{\normalsize}{9bp}{10.8bp}} -\setlength{\@IEEEnormalsizeunitybaselineskip}{10.8bp} -\normalsize -\abovedisplayskip 1.5ex plus 3bp minus 1bp -\belowdisplayskip \abovedisplayskip -\abovedisplayshortskip 0bp plus 3bp -\belowdisplayshortskip 1.5ex plus 3bp minus 1bp -\fi -% 10pt -\ifx\CLASSOPTIONpt\@IEEEptsizeten -% the official spec is 9.5bp with 11.4bp leading for 10pt, -% but measurements of proofs suggest upto 11.723bp leading -% here we'll use 11.54bp which gives 61 lines per column -% with the standard compsoc margins -\def\normalsize{\@setfontsize{\normalsize}{9.5bp}{11.54bp}} -\setlength{\@IEEEnormalsizeunitybaselineskip}{11.54bp} -\normalsize -\abovedisplayskip 1.5ex plus 4bp minus 2bp -\belowdisplayskip \abovedisplayskip -\abovedisplayshortskip 0pt plus 4bp -\belowdisplayshortskip 1.5ex plus 4bp minus 2bp -\fi -% 11pt -\ifx\CLASSOPTIONpt\@IEEEptsizeeleven -\def\normalsize{\@setfontsize{\normalsize}{11bp}{13.2bp}} -\setlength{\@IEEEnormalsizeunitybaselineskip}{13.2bp} -\normalsize -\abovedisplayskip 1.5ex plus 5bp minus 3bp -\belowdisplayskip \abovedisplayskip -\abovedisplayshortskip 0pt plus 5bp -\belowdisplayshortskip 1.5ex plus 5bp minus 3bp -\fi -% 12pt -\ifx\CLASSOPTIONpt\@IEEEptsizetwelve -\def\normalsize{\@setfontsize{\normalsize}{12bp}{14.4bp}} -\setlength{\@IEEEnormalsizeunitybaselineskip}{14.4bp} -\normalsize -\abovedisplayskip 1.5ex plus 6bp minus 4bp -\belowdisplayskip \abovedisplayskip -\abovedisplayshortskip 0pt plus 6bp -\belowdisplayshortskip 1.5ex plus 6bp minus 4bp -\fi -\fi\fi - - - - -% V1.6 The Computer Modern Fonts will issue a substitution warning for -% 24pt titles (24.88pt is used instead, but the default and correct -% Times font will scale exactly as needed) increase the substitution -% tolerance to turn off this warning. -% -% V1.8a, the compsoc bp font sizes can also cause bogus font substitution -% warnings with footnote or scriptsize math and the $\bullet$ itemized -% list of \IEEEcompsocitemizethanks. So, increase this to 1.5pt or more. -\def\fontsubfuzz{1.7bp} - - -% warn the user in case they forget to use the 9pt option with -% technote -\ifCLASSOPTIONtechnote% - \ifx\CLASSOPTIONpt\@IEEEptsizenine\else% - \typeout{** ATTENTION: Technotes are normally 9pt documents.}% - \fi% -\fi - - -% V1.7 -% Improved \textunderscore to provide a much better fake _ when used with -% OT1 encoding. Under OT1, detect use of pcr or cmtt \ttfamily and use -% available true _ glyph for those two typewriter fonts. -\def\@IEEEstringptm{ptm} % Times Roman family -\def\@IEEEstringppl{ppl} % Palatino Roman family -\def\@IEEEstringphv{phv} % Helvetica Sans Serif family -\def\@IEEEstringpcr{pcr} % Courier typewriter family -\def\@IEEEstringcmtt{cmtt} % Computer Modern typewriter family -\DeclareTextCommandDefault{\textunderscore}{\leavevmode -\ifx\f@family\@IEEEstringpcr\string_\else -\ifx\f@family\@IEEEstringcmtt\string_\else -\ifx\f@family\@IEEEstringptm\kern 0em\vbox{\hrule\@width 0.5em\@height 0.5pt\kern -0.3ex}\else -\ifx\f@family\@IEEEstringppl\kern 0em\vbox{\hrule\@width 0.5em\@height 0.5pt\kern -0.3ex}\else -\ifx\f@family\@IEEEstringphv\kern -0.03em\vbox{\hrule\@width 0.62em\@height 0.52pt\kern -0.33ex}\kern -0.03em\else -\kern 0.09em\vbox{\hrule\@width 0.6em\@height 0.44pt\kern -0.63pt\kern -0.42ex}\kern 0.09em\fi\fi\fi\fi\fi\relax} - - - - -% set the default \baselinestretch -\def\baselinestretch{1} -\ifCLASSOPTIONdraftcls - \def\baselinestretch{1.5}% default baselinestretch for draft modes -\fi - - -% process CLASSINPUT baselinestretch -\ifx\CLASSINPUTbaselinestretch\@IEEEundefined -\else - \edef\baselinestretch{\CLASSINPUTbaselinestretch} % user CLASSINPUT override - \typeout{** ATTENTION: Overriding \string\baselinestretch\space to - \baselinestretch\space via \string\CLASSINPUT.} -\fi - -\small\normalsize % make \baselinestretch take affect - - - - -% store the normalsize baselineskip -\newdimen\CLASSINFOnormalsizebaselineskip -\CLASSINFOnormalsizebaselineskip=\baselineskip\relax -% and the normalsize unity (baselinestretch=1) baselineskip -% we could save a register by giving the user access to -% \@IEEEnormalsizeunitybaselineskip. However, let's protect -% its read only internal status -\newdimen\CLASSINFOnormalsizeunitybaselineskip -\CLASSINFOnormalsizeunitybaselineskip=\@IEEEnormalsizeunitybaselineskip\relax -% store the nominal value of jot -\newdimen\IEEEnormaljot -\IEEEnormaljot=0.25\baselineskip\relax - -% set \jot -\jot=\IEEEnormaljot\relax - - - - -% V1.6, we are now going to fine tune the interword spacing -% The default interword glue for Times under TeX appears to use a -% nominal interword spacing of 25% (relative to the font size, i.e., 1em) -% a maximum of 40% and a minimum of 19%. -% For example, 10pt text uses an interword glue of: -% -% 2.5pt plus 1.49998pt minus 0.59998pt -% -% However, the IEEE allows for a more generous range which reduces the need -% for hyphenation, especially for two column text. Furthermore, the IEEE -% tends to use a little bit more nominal space between the words. -% The IEEE's interword spacing percentages appear to be: -% 35% nominal -% 23% minimum -% 50% maximum -% (They may even be using a tad more for the largest fonts such as 24pt.) -% -% for bold text, the IEEE increases the spacing a little more: -% 37.5% nominal -% 23% minimum -% 55% maximum - -% here are the interword spacing ratios we'll use -% for medium (normal weight) -\def\@IEEEinterspaceratioM{0.35} -\def\@IEEEinterspaceMINratioM{0.23} -\def\@IEEEinterspaceMAXratioM{0.50} - -% for bold -\def\@IEEEinterspaceratioB{0.375} -\def\@IEEEinterspaceMINratioB{0.23} -\def\@IEEEinterspaceMAXratioB{0.55} - - -% compsoc nonconference papers use Palatino, -% tweak settings to better match the proofs -\ifCLASSOPTIONcompsoc -\ifCLASSOPTIONconference\else -% for medium (normal weight) -\def\@IEEEinterspaceratioM{0.28} -\def\@IEEEinterspaceMINratioM{0.21} -\def\@IEEEinterspaceMAXratioM{0.47} -% for bold -\def\@IEEEinterspaceratioB{0.305} -\def\@IEEEinterspaceMINratioB{0.21} -\def\@IEEEinterspaceMAXratioB{0.52} -\fi\fi - - -% command to revise the interword spacing for the current font under TeX: -% \fontdimen2 = nominal interword space -% \fontdimen3 = interword stretch -% \fontdimen4 = interword shrink -% since all changes to the \fontdimen are global, we can enclose these commands -% in braces to confine any font attribute or length changes -\def\@@@IEEEsetfontdimens#1#2#3{{% -\setlength{\@IEEEtrantmpdimenB}{\f@size pt}% grab the font size in pt, could use 1em instead. -\setlength{\@IEEEtrantmpdimenA}{#1\@IEEEtrantmpdimenB}% -\fontdimen2\font=\@IEEEtrantmpdimenA\relax -\addtolength{\@IEEEtrantmpdimenA}{-#2\@IEEEtrantmpdimenB}% -\fontdimen3\font=-\@IEEEtrantmpdimenA\relax -\setlength{\@IEEEtrantmpdimenA}{#1\@IEEEtrantmpdimenB}% -\addtolength{\@IEEEtrantmpdimenA}{-#3\@IEEEtrantmpdimenB}% -\fontdimen4\font=\@IEEEtrantmpdimenA\relax}} - -% revise the interword spacing for each font weight -\def\@@IEEEsetfontdimens{{% -\mdseries -\@@@IEEEsetfontdimens{\@IEEEinterspaceratioM}{\@IEEEinterspaceMAXratioM}{\@IEEEinterspaceMINratioM}% -\bfseries -\@@@IEEEsetfontdimens{\@IEEEinterspaceratioB}{\@IEEEinterspaceMAXratioB}{\@IEEEinterspaceMINratioB}% -}} - -% revise the interword spacing for each font shape -% \slshape is not often used for IEEE work and is not altered here. The \scshape caps are -% already a tad too large in the free LaTeX fonts (as compared to what the IEEE uses) so we -% won't alter these either. -\def\@IEEEsetfontdimens{{% -\normalfont -\@@IEEEsetfontdimens -\normalfont\itshape -\@@IEEEsetfontdimens -}} - -% command to revise the interword spacing for each font size (and shape -% and weight). Only the \rmfamily is done here as \ttfamily uses a -% fixed spacing and \sffamily is not used as the main text of IEEE papers. -\def\@IEEEtunefonts{{\selectfont\rmfamily -\tiny\@IEEEsetfontdimens -\scriptsize\@IEEEsetfontdimens -\footnotesize\@IEEEsetfontdimens -\small\@IEEEsetfontdimens -\normalsize\@IEEEsetfontdimens -\sublargesize\@IEEEsetfontdimens -\large\@IEEEsetfontdimens -\LARGE\@IEEEsetfontdimens -\huge\@IEEEsetfontdimens -\Huge\@IEEEsetfontdimens}} - -% if the nofonttune class option is not given, revise the interword spacing -% now - in case IEEEtran makes any default length measurements, and make -% sure all the default fonts are loaded -\ifCLASSOPTIONnofonttune\else -\@IEEEtunefonts -\fi - -% and again at the start of the document in case the user loaded different fonts -\AtBeginDocument{\ifCLASSOPTIONnofonttune\else\@IEEEtunefonts\fi} - - - - - -% -- V1.8a page setup commands -- - -% The default sample text for calculating margins -% Note that IEEE publications use \scriptsize for headers and footers. -\def\IEEEdefaultsampletext{\normalfont\normalsize gT} -\def\IEEEdefaultheadersampletext{\normalfont\scriptsize T}% IEEE headers default to uppercase -\def\IEEEdefaultfootersampletext{\normalfont\scriptsize gT} - - - -% usage: \IEEEsettextwidth{inner margin}{outer margin} -% Sets \textwidth to allow the specified inner and outer margins -% for the current \paperwidth. -\def\IEEEsettextwidth#1#2{\@IEEEtrantmpdimenA\paperwidth -\@IEEEtrantmpdimenB#1\relax -\advance\@IEEEtrantmpdimenA by -\@IEEEtrantmpdimenB -\@IEEEtrantmpdimenB#2\relax -\advance\@IEEEtrantmpdimenA by -\@IEEEtrantmpdimenB -\textwidth\@IEEEtrantmpdimenA} - - - -% usage: \IEEEsetsidemargin{mode: i, o, c, a}{margin/offset} -% Sets \oddsidemargin and \evensidemargin to yield the specified margin -% of the given mode. -% The available modes are: -% i = inner margin -% o = outer margin -% c = centered, with the given offset -% a = adjust the margins using the given offset -% For the offsets, positive values increase the inner margin. -% \textwidth should be set properly for the given margins before calling this -% function. -\def\IEEEsetsidemargin#1#2{\@IEEEtrantmpdimenA #2\relax -\@IEEEextracttoken{#1}\relax -% check for mode errors -\ifx\@IEEEextractedtokenmacro\@empty - \@IEEEclspkgerror{Empty mode type in \string\IEEEsetsidemargin\space (line \the\inputlineno).\MessageBreak - Defaulting to `i'}{Valid modes for \string\IEEEsetsidemargin\space are: i, o, c and a.}\relax - \let\@IEEEextractedtoken=i\relax - \def\@IEEEextractedtokenmacro{i}\relax -\else - \ifx\@IEEEextractedtokensdiscarded\@empty\else - \typeout{** WARNING: \string\IEEEsetsidemargin\space mode specifiers after the first in `\@IEEEextracttokenarg' ignored (line \the\inputlineno).}\relax - \fi -\fi -% handle each mode -\if\@IEEEextractedtoken a\relax - \advance\oddsidemargin by \@IEEEtrantmpdimenA\relax -\else -\if\@IEEEextractedtoken c\relax - \oddsidemargin\paperwidth - \advance\oddsidemargin by -\textwidth - \divide\oddsidemargin by 2\relax - \advance\oddsidemargin by -1in\relax - \advance\oddsidemargin by \@IEEEtrantmpdimenA\relax -\else -\if\@IEEEextractedtoken o\relax - \oddsidemargin\paperwidth - \advance\oddsidemargin by -\textwidth - \advance\oddsidemargin by -\@IEEEtrantmpdimenA - \advance\oddsidemargin by -1in\relax -\else - \if\@IEEEextractedtoken i\relax - \else - \@IEEEclspkgerror{Unknown mode type `\@IEEEextractedtokenmacro' in \string\IEEEsetsidemargin\space (line \the\inputlineno).\MessageBreak - Defaulting to `i'}% - {Valid modes for \string\IEEEsetsidemargin\space are: i, o, c and a.}% - \fi - \oddsidemargin\@IEEEtrantmpdimenA - \advance\oddsidemargin by -1in\relax -\fi\fi\fi -% odd and even side margins both mean "inner" for single sided pages -\evensidemargin\oddsidemargin -% but are mirrors of each other when twosided is in effect -\if@twoside - \evensidemargin\paperwidth - \advance\evensidemargin by -\textwidth - \advance\evensidemargin by -\oddsidemargin - % have to compensate for both the builtin 1in LaTex offset - % and the fact we already subtracted this offset from \oddsidemargin - \advance\evensidemargin -2in\relax -\fi} - - - -% usage: \IEEEsettextheight[sample text]{top text margin}{bottom text margin} -% Sets \textheight based on the specified top margin and bottom margin. -% Takes into consideration \paperheight, \topskip, and (by default) the -% the actual height and depth of the \IEEEdefaultsampletext text. -\def\IEEEsettextheight{\@ifnextchar [{\@IEEEsettextheight}{\@IEEEsettextheight[\IEEEdefaultsampletext]}} -\def\@IEEEsettextheight[#1]#2#3{\textheight\paperheight\relax - \@IEEEtrantmpdimenA #2\relax - \advance \textheight by -\@IEEEtrantmpdimenA% subtract top margin - \@IEEEtrantmpdimenA #3\relax - \advance \textheight by -\@IEEEtrantmpdimenA% subtract bottom margin - \advance \textheight by \topskip% add \topskip - % subtract off everything above the top, and below the bottom, baselines - \settoheight{\@IEEEtrantmpdimenA}{\begingroup #1\relax\relax\relax\endgroup}\relax - \advance \textheight by -\@IEEEtrantmpdimenA - \settodepth{\@IEEEtrantmpdimenA}{\begingroup #1\relax\relax\relax\endgroup}\relax - \advance \textheight by -\@IEEEtrantmpdimenA} - - - -\newdimen\IEEEquantizedlength -\IEEEquantizedlength 0sp\relax -\newdimen\IEEEquantizedlengthdiff -\IEEEquantizedlengthdiff 0sp\relax -\def\IEEEquantizedlengthint{0} - -% usage: \IEEEquantizelength{mode: d, c, i}{base unit}{length} -% Sets the length \IEEEquantizedlength to be an integer multiple of the given -% (nonzero) base unit such that \IEEEquantizedlength approximates the given -% length. -% \IEEEquantizedlengthdiff is a length equal to the difference between the -% \IEEEquantizedlength and the given length. -% \IEEEquantizedlengthint is a macro containing the integer number of base units -% in \IEEEquantizedlength. -% i.e., \IEEEquantizedlength = \IEEEquantizedlengthint * base unit -% The mode determines how \IEEEquantizedlength is quantized: -% d = always decrease (always round down \IEEEquantizeint) -% c = use the closest match -% i = always increase (always round up \IEEEquantizeint) -% In anycase, if the given length is already quantized, -% \IEEEquantizedlengthdiff will be set to zero. -\def\IEEEquantizelength#1#2#3{\begingroup -% work in isolation so as not to externally disturb the \@IEEEtrantmp -% variables -% load the argument values indirectly via \IEEEquantizedlengthdiff -% in case the user refers to our \@IEEEtrantmpdimenX, \IEEEquantizedlength, -% etc. in the arguments. we also will work with these as counters, -% i.e., in sp units -% A has the base unit -\IEEEquantizedlengthdiff #2\relax\relax\relax\relax -\@IEEEtrantmpcountA\IEEEquantizedlengthdiff -% B has the input length -\IEEEquantizedlengthdiff #3\relax\relax\relax\relax -\@IEEEtrantmpcountB\IEEEquantizedlengthdiff -\@IEEEtrantmpdimenA\the\@IEEEtrantmpcountA sp\relax -\@IEEEtrantmpdimenB\the\@IEEEtrantmpcountB sp\relax -% \@IEEEtrantmpcountC will have the quantized int -% \IEEEquantizedlength will have the quantized length -% \@IEEEtrantmpdimenC will have the quantized diff -% initialize them to zero as this is what will be -% exported if an error occurs -\@IEEEtrantmpcountC 0\relax -\IEEEquantizedlength 0sp\relax -\@IEEEtrantmpdimenC 0sp\relax -% extract mode -\@IEEEextracttoken{#1}\relax -% check for mode errors -\ifx\@IEEEextractedtokenmacro\@empty - \@IEEEclspkgerror{Empty mode type in \string\IEEEquantizelength\space (line \the\inputlineno).\MessageBreak - Defaulting to `d'}{Valid modes for \string\IEEEquantizelength\space are: d, c and i.}\relax - \let\@IEEEextractedtoken=d\relax - \def\@IEEEextractedtokenmacro{d}\relax -\else - \ifx\@IEEEextractedtokensdiscarded\@empty\else - \typeout{** WARNING: \string\IEEEquantizelength\space mode specifiers after the first in `\@IEEEextracttokenarg' ignored (line \the\inputlineno).}\relax - \fi -\fi -% check for base unit is zero error -\ifnum\@IEEEtrantmpcountA=0\relax -\@IEEEclspkgerror{Base unit is zero in \string\IEEEquantizelength\space (line \the\inputlineno).\MessageBreak - \string\IEEEquantizedlength\space and \string\IEEEquantizedlengthdiff\space are set to zero}{Division by zero is not allowed.}\relax -\else% base unit is nonzero - % \@IEEEtrantmpcountC carries the number of integer units - % in the quantized length (integer length \ base) - \@IEEEtrantmpcountC\@IEEEtrantmpcountB\relax - \divide\@IEEEtrantmpcountC by \@IEEEtrantmpcountA\relax - % \IEEEquantizedlength has the (rounded down) quantized length - % = base * int - \IEEEquantizedlength\@IEEEtrantmpdimenA\relax - \multiply\IEEEquantizedlength by \@IEEEtrantmpcountC\relax - % \@IEEEtrantmpdimenC has the difference - % = quantized length - length - \@IEEEtrantmpdimenC\IEEEquantizedlength\relax - \advance\@IEEEtrantmpdimenC by -\@IEEEtrantmpdimenB\relax - % trap special case of length being already quantized - % to avoid a roundup under i option - \ifdim\@IEEEtrantmpdimenC=0sp\relax - \else % length not is already quantized - % set dimenA to carry the upper quantized (absolute value) difference: - % quantizedlength + base - length - \advance\@IEEEtrantmpdimenA by \IEEEquantizedlength\relax - \advance\@IEEEtrantmpdimenA by -\@IEEEtrantmpdimenB\relax - % set dimenB to carry the lower quantized (absolute value) difference: - % length - quantizedlength - \advance\@IEEEtrantmpdimenB by -\IEEEquantizedlength\relax - % handle each mode - \if\@IEEEextractedtoken c\relax - % compare upper and lower amounts, select upper if lower > upper - \ifdim\@IEEEtrantmpdimenB>\@IEEEtrantmpdimenA\relax - % use upper - \advance\IEEEquantizedlength by \the\@IEEEtrantmpcountA sp\relax - \advance\@IEEEtrantmpcountC by 1\relax - \@IEEEtrantmpdimenC\@IEEEtrantmpdimenA - \else% <=. uselower - % no need to do anything for lower, use output values already setup - \fi - \else% not mode c - \if\@IEEEextractedtoken i\relax - % always round up under i mode - \advance\IEEEquantizedlength by \the\@IEEEtrantmpcountA sp\relax - \advance\@IEEEtrantmpcountC by 1\relax - \@IEEEtrantmpdimenC\@IEEEtrantmpdimenA - \else - \if\@IEEEextractedtoken d\relax - \else - \@IEEEclspkgerror{Unknown mode type `\@IEEEextractedtokenmacro' in \string\IEEEquantizelength\space (line \the\inputlineno).\MessageBreak - Defaulting to `d'}% - {Valid modes for \string\IEEEquantizelength\space are: d, c, and i.}\relax - \fi % if d - % no need to do anything for d, use output values already setup - \fi\fi % if i, c - \fi % if length is already quantized -\fi% if base unit is zero -% globally assign the results to macros we use here to escape the enclosing -% group without needing to call \global on any of the \@IEEEtrantmp variables. -% \@IEEEtrantmpcountC has the quantized int -% \IEEEquantizedlength has the quantized length -% \@IEEEtrantmpdimenC has the quantized diff -\xdef\@IEEEquantizedlengthintmacro{\the\@IEEEtrantmpcountC}\relax -\@IEEEtrantmpcountC\IEEEquantizedlength\relax -\xdef\@IEEEquantizedlengthmacro{\the\@IEEEtrantmpcountC}\relax -\@IEEEtrantmpcountC\@IEEEtrantmpdimenC\relax -\xdef\@IEEEquantizedlengthdiffmacro{\the\@IEEEtrantmpcountC}\relax -\endgroup -% locally assign the outputs here from the macros -\expandafter\IEEEquantizedlength\@IEEEquantizedlengthmacro sp\relax -\expandafter\IEEEquantizedlengthdiff\@IEEEquantizedlengthdiffmacro sp\relax -\edef\IEEEquantizedlengthint{\@IEEEquantizedlengthintmacro}\relax} - - - -\newdimen\IEEEquantizedtextheightdiff -\IEEEquantizedtextheightdiff 0sp\relax - -% usage: \IEEEquantizetextheight[base unit]{mode: d, c, i} -% Sets \textheight to be an integer multiple of the current \baselineskip -% (or the optionally specified base unit) plus the first (\topskip) line. -% \IEEEquantizedtextheightdiff is a length equal to the difference between -% the new quantized and original \textheight. -% \IEEEquantizedtextheightlpc is a macro containing the integer number of -% lines per column under the quantized \textheight. i.e., -% \textheight = \IEEEquantizedtextheightlpc * \baselineskip + \topskip -% The mode determines how \textheight is quantized: -% d = always decrease (always round down the number of lines per column) -% c = use the closest match -% i = always increase (always round up the number of lines per column) -% In anycase, if \textheight is already quantized, it will remain unchanged, -% and \IEEEquantizedtextheightdiff will be set to zero. -% Depends on: \IEEEquantizelength -\def\IEEEquantizetextheight{\@ifnextchar [{\@IEEEquantizetextheight}{\@IEEEquantizetextheight[\baselineskip]}} -\def\@IEEEquantizetextheight[#1]#2{\begingroup -% use our \IEEEquantizedtextheightdiff as a scratch pad -% we need to subtract off \topskip before quantization -\IEEEquantizedtextheightdiff\textheight -\advance\IEEEquantizedtextheightdiff by -\topskip\relax -\IEEEquantizelength{#2}{#1}{\IEEEquantizedtextheightdiff} -% add back \topskip line -\advance\IEEEquantizedlength by \topskip -\@IEEEtrantmpcountC\IEEEquantizedlengthint\relax -\advance\@IEEEtrantmpcountC by 1\relax -% globally assign the results to macros we use here to escape the enclosing -% group without needing to call \global on any of the \@IEEEtrantmp variables. -\xdef\@IEEEquantizedtextheightlpcmacro{\the\@IEEEtrantmpcountC}\relax -\@IEEEtrantmpcountC\IEEEquantizedlength\relax -\xdef\@IEEEquantizedtextheightmacro{\the\@IEEEtrantmpcountC}\relax -\@IEEEtrantmpcountC\IEEEquantizedlengthdiff\relax -\xdef\@IEEEquantizedtextheightdiffmacro{\the\@IEEEtrantmpcountC}\relax -\endgroup -% locally assign the outputs here from the macros -\textheight\@IEEEquantizedtextheightmacro sp\relax -\IEEEquantizedtextheightdiff\@IEEEquantizedtextheightdiffmacro sp\relax -\edef\IEEEquantizedtextheightlpc{\@IEEEquantizedtextheightlpcmacro}} - - - -% usage: \IEEEsettopmargin[sample text]{mode: t, b, c, a, q}{margin/offset} -% Sets \topmargin based on the specified vertical margin. -% Takes into consideration the base 1in offset, \headheight, \headsep, -% \topskip, and (by default) the the actual height (or, for the bottom, depth) -% of the \IEEEdefaultsampletext text. -% The available modes are: -% t = top margin -% b = bottom margin -% c = vertically centered, with the given offset -% a = adjust the vertical margins using the given offset -% q = adjust the margins using \IEEEquantizedtextheightdiff and the given offset -% For the offsets, positive values increase the top margin. -% \headheight, \headsep, \topskip and \textheight should be set properly for the -% given margins before calling this function. -\def\IEEEsettopmargin{\@ifnextchar [{\@IEEEsettopmargin}{\@IEEEsettopmargin[\IEEEdefaultsampletext]}} -\def\@IEEEsettopmargin[#1]#2#3{\@IEEEtrantmpdimenA #3\relax -\@IEEEextracttoken{#2}\relax -% check for mode errors -\ifx\@IEEEextractedtokenmacro\@empty - \@IEEEclspkgerror{Empty mode type in \string\IEEEsettopmargin\space (line \the\inputlineno).\MessageBreak - Defaulting to `t'}{Valid modes for \string\IEEEsettopmargin\space are: t, b, c, a and q.}\relax - \let\@IEEEextractedtoken=t\relax - \def\@IEEEextractedtokenmacro{t}\relax -\else - \ifx\@IEEEextractedtokensdiscarded\@empty\else - \typeout{** WARNING: \string\IEEEsettopmargin\space mode specifiers after the first in `\@IEEEextracttokenarg' ignored (line \the\inputlineno).}\relax - \fi -\fi -% handle each mode -\if\@IEEEextractedtoken a\relax - \advance\topmargin by \@IEEEtrantmpdimenA\relax -\else -\if\@IEEEextractedtoken q\relax - % we need to adjust by half the \IEEEquantizedtextheightdiff value - \@IEEEtrantmpdimenB\IEEEquantizedtextheightdiff\relax - \divide\@IEEEtrantmpdimenB by 2\relax - % a positive \IEEEquantizedtextheightdiff means we need to reduce \topmargin - % because \textheight has been lenghtened - \advance\topmargin by -\@IEEEtrantmpdimenB\relax - \advance\topmargin by \@IEEEtrantmpdimenA\relax -\else -\if\@IEEEextractedtoken c\relax - \topmargin\paperheight - \advance\topmargin by -\textheight - % \textheight includes \topskip, but we should not count topskip whitespace here, backout - \advance \topmargin by \topskip - \settoheight{\@IEEEtrantmpdimenB}{\begingroup #1\relax\relax\relax\endgroup}\relax - \advance\topmargin by -\@IEEEtrantmpdimenB\relax - \settodepth{\@IEEEtrantmpdimenB}{\begingroup #1\relax\relax\relax\endgroup}\relax - \advance\topmargin by -\@IEEEtrantmpdimenB\relax - \divide\topmargin by 2\relax - \advance\topmargin by \@IEEEtrantmpdimenA\relax -\else -\if\@IEEEextractedtoken b\relax - \topmargin\paperheight - \advance\topmargin by -\textheight - % \textheight includes \topskip, but we should not count topskip whitespace here, backout - \advance \topmargin by \topskip - \settodepth{\@IEEEtrantmpdimenB}{\begingroup #1\relax\relax\relax\endgroup}\relax - \advance\topmargin by -\@IEEEtrantmpdimenB\relax - \advance\topmargin by -\@IEEEtrantmpdimenA\relax -\else - \if\@IEEEextractedtoken t\relax - \else - \@IEEEclspkgerror{Unknown mode type `\@IEEEextractedtokenmacro' in \string\IEEEsettopmargin\space (line \the\inputlineno).\MessageBreak - Defaulting to `t'}% - {Valid modes for \string\IEEEsettopmargin\space are: t, b, c, a and q.}\relax - \fi - \topmargin\@IEEEtrantmpdimenA\relax - \settoheight{\@IEEEtrantmpdimenB}{\begingroup #1\relax\relax\relax\endgroup}\relax - \advance\topmargin by \@IEEEtrantmpdimenB\relax -\fi\fi % if t, b, c -% convert desired top margin into actual \topmargin -% this is not done for the q or a modes because they are only adjustments -\advance \topmargin by -\topskip -\advance \topmargin by -1in -\advance \topmargin by -\headheight -\advance \topmargin by -\headsep -\fi\fi % if q, a -} - - - -% usage: \IEEEsetheadermargin[header sample][text sample]{mode: t, b, c, a}{margin/offset} -% Differentially adjusts \topmargin and \headsep (such that their sum is unchanged) -% based on the specified header margin. -% Takes into consideration the base 1in offset, \headheight, \topskip, and (by default) -% the actual height (or depth) of the \IEEEdefaultheadersampletext and -% \IEEEdefaultsampletext text. -% The available modes are: -% t = top margin (top of the header text to the top of the page) -% b = bottom margin (bottom of the header text to the top of the main text) -% c = vertically centered between the main text and the top of the page, -% with the given offset -% a = adjust the vertical position using the given offset -% For the offsets, positive values move the header downward. -% \headheight, \headsep, \topskip and \topmargin should be set properly before -% calling this function. -\def\IEEEsetheadermargin{\@ifnextchar [{\@IEEEsetheadermargin}{\@IEEEsetheadermargin[\IEEEdefaultheadersampletext]}} -\def\@IEEEsetheadermargin[#1]{\@ifnextchar [{\@@IEEEsetheadermargin[#1]}{\@@IEEEsetheadermargin[#1][\IEEEdefaultsampletext]}} -\def\@@IEEEsetheadermargin[#1][#2]#3#4{\@IEEEtrantmpdimenA #4\relax -\@IEEEextracttoken{#3}\relax -% check for mode errors -\ifx\@IEEEextractedtokenmacro\@empty - \@IEEEclspkgerror{Empty mode type in \string\IEEEsetheadermargin\space (line \the\inputlineno).\MessageBreak - Defaulting to `t'}{Valid modes for \string\IEEEsetheadermargin\space are: t, b, c, and a.}\relax - \let\@IEEEextractedtoken=t\relax - \def\@IEEEextractedtokenmacro{t}\relax -\else - \ifx\@IEEEextractedtokensdiscarded\@empty\else - \typeout{** WARNING: \string\IEEEsetheadermargin\space mode specifiers after the first in `\@IEEEextracttokenarg' ignored (line \the\inputlineno).}\relax - \fi -\fi -% handle each mode -\if\@IEEEextractedtoken a\relax - % No need to do anything here and can pass through the adjustment - % value as is. The end adjustment of \topmargin and \headsep will - % do all that is needed -\else -\if\@IEEEextractedtoken c\relax - % get the bottom margin - \@IEEEtrantmpdimenB\headsep\relax - \settodepth{\@IEEEtrantmpdimenC}{\begingroup #1\relax\relax\relax\endgroup}\relax - \advance\@IEEEtrantmpdimenB by -\@IEEEtrantmpdimenC - \advance\@IEEEtrantmpdimenB by \topskip - \settoheight{\@IEEEtrantmpdimenC}{\begingroup #2\relax\relax\relax\endgroup}\relax - \advance\@IEEEtrantmpdimenB by -\@IEEEtrantmpdimenC - % at this point \@IEEEtrantmpdimenB has the actual header bottom margin - % subtract from it the top header margin - \advance\@IEEEtrantmpdimenB -1in\relax % take into consideration the system 1in offset of the top margin - \advance\@IEEEtrantmpdimenB by -\topmargin - \advance\@IEEEtrantmpdimenB by -\headheight - \settoheight{\@IEEEtrantmpdimenC}{\begingroup #1\relax\relax\relax\endgroup}\relax - \advance\@IEEEtrantmpdimenB by \@IEEEtrantmpdimenC - % at this point \@IEEEtrantmpdimenB has the difference between the bottom and top margins - % we need to adjust by half this amount to center the header - \divide\@IEEEtrantmpdimenB by 2\relax - % and add to offset - \advance\@IEEEtrantmpdimenA by \@IEEEtrantmpdimenB -\else -\if\@IEEEextractedtoken b\relax - \@IEEEtrantmpdimenB\headsep\relax - \settodepth{\@IEEEtrantmpdimenC}{\begingroup #1\relax\relax\relax\endgroup}\relax - \advance\@IEEEtrantmpdimenB by -\@IEEEtrantmpdimenC - \advance\@IEEEtrantmpdimenB by \topskip - \settoheight{\@IEEEtrantmpdimenC}{\begingroup #2\relax\relax\relax\endgroup}\relax - \advance\@IEEEtrantmpdimenB by -\@IEEEtrantmpdimenC - % at this point \@IEEEtrantmpdimenB has the actual header bottom margin - % get the difference between the actual and the desired - \advance\@IEEEtrantmpdimenB by -\@IEEEtrantmpdimenA - \@IEEEtrantmpdimenA\@IEEEtrantmpdimenB -\else - \if\@IEEEextractedtoken t\relax - \else - \@IEEEclspkgerror{Unknown mode type `\@IEEEextractedtokenmacro' in \string\IEEEsetheadermargin\space (line \the\inputlineno).\MessageBreak - Defaulting to `t'}% - {Valid modes for \string\IEEEsetheadermargin\space are: t, b, c and a.}\relax - \fi - \@IEEEtrantmpdimenB 1in\relax % take into consideration the system 1in offset of the top margin - \advance\@IEEEtrantmpdimenB by \topmargin - \advance\@IEEEtrantmpdimenB by \headheight - \settoheight{\@IEEEtrantmpdimenC}{\begingroup #1\relax\relax\relax\endgroup}\relax - \advance\@IEEEtrantmpdimenB by -\@IEEEtrantmpdimenC - % at this point \@IEEEtrantmpdimenB has the actual header top margin - % get the difference between the desired and the actual - \advance\@IEEEtrantmpdimenA by -\@IEEEtrantmpdimenB -\fi\fi % if t, b, c -\fi % if a -% advance \topmargin by the needed amount and reduce \headsep by the same -% so as not to disturb the location of the main text -\advance\topmargin by \@IEEEtrantmpdimenA\relax -\advance\headsep by -\@IEEEtrantmpdimenA\relax -} - - - -% usage: \IEEEsetfootermargin[footer sample][text sample]{mode: t, b, c, a}{margin/offset} -% Adjusts \footskip based on the specified footer margin. -% Takes into consideration the base 1in offset, \paperheight, \headheight, -% \headsep, \textheight and (by default) the actual height (or depth) of the -% \IEEEdefaultfootersampletext and \IEEEdefaultsampletext text. -% The available modes are: -% t = top margin (top of the footer text to the bottom of the main text) -% b = bottom margin (bottom of the footer text to the bottom of page) -% c = vertically centered between the main text and the bottom of the page, -% with the given offset -% a = adjust the vertical position using the given offset -% For the offsets, positive values move the footer downward. -% \headheight, \headsep, \topskip, \topmargin, and \textheight should be set -% properly before calling this function. -\def\IEEEsetfootermargin{\@ifnextchar [{\@IEEEsetfootermargin}{\@IEEEsetfootermargin[\IEEEdefaultfootersampletext]}} -\def\@IEEEsetfootermargin[#1]{\@ifnextchar [{\@@IEEEsetfootermargin[#1]}{\@@IEEEsetfootermargin[#1][\IEEEdefaultsampletext]}} -\def\@@IEEEsetfootermargin[#1][#2]#3#4{\@IEEEtrantmpdimenA #4\relax -\@IEEEextracttoken{#3}\relax -% check for mode errors -\ifx\@IEEEextractedtokenmacro\@empty - \@IEEEclspkgerror{Empty mode type in \string\IEEEsetfootermargin\space (line \the\inputlineno).\MessageBreak - Defaulting to `t'}{Valid modes for \string\IEEEsetfootermargin\space are: t, b, c, and a.}\relax - \let\@IEEEextractedtoken=t\relax - \def\@IEEEextractedtokenmacro{t}\relax -\else - \ifx\@IEEEextractedtokensdiscarded\@empty\else - \typeout{** WARNING: \string\IEEEsetfootermargin\space mode specifiers after the first in `\@IEEEextracttokenarg' ignored (line \the\inputlineno).}\relax - \fi -\fi -% handle each mode -\if\@IEEEextractedtoken a\relax - % No need to do anything here and can pass through the adjustment - % value as is. The end adjustment of \footskip will do all that - % is needed -\else -\if\@IEEEextractedtoken c\relax - % calculate the bottom margin - \@IEEEtrantmpdimenB 1in\relax % system 1in offset - \advance\@IEEEtrantmpdimenB\topmargin\relax - \advance\@IEEEtrantmpdimenB\headheight\relax - \advance\@IEEEtrantmpdimenB\headsep\relax - \advance\@IEEEtrantmpdimenB\textheight\relax - \advance\@IEEEtrantmpdimenB\footskip\relax - \settodepth{\@IEEEtrantmpdimenC}{\begingroup #1\relax\relax\relax\endgroup}\relax - \advance\@IEEEtrantmpdimenC by \@IEEEtrantmpdimenB - \@IEEEtrantmpdimenB\paperheight - \advance\@IEEEtrantmpdimenB by -\@IEEEtrantmpdimenC - % at this point \@IEEEtrantmpdimenB has the actual footer bottom margin - % now subtract off the footer top margin - \advance\@IEEEtrantmpdimenB -\footskip\relax - \settodepth{\@IEEEtrantmpdimenC}{\begingroup #2\relax\relax\relax\endgroup}\relax - \advance\@IEEEtrantmpdimenB by \@IEEEtrantmpdimenC - \settoheight{\@IEEEtrantmpdimenC}{\begingroup #1\relax\relax\relax\endgroup}\relax - \advance\@IEEEtrantmpdimenB by \@IEEEtrantmpdimenC - % at this point \@IEEEtrantmpdimenB has the difference between the bottom - % and top footer margins - % our adjustment must be half this value to center the footer - \divide\@IEEEtrantmpdimenB by 2\relax - % add to the offset - \advance\@IEEEtrantmpdimenA by \@IEEEtrantmpdimenB -\else -\if\@IEEEextractedtoken b\relax - % calculate the bottom margin - \@IEEEtrantmpdimenB 1in\relax % system 1in offset - \advance\@IEEEtrantmpdimenB\topmargin\relax - \advance\@IEEEtrantmpdimenB\headheight\relax - \advance\@IEEEtrantmpdimenB\headsep\relax - \advance\@IEEEtrantmpdimenB\textheight\relax - \advance\@IEEEtrantmpdimenB\footskip\relax - \settodepth{\@IEEEtrantmpdimenC}{\begingroup #1\relax\relax\relax\endgroup}\relax - \advance\@IEEEtrantmpdimenC by \@IEEEtrantmpdimenB - \@IEEEtrantmpdimenB\paperheight - \advance\@IEEEtrantmpdimenB by -\@IEEEtrantmpdimenC - % at this point \@IEEEtrantmpdimenB has the actual footer bottom margin - % get the difference between the actual and the desired - \advance\@IEEEtrantmpdimenB by -\@IEEEtrantmpdimenA - \@IEEEtrantmpdimenA\@IEEEtrantmpdimenB -\else - \if\@IEEEextractedtoken t\relax - \else - \@IEEEclspkgerror{Unknown mode type `\@IEEEextractedtokenmacro' in \string\IEEEsetfootermargin\space (line \the\inputlineno).\MessageBreak - Defaulting to `t'}% - {Valid modes for \string\IEEEsetfootermargin\space are: t, b, c and a.}\relax - \fi - \@IEEEtrantmpdimenB\footskip\relax - \settodepth{\@IEEEtrantmpdimenC}{\begingroup #2\relax\relax\relax\endgroup}\relax - \advance\@IEEEtrantmpdimenB by -\@IEEEtrantmpdimenC - \settoheight{\@IEEEtrantmpdimenC}{\begingroup #1\relax\relax\relax\endgroup}\relax - \advance\@IEEEtrantmpdimenB by -\@IEEEtrantmpdimenC - % at this point \@IEEEtrantmpdimenB has the actual footer top margin - % get the difference between the desired and the actual - \advance\@IEEEtrantmpdimenA by -\@IEEEtrantmpdimenB -\fi\fi % if t, b, c -\fi % if a -% advance \footskip by the needed amount -\advance\footskip by \@IEEEtrantmpdimenA\relax -} - -% -- End V1.8a page setup commands -- - - - - - -% V1.6 -% LaTeX is a little to quick to use hyphenations -% So, we increase the penalty for their use and raise -% the badness level that triggers an underfull hbox -% warning. The author may still have to tweak things, -% but the appearance will be much better "right out -% of the box" than that under V1.5 and prior. -% TeX default is 50 -\hyphenpenalty=750 -\ifCLASSOPTIONcompsoc -\hyphenpenalty 500 -\fi -% If we didn't adjust the interword spacing, 2200 might be better. -% The TeX default is 1000 -\hbadness=1350 -% The IEEE does not use extra spacing after punctuation -\frenchspacing - -% V1.7 increase this a tad to discourage equation breaks -\binoppenalty=1000 % default 700 -\relpenalty=800 % default 500 - -% v1.8a increase these to discourage widows and orphans -\clubpenalty=1000 % default 150 -\widowpenalty=1000 % default 150 -\displaywidowpenalty=1000 % default 50 - - -% margin note stuff -\marginparsep 10pt -\marginparwidth 20pt -\marginparpush 25pt - - -% if things get too close, go ahead and let them touch -\lineskip 0pt -\normallineskip 0pt -\lineskiplimit 0pt -\normallineskiplimit 0pt - -% The distance from the lower edge of the text body to the -% footline -\footskip 0.4in - -% normally zero, should be relative to font height. -% put in a little rubber to help stop some bad breaks (underfull vboxes) -\parskip 0ex plus 0.2ex minus 0.1ex - -\parindent 1.0em -\ifCLASSOPTIONcompsoc - \parindent 1.5em -\fi - -\headheight 12pt -\headsep 18pt -% use the normal font baselineskip -% so that \topskip is unaffected by changes in \baselinestretch -\topskip=\@IEEEnormalsizeunitybaselineskip - - -% V1.8 \maxdepth defaults to 4pt, but should be font size dependent -\maxdepth=0.5\@IEEEnormalsizeunitybaselineskip -\textheight 58pc % 9.63in, 696pt - -% set the default top margin to 58pt -% which results in a \topmargin of -49.59pt for 10pt documents -\IEEEsettopmargin{t}{58pt} -% tweak textheight to a perfect integer number of lines/column. -% standard is: 9pt/63 lpc; 10pt/58 lpc; 11pt/52 lpc; 12pt/50 lpc -\IEEEquantizetextheight{c} -% tweak top margin so that the error is shared equally at the top and bottom -\IEEEsettopmargin{q}{0sp} - - -\columnsep 1pc -\textwidth 43pc % 2 x 21pc + 1pc = 43pc - -% set the default side margins to center the text -\IEEEsetsidemargin{c}{0pt} - - -% adjust margins for default conference mode -\ifCLASSOPTIONconference - \textheight 9.25in % The standard for conferences (668.4975pt) - \IEEEsettopmargin{t}{0.75in} - % tweak textheight to a perfect integer number of lines/page. - % standard is: 9pt/61 lpc; 10pt/56 lpc; 11pt/50 lpc; 12pt/48 lpc - \IEEEquantizetextheight{c} - % tweak top margin so that the error is shared equally at the top and bottom - \IEEEsettopmargin{q}{0sp} -\fi - - -% compsoc text sizes, margins and spacings -\ifCLASSOPTIONcompsoc - \columnsep 12bp - % CS specs for \textwdith are 6.875in - % \textwidth 6.875in - % however, measurements from proofs show they are using 3.5in columns - \textwidth 7in - \advance\textwidth by \columnsep - % set the side margins to center the text - \IEEEsetsidemargin{c}{0pt} - % top/bottom margins to center - % could just set \textheight to 9.75in for all the different paper sizes - % and then quantize, but we'll do it the long way here to allow for easy - % future per-paper size adjustments - \IEEEsettextheight{0.625in}{0.625in}% 11in - 2 * 0.625in = 9.75in is the standard text height for compsoc journals - \IEEEsettopmargin{t}{0.625in} - \if@IEEEusingcspaper - \IEEEsettextheight{0.5in}{0.5in}% 10.75in - 2 * 0.5in = 9.75in - \IEEEsettopmargin{t}{0.5in} - \fi - \if@IEEEusingAfourpaper - \IEEEsettextheight{24.675mm}{24.675mm}% 297mm - 2 * 24.675mm = 247.650mm (9.75in) - \IEEEsettopmargin{t}{24.675mm} - \fi - % tweak textheight to a perfect integer number of lines/page. - % standard is: 9pt/65 lpc; 10pt/61 lpc; 11pt/53 lpc; 12pt/49 lpc - \IEEEquantizetextheight{c} - % tweak top margin so that the error is shared equally at the top and bottom - \IEEEsettopmargin{q}{0sp} - -% compsoc conference - \ifCLASSOPTIONconference - % compsoc conference use a larger value for columnsep - \columnsep 0.25in - \IEEEsettextwidth{0.75in}{0.75in} - % set the side margins to center the text (0.75in for letterpaper) - \IEEEsetsidemargin{c}{0pt} - % compsoc conferences want 1in top and bottom margin - \IEEEsettextheight{1in}{1in} - \IEEEsettopmargin{t}{1in} - % tweak textheight to a perfect integer number of lines/page. - % standard is: 9pt/58 lpc; 10pt/53 lpc; 11pt/48 lpc; 12pt/46 lpc - \IEEEquantizetextheight{c} - % tweak top margin so that the error is shared equally at the top and bottom - \IEEEsettopmargin{q}{0sp} - \fi -\fi - - - -% draft mode settings override that of all other modes -% provides a nice 1in margin all around the paper and extra -% space between the lines for editor's comments -\ifCLASSOPTIONdraftcls - % we want 1in side margins regardless of paper type - \IEEEsettextwidth{1in}{1in} - \IEEEsetsidemargin{c}{0pt} - % want 1in top and bottom margins - \IEEEsettextheight{1in}{1in} - \IEEEsettopmargin{t}{1in} - % digitize textheight to be an integer number of lines. - % this may cause the top and bottom margins to be off a tad - \IEEEquantizetextheight{c} - % tweak top margin so that the error is shared equally at the top and bottom - \IEEEsettopmargin{q}{0sp} -\fi - - - -% process CLASSINPUT inner/outer margin -% if inner margin defined, but outer margin not, set outer to inner. -\ifx\CLASSINPUTinnersidemargin\@IEEEundefined -\else - \ifx\CLASSINPUToutersidemargin\@IEEEundefined - \edef\CLASSINPUToutersidemargin{\CLASSINPUTinnersidemargin} - \fi -\fi - -\ifx\CLASSINPUToutersidemargin\@IEEEundefined -\else - % if outer margin defined, but inner margin not, set inner to outer. - \ifx\CLASSINPUTinnersidemargin\@IEEEundefined - \edef\CLASSINPUTinnersidemargin{\CLASSINPUToutersidemargin} - \fi - \IEEEsettextwidth{\CLASSINPUTinnersidemargin}{\CLASSINPUToutersidemargin} - \IEEEsetsidemargin{i}{\CLASSINPUTinnersidemargin} - \typeout{** ATTENTION: Overriding inner side margin to \CLASSINPUTinnersidemargin\space and - outer side margin to \CLASSINPUToutersidemargin\space via \string\CLASSINPUT.} -\fi - - - -% process CLASSINPUT top/bottom text margin -% if toptext margin defined, but bottomtext margin not, set bottomtext to toptext margin -\ifx\CLASSINPUTtoptextmargin\@IEEEundefined -\else - \ifx\CLASSINPUTbottomtextmargin\@IEEEundefined - \edef\CLASSINPUTbottomtextmargin{\CLASSINPUTtoptextmargin} - \fi -\fi - -\ifx\CLASSINPUTbottomtextmargin\@IEEEundefined -\else - % if bottomtext margin defined, but toptext margin not, set toptext to bottomtext margin - \ifx\CLASSINPUTtoptextmargin\@IEEEundefined - \edef\CLASSINPUTtoptextmargin{\CLASSINPUTbottomtextmargin} - \fi - \IEEEsettextheight{\CLASSINPUTtoptextmargin}{\CLASSINPUTbottomtextmargin} - \IEEEsettopmargin{t}{\CLASSINPUTtoptextmargin} - \typeout{** ATTENTION: Overriding top text margin to \CLASSINPUTtoptextmargin\space and - bottom text margin to \CLASSINPUTbottomtextmargin\space via \string\CLASSINPUT.} -\fi - - - -% default to center header and footer text in the margins -\IEEEsetheadermargin{c}{0pt} -\IEEEsetfootermargin{c}{0pt} - -% adjust header and footer positions for compsoc journals -\ifCLASSOPTIONcompsoc - \ifCLASSOPTIONjournal - \IEEEsetheadermargin{b}{\@IEEEnormalsizeunitybaselineskip} - \IEEEsetfootermargin{t}{\@IEEEnormalsizeunitybaselineskip} - \fi -\fi - - -% V1.8a display lines per column info message on user's console -\def\IEEEdisplayinfolinespercolumn{\@IEEEtrantmpdimenA=\textheight -% topskip represents only one line even if > baselineskip -\advance\@IEEEtrantmpdimenA by -1\topskip -\@IEEEtrantmpcountA=\@IEEEtrantmpdimenA -\@IEEEtrantmpcountB=\@IEEEtrantmpdimenA -\divide\@IEEEtrantmpcountB by \baselineskip -% need to add one line to include topskip (first) line -\advance\@IEEEtrantmpcountB by 1 -% save lines per column value as text -\edef\@IEEEnumlinespercolumninfotxt{\the\@IEEEtrantmpcountB} -% backout topskip advance to allow direct \@IEEEtrantmpcountA comparison -\advance\@IEEEtrantmpcountB by -1 -% restore value as text height (without topskip) rather than just as number of lines -\multiply\@IEEEtrantmpcountB by \baselineskip -% is the column height an integer number of lines per column? -\ifnum\@IEEEtrantmpcountA=\@IEEEtrantmpcountB -\edef\@IEEEnumlinespercolumnexactinfotxt{exact} -\else -\@IEEEtrantmpdimenA\@IEEEtrantmpcountA sp\relax -\advance\@IEEEtrantmpdimenA by -\@IEEEtrantmpcountB sp\relax -\edef\@IEEEnumlinespercolumnexactinfotxt{approximate, difference = \the\@IEEEtrantmpdimenA} -\fi -\typeout{-- Lines per column: \@IEEEnumlinespercolumninfotxt\space (\@IEEEnumlinespercolumnexactinfotxt).}} -% delay execution till start of document to allow for user changes -\AtBeginDocument{\IEEEdisplayinfolinespercolumn} - - - -% LIST SPACING CONTROLS - -% Controls the amount of EXTRA spacing -% above and below \trivlist -% Both \list and IED lists override this. -% However, \trivlist will use this as will most -% things built from \trivlist like the \center -% environment. -\topsep 0.5\baselineskip - -% Controls the additional spacing around lists preceded -% or followed by blank lines. the IEEE does not increase -% spacing before or after paragraphs so it is set to zero. -% \z@ is the same as zero, but faster. -\partopsep \z@ - -% Controls the spacing between paragraphs in lists. -% The IEEE does not increase spacing before or after paragraphs -% so this is also zero. -% With IEEEtran.cls, global changes to -% this value DO affect lists (but not IED lists). -\parsep \z@ - -% Controls the extra spacing between list items. -% The IEEE does not put extra spacing between items. -% With IEEEtran.cls, global changes to this value DO affect -% lists (but not IED lists). -\itemsep \z@ - -% \itemindent is the amount to indent the FIRST line of a list -% item. It is auto set to zero within the \list environment. To alter -% it, you have to do so when you call the \list. -% However, the IEEE uses this for the theorem environment -% There is an alternative value for this near \leftmargini below -\itemindent -1em - -% \leftmargin, the spacing from the left margin of the main text to -% the left of the main body of a list item is set by \list. -% Hence this statement does nothing for lists. -% But, quote and verse do use it for indention. -\leftmargin 2em - -% we retain this stuff from the older IEEEtran.cls so that \list -% will work the same way as before. However, itemize, enumerate and -% description (IED) could care less about what these are as they -% all are overridden. -\leftmargini 2em -%\itemindent 2em % Alternative values: sometimes used. -%\leftmargini 0em -\leftmarginii 1em -\leftmarginiii 1.5em -\leftmarginiv 1.5em -\leftmarginv 1.0em -\leftmarginvi 1.0em -\labelsep 0.5em -\labelwidth \z@ - - -% The old IEEEtran.cls behavior of \list is retained. -% However, the new V1.3 IED list environments override all the -% @list stuff (\@listX is called within \list for the -% appropriate level just before the user's list_decl is called). -% \topsep is now 2pt as the IEEE puts a little extra space around -% lists - used by those non-IED macros that depend on \list. -% Note that \parsep and \itemsep are not redefined as in -% the sizexx.clo \@listX (which article.cls uses) so global changes -% of these values DO affect \list -% -\def\@listi{\leftmargin\leftmargini \topsep 2pt plus 1pt minus 1pt} -\let\@listI\@listi -\def\@listii{\leftmargin\leftmarginii\labelwidth\leftmarginii% - \advance\labelwidth-\labelsep \topsep 2pt} -\def\@listiii{\leftmargin\leftmarginiii\labelwidth\leftmarginiii% - \advance\labelwidth-\labelsep \topsep 2pt} -\def\@listiv{\leftmargin\leftmarginiv\labelwidth\leftmarginiv% - \advance\labelwidth-\labelsep \topsep 2pt} -\def\@listv{\leftmargin\leftmarginv\labelwidth\leftmarginv% - \advance\labelwidth-\labelsep \topsep 2pt} -\def\@listvi{\leftmargin\leftmarginvi\labelwidth\leftmarginvi% - \advance\labelwidth-\labelsep \topsep 2pt} - - -% The IEEE uses 5) not 5. -\def\labelenumi{\theenumi)} \def\theenumi{\arabic{enumi}} - -% The IEEE uses a) not (a) -\def\labelenumii{\theenumii)} \def\theenumii{\alph{enumii}} - -% The IEEE uses iii) not iii. -\def\labelenumiii{\theenumiii)} \def\theenumiii{\roman{enumiii}} - -% The IEEE uses A) not A. -\def\labelenumiv{\theenumiv)} \def\theenumiv{\Alph{enumiv}} - -% exactly the same as in article.cls -\def\p@enumii{\theenumi} -\def\p@enumiii{\theenumi(\theenumii)} -\def\p@enumiv{\p@enumiii\theenumiii} - -% itemized list label styles -\def\labelitemi{$\scriptstyle\bullet$} -\def\labelitemii{\textbf{--}} -\def\labelitemiii{$\ast$} -\def\labelitemiv{$\cdot$} - - - -% **** V1.3 ENHANCEMENTS **** -% Itemize, Enumerate and Description (IED) List Controls -% *************************** -% -% -% The IEEE seems to use at least two different values by -% which ITEMIZED list labels are indented to the right -% For The Journal of Lightwave Technology (JLT) and The Journal -% on Selected Areas in Communications (JSAC), they tend to use -% an indention equal to \parindent. For Transactions on Communications -% they tend to indent ITEMIZED lists a little more--- 1.3\parindent. -% We'll provide both values here for you so that you can choose -% which one you like in your document using a command such as: -% setlength{\IEEEilabelindent}{\IEEEilabelindentB} -\newdimen\IEEEilabelindentA -\IEEEilabelindentA \parindent - -\newdimen\IEEEilabelindentB -\IEEEilabelindentB 1.3\parindent -% However, we'll default to using \parindent -% which makes more sense to me -\newdimen\IEEEilabelindent -\IEEEilabelindent \IEEEilabelindentA - - -% This controls the default amount the enumerated list labels -% are indented to the right. -% Normally, this is the same as the paragraph indention -\newdimen\IEEEelabelindent -\IEEEelabelindent \parindent - -% This controls the default amount the description list labels -% are indented to the right. -% Normally, this is the same as the paragraph indention -\newdimen\IEEEdlabelindent -\IEEEdlabelindent \parindent - -% This is the value actually used within the IED lists. -% The IED environments automatically set its value to -% one of the three values above, so global changes do -% not have any effect -\newdimen\IEEElabelindent -\IEEElabelindent \parindent - -% The actual amount labels will be indented is -% \IEEElabelindent multiplied by the factor below -% corresponding to the level of nesting depth -% This provides a means by which the user can -% alter the effective \IEEElabelindent for deeper -% levels -% There may not be such a thing as correct "standard IEEE" -% values. What the IEEE actually does may depend on the specific -% circumstances. -% The first list level almost always has full indention. -% The second levels I've seen have only 75% of the normal indentation -% Three level or greater nestings are very rare. I am guessing -% that they don't use any indentation. -\def\IEEElabelindentfactori{1.0} % almost always one -\def\IEEElabelindentfactorii{0.75} % 0.0 or 1.0 may be used in some cases -\def\IEEElabelindentfactoriii{0.0} % 0.75? 0.5? 0.0? -\def\IEEElabelindentfactoriv{0.0} -\def\IEEElabelindentfactorv{0.0} -\def\IEEElabelindentfactorvi{0.0} - -% value actually used within IED lists, it is auto -% set to one of the 6 values above -% global changes here have no effect -\def\IEEElabelindentfactor{1.0} - -% This controls the default spacing between the end of the IED -% list labels and the list text, when normal text is used for -% the labels. -% compsoc uses a larger value here, but we'll set that later -% in the class so that this code block area can be extracted -% as-is for IEEEtrantools.sty -\newdimen\IEEEiednormlabelsep -\IEEEiednormlabelsep 0.6em - -% This controls the default spacing between the end of the IED -% list labels and the list text, when math symbols are used for -% the labels (nomenclature lists). The IEEE usually increases the -% spacing in these cases -\newdimen\IEEEiedmathlabelsep -\IEEEiedmathlabelsep 1.2em - -% This controls the extra vertical separation put above and -% below each IED list. the IEEE usually puts a little extra spacing -% around each list. However, this spacing is barely noticeable. -% compsoc uses a larger value here, but we'll set that later -% in the class so that this code block area can be extracted -% as-is for IEEEtrantools.sty -\newskip\IEEEiedtopsep -\IEEEiedtopsep 2pt plus 1pt minus 1pt - - -% This command is executed within each IED list environment -% at the beginning of the list. You can use this to set the -% parameters for some/all your IED list(s) without disturbing -% global parameters that affect things other than lists. -% i.e., renewcommand{\IEEEiedlistdecl}{\setlength{\labelsep}{5em}} -% will alter the \labelsep for the next list(s) until -% \IEEEiedlistdecl is redefined. -\def\IEEEiedlistdecl{\relax} - -% This command provides an easy way to set \leftmargin based -% on the \labelwidth, \labelsep and the argument \IEEElabelindent -% Usage: \IEEEcalcleftmargin{width-to-indent-the-label} -% output is in the \leftmargin variable, i.e., effectively: -% \leftmargin = argument + \labelwidth + \labelsep -% Note controlled spacing here, shield end of lines with % -\def\IEEEcalcleftmargin#1{\setlength{\leftmargin}{#1}% -\addtolength{\leftmargin}{\labelwidth}% -\addtolength{\leftmargin}{\labelsep}} - -% This command provides an easy way to set \labelwidth to the -% width of the given text. It is the same as -% \settowidth{\labelwidth}{label-text} -% and useful as a shorter alternative. -% Typically used to set \labelwidth to be the width -% of the longest label in the list -\def\IEEEsetlabelwidth#1{\settowidth{\labelwidth}{#1}} - -% When this command is executed, IED lists will use the -% IEEEiedmathlabelsep label separation rather than the normal -% spacing. To have an effect, this command must be executed via -% the \IEEEiedlistdecl or within the option of the IED list -% environments. -\def\IEEEusemathlabelsep{\setlength{\labelsep}{\IEEEiedmathlabelsep}} - -% A flag which controls whether the IED lists automatically -% calculate \leftmargin from \IEEElabelindent, \labelwidth and \labelsep -% Useful if you want to specify your own \leftmargin -% This flag must be set (\IEEEnocalcleftmargintrue or \IEEEnocalcleftmarginfalse) -% via the \IEEEiedlistdecl or within the option of the IED list -% environments to have an effect. -\newif\ifIEEEnocalcleftmargin -\IEEEnocalcleftmarginfalse - -% A flag which controls whether \IEEElabelindent is multiplied by -% the \IEEElabelindentfactor for each list level. -% This flag must be set via the \IEEEiedlistdecl or within the option -% of the IED list environments to have an effect. -\newif\ifIEEEnolabelindentfactor -\IEEEnolabelindentfactorfalse - - -% internal variable to indicate type of IED label -% justification -% 0 - left; 1 - center; 2 - right -\def\@IEEEiedjustify{0} - - -% commands to allow the user to control IED -% label justifications. Use these commands within -% the IED environment option or in the \IEEEiedlistdecl -% Note that changing the normal list justifications -% is nonstandard and the IEEE may not like it if you do so! -% I include these commands as they may be helpful to -% those who are using these enhanced list controls for -% other non-IEEE related LaTeX work. -% itemize and enumerate automatically default to right -% justification, description defaults to left. -\def\IEEEiedlabeljustifyl{\def\@IEEEiedjustify{0}}%left -\def\IEEEiedlabeljustifyc{\def\@IEEEiedjustify{1}}%center -\def\IEEEiedlabeljustifyr{\def\@IEEEiedjustify{2}}%right - - - - -% commands to save to and restore from the list parameter copies -% this allows us to set all the list parameters within -% the list_decl and prevent \list (and its \@list) -% from overriding any of our parameters -% V1.6 use \edefs instead of dimen's to conserve dimen registers -% Note controlled spacing here, shield end of lines with % -\def\@IEEEsavelistparams{\edef\@IEEEiedtopsep{\the\topsep}% -\edef\@IEEEiedlabelwidth{\the\labelwidth}% -\edef\@IEEEiedlabelsep{\the\labelsep}% -\edef\@IEEEiedleftmargin{\the\leftmargin}% -\edef\@IEEEiedpartopsep{\the\partopsep}% -\edef\@IEEEiedparsep{\the\parsep}% -\edef\@IEEEieditemsep{\the\itemsep}% -\edef\@IEEEiedrightmargin{\the\rightmargin}% -\edef\@IEEEiedlistparindent{\the\listparindent}% -\edef\@IEEEieditemindent{\the\itemindent}} - -% Note controlled spacing here -\def\@IEEErestorelistparams{\topsep\@IEEEiedtopsep\relax% -\labelwidth\@IEEEiedlabelwidth\relax% -\labelsep\@IEEEiedlabelsep\relax% -\leftmargin\@IEEEiedleftmargin\relax% -\partopsep\@IEEEiedpartopsep\relax% -\parsep\@IEEEiedparsep\relax% -\itemsep\@IEEEieditemsep\relax% -\rightmargin\@IEEEiedrightmargin\relax% -\listparindent\@IEEEiedlistparindent\relax% -\itemindent\@IEEEieditemindent\relax} - - -% v1.6b provide original LaTeX IED list environments -% note that latex.ltx defines \itemize and \enumerate, but not \description -% which must be created by the base classes -% save original LaTeX itemize and enumerate -\let\LaTeXitemize\itemize -\let\endLaTeXitemize\enditemize -\let\LaTeXenumerate\enumerate -\let\endLaTeXenumerate\endenumerate - -% provide original LaTeX description environment from article.cls -\newenvironment{LaTeXdescription} - {\list{}{\labelwidth\z@ \itemindent-\leftmargin - \let\makelabel\descriptionlabel}} - {\endlist} -\newcommand*\descriptionlabel[1]{\hspace\labelsep - \normalfont\bfseries #1} - - -% override LaTeX's default IED lists -\def\itemize{\@IEEEitemize} -\def\enditemize{\@endIEEEitemize} -\def\enumerate{\@IEEEenumerate} -\def\endenumerate{\@endIEEEenumerate} -\def\description{\@IEEEdescription} -\def\enddescription{\@endIEEEdescription} - -% provide the user with aliases - may help those using packages that -% override itemize, enumerate, or description -\def\IEEEitemize{\@IEEEitemize} -\def\endIEEEitemize{\@endIEEEitemize} -\def\IEEEenumerate{\@IEEEenumerate} -\def\endIEEEenumerate{\@endIEEEenumerate} -\def\IEEEdescription{\@IEEEdescription} -\def\endIEEEdescription{\@endIEEEdescription} - - -% V1.6 we want to keep the IEEEtran IED list definitions as our own internal -% commands so they are protected against redefinition -\def\@IEEEitemize{\@ifnextchar[{\@@IEEEitemize}{\@@IEEEitemize[\relax]}} -\def\@IEEEenumerate{\@ifnextchar[{\@@IEEEenumerate}{\@@IEEEenumerate[\relax]}} -\def\@IEEEdescription{\@ifnextchar[{\@@IEEEdescription}{\@@IEEEdescription[\relax]}} -\def\@endIEEEitemize{\endlist} -\def\@endIEEEenumerate{\endlist} -\def\@endIEEEdescription{\endlist} - - -% DO NOT ALLOW BLANK LINES TO BE IN THESE IED ENVIRONMENTS -% AS THIS WILL FORCE NEW PARAGRAPHS AFTER THE IED LISTS -% IEEEtran itemized list MDS 1/2001 -% Note controlled spacing here, shield end of lines with % -\def\@@IEEEitemize[#1]{% - \ifnum\@itemdepth>3\relax\@toodeep\else% - \ifnum\@listdepth>5\relax\@toodeep\else% - \advance\@itemdepth\@ne% - \edef\@itemitem{labelitem\romannumeral\the\@itemdepth}% - % get the IEEElabelindentfactor for this level - \advance\@listdepth\@ne% we need to know what the level WILL be - \edef\IEEElabelindentfactor{\csname IEEElabelindentfactor\romannumeral\the\@listdepth\endcsname}% - \advance\@listdepth-\@ne% undo our increment - \def\@IEEEiedjustify{2}% right justified labels are default - % set other defaults - \IEEEnocalcleftmarginfalse% - \IEEEnolabelindentfactorfalse% - \topsep\IEEEiedtopsep% - \IEEElabelindent\IEEEilabelindent% - \labelsep\IEEEiednormlabelsep% - \partopsep 0ex% - \parsep 0ex% - \itemsep 0ex% - \rightmargin 0em% - \listparindent 0em% - \itemindent 0em% - % calculate the label width - % the user can override this later if - % they specified a \labelwidth - \settowidth{\labelwidth}{\csname labelitem\romannumeral\the\@itemdepth\endcsname}% - \@IEEEsavelistparams% save our list parameters - \list{\csname\@itemitem\endcsname}{% - \@IEEErestorelistparams% override any list{} changes - % to our globals - \let\makelabel\@IEEEiedmakelabel% v1.6b setup \makelabel - \IEEEiedlistdecl% let user alter parameters - #1\relax% - % If the user has requested not to use the - % IEEElabelindent factor, don't revise \IEEElabelindent - \ifIEEEnolabelindentfactor\relax% - \else\IEEElabelindent=\IEEElabelindentfactor\IEEElabelindent% - \fi% - % Unless the user has requested otherwise, - % calculate our left margin based - % on \IEEElabelindent, \labelwidth and - % \labelsep - \ifIEEEnocalcleftmargin\relax% - \else\IEEEcalcleftmargin{\IEEElabelindent}% - \fi}\fi\fi}% - - -% DO NOT ALLOW BLANK LINES TO BE IN THESE IED ENVIRONMENTS -% AS THIS WILL FORCE NEW PARAGRAPHS AFTER THE IED LISTS -% IEEEtran enumerate list MDS 1/2001 -% Note controlled spacing here, shield end of lines with % -\def\@@IEEEenumerate[#1]{% - \ifnum\@enumdepth>3\relax\@toodeep\else% - \ifnum\@listdepth>5\relax\@toodeep\else% - \advance\@enumdepth\@ne% - \edef\@enumctr{enum\romannumeral\the\@enumdepth}% - % get the IEEElabelindentfactor for this level - \advance\@listdepth\@ne% we need to know what the level WILL be - \edef\IEEElabelindentfactor{\csname IEEElabelindentfactor\romannumeral\the\@listdepth\endcsname}% - \advance\@listdepth-\@ne% undo our increment - \def\@IEEEiedjustify{2}% right justified labels are default - % set other defaults - \IEEEnocalcleftmarginfalse% - \IEEEnolabelindentfactorfalse% - \topsep\IEEEiedtopsep% - \IEEElabelindent\IEEEelabelindent% - \labelsep\IEEEiednormlabelsep% - \partopsep 0ex% - \parsep 0ex% - \itemsep 0ex% - \rightmargin 0em% - \listparindent 0em% - \itemindent 0em% - % calculate the label width - % We'll set it to the width suitable for all labels using - % normalfont 1) to 9) - % The user can override this later - \settowidth{\labelwidth}{9)}% - \@IEEEsavelistparams% save our list parameters - \list{\csname label\@enumctr\endcsname}{\usecounter{\@enumctr}% - \@IEEErestorelistparams% override any list{} changes - % to our globals - \let\makelabel\@IEEEiedmakelabel% v1.6b setup \makelabel - \IEEEiedlistdecl% let user alter parameters - #1\relax% - % If the user has requested not to use the - % IEEElabelindent factor, don't revise \IEEElabelindent - \ifIEEEnolabelindentfactor\relax% - \else\IEEElabelindent=\IEEElabelindentfactor\IEEElabelindent% - \fi% - % Unless the user has requested otherwise, - % calculate our left margin based - % on \IEEElabelindent, \labelwidth and - % \labelsep - \ifIEEEnocalcleftmargin\relax% - \else\IEEEcalcleftmargin{\IEEElabelindent}% - \fi}\fi\fi}% - - -% DO NOT ALLOW BLANK LINES TO BE IN THESE IED ENVIRONMENTS -% AS THIS WILL FORCE NEW PARAGRAPHS AFTER THE IED LISTS -% IEEEtran description list MDS 1/2001 -% Note controlled spacing here, shield end of lines with % -\def\@@IEEEdescription[#1]{% - \ifnum\@listdepth>5\relax\@toodeep\else% - % get the IEEElabelindentfactor for this level - \advance\@listdepth\@ne% we need to know what the level WILL be - \edef\IEEElabelindentfactor{\csname IEEElabelindentfactor\romannumeral\the\@listdepth\endcsname}% - \advance\@listdepth-\@ne% undo our increment - \def\@IEEEiedjustify{0}% left justified labels are default - % set other defaults - \IEEEnocalcleftmarginfalse% - \IEEEnolabelindentfactorfalse% - \topsep\IEEEiedtopsep% - \IEEElabelindent\IEEEdlabelindent% - % assume normal labelsep - \labelsep\IEEEiednormlabelsep% - \partopsep 0ex% - \parsep 0ex% - \itemsep 0ex% - \rightmargin 0em% - \listparindent 0em% - \itemindent 0em% - % Bogus label width in case the user forgets - % to set it. - % TIP: If you want to see what a variable's width is you - % can use the TeX command \showthe\width-variable to - % display it on the screen during compilation - % (This might be helpful to know when you need to find out - % which label is the widest) - \settowidth{\labelwidth}{Hello}% - \@IEEEsavelistparams% save our list parameters - \list{}{\@IEEErestorelistparams% override any list{} changes - % to our globals - \let\makelabel\@IEEEiedmakelabel% v1.6b setup \makelabel - \IEEEiedlistdecl% let user alter parameters - #1\relax% - % If the user has requested not to use the - % labelindent factor, don't revise \IEEElabelindent - \ifIEEEnolabelindentfactor\relax% - \else\IEEElabelindent=\IEEElabelindentfactor\IEEElabelindent% - \fi% - % Unless the user has requested otherwise, - % calculate our left margin based - % on \IEEElabelindent, \labelwidth and - % \labelsep - \ifIEEEnocalcleftmargin\relax% - \else\IEEEcalcleftmargin{\IEEElabelindent}\relax% - \fi}\fi} - -% v1.6b we use one makelabel that does justification as needed. -\def\@IEEEiedmakelabel#1{\relax\if\@IEEEiedjustify 0\relax -\makebox[\labelwidth][l]{\normalfont #1}\else -\if\@IEEEiedjustify 1\relax -\makebox[\labelwidth][c]{\normalfont #1}\else -\makebox[\labelwidth][r]{\normalfont #1}\fi\fi} - - -% compsoc uses a larger value for the normal labelsep -% and also extra spacing above and below each list -\ifCLASSOPTIONcompsoc - \IEEEiednormlabelsep 1.2em - \IEEEiedtopsep 6pt plus 3pt minus 3pt -\fi - - -% VERSE and QUOTE -% V1.7 define environments with newenvironment -\newenvironment{verse}{\let\\=\@centercr - \list{}{\itemsep\z@ \itemindent -1.5em \listparindent \itemindent - \rightmargin\leftmargin\advance\leftmargin 1.5em}\item\relax} - {\endlist} -\newenvironment{quotation}{\list{}{\listparindent 1.5em \itemindent\listparindent - \rightmargin\leftmargin \parsep 0pt plus 1pt}\item\relax} - {\endlist} -\newenvironment{quote}{\list{}{\rightmargin\leftmargin}\item\relax} - {\endlist} - - -% \titlepage -% provided only for backward compatibility. \maketitle is the correct -% way to create the title page. -\def\titlepage{\@restonecolfalse\if@twocolumn\@restonecoltrue\onecolumn - \else \newpage \fi \thispagestyle{empty}\c@page\z@} -\def\endtitlepage{\if@restonecol\twocolumn \else \newpage \fi} - -% standard values from article.cls -\arraycolsep 5pt -\arrayrulewidth .4pt -\doublerulesep 2pt - -\tabcolsep 6pt -\tabbingsep 0.5em - - -%% FOOTNOTES -% -%\skip\footins 10pt plus 4pt minus 2pt -% V1.6 respond to changes in font size -% space added above the footnotes (if present) -\skip\footins 0.9\baselineskip plus 0.4\baselineskip minus 0.2\baselineskip - -% V1.6, we need to make \footnotesep responsive to changes -% in \baselineskip or strange spacings will result when in -% draft mode. Here is a little LaTeX secret - \footnotesep -% determines the height of an invisible strut that is placed -% *above* the baseline of footnotes after the first. Since -% LaTeX considers the space for characters to be 0.7\baselineskip -% above the baseline and 0.3\baselineskip below it, we need to -% use 0.7\baselineskip as a \footnotesep to maintain equal spacing -% between all the lines of the footnotes. The IEEE often uses a tad -% more, so use 0.8\baselineskip. This slightly larger value also helps -% the text to clear the footnote marks. Note that \thanks in IEEEtran -% uses its own value of \footnotesep which is set in \maketitle. -{\footnotesize -\global\footnotesep 0.8\baselineskip} - - -\skip\@mpfootins = \skip\footins -\fboxsep = 3pt -\fboxrule = .4pt -% V1.6 use 1em, then use LaTeX2e's \@makefnmark -% Note that the IEEE normally *left* aligns the footnote marks, so we don't need -% box resizing tricks here. -\long\def\@makefntext#1{\parindent 1em\indent\hbox{\@makefnmark}#1}% V1.6 use 1em -% V1.7 compsoc does not use superscipts for footnote marks -\ifCLASSOPTIONcompsoc -\def\@IEEEcompsocmakefnmark{\hbox{\normalfont\@thefnmark.\ }} -\long\def\@makefntext#1{\parindent 1em\indent\hbox{\@IEEEcompsocmakefnmark}#1} -\fi - -% The IEEE does not use footnote rules -\def\footnoterule{} - -% V1.7 for compsoc, the IEEE uses a footnote rule only for \thanks. We devise a "one-shot" -% system to implement this. -\newif\if@IEEEenableoneshotfootnoterule -\@IEEEenableoneshotfootnoterulefalse -\ifCLASSOPTIONcompsoc -\def\footnoterule{\relax\if@IEEEenableoneshotfootnoterule -\kern-5pt -\hbox to \columnwidth{\hfill\vrule width 0.5\columnwidth height 0.4pt\hfill} -\kern4.6pt -\global\@IEEEenableoneshotfootnoterulefalse -\else -\relax -\fi} -\fi - -% V1.6 do not allow LaTeX to break a footnote across multiple pages -\interfootnotelinepenalty=10000 - -% V1.6 discourage breaks within equations -% Note that amsmath normally sets this to 10000, -% but LaTeX2e normally uses 100. -\interdisplaylinepenalty=2500 - -% default allows section depth up to /paragraph -\setcounter{secnumdepth}{4} - -% technotes do not allow /paragraph -\ifCLASSOPTIONtechnote - \setcounter{secnumdepth}{3} -\fi -% neither do compsoc conferences -\@IEEEcompsocconfonly{\setcounter{secnumdepth}{3}} - - -\newcounter{section} -\newcounter{subsection}[section] -\newcounter{subsubsection}[subsection] -\newcounter{paragraph}[subsubsection] - -% used only by IEEEtran's IEEEeqnarray as other packages may -% have their own, different, implementations -\newcounter{IEEEsubequation}[equation] - -% as shown when called by user from \ref, \label and in table of contents -\def\theequation{\arabic{equation}} % 1 -\def\theIEEEsubequation{\theequation\alph{IEEEsubequation}} % 1a (used only by IEEEtran's IEEEeqnarray) -\ifCLASSOPTIONcompsoc -% compsoc is all arabic -\def\thesection{\arabic{section}} -\def\thesubsection{\thesection.\arabic{subsection}} -\def\thesubsubsection{\thesubsection.\arabic{subsubsection}} -\def\theparagraph{\thesubsubsection.\arabic{paragraph}} -\else -\def\thesection{\Roman{section}} % I -% V1.7, \mbox prevents breaks around - -\def\thesubsection{\mbox{\thesection-\Alph{subsection}}} % I-A -% V1.7 use I-A1 format used by the IEEE rather than I-A.1 -\def\thesubsubsection{\thesubsection\arabic{subsubsection}} % I-A1 -\def\theparagraph{\thesubsubsection\alph{paragraph}} % I-A1a -\fi - -% From Heiko Oberdiek. Because of the \mbox in \thesubsection, we need to -% tell hyperref to disable the \mbox command when making PDF bookmarks. -% This done already with hyperref.sty version 6.74o and later, but -% it will not hurt to do it here again for users of older versions. -\@ifundefined{pdfstringdefPreHook}{\let\pdfstringdefPreHook\@empty}{}% -\g@addto@macro\pdfstringdefPreHook{\let\mbox\relax} - - -% Main text forms (how shown in main text headings) -% V1.6, using \thesection in \thesectiondis allows changes -% in the former to automatically appear in the latter -\ifCLASSOPTIONcompsoc - \ifCLASSOPTIONconference% compsoc conference - \def\thesectiondis{\thesection.} - \def\thesubsectiondis{\thesectiondis\arabic{subsection}.} - \def\thesubsubsectiondis{\thesubsectiondis\arabic{subsubsection}.} - \def\theparagraphdis{\thesubsubsectiondis\arabic{paragraph}.} - \else% compsoc not conferencs - \def\thesectiondis{\thesection} - \def\thesubsectiondis{\thesectiondis.\arabic{subsection}} - \def\thesubsubsectiondis{\thesubsectiondis.\arabic{subsubsection}} - \def\theparagraphdis{\thesubsubsectiondis.\arabic{paragraph}} - \fi -\else% not compsoc - \def\thesectiondis{\thesection.} % I. - \def\thesubsectiondis{\Alph{subsection}.} % B. - \def\thesubsubsectiondis{\arabic{subsubsection})} % 3) - \def\theparagraphdis{\alph{paragraph})} % d) -\fi - -% just like LaTeX2e's \@eqnnum -\def\theequationdis{{\normalfont \normalcolor (\theequation)}}% (1) -% IEEEsubequation used only by IEEEtran's IEEEeqnarray -\def\theIEEEsubequationdis{{\normalfont \normalcolor (\theIEEEsubequation)}}% (1a) -% redirect LaTeX2e's equation number display and all that depend on -% it, through IEEEtran's \theequationdis -\def\@eqnnum{\theequationdis} - - - -% V1.7 provide string macros as article.cls does -\def\contentsname{Contents} -\def\listfigurename{List of Figures} -\def\listtablename{List of Tables} -\def\refname{References} -\def\indexname{Index} -\def\figurename{Fig.} -\def\tablename{TABLE} -\@IEEEcompsocconfonly{\def\figurename{Figure}} -\def\partname{Part} -\def\appendixname{Appendix} -\def\abstractname{Abstract} -% IEEE specific names -\def\IEEEkeywordsname{Index Terms} -\def\IEEEproofname{Proof} - - -% LIST OF FIGURES AND TABLES AND TABLE OF CONTENTS -% -\def\@pnumwidth{1.55em} -\def\@tocrmarg{2.55em} -\def\@dotsep{4.5} -\setcounter{tocdepth}{3} - -% adjusted some spacings here so that section numbers will not easily -% collide with the section titles. -% VIII; VIII-A; and VIII-A.1 are usually the worst offenders. -% MDS 1/2001 -\def\tableofcontents{\section*{\contentsname}\@starttoc{toc}} -\def\l@section#1#2{\addpenalty{\@secpenalty}\addvspace{1.0em plus 1pt}% - \@tempdima 2.75em \begingroup \parindent \z@ \rightskip \@pnumwidth% - \parfillskip-\@pnumwidth {\bfseries\leavevmode #1}\hfil\hbox to\@pnumwidth{\hss #2}\par% - \endgroup} -% argument format #1:level, #2:labelindent,#3:labelsep -\def\l@subsection{\@dottedtocline{2}{2.75em}{3.75em}} -\def\l@subsubsection{\@dottedtocline{3}{6.5em}{4.5em}} -% must provide \l@ defs for ALL sublevels EVEN if tocdepth -% is such as they will not appear in the table of contents -% these defs are how TOC knows what level these things are! -\def\l@paragraph{\@dottedtocline{4}{6.5em}{5.5em}} -\def\l@subparagraph{\@dottedtocline{5}{6.5em}{6.5em}} -\def\listoffigures{\section*{\listfigurename}\@starttoc{lof}} -\def\l@figure{\@dottedtocline{1}{0em}{2.75em}} -\def\listoftables{\section*{\listtablename}\@starttoc{lot}} -\let\l@table\l@figure - - -% Definitions for floats -% -% Normal Floats -% V1.8 floatsep et al. revised down by 0.15\baselineskip -% to account for the sideeffects of \topskip compensation -\floatsep 0.85\baselineskip plus 0.2\baselineskip minus 0.2\baselineskip -\textfloatsep 1.55\baselineskip plus 0.2\baselineskip minus 0.4\baselineskip -\@fptop 0pt plus 1fil -\@fpsep 0.75\baselineskip plus 2fil -\@fpbot 0pt plus 1fil -\def\topfraction{0.9} -\def\bottomfraction{0.4} -\def\floatpagefraction{0.8} -% V1.7, let top floats approach 90% of page -\def\textfraction{0.1} - -% Double Column Floats -\dblfloatsep 0.85\baselineskip plus 0.2\baselineskip minus 0.2\baselineskip - -\dbltextfloatsep 1.55\baselineskip plus 0.2\baselineskip minus 0.4\baselineskip -% Note that it would be nice if the rubber here actually worked in LaTeX2e. -% There is a long standing limitation in LaTeX, first discovered (to the best -% of my knowledge) by Alan Jeffrey in 1992. LaTeX ignores the stretchable -% portion of \dbltextfloatsep, and as a result, double column figures can and -% do result in an non-integer number of lines in the main text columns with -% underfull vbox errors as a consequence. A post to comp.text.tex -% by Donald Arseneau confirms that this had not yet been fixed in 1998. -% IEEEtran V1.6 will fix this problem for you in the titles, but it doesn't -% protect you from other double floats. Happy vspace'ing. - -\@dblfptop 0pt plus 1fil -\@dblfpsep 0.75\baselineskip plus 2fil -\@dblfpbot 0pt plus 1fil -\def\dbltopfraction{0.8} -\def\dblfloatpagefraction{0.8} -\setcounter{dbltopnumber}{4} - -\intextsep 0.85\baselineskip plus 0.2\baselineskip minus 0.2\baselineskip -\setcounter{topnumber}{2} -\setcounter{bottomnumber}{2} -\setcounter{totalnumber}{4} - - - -% article class provides these, we should too. -\newlength\abovecaptionskip -\newlength\belowcaptionskip -% but only \abovecaptionskip is used above figure captions and *below* table -% captions -\setlength\abovecaptionskip{0.5\baselineskip} -% compsoc journals are a little more generous -\ifCLASSOPTIONcompsoc\ifCLASSOPTIONjournal - \setlength\abovecaptionskip{0.75\baselineskip} -\fi\fi -\setlength\belowcaptionskip{0pt} -% V1.6 create hooks in case the caption spacing ever needs to be -% overridden by a user -\def\@IEEEfigurecaptionsepspace{\vskip\abovecaptionskip\relax}% -\def\@IEEEtablecaptionsepspace{\vskip\abovecaptionskip\relax}% - - -% 1.6b revise caption system so that \@makecaption uses two arguments -% as with LaTeX2e. Otherwise, there will be problems when using hyperref. -\def\@IEEEtablestring{table} - - -% V1.8 compensate for \topskip so top of top figures align with tops of the first lines of main text -% here we calculate a space equal to the amount \topskip exceeds the main text height -% we hook in at \@floatboxreset -\def\@IEEEfiguretopskipspace{\ifdim\prevdepth=-1000pt\relax -\setlength{\@IEEEtrantmpdimenA}{1\topskip}\relax -\addtolength{\@IEEEtrantmpdimenA}{-0.7\@IEEEnormalsizeunitybaselineskip}\relax -\vspace*{\@IEEEtrantmpdimenA}\fi} -% V1.8 compensate for \topskip at the top of top tables so caption text is on main text baseline -% use a strut set on the caption baseline within \@makecaption -\def\@IEEEtabletopskipstrut{\ifdim\prevdepth=-1000pt\rule{0pt}{\topskip}\fi} -% the \ifdim\prevdepth checks are always expected to be true for IEEE style float caption ordering -% because top of figure content and top of captions in tables is the first thing on the vertical -% list of these floats -% thanks to Donald Arseneau for his 2000/11/11 post "Re: caption hacking" with info on this topic. - - -\ifCLASSOPTIONcompsoc -% V1.7 compsoc \@makecaption -\ifCLASSOPTIONconference% compsoc conference -\long\def\@makecaption#1#2{% -% test if is a for a figure or table -\ifx\@captype\@IEEEtablestring% -% if a table, do table caption -\footnotesize\bgroup\par\centering\@IEEEtabletopskipstrut{\normalfont\footnotesize {#1.}\nobreakspace\scshape #2}\par\addvspace{0.5\baselineskip}\egroup% -\@IEEEtablecaptionsepspace -% if not a table, format it as a figure -\else -\@IEEEfigurecaptionsepspace -\setbox\@tempboxa\hbox{\normalfont\footnotesize {#1.}\nobreakspace #2}% -\ifdim \wd\@tempboxa >\hsize% -% if caption is longer than a line, let it wrap around -\setbox\@tempboxa\hbox{\normalfont\footnotesize {#1.}\nobreakspace}% -\parbox[t]{\hsize}{\normalfont\footnotesize \noindent\unhbox\@tempboxa#2}% -% if caption is shorter than a line, center -\else% -\hbox to\hsize{\normalfont\footnotesize\hfil\box\@tempboxa\hfil}% -\fi\fi} -% -\else% nonconference compsoc -\long\def\@makecaption#1#2{% -% test if is a for a figure or table -\ifx\@captype\@IEEEtablestring% -% if a table, do table caption -\footnotesize\bgroup\par\centering\@IEEEtabletopskipstrut{\normalfont\sffamily\footnotesize #1}\\{\normalfont\sffamily\footnotesize #2}\par\addvspace{0.5\baselineskip}\egroup% -\@IEEEtablecaptionsepspace -% if not a table, format it as a figure -\else -\@IEEEfigurecaptionsepspace -\setbox\@tempboxa\hbox{\normalfont\sffamily\footnotesize {#1.}\nobreakspace #2}% -\ifdim \wd\@tempboxa >\hsize% -% if caption is longer than a line, let it wrap around -\setbox\@tempboxa\hbox{\normalfont\sffamily\footnotesize {#1.}\nobreakspace}% -\parbox[t]{\hsize}{\normalfont\sffamily\footnotesize \noindent\unhbox\@tempboxa#2}% -% if caption is shorter than a line, left justify -\else% -\hbox to\hsize{\normalfont\sffamily\footnotesize\box\@tempboxa\hfil}% -\fi\fi} -\fi -% -\else% traditional noncompsoc \@makecaption -\long\def\@makecaption#1#2{% -% test if is a for a figure or table -\ifx\@captype\@IEEEtablestring% -% if a table, do table caption -\footnotesize\bgroup\par\centering\@IEEEtabletopskipstrut{\normalfont\footnotesize #1}\\{\normalfont\footnotesize\scshape #2}\par\addvspace{0.5\baselineskip}\egroup% -\@IEEEtablecaptionsepspace -% if not a table, format it as a figure -\else -\@IEEEfigurecaptionsepspace -% 3/2001 use footnotesize, not small; use two nonbreaking spaces, not one -\setbox\@tempboxa\hbox{\normalfont\footnotesize {#1.}\nobreakspace\nobreakspace #2}% -\ifdim \wd\@tempboxa >\hsize% -% if caption is longer than a line, let it wrap around -\setbox\@tempboxa\hbox{\normalfont\footnotesize {#1.}\nobreakspace\nobreakspace}% -\parbox[t]{\hsize}{\normalfont\footnotesize\noindent\unhbox\@tempboxa#2}% -% if caption is shorter than a line, center if conference, left justify otherwise -\else% -\ifCLASSOPTIONconference \hbox to\hsize{\normalfont\footnotesize\hfil\box\@tempboxa\hfil}% -\else \hbox to\hsize{\normalfont\footnotesize\box\@tempboxa\hfil}% -\fi\fi\fi} -\fi - - - -% V1.7 disable captions class option, do so in a way that retains operation of \label -% within \caption -\ifCLASSOPTIONcaptionsoff -\long\def\@makecaption#1#2{\vspace*{2em}\footnotesize\bgroup\par\addvspace{0.5\baselineskip}\centering{\footnotesize #1}\par\addvspace{0.5\baselineskip}\egroup% -\let\@IEEEtemporiglabeldefsave\label -\let\@IEEEtemplabelargsave\relax -\def\label##1{\gdef\@IEEEtemplabelargsave{##1}}% -\setbox\@tempboxa\hbox{#2}% -\let\label\@IEEEtemporiglabeldefsave -\ifx\@IEEEtemplabelargsave\relax\else\label{\@IEEEtemplabelargsave}\fi} -\fi - - -% V1.7 define end environments with \def not \let so as to work OK with -% preview-latex -\newcounter{figure} -\def\thefigure{\@arabic\c@figure} -\def\fps@figure{tbp} -\def\ftype@figure{1} -\def\ext@figure{lof} -\def\fnum@figure{\figurename\nobreakspace\thefigure} -% V1.8 within figures add \@IEEEfiguretopskipspace compensation to LaTeX2e's \@floatboxreset -\def\figure{\def\@floatboxreset{\reset@font\normalsize\@setminipage\@IEEEfiguretopskipspace}\@float{figure}} -\def\endfigure{\end@float} -% V1.8 also add \@IEEEfiguretopskipspace compensation to \figure* -\@namedef{figure*}{\def\@floatboxreset{\reset@font\normalsize\@setminipage\@IEEEfiguretopskipspace}\@dblfloat{figure}} -\@namedef{endfigure*}{\end@dblfloat} - -\newcounter{table} -\ifCLASSOPTIONcompsoc -\def\thetable{\arabic{table}} -\else -\def\thetable{\@Roman\c@table} -\fi -\def\fps@table{tbp} -\def\ftype@table{2} -\def\ext@table{lot} -\def\fnum@table{\tablename\nobreakspace\thetable} -% V1.6 The IEEE uses 8pt text for tables -% within tables alter LaTeX2e's \@floatboxreset to use \footnotesize -\def\table{\def\@floatboxreset{\reset@font\footnotesize\@setminipage}\@float{table}} -\def\endtable{\end@float} -% v1.6b double column tables need to default to footnotesize as well. -\@namedef{table*}{\def\@floatboxreset{\reset@font\footnotesize\@setminipage}\@dblfloat{table}} -\@namedef{endtable*}{\end@dblfloat} - - - - -%% -- Command Argument Scanning Support Functions -- -%% V1.8a - -% usage: \@IEEEstripouterbraces*{} -% \@IEEEstripouterbraces fully expands its argument (which it then stores -% in \@IEEEstripouterbracesarg) via \edef, then removes any outer enclosing -% braces, and finally stores the result in the macro -% \@IEEEstrippedouterbraces. -% -% For example: -% \@IEEEstripouterbraces{{{{ab}c}}} -% results in: -% -% \@IEEEstripouterbracesarg ==> a macro containing {{{ab}c}} -% \@IEEEstrippedouterbraces ==> a macro containing {ab}c -% -% the *-star form,\@IEEEstripouterbraces*, does not expand the argument -% contents during processing -\def\@IEEEstripouterbraces{\@ifstar{\let\@IEEEstripouterbracesdef=\def\@@IEEEstripouterbraces}{\let\@IEEEstripouterbracesdef=\edef\@@IEEEstripouterbraces}} - -\def\@@IEEEstripouterbraces#1{\@IEEEstripouterbracesdef\@IEEEstripouterbracesarg{#1}\relax -% If the macro is unchanged after being acquired as a single delimited -% argument, we know we have one sequence of tokens without any enclosing -% braces. Loop until this is true. -\loop - \expandafter\@@@IEEEstripouterbraces\@IEEEstripouterbracesarg\@IEEEgeneralsequenceDELIMITER -\ifx\@IEEEstrippedouterbraces\@IEEEstripouterbracesarg -\else - \let\@IEEEstripouterbracesarg\@IEEEstrippedouterbraces -\repeat} - -\def\@@@IEEEstripouterbraces#1\@IEEEgeneralsequenceDELIMITER{\def\@IEEEstrippedouterbraces{#1}} - - - -% usage: \@IEEEextractgroup*{} -% \@IEEEextractgroup fully expands its argument (which it then stores in -% \@IEEEextractgrouparg) via \edef and then assigns the first "brace group" -% of tokens to the macro \@IEEEextractedgroup. -% The remaining groups, if any, are stored in the macro -% \@IEEEextractedgroupremain. If the argument does not contain the requisite -% groups, the respective macros will be defined to be empty. -% There is an asymmetry in that \@IEEEextractedgroup is stripped of its first -% outer grouping while \@IEEEextractedgroupremain retains even the outer -% grouping (if present) that originally identified it as a group. -% -% For example: -% \@IEEEextractgroup{{{ab}}{c{de}}} -% results in: -% -% \@IEEEextractgrouparg ==> a macro containing {{ab}}{c{de}} -% \@IEEEextractedgroup ==> a macro containing {ab} -% \@IEEEextractedgroupremain ==> a macro containing {c{de}} -% -% The *-star form, \@IEEEextractgroup*, does not expand its argument -% contents during processing. -\def\@IEEEextractgroup{\@ifstar{\let\@IEEEextractgroupdef=\def\@@IEEEextractgroup}{\let\@IEEEextractgroupdef=\edef\@@IEEEextractgroup}} - -\def\@@IEEEextractgroup#1{\@IEEEextractgroupdef\@IEEEextractgrouparg{#1}\relax -% trap the case of an empty extracted group as this would cause problems with -% \@IEEEextractgroupremain's argument acquisition -\ifx\@IEEEextractgrouparg\@empty - \def\@IEEEextractedgroup{}\relax - \def\@IEEEextractedgroupremain{}\relax -\else - % We have to use some dirty tricks here. We want to insert {} around - % whatever remains after the first group so that TeX's argument scanner - % will preserve any originally enclosing braces as well as provide an - % empty argument to acquire even if there isn't a second group. - % In this first of two dirty tricks, we put a } at the end of the structure - % we are going to extract from. The \ifnum0=`{\fi keeps TeX happy to allow - % what would otherwise be an unbalanced macro definition for - % \@@IEEEextractgroup to be acceptable to it. - \ifnum0=`{\fi\expandafter\@IEEEextractgroupremain\@IEEEextractgrouparg}\relax -\fi} - -% In the second part of the dirty tricks, we insert a leading { right after -% the first group is acquired, but before the remainder is. Again, the -% \ifnum0=`}\fi keeps TeX happy during definition time, but will disappear -% during run time. -\def\@IEEEextractgroupremain#1{\def\@IEEEextractedgroup{#1}\expandafter\@@IEEEextractgroupremain\expandafter{\ifnum0=`}\fi} - -\def\@@IEEEextractgroupremain#1{\def\@IEEEextractedgroupremain{#1}} - - - -% \@IEEEextracttoken relocated at top because margin setting commands rely on it - - - -% usage: \@IEEEextracttokengroups*{} -% \@IEEEextracttokengroups fully expands its argument (which it then stores -% in \@IEEEextracttokengroupsarg) and then assigns the first "brace group" of -% tokens (with the outermost braces removed) to the macro -% \@IEEEextractedfirstgroup. -% The meaning of the first nonbrace (but including the empty group) token -% within this first group is assigned via \let to \@IEEEextractedfirsttoken -% as well as stored in the macro \@IEEEextractedfirsttokenmacro. If a first -% nonbrace token does not exist (or is an empty group), these will be \relax -% and empty, respectively. Tokens that would otherwise be discarded during -% the acquisition of the first token in the first group are stored in -% \@IEEEextractedfirsttokensdiscarded, however their original relative brace -% nesting depths are not guaranteed to be preserved. -% The first group within this first group is stored in the macro -% \@IEEEextractedfirstfirstgroup. -% Likewise for the next group after the first: \@IEEEextractednextgroup, -% \@IEEEextractednextfirstgroup, \@IEEEextractednextgroupfirsttoken, -% \@IEEEextractednextgroupfirsttokenmacro, and -% \@IEEEextractednextfirsttokensdiscarded. -% All tokens/groups after the first group, including any enclosing braces, -% are stored in the macro \@IEEEextractedafterfirstgroupremain which will -% be empty if none exist. -% -% For example: -% \@IEEEextracttokengroups{{{ab}{cd}}{{ef}g}} -% will result in: -% -% \@IEEEextracttokengroupsarg ==> a macro containing {{ab}{cd}}{{ef}g} -% \@IEEEextractedfirstgroup ==> a macro containing {ab}{cd} -% \@IEEEextractedafterfirstgroupremain ==> a macro containing {{ef}g} -% \@IEEEextractedfirsttoken ==> the letter a -% \@IEEEextractedfirsttokenmacro ==> a macro containing a -% \@IEEEextractedfirsttokensdiscarded ==> a macro containing bcd -% \@IEEEextractedfirstfirstgroup ==> a macro containing ab -% \@IEEEextractednextgroup ==> a macro containing {ef}g -% \@IEEEextractednextfirsttoken ==> the letter e -% \@IEEEextractednextfirsttokenmacro ==> a macro containing e -% \@IEEEextractednextfirsttokensdiscarded ==> a macro containing fg -% \@IEEEextractednextfirstgroup ==> a macro containing ef -% -% If given an empty argument, \@IEEEextractedfirsttoken and -% \@IEEEextractednextfirsttoken will be set to \relax -% and all the macros will be empty. -% the *-star form, \@IEEEextracttokengroups*, does not expand its argument -% contents during processing. -% -% Depends on: \@IEEEextractgroup, \@IEEEextracttoken -\def\@IEEEextracttokengroups{\@ifstar{\let\@IEEEextracttokengroupsdef=\def\@@IEEEextracttokengroups}{\let\@IEEEextracttokengroupsdef=\edef\@@IEEEextracttokengroups}} -\def\@@IEEEextracttokengroups#1{\@IEEEextracttokengroupsdef\@IEEEextracttokengroupsarg{#1}\relax -% begin extraction, these functions are safe with empty arguments -% first group -\expandafter\@IEEEextractgroup\expandafter*\expandafter{\@IEEEextracttokengroupsarg}\relax -\let\@IEEEextractedfirstgroup\@IEEEextractedgroup -\let\@IEEEextractedafterfirstgroupremain\@IEEEextractedgroupremain -\expandafter\@IEEEextracttoken\expandafter*\expandafter{\@IEEEextractedfirstgroup}\relax -\let\@IEEEextractedfirsttoken\@IEEEextractedtoken -\let\@IEEEextractedfirsttokenmacro\@IEEEextractedtokenmacro -\let\@IEEEextractedfirsttokensdiscarded\@IEEEextractedtokensdiscarded -% first first group -\expandafter\@IEEEextractgroup\expandafter*\expandafter{\@IEEEextractedfirstgroup}\relax -\let\@IEEEextractedfirstfirstgroup\@IEEEextractedgroup -% next group -\expandafter\@IEEEextractgroup\expandafter*\expandafter{\@IEEEextractedafterfirstgroupremain}\relax -\let\@IEEEextractednextgroup\@IEEEextractedgroup -\expandafter\@IEEEextracttoken\expandafter*\expandafter{\@IEEEextractednextgroup}\relax -\let\@IEEEextractednextfirsttoken\@IEEEextractedtoken -\let\@IEEEextractednextfirsttokenmacro\@IEEEextractedtokenmacro -\let\@IEEEextractednextfirsttokensdiscarded\@IEEEextractedtokensdiscarded -% next first group -\expandafter\@IEEEextractgroup\expandafter*\expandafter{\@IEEEextractednextgroup}\relax -\let\@IEEEextractednextfirstgroup\@IEEEextractedgroup} - - -%% -- End of Command Argument Scanning Support Functions -- - - - - -%% -%% START OF IEEEeqnarray DEFINITIONS -%% -%% Inspired by the concepts, examples, and previous works of LaTeX -%% coders and developers such as Donald Arseneau, Fred Bartlett, -%% David Carlisle, Tony Liu, Frank Mittelbach, Piet van Oostrum, -%% Roland Winkler and Mark Wooding. -%% I don't make the claim that my work here is even near their calibre. ;) - - -\newif\if@IEEEeqnarrayboxnojot% flag to indicate if the environment was called as the star form -\@IEEEeqnarrayboxnojotfalse - -\newif\if@advanceIEEEeqncolcnt% tracks if the environment should advance the col counter -% allows a way to make an \IEEEeqnarraybox that can be used within an \IEEEeqnarray -% used by IEEEeqnarraymulticol so that it can work properly in both -\@advanceIEEEeqncolcnttrue - -\newcount\@IEEEeqnnumcols % tracks how many IEEEeqnarray cols are defined -\newcount\@IEEEeqncolcnt % tracks how many IEEEeqnarray cols the user actually used - - -% The default math style used by the columns -\def\IEEEeqnarraymathstyle{\displaystyle} -% The default text style used by the columns -% default to using the current font -\def\IEEEeqnarraytextstyle{\relax} - -% like the iedlistdecl but for \IEEEeqnarray -\def\IEEEeqnarraydecl{\relax} -\def\IEEEeqnarrayboxdecl{\relax} - - - -% V1.8 flags to indicate that equation numbering is to persist -\newif\if@IEEEeqnumpersist% -\@IEEEeqnumpersistfalse -\newif\if@IEEEsubeqnumpersist% -\@IEEEsubeqnumpersistfalse -% -% V1.8 flags to indicate if (sub)equation number of last line was preadvanced -\newif\if@IEEEeqnumpreadv% -\@IEEEeqnumpreadvfalse -\newif\if@IEEEsubeqnumpreadv% -\@IEEEsubeqnumpreadvfalse - -\newcount\@IEEEsubeqnnumrollback% saves previous value of IEEEsubequation number in case we need to restore it - -% \yesnumber is the opposite of \nonumber -% a novel concept with the same def as the equationarray package -% However, we give IEEE versions too since some LaTeX packages such as -% the MDWtools mathenv.sty redefine \nonumber to something else. -% This command is intended for use in non-IEEEeqnarray math environments -\providecommand{\yesnumber}{\global\@eqnswtrue} - - -% IEEEyes/nonumber -% V1.8 add persistant * forms -% These commands can alter the type of equation an IEEEeqnarray line is. -\def\IEEEyesnumber{\@ifstar{\global\@IEEEeqnumpersisttrue\global\@IEEEsubeqnumpersistfalse\@IEEEyesnumber}{\@IEEEyesnumber}} - -\def\@IEEEyesnumber{\global\@eqnswtrue -\if@IEEEeqnarrayISinner% alter counters and label only inside an IEEEeqnarray -\ifnum\c@IEEEsubequation>0\relax - \stepcounter{equation}\setcounter{IEEEsubequation}{0}\gdef\@currentlabel{\p@equation\theequation}\relax - \gdef\@currentHref{\@IEEEtheHrefequation}% setup hyperref label -\fi -% even if we reached this eqn num via a preadv, it is legit now -\global\@IEEEeqnumpreadvfalse\global\@IEEEsubeqnumpreadvfalse -\fi} - -\def\IEEEnonumber{\@ifstar{\global\@IEEEeqnumpersistfalse\global\@IEEEsubeqnumpersistfalse\global\@eqnswfalse}{\global\@eqnswfalse}} - - -\def\IEEEyessubnumber{\@ifstar{\global\@IEEEsubeqnumpersisttrue\@IEEEyessubnumber}{\@IEEEyessubnumber}} -% -\def\@IEEEyessubnumber{\if@IEEEeqnarrayISinner% alter counters and label only inside an IEEEeqnarray - \ifnum\c@IEEEsubequation>0\relax% if it already is a subequation, we are good to go as-is - \else% if we are a regular equation we have to watch out for two cases - \if@IEEEeqnumpreadv% if this equation is the result of a preadvance, backout and bump the sub eqnnum - \global\advance\c@equation\m@ne\global\c@IEEEsubequation=\@IEEEsubeqnnumrollback\addtocounter{IEEEsubequation}{1}\relax - \else% non-preadvanced equations just need initialization of their sub eqnnum - \setcounter{IEEEsubequation}{1}\relax - \fi - \fi% fi already is subequation - \gdef\@currentlabel{\p@IEEEsubequation\theIEEEsubequation}\relax - \gdef\@currentHref{\@IEEEtheHrefsubequation}% setup hyperref label - \global\@IEEEeqnumpreadvfalse\global\@IEEEsubeqnumpreadvfalse% no longer a preadv anymore - \global\@eqnswtrue -\fi} - - -\def\IEEEnosubnumber{\@ifstar{\global\@IEEEsubeqnumpersistfalse\@IEEEnosubnumber}{\@IEEEnosubnumber}} -% -\def\@IEEEnosubnumber{\if@IEEEeqnarrayISinner% alter counters and label only inside an IEEEeqnarray - \if@eqnsw % we do nothing unless we know we will display because we play with the counters here - % if it currently is a subequation, bump up to the next equation number and turn off the subequation - \ifnum\c@IEEEsubequation>0\relax\addtocounter{equation}{1}\setcounter{IEEEsubequation}{0}\relax - \fi - \global\@IEEEeqnumpreadvfalse\global\@IEEEsubeqnumpreadvfalse% no longer a preadv anymore - \gdef\@currentlabel{\p@equation\theequation}\relax - \gdef\@currentHref{\@IEEEtheHrefequation}% setup hyperref label - \fi -\fi} - - - -% allows users to "push away" equations that get too close to the equation numbers -\def\IEEEeqnarraynumspace{\hphantom{\ifnum\c@IEEEsubequation>0\relax\theIEEEsubequationdis\else\theequationdis\fi}} - -% provides a way to span multiple columns within IEEEeqnarray environments -% will consider \if@advanceIEEEeqncolcnt before globally advancing the -% column counter - so as to work within \IEEEeqnarraybox -% usage: \IEEEeqnarraymulticol{number cols. to span}{col type}{cell text} -\long\def\IEEEeqnarraymulticol#1#2#3{\multispan{#1}\relax -% check if column is defined for the precolumn definition -% We have to be careful here because TeX scans for & even within an \iffalse -% where it does not expand macros. So, if we used only one \ifx and a #3 -% appeared in the false branch and the user inserted another alignment -% structure that uses & in the \IEEEeqnarraymulticol{}, TeX will not see that -% there is an inner alignment in the false branch yet still will see any & -% there and will think that they apply to the outer alignment resulting in an -% incomplete \ifx error. -% So, here we use separate checks for the pre and post parts in order to keep -% the #3 outside of all conditionals. -\relax\expandafter\ifx\csname @IEEEeqnarraycolDEF#2\endcsname\@IEEEeqnarraycolisdefined\relax -\csname @IEEEeqnarraycolPRE#2\endcsname -\else% if not, error and use default type -\@IEEEclspkgerror{Invalid column type "#2" in \string\IEEEeqnarraymulticol.\MessageBreak -Using a default centering column instead}% -{You must define IEEEeqnarray column types before use.}% -\csname @IEEEeqnarraycolPRE@IEEEdefault\endcsname -\fi -% The ten \relax are to help prevent misleading error messages in case a user -% accidently inserted a macro that tries to acquire additional arguments. -#3\relax\relax\relax\relax\relax\relax\relax\relax\relax\relax -% check if column is defined for the postcolumn definition -\expandafter\ifx\csname @IEEEeqnarraycolDEF#2\endcsname\@IEEEeqnarraycolisdefined\relax -\csname @IEEEeqnarraycolPOST#2\endcsname -\else% if not, use the default type -\csname @IEEEeqnarraycolPOST@IEEEdefault\endcsname -\fi -% advance column counter only if the IEEEeqnarray environment wants it -\if@advanceIEEEeqncolcnt\global\advance\@IEEEeqncolcnt by #1\relax\fi} - -% like \omit, but maintains track of the column counter for \IEEEeqnarray -\def\IEEEeqnarrayomit{\omit\if@advanceIEEEeqncolcnt\global\advance\@IEEEeqncolcnt by 1\relax\fi} - - -% provides a way to define a letter referenced column type -% usage: \IEEEeqnarraydefcol{col. type letter/name}{pre insertion text}{post insertion text} -\def\IEEEeqnarraydefcol#1#2#3{\expandafter\def\csname @IEEEeqnarraycolPRE#1\endcsname{#2}% -\expandafter\def\csname @IEEEeqnarraycolPOST#1\endcsname{#3}% -\expandafter\def\csname @IEEEeqnarraycolDEF#1\endcsname{1}} - - -% provides a way to define a numerically referenced inter-column glue types -% usage: \IEEEeqnarraydefcolsep{col. glue number}{glue definition} -\def\IEEEeqnarraydefcolsep#1#2{\expandafter\def\csname @IEEEeqnarraycolSEP\romannumeral #1\endcsname{#2}% -\expandafter\def\csname @IEEEeqnarraycolSEPDEF\romannumeral #1\endcsname{1}} - - -\def\@IEEEeqnarraycolisdefined{1}% just a macro for 1, used for checking undefined column types - - -% expands and appends the given argument to the \@IEEEtrantmptoksA token list -% used to build up the \halign preamble -\def\@IEEEappendtoksA#1{\edef\@@IEEEappendtoksA{\@IEEEtrantmptoksA={\the\@IEEEtrantmptoksA #1}}% -\@@IEEEappendtoksA} - -% also appends to \@IEEEtrantmptoksA, but does not expand the argument -% uses \toks8 as a scratchpad register -\def\@IEEEappendNOEXPANDtoksA#1{\toks8={#1}% -\edef\@@IEEEappendNOEXPANDtoksA{\@IEEEtrantmptoksA={\the\@IEEEtrantmptoksA\the\toks8}}% -\@@IEEEappendNOEXPANDtoksA} - -% define some common column types for the user -% math -\IEEEeqnarraydefcol{l}{$\IEEEeqnarraymathstyle}{$\hfil} -\IEEEeqnarraydefcol{c}{\hfil$\IEEEeqnarraymathstyle}{$\hfil} -\IEEEeqnarraydefcol{r}{\hfil$\IEEEeqnarraymathstyle}{$} -\IEEEeqnarraydefcol{L}{$\IEEEeqnarraymathstyle{}}{{}$\hfil} -\IEEEeqnarraydefcol{C}{\hfil$\IEEEeqnarraymathstyle{}}{{}$\hfil} -\IEEEeqnarraydefcol{R}{\hfil$\IEEEeqnarraymathstyle{}}{{}$} -% text -\IEEEeqnarraydefcol{s}{\IEEEeqnarraytextstyle}{\hfil} -\IEEEeqnarraydefcol{t}{\hfil\IEEEeqnarraytextstyle}{\hfil} -\IEEEeqnarraydefcol{u}{\hfil\IEEEeqnarraytextstyle}{} - -% vertical rules -\IEEEeqnarraydefcol{v}{}{\vrule width\arrayrulewidth} -\IEEEeqnarraydefcol{vv}{\vrule width\arrayrulewidth\hfil}{\hfil\vrule width\arrayrulewidth} -\IEEEeqnarraydefcol{V}{}{\vrule width\arrayrulewidth\hskip\doublerulesep\vrule width\arrayrulewidth} -\IEEEeqnarraydefcol{VV}{\vrule width\arrayrulewidth\hskip\doublerulesep\vrule width\arrayrulewidth\hfil}% -{\hfil\vrule width\arrayrulewidth\hskip\doublerulesep\vrule width\arrayrulewidth} - -% horizontal rules -\IEEEeqnarraydefcol{h}{}{\leaders\hrule height\arrayrulewidth\hfil} -\IEEEeqnarraydefcol{H}{}{\leaders\vbox{\hrule width\arrayrulewidth\vskip\doublerulesep\hrule width\arrayrulewidth}\hfil} - -% plain -\IEEEeqnarraydefcol{x}{}{} -\IEEEeqnarraydefcol{X}{$}{$} - -% the default column type to use in the event a column type is not defined -\IEEEeqnarraydefcol{@IEEEdefault}{\hfil$\IEEEeqnarraymathstyle}{$\hfil} - - -% a zero tabskip (used for "-" col types) -\def\@IEEEeqnarraycolSEPzero{0pt plus 0pt minus 0pt} -% a centering tabskip (used for "+" col types) -\def\@IEEEeqnarraycolSEPcenter{1000pt plus 0pt minus 1000pt} - -% top level default tabskip glues for the start, end, and inter-column -% may be reset within environments not always at the top level, e.g., \IEEEeqnarraybox -\edef\@IEEEeqnarraycolSEPdefaultstart{\@IEEEeqnarraycolSEPcenter}% default start glue -\edef\@IEEEeqnarraycolSEPdefaultend{\@IEEEeqnarraycolSEPcenter}% default end glue -\edef\@IEEEeqnarraycolSEPdefaultmid{\@IEEEeqnarraycolSEPzero}% default inter-column glue - - - -% creates a vertical rule that extends from the bottom to the top a a cell -% Provided in case other packages redefine \vline some other way. -% usage: \IEEEeqnarrayvrule[rule thickness] -% If no argument is provided, \arrayrulewidth will be used for the rule thickness. -\newcommand\IEEEeqnarrayvrule[1][\arrayrulewidth]{\vrule\@width#1\relax} - -% creates a blank separator row -% usage: \IEEEeqnarrayseprow[separation length][font size commands] -% default is \IEEEeqnarrayseprow[0.25\normalbaselineskip][\relax] -% blank arguments inherit the default values -% uses \skip5 as a scratch register - calls \@IEEEeqnarraystrutsize which uses more scratch registers -\def\IEEEeqnarrayseprow{\relax\@ifnextchar[{\@IEEEeqnarrayseprow}{\@IEEEeqnarrayseprow[0.25\normalbaselineskip]}} -\def\@IEEEeqnarrayseprow[#1]{\relax\@ifnextchar[{\@@IEEEeqnarrayseprow[#1]}{\@@IEEEeqnarrayseprow[#1][\relax]}} -\def\@@IEEEeqnarrayseprow[#1][#2]{\def\@IEEEeqnarrayseprowARGONE{#1}% -\ifx\@IEEEeqnarrayseprowARGONE\@empty% -% get the skip value, based on the font commands -% use skip5 because \IEEEeqnarraystrutsize uses \skip0, \skip2, \skip3 -% assign within a bogus box to confine the font changes -{\setbox0=\hbox{#2\relax\global\skip5=0.25\normalbaselineskip}}% -\else% -{\setbox0=\hbox{#2\relax\global\skip5=#1}}% -\fi% -\@IEEEeqnarrayhoptolastcolumn\IEEEeqnarraystrutsize{\skip5}{0pt}[\relax]\relax} - -% creates a blank separator row, but omits all the column templates -% usage: \IEEEeqnarrayseprowcut[separation length][font size commands] -% default is \IEEEeqnarrayseprowcut[0.25\normalbaselineskip][\relax] -% blank arguments inherit the default values -% uses \skip5 as a scratch register - calls \@IEEEeqnarraystrutsize which uses more scratch registers -\def\IEEEeqnarrayseprowcut{\multispan{\@IEEEeqnnumcols}\relax% span all the cols -% advance column counter only if the IEEEeqnarray environment wants it -\if@advanceIEEEeqncolcnt\global\advance\@IEEEeqncolcnt by \@IEEEeqnnumcols\relax\fi% -\@ifnextchar[{\@IEEEeqnarrayseprowcut}{\@IEEEeqnarrayseprowcut[0.25\normalbaselineskip]}} -\def\@IEEEeqnarrayseprowcut[#1]{\relax\@ifnextchar[{\@@IEEEeqnarrayseprowcut[#1]}{\@@IEEEeqnarrayseprowcut[#1][\relax]}} -\def\@@IEEEeqnarrayseprowcut[#1][#2]{\def\@IEEEeqnarrayseprowARGONE{#1}% -\ifx\@IEEEeqnarrayseprowARGONE\@empty% -% get the skip value, based on the font commands -% use skip5 because \IEEEeqnarraystrutsize uses \skip0, \skip2, \skip3 -% assign within a bogus box to confine the font changes -{\setbox0=\hbox{#2\relax\global\skip5=0.25\normalbaselineskip}}% -\else% -{\setbox0=\hbox{#2\relax\global\skip5=#1}}% -\fi% -\IEEEeqnarraystrutsize{\skip5}{0pt}[\relax]\relax} - - - -% draws a single rule across all the columns optional -% argument determines the rule width, \arrayrulewidth is the default -% updates column counter as needed and turns off struts -% usage: \IEEEeqnarrayrulerow[rule line thickness] -\def\IEEEeqnarrayrulerow{\multispan{\@IEEEeqnnumcols}\relax% span all the cols -% advance column counter only if the IEEEeqnarray environment wants it -\if@advanceIEEEeqncolcnt\global\advance\@IEEEeqncolcnt by \@IEEEeqnnumcols\relax\fi% -\@ifnextchar[{\@IEEEeqnarrayrulerow}{\@IEEEeqnarrayrulerow[\arrayrulewidth]}} -\def\@IEEEeqnarrayrulerow[#1]{\leaders\hrule height#1\hfil\relax% put in our rule -% turn off any struts -\IEEEeqnarraystrutsize{0pt}{0pt}[\relax]\relax} - - -% draws a double rule by using a single rule row, a separator row, and then -% another single rule row -% first optional argument determines the rule thicknesses, \arrayrulewidth is the default -% second optional argument determines the rule spacing, \doublerulesep is the default -% usage: \IEEEeqnarraydblrulerow[rule line thickness][rule spacing] -\def\IEEEeqnarraydblrulerow{\multispan{\@IEEEeqnnumcols}\relax% span all the cols -% advance column counter only if the IEEEeqnarray environment wants it -\if@advanceIEEEeqncolcnt\global\advance\@IEEEeqncolcnt by \@IEEEeqnnumcols\relax\fi% -\@ifnextchar[{\@IEEEeqnarraydblrulerow}{\@IEEEeqnarraydblrulerow[\arrayrulewidth]}} -\def\@IEEEeqnarraydblrulerow[#1]{\relax\@ifnextchar[{\@@IEEEeqnarraydblrulerow[#1]}% -{\@@IEEEeqnarraydblrulerow[#1][\doublerulesep]}} -\def\@@IEEEeqnarraydblrulerow[#1][#2]{\def\@IEEEeqnarraydblrulerowARG{#1}% -% we allow the user to say \IEEEeqnarraydblrulerow[][] -\ifx\@IEEEeqnarraydblrulerowARG\@empty% -\@IEEEeqnarrayrulerow[\arrayrulewidth]% -\else% -\@IEEEeqnarrayrulerow[#1]\relax% -\fi% -\def\@IEEEeqnarraydblrulerowARG{#2}% -\ifx\@IEEEeqnarraydblrulerowARG\@empty% -\\\IEEEeqnarrayseprow[\doublerulesep][\relax]% -\else% -\\\IEEEeqnarrayseprow[#2][\relax]% -\fi% -\\\multispan{\@IEEEeqnnumcols}% -% advance column counter only if the IEEEeqnarray environment wants it -\if@advanceIEEEeqncolcnt\global\advance\@IEEEeqncolcnt by \@IEEEeqnnumcols\relax\fi% -\def\@IEEEeqnarraydblrulerowARG{#1}% -\ifx\@IEEEeqnarraydblrulerowARG\@empty% -\@IEEEeqnarrayrulerow[\arrayrulewidth]% -\else% -\@IEEEeqnarrayrulerow[#1]% -\fi% -} - -% draws a double rule by using a single rule row, a separator (cutting) row, and then -% another single rule row -% first optional argument determines the rule thicknesses, \arrayrulewidth is the default -% second optional argument determines the rule spacing, \doublerulesep is the default -% usage: \IEEEeqnarraydblrulerow[rule line thickness][rule spacing] -\def\IEEEeqnarraydblrulerowcut{\multispan{\@IEEEeqnnumcols}\relax% span all the cols -% advance column counter only if the IEEEeqnarray environment wants it -\if@advanceIEEEeqncolcnt\global\advance\@IEEEeqncolcnt by \@IEEEeqnnumcols\relax\fi% -\@ifnextchar[{\@IEEEeqnarraydblrulerowcut}{\@IEEEeqnarraydblrulerowcut[\arrayrulewidth]}} -\def\@IEEEeqnarraydblrulerowcut[#1]{\relax\@ifnextchar[{\@@IEEEeqnarraydblrulerowcut[#1]}% -{\@@IEEEeqnarraydblrulerowcut[#1][\doublerulesep]}} -\def\@@IEEEeqnarraydblrulerowcut[#1][#2]{\def\@IEEEeqnarraydblrulerowARG{#1}% -% we allow the user to say \IEEEeqnarraydblrulerow[][] -\ifx\@IEEEeqnarraydblrulerowARG\@empty% -\@IEEEeqnarrayrulerow[\arrayrulewidth]% -\else% -\@IEEEeqnarrayrulerow[#1]% -\fi% -\def\@IEEEeqnarraydblrulerowARG{#2}% -\ifx\@IEEEeqnarraydblrulerowARG\@empty% -\\\IEEEeqnarrayseprowcut[\doublerulesep][\relax]% -\else% -\\\IEEEeqnarrayseprowcut[#2][\relax]% -\fi% -\\\multispan{\@IEEEeqnnumcols}% -% advance column counter only if the IEEEeqnarray environment wants it -\if@advanceIEEEeqncolcnt\global\advance\@IEEEeqncolcnt by \@IEEEeqnnumcols\relax\fi% -\def\@IEEEeqnarraydblrulerowARG{#1}% -\ifx\@IEEEeqnarraydblrulerowARG\@empty% -\@IEEEeqnarrayrulerow[\arrayrulewidth]% -\else% -\@IEEEeqnarrayrulerow[#1]% -\fi% -} - - - -% inserts a full row's worth of &'s -% relies on \@IEEEeqnnumcols to provide the correct number of columns -% uses \@IEEEtrantmptoksA, \count0 as scratch registers -\def\@IEEEeqnarrayhoptolastcolumn{\@IEEEtrantmptoksA={}\count0=1\relax% -\loop% add cols if the user did not use them all -\ifnum\count0<\@IEEEeqnnumcols\relax% -\@IEEEappendtoksA{&}% -\advance\count0 by 1\relax% update the col count -\repeat% -\the\@IEEEtrantmptoksA%execute the &'s -} - - - -\newif\if@IEEEeqnarrayISinner % flag to indicate if we are within the lines -\@IEEEeqnarrayISinnerfalse % of an IEEEeqnarray - after the IEEEeqnarraydecl - -\edef\@IEEEeqnarrayTHEstrutheight{0pt} % height and depth of IEEEeqnarray struts -\edef\@IEEEeqnarrayTHEstrutdepth{0pt} - -\edef\@IEEEeqnarrayTHEmasterstrutheight{0pt} % default height and depth of -\edef\@IEEEeqnarrayTHEmasterstrutdepth{0pt} % struts within an IEEEeqnarray - -\edef\@IEEEeqnarrayTHEmasterstrutHSAVE{0pt} % saved master strut height -\edef\@IEEEeqnarrayTHEmasterstrutDSAVE{0pt} % and depth - -\newif\if@IEEEeqnarrayusemasterstrut % flag to indicate that the master strut value -\@IEEEeqnarrayusemasterstruttrue % is to be used - - - -% saves the strut height and depth of the master strut -\def\@IEEEeqnarraymasterstrutsave{\relax% -\expandafter\skip0=\@IEEEeqnarrayTHEmasterstrutheight\relax% -\expandafter\skip2=\@IEEEeqnarrayTHEmasterstrutdepth\relax% -% remove stretchability -\dimen0\skip0\relax% -\dimen2\skip2\relax% -% save values -\edef\@IEEEeqnarrayTHEmasterstrutHSAVE{\the\dimen0}% -\edef\@IEEEeqnarrayTHEmasterstrutDSAVE{\the\dimen2}} - -% restores the strut height and depth of the master strut -\def\@IEEEeqnarraymasterstrutrestore{\relax% -\expandafter\skip0=\@IEEEeqnarrayTHEmasterstrutHSAVE\relax% -\expandafter\skip2=\@IEEEeqnarrayTHEmasterstrutDSAVE\relax% -% remove stretchability -\dimen0\skip0\relax% -\dimen2\skip2\relax% -% restore values -\edef\@IEEEeqnarrayTHEmasterstrutheight{\the\dimen0}% -\edef\@IEEEeqnarrayTHEmasterstrutdepth{\the\dimen2}} - - -% globally restores the strut height and depth to the -% master values and sets the master strut flag to true -\def\@IEEEeqnarraystrutreset{\relax% -\expandafter\skip0=\@IEEEeqnarrayTHEmasterstrutheight\relax% -\expandafter\skip2=\@IEEEeqnarrayTHEmasterstrutdepth\relax% -% remove stretchability -\dimen0\skip0\relax% -\dimen2\skip2\relax% -% restore values -\xdef\@IEEEeqnarrayTHEstrutheight{\the\dimen0}% -\xdef\@IEEEeqnarrayTHEstrutdepth{\the\dimen2}% -\global\@IEEEeqnarrayusemasterstruttrue} - - -% if the master strut is not to be used, make the current -% values of \@IEEEeqnarrayTHEstrutheight, \@IEEEeqnarrayTHEstrutdepth -% and the use master strut flag, global -% this allows user strut commands issued in the last column to be carried -% into the isolation/strut column -\def\@IEEEeqnarrayglobalizestrutstatus{\relax% -\if@IEEEeqnarrayusemasterstrut\else% -\xdef\@IEEEeqnarrayTHEstrutheight{\@IEEEeqnarrayTHEstrutheight}% -\xdef\@IEEEeqnarrayTHEstrutdepth{\@IEEEeqnarrayTHEstrutdepth}% -\global\@IEEEeqnarrayusemasterstrutfalse% -\fi} - - - -% usage: \IEEEeqnarraystrutsize{height}{depth}[font size commands] -% If called outside the lines of an IEEEeqnarray, sets the height -% and depth of both the master and local struts. If called inside -% an IEEEeqnarray line, sets the height and depth of the local strut -% only and sets the flag to indicate the use of the local strut -% values. If the height or depth is left blank, 0.7\normalbaselineskip -% and 0.3\normalbaselineskip will be used, respectively. -% The optional argument can be used to evaluate the lengths under -% a different font size and styles. If none is specified, the current -% font is used. -% uses scratch registers \skip0, \skip2, \skip3, \dimen0, \dimen2 -\def\IEEEeqnarraystrutsize#1#2{\relax\@ifnextchar[{\@IEEEeqnarraystrutsize{#1}{#2}}{\@IEEEeqnarraystrutsize{#1}{#2}[\relax]}} -\def\@IEEEeqnarraystrutsize#1#2[#3]{\def\@IEEEeqnarraystrutsizeARG{#1}% -\ifx\@IEEEeqnarraystrutsizeARG\@empty% -{\setbox0=\hbox{#3\relax\global\skip3=0.7\normalbaselineskip}}% -\skip0=\skip3\relax% -\else% arg one present -{\setbox0=\hbox{#3\relax\global\skip3=#1\relax}}% -\skip0=\skip3\relax% -\fi% if null arg -\def\@IEEEeqnarraystrutsizeARG{#2}% -\ifx\@IEEEeqnarraystrutsizeARG\@empty% -{\setbox0=\hbox{#3\relax\global\skip3=0.3\normalbaselineskip}}% -\skip2=\skip3\relax% -\else% arg two present -{\setbox0=\hbox{#3\relax\global\skip3=#2\relax}}% -\skip2=\skip3\relax% -\fi% if null arg -% remove stretchability, just to be safe -\dimen0\skip0\relax% -\dimen2\skip2\relax% -% dimen0 = height, dimen2 = depth -\if@IEEEeqnarrayISinner% inner does not touch master strut size -\edef\@IEEEeqnarrayTHEstrutheight{\the\dimen0}% -\edef\@IEEEeqnarrayTHEstrutdepth{\the\dimen2}% -\@IEEEeqnarrayusemasterstrutfalse% do not use master -\else% outer, have to set master strut too -\edef\@IEEEeqnarrayTHEmasterstrutheight{\the\dimen0}% -\edef\@IEEEeqnarrayTHEmasterstrutdepth{\the\dimen2}% -\edef\@IEEEeqnarrayTHEstrutheight{\the\dimen0}% -\edef\@IEEEeqnarrayTHEstrutdepth{\the\dimen2}% -\@IEEEeqnarrayusemasterstruttrue% use master strut -\fi} - - -% usage: \IEEEeqnarraystrutsizeadd{added height}{added depth}[font size commands] -% If called outside the lines of an IEEEeqnarray, adds the given height -% and depth to both the master and local struts. -% If called inside an IEEEeqnarray line, adds the given height and depth -% to the local strut only and sets the flag to indicate the use -% of the local strut values. -% In both cases, if a height or depth is left blank, 0pt is used instead. -% The optional argument can be used to evaluate the lengths under -% a different font size and styles. If none is specified, the current -% font is used. -% uses scratch registers \skip0, \skip2, \skip3, \dimen0, \dimen2 -\def\IEEEeqnarraystrutsizeadd#1#2{\relax\@ifnextchar[{\@IEEEeqnarraystrutsizeadd{#1}{#2}}{\@IEEEeqnarraystrutsizeadd{#1}{#2}[\relax]}} -\def\@IEEEeqnarraystrutsizeadd#1#2[#3]{\def\@IEEEeqnarraystrutsizearg{#1}% -\ifx\@IEEEeqnarraystrutsizearg\@empty% -\skip0=0pt\relax% -\else% arg one present -{\setbox0=\hbox{#3\relax\global\skip3=#1}}% -\skip0=\skip3\relax% -\fi% if null arg -\def\@IEEEeqnarraystrutsizearg{#2}% -\ifx\@IEEEeqnarraystrutsizearg\@empty% -\skip2=0pt\relax% -\else% arg two present -{\setbox0=\hbox{#3\relax\global\skip3=#2}}% -\skip2=\skip3\relax% -\fi% if null arg -% remove stretchability, just to be safe -\dimen0\skip0\relax% -\dimen2\skip2\relax% -% dimen0 = height, dimen2 = depth -\if@IEEEeqnarrayISinner% inner does not touch master strut size -% get local strut size -\expandafter\skip0=\@IEEEeqnarrayTHEstrutheight\relax% -\expandafter\skip2=\@IEEEeqnarrayTHEstrutdepth\relax% -% add it to the user supplied values -\advance\dimen0 by \skip0\relax% -\advance\dimen2 by \skip2\relax% -% update the local strut size -\edef\@IEEEeqnarrayTHEstrutheight{\the\dimen0}% -\edef\@IEEEeqnarrayTHEstrutdepth{\the\dimen2}% -\@IEEEeqnarrayusemasterstrutfalse% do not use master -\else% outer, have to set master strut too -% get master strut size -\expandafter\skip0=\@IEEEeqnarrayTHEmasterstrutheight\relax% -\expandafter\skip2=\@IEEEeqnarrayTHEmasterstrutdepth\relax% -% add it to the user supplied values -\advance\dimen0 by \skip0\relax% -\advance\dimen2 by \skip2\relax% -% update the local and master strut sizes -\edef\@IEEEeqnarrayTHEmasterstrutheight{\the\dimen0}% -\edef\@IEEEeqnarrayTHEmasterstrutdepth{\the\dimen2}% -\edef\@IEEEeqnarrayTHEstrutheight{\the\dimen0}% -\edef\@IEEEeqnarrayTHEstrutdepth{\the\dimen2}% -\@IEEEeqnarrayusemasterstruttrue% use master strut -\fi} - - -% allow user a way to see the struts -\newif\ifIEEEvisiblestruts -\IEEEvisiblestrutsfalse - -% inserts an invisible strut using the master or local strut values -% uses scratch registers \skip0, \skip2, \dimen0, \dimen2 -\def\@IEEEeqnarrayinsertstrut{\relax% -\if@IEEEeqnarrayusemasterstrut -% get master strut size -\expandafter\skip0=\@IEEEeqnarrayTHEmasterstrutheight\relax% -\expandafter\skip2=\@IEEEeqnarrayTHEmasterstrutdepth\relax% -\else% -% get local strut size -\expandafter\skip0=\@IEEEeqnarrayTHEstrutheight\relax% -\expandafter\skip2=\@IEEEeqnarrayTHEstrutdepth\relax% -\fi% -% remove stretchability, probably not needed -\dimen0\skip0\relax% -\dimen2\skip2\relax% -% dimen0 = height, dimen2 = depth -% allow user to see struts if desired -\ifIEEEvisiblestruts% -\vrule width0.2pt height\dimen0 depth\dimen2\relax% -\else% -\vrule width0pt height\dimen0 depth\dimen2\relax\fi} - - -% creates an invisible strut, useable even outside \IEEEeqnarray -% if \IEEEvisiblestrutstrue, the strut will be visible and 0.2pt wide. -% usage: \IEEEstrut[height][depth][font size commands] -% default is \IEEEstrut[0.7\normalbaselineskip][0.3\normalbaselineskip][\relax] -% blank arguments inherit the default values -% uses \dimen0, \dimen2, \skip0, \skip2 -\def\IEEEstrut{\relax\@ifnextchar[{\@IEEEstrut}{\@IEEEstrut[0.7\normalbaselineskip]}} -\def\@IEEEstrut[#1]{\relax\@ifnextchar[{\@@IEEEstrut[#1]}{\@@IEEEstrut[#1][0.3\normalbaselineskip]}} -\def\@@IEEEstrut[#1][#2]{\relax\@ifnextchar[{\@@@IEEEstrut[#1][#2]}{\@@@IEEEstrut[#1][#2][\relax]}} -\def\@@@IEEEstrut[#1][#2][#3]{\mbox{#3\relax% -\def\@IEEEstrutARG{#1}% -\ifx\@IEEEstrutARG\@empty% -\skip0=0.7\normalbaselineskip\relax% -\else% -\skip0=#1\relax% -\fi% -\def\@IEEEstrutARG{#2}% -\ifx\@IEEEstrutARG\@empty% -\skip2=0.3\normalbaselineskip\relax% -\else% -\skip2=#2\relax% -\fi% -% remove stretchability, probably not needed -\dimen0\skip0\relax% -\dimen2\skip2\relax% -\ifIEEEvisiblestruts% -\vrule width0.2pt height\dimen0 depth\dimen2\relax% -\else% -\vrule width0.0pt height\dimen0 depth\dimen2\relax\fi}} - - -% enables strut mode by setting a default strut size and then zeroing the -% \baselineskip, \lineskip, \lineskiplimit and \jot -\def\IEEEeqnarraystrutmode{\IEEEeqnarraystrutsize{0.7\normalbaselineskip}{0.3\normalbaselineskip}[\relax]% -\baselineskip=0pt\lineskip=0pt\lineskiplimit=0pt\jot=0pt} - - -% equation and subequation forms to use to setup hyperref's \@currentHref -\def\@IEEEtheHrefequation{equation.\theHequation} -\def\@IEEEtheHrefsubequation{equation.\theHequation\alph{IEEEsubequation}} - - -\def\IEEEeqnarray{\@IEEEeqnumpersisttrue\@IEEEsubeqnumpersistfalse\@IEEEeqnarray} -\def\endIEEEeqnarray{\end@IEEEeqnarray} - -\@namedef{IEEEeqnarray*}{\@IEEEeqnumpersistfalse\@IEEEsubeqnumpersistfalse\@IEEEeqnarray} -\@namedef{endIEEEeqnarray*}{\end@IEEEeqnarray} - - -% \IEEEeqnarray is an enhanced \eqnarray. -% The star form defaults to not putting equation numbers at the end of each row. -% usage: \IEEEeqnarray[decl]{cols} -\def\@IEEEeqnarray{\relax\@ifnextchar[{\@@IEEEeqnarray}{\@@IEEEeqnarray[\relax]}} -% We have to be careful here to normalize catcodes just before acquiring the -% cols as that specification may contain punctuation which could be subject -% to document catcode changes. -\def\@@IEEEeqnarray[#1]{\begingroup\IEEEnormalcatcodes\@@@IEEEeqnarray[#1]} -\def\@@@IEEEeqnarray[#1]#2{\endgroup - % default to showing the equation number or not based on whether or not - % the star form was involked - \if@IEEEeqnumpersist\global\@eqnswtrue - \else% not the star form - \global\@eqnswfalse - \fi% if star form - % provide a basic hyperref \theHequation if this has not already been setup (hyperref not loaded, or no section counter) - \@ifundefined{theHequation}{\def\theHequation{\arabic{equation}}}{}\relax - % provide dummy hyperref commands in case hyperref is not loaded - \providecommand{\Hy@raisedlink}[1]{}\relax - \providecommand{\hyper@anchorstart}[1]{}\relax - \providecommand{\hyper@anchorend}{}\relax - \providecommand{\@currentHref}{}\relax - \@IEEEeqnumpreadvfalse% reset eqnpreadv flag - \@IEEEsubeqnumpreadvfalse% reset subeqnpreadv flag - \@IEEEeqnarrayISinnerfalse% not yet within the lines of the halign - \@IEEEeqnarraystrutsize{0pt}{0pt}[\relax]% turn off struts by default - \@IEEEeqnarrayusemasterstruttrue% use master strut till user asks otherwise - \IEEEvisiblestrutsfalse% diagnostic mode defaults to off - % no extra space unless the user specifically requests it - \lineskip=0pt\relax - \lineskiplimit=0pt\relax - \baselineskip=\normalbaselineskip\relax% - \jot=\IEEEnormaljot\relax% - \mathsurround\z@\relax% no extra spacing around math - \@advanceIEEEeqncolcnttrue% advance the col counter for each col the user uses, - % used in \IEEEeqnarraymulticol and in the preamble build - %V1.8 Here we preadvance to the next equation number. - % If the user later wants a continued subequation, we can roll back. - \global\@IEEEsubeqnnumrollback=\c@IEEEsubequation% - \stepcounter{equation}\@IEEEeqnumpreadvtrue% advance equation counter before first line - \setcounter{IEEEsubequation}{0}% no subequation yet - \let\@IEEEcurrentlabelsave\@currentlabel% save current label as we later change it globally - \let\@IEEEcurrentHrefsave\@currentHref% save current href label as we later change it globally - \def\@currentlabel{\p@equation\theequation}% redefine the ref label - \def\@currentHref{\@IEEEtheHrefequation}% setup hyperref label - \IEEEeqnarraydecl\relax% allow a way for the user to make global overrides - #1\relax% allow user to override defaults - \let\\\@IEEEeqnarraycr% replace newline with one that can put in eqn. numbers - \global\@IEEEeqncolcnt\z@% col. count = 0 for first line - \@IEEEbuildpreamble{#2}\relax% build the preamble and put it into \@IEEEtrantmptoksA - % put in the column for the equation number - \ifnum\@IEEEeqnnumcols>0\relax\@IEEEappendtoksA{&}\fi% col separator for those after the first - \toks0={##}% - % advance the \@IEEEeqncolcnt for the isolation col, this helps with error checking - \@IEEEappendtoksA{\global\advance\@IEEEeqncolcnt by 1\relax}% - % add the isolation column - \@IEEEappendtoksA{\tabskip\z@skip\bgroup\the\toks0\egroup}% - % advance the \@IEEEeqncolcnt for the equation number col, this helps with error checking - \@IEEEappendtoksA{&\global\advance\@IEEEeqncolcnt by 1\relax}% - % add the equation number col to the preamble - \@IEEEappendtoksA{\tabskip\z@skip\hb@xt@\z@\bgroup\hss\the\toks0\egroup}% - % note \@IEEEeqnnumcols does not count the equation col or isolation col - % set the starting tabskip glue as determined by the preamble build - \tabskip=\@IEEEBPstartglue\relax - % begin the display alignment - \@IEEEeqnarrayISinnertrue% commands are now within the lines - $$\everycr{}\halign to\displaywidth\bgroup - % "exspand" the preamble - \span\the\@IEEEtrantmptoksA\cr} - -% enter isolation/strut column (or the next column if the user did not use -% every column), record the strut status, complete the columns, do the strut if needed, -% restore counters (to backout any equation setup for a next line that was never used) -% to their correct values and exit -\def\end@IEEEeqnarray{\@IEEEeqnarrayglobalizestrutstatus&\@@IEEEeqnarraycr\egroup -\if@IEEEsubeqnumpreadv\global\advance\c@IEEEsubequation\m@ne\fi -\if@IEEEeqnumpreadv\global\advance\c@equation\m@ne\global\c@IEEEsubequation=\@IEEEsubeqnnumrollback\fi -\global\let\@currentlabel\@IEEEcurrentlabelsave% restore current label -\global\let\@currentHref\@IEEEcurrentHrefsave% restore current href label -$$\@ignoretrue} - - -% IEEEeqnarray uses a modifed \\ instead of the plain \cr to -% end rows. This allows for things like \\*[vskip amount] -% These "cr" macros are modified versions of those for LaTeX2e's eqnarray -% the {\ifnum0=`} braces must be kept away from the last column to avoid -% altering spacing of its math, so we use & to advance to the next column -% as there is an isolation/strut column after the user's columns -\def\@IEEEeqnarraycr{\@IEEEeqnarrayglobalizestrutstatus&% save strut status and advance to next column - {\ifnum0=`}\fi - \@ifstar{% - \global\@eqpen\@M\@IEEEeqnarrayYCR - }{% - \global\@eqpen\interdisplaylinepenalty \@IEEEeqnarrayYCR - }% -} - -\def\@IEEEeqnarrayYCR{\@testopt\@IEEEeqnarrayXCR\z@skip} - -\def\@IEEEeqnarrayXCR[#1]{% - \ifnum0=`{\fi}% - \@@IEEEeqnarraycr - \noalign{\penalty\@eqpen\vskip\jot\vskip #1\relax}}% - -\def\@@IEEEeqnarraycr{\@IEEEtrantmptoksA={}% clear token register - \advance\@IEEEeqncolcnt by -1\relax% adjust col count because of the isolation column - \ifnum\@IEEEeqncolcnt>\@IEEEeqnnumcols\relax - \@IEEEclspkgerror{Too many columns within the IEEEeqnarray\MessageBreak - environment}% - {Use fewer \string &'s or put more columns in the IEEEeqnarray column\MessageBreak - specifications.}\relax% - \else - \loop% add cols if the user did not use them all - \ifnum\@IEEEeqncolcnt<\@IEEEeqnnumcols\relax - \@IEEEappendtoksA{&}% - \advance\@IEEEeqncolcnt by 1\relax% update the col count - \repeat - % this number of &'s will take us the the isolation column - \fi - % execute the &'s - \the\@IEEEtrantmptoksA% - % handle the strut/isolation column - \@IEEEeqnarrayinsertstrut% do the strut if needed - \@IEEEeqnarraystrutreset% reset the strut system for next line or IEEEeqnarray - &% and enter the equation number column - \if@eqnsw% only if we display something - \Hy@raisedlink{\hyper@anchorstart{\@currentHref}}% start a hyperref anchor - \global\@IEEEeqnumpreadvfalse\relax% displaying an equation number means - \global\@IEEEsubeqnumpreadvfalse\relax% the equation counters point to valid equations - % V1.8 Here we setup the counters, currentlabel and status for what would be the *next* - % equation line as would be the case under the current settings. However, there are two problems. - % One problem is that there might not ever be a next line. The second problem is that the user - % may later alter the meaning of a line with commands such as \IEEEyessubnumber. So, to handle - % these cases we have to record the current values of the (sub)equation counters and revert back - % to them if the next line is changed or never comes. The \if@IEEEeqnumpreadv, \if@IEEEsubeqnumpreadv - % and \@IEEEsubeqnnumrollback stuff tracks this. - % The logic to handle all this is surprisingly complex, but a nice feature of the approach here is - % that the equation counters and labels remain valid for what the line would be unless a - % \IEEEyessubnumber et al. later changes it. So, any hyperref links are always correct. - \ifnum\c@IEEEsubequation>0\relax% handle subequation - \theIEEEsubequationdis\relax - \if@IEEEsubeqnumpersist% setup for default type of next line - \stepcounter{IEEEsubequation}\global\@IEEEsubeqnumpreadvtrue\relax - \gdef\@currentlabel{\p@IEEEsubequation\theIEEEsubequation}\relax - \gdef\@currentHref{\@IEEEtheHrefsubequation}% setup hyperref label - \else - % if no subeqnum persist, go ahead and setup for a new equation number - \global\@IEEEsubeqnnumrollback=\c@IEEEsubequation - \stepcounter{equation}\global\@IEEEeqnumpreadvtrue\relax - \setcounter{IEEEsubequation}{0}\gdef\@currentlabel{\p@equation\theequation}\relax - \gdef\@currentHref{\@IEEEtheHrefequation}% setup hyperref label - \fi - \else% display a standard equation number - \theequationdis\relax - \setcounter{IEEEsubequation}{0}\relax% not really needed - \if@IEEEsubeqnumpersist% setup for default type of next line - % subequations that follow plain equations carry the same equation number e.g, 5, 5a rather than 5, 6a - \stepcounter{IEEEsubequation}\global\@IEEEsubeqnumpreadvtrue\relax - \gdef\@currentlabel{\p@IEEEsubequation\theIEEEsubequation}\relax - \gdef\@currentHref{\@IEEEtheHrefsubequation}% setup hyperref label - \else - % if no subeqnum persist, go ahead and setup for a new equation number - \global\@IEEEsubeqnnumrollback=\c@IEEEsubequation - \stepcounter{equation}\global\@IEEEeqnumpreadvtrue\relax - \setcounter{IEEEsubequation}{0}\gdef\@currentlabel{\p@equation\theequation}\relax - \gdef\@currentHref{\@IEEEtheHrefequation}% setup hyperref label - \fi - \fi% - \Hy@raisedlink{\hyper@anchorend}% end hyperref anchor - \fi% fi only if we display something - % reset the flags to indicate the default preferences of the display of equation numbers - \if@IEEEeqnumpersist\global\@eqnswtrue\else\global\@eqnswfalse\fi - \if@IEEEsubeqnumpersist\global\@eqnswtrue\fi% ditto for the subequation flag - % reset the number of columns the user actually used - \global\@IEEEeqncolcnt\z@\relax - % the real end of the line - \cr} - - - - - -% \IEEEeqnarraybox is like \IEEEeqnarray except the box form puts everything -% inside a vtop, vbox, or vcenter box depending on the letter in the second -% optional argument (t,b,c). Vbox is the default. Unlike \IEEEeqnarray, -% equation numbers are not displayed and \IEEEeqnarraybox can be nested. -% \IEEEeqnarrayboxm is for math mode (like \array) and does not put the vbox -% within an hbox. -% \IEEEeqnarrayboxt is for text mode (like \tabular) and puts the vbox within -% a \hbox{$ $} construct. -% \IEEEeqnarraybox will auto detect whether to use \IEEEeqnarrayboxm or -% \IEEEeqnarrayboxt depending on the math mode. -% The third optional argument specifies the width this box is to be set to - -% natural width is the default. -% The * forms do not add \jot line spacing -% usage: \IEEEeqnarraybox[decl][pos][width]{cols} -\def\IEEEeqnarrayboxm{\@IEEEeqnarrayboxnojotfalse\@IEEEeqnarrayboxHBOXSWfalse\@IEEEeqnarraybox} -\def\endIEEEeqnarrayboxm{\end@IEEEeqnarraybox} -\@namedef{IEEEeqnarrayboxm*}{\@IEEEeqnarrayboxnojottrue\@IEEEeqnarrayboxHBOXSWfalse\@IEEEeqnarraybox} -\@namedef{endIEEEeqnarrayboxm*}{\end@IEEEeqnarraybox} - -\def\IEEEeqnarrayboxt{\@IEEEeqnarrayboxnojotfalse\@IEEEeqnarrayboxHBOXSWtrue\@IEEEeqnarraybox} -\def\endIEEEeqnarrayboxt{\end@IEEEeqnarraybox} -\@namedef{IEEEeqnarrayboxt*}{\@IEEEeqnarrayboxnojottrue\@IEEEeqnarrayboxHBOXSWtrue\@IEEEeqnarraybox} -\@namedef{endIEEEeqnarrayboxt*}{\end@IEEEeqnarraybox} - -\def\IEEEeqnarraybox{\@IEEEeqnarrayboxnojotfalse\ifmmode\@IEEEeqnarrayboxHBOXSWfalse\else\@IEEEeqnarrayboxHBOXSWtrue\fi% -\@IEEEeqnarraybox} -\def\endIEEEeqnarraybox{\end@IEEEeqnarraybox} - -\@namedef{IEEEeqnarraybox*}{\@IEEEeqnarrayboxnojottrue\ifmmode\@IEEEeqnarrayboxHBOXSWfalse\else\@IEEEeqnarrayboxHBOXSWtrue\fi% -\@IEEEeqnarraybox} -\@namedef{endIEEEeqnarraybox*}{\end@IEEEeqnarraybox} - -% flag to indicate if the \IEEEeqnarraybox needs to put things into an hbox{$ $} -% for \vcenter in non-math mode -\newif\if@IEEEeqnarrayboxHBOXSW% -\@IEEEeqnarrayboxHBOXSWfalse - -\def\@IEEEeqnarraybox{\relax\@ifnextchar[{\@@IEEEeqnarraybox}{\@@IEEEeqnarraybox[\relax]}} -% We have to be careful here to normalize catcodes just before acquiring the -% cols as that specification may contain punctuation which could be subject -% to document catcode changes. -\def\@@IEEEeqnarraybox[#1]{\relax\begingroup\IEEEnormalcatcodes\@ifnextchar[{\@@@IEEEeqnarraybox[#1]}{\@@@IEEEeqnarraybox[#1][b]}} -\def\@@@IEEEeqnarraybox[#1][#2]{\relax\@ifnextchar[{\@@@@IEEEeqnarraybox[#1][#2]}{\@@@@IEEEeqnarraybox[#1][#2][\relax]}} - -% #1 = decl; #2 = t,b,c; #3 = width, #4 = col specs -\def\@@@@IEEEeqnarraybox[#1][#2][#3]#4{\endgroup\@IEEEeqnarrayISinnerfalse % not yet within the lines of the halign - \@IEEEeqnarraymasterstrutsave% save current master strut values - \@IEEEeqnarraystrutsize{0pt}{0pt}[\relax]% turn off struts by default - \@IEEEeqnarrayusemasterstruttrue% use master strut till user asks otherwise - \IEEEvisiblestrutsfalse% diagnostic mode defaults to off - % no extra space unless the user specifically requests it - \lineskip=0pt\relax% - \lineskiplimit=0pt\relax% - \baselineskip=\normalbaselineskip\relax% - \jot=\IEEEnormaljot\relax% - \mathsurround\z@\relax% no extra spacing around math - % the default end glues are zero for an \IEEEeqnarraybox - \edef\@IEEEeqnarraycolSEPdefaultstart{\@IEEEeqnarraycolSEPzero}% default start glue - \edef\@IEEEeqnarraycolSEPdefaultend{\@IEEEeqnarraycolSEPzero}% default end glue - \edef\@IEEEeqnarraycolSEPdefaultmid{\@IEEEeqnarraycolSEPzero}% default inter-column glue - \@advanceIEEEeqncolcntfalse% do not advance the col counter for each col the user uses, - % used in \IEEEeqnarraymulticol and in the preamble build - \IEEEeqnarrayboxdecl\relax% allow a way for the user to make global overrides - #1\relax% allow user to override defaults - \let\\\@IEEEeqnarrayboxcr% replace newline with one that allows optional spacing - \@IEEEbuildpreamble{#4}\relax% build the preamble and put it into \@IEEEtrantmptoksA - % add an isolation column to the preamble to stop \\'s {} from getting into the last col - \ifnum\@IEEEeqnnumcols>0\relax\@IEEEappendtoksA{&}\fi% col separator for those after the first - \toks0={##}% - % add the isolation column to the preamble - \@IEEEappendtoksA{\tabskip\z@skip\bgroup\the\toks0\egroup}% - % set the starting tabskip glue as determined by the preamble build - \tabskip=\@IEEEBPstartglue\relax - % begin the alignment - \everycr{}% - % use only the very first token to determine the positioning - \@IEEEextracttoken{#2}\relax - \ifx\@IEEEextractedtokensdiscarded\@empty\else - \typeout{** WARNING: IEEEeqnarraybox position specifiers after the first in `\@IEEEextracttokenarg' ignored (line \the\inputlineno).}\relax - \fi - % \@IEEEextractedtoken has the first token, the rest are ignored - % if we need to put things into and hbox and go into math mode, do so now - \if@IEEEeqnarrayboxHBOXSW \leavevmode \hbox \bgroup $\fi% - % use the appropriate vbox type - \if\@IEEEextractedtoken t\relax\vtop\else\if\@IEEEextractedtoken c\relax% - \vcenter\else\vbox\fi\fi\bgroup% - \@IEEEeqnarrayISinnertrue% commands are now within the lines - \ifx#3\relax\halign\else\halign to #3\relax\fi% - \bgroup - % "exspand" the preamble - \span\the\@IEEEtrantmptoksA\cr} - -% carry strut status and enter the isolation/strut column, -% exit from math mode if needed, and exit -\def\end@IEEEeqnarraybox{\@IEEEeqnarrayglobalizestrutstatus% carry strut status -&% enter isolation/strut column -\@IEEEeqnarrayinsertstrut% do strut if needed -\@IEEEeqnarraymasterstrutrestore% restore the previous master strut values -% reset the strut system for next IEEEeqnarray -% (sets local strut values back to previous master strut values) -\@IEEEeqnarraystrutreset% -% ensure last line, exit from halign, close vbox -\crcr\egroup\egroup% -% exit from math mode and close hbox if needed -\if@IEEEeqnarrayboxHBOXSW $\egroup\fi} - - - -% IEEEeqnarraybox uses a modifed \\ instead of the plain \cr to -% end rows. This allows for things like \\[vskip amount] -% This "cr" macros are modified versions those for LaTeX2e's eqnarray -% For IEEEeqnarraybox, \\* is the same as \\ -% the {\ifnum0=`} braces must be kept away from the last column to avoid -% altering spacing of its math, so we use & to advance to the isolation/strut column -% carry strut status into isolation/strut column -\def\@IEEEeqnarrayboxcr{\@IEEEeqnarrayglobalizestrutstatus% carry strut status -&% enter isolation/strut column -\@IEEEeqnarrayinsertstrut% do strut if needed -% reset the strut system for next line or IEEEeqnarray -\@IEEEeqnarraystrutreset% -{\ifnum0=`}\fi% -\@ifstar{\@IEEEeqnarrayboxYCR}{\@IEEEeqnarrayboxYCR}} - -% test and setup the optional argument to \\[] -\def\@IEEEeqnarrayboxYCR{\@testopt\@IEEEeqnarrayboxXCR\z@skip} - -% IEEEeqnarraybox does not automatically increase line spacing by \jot -\def\@IEEEeqnarrayboxXCR[#1]{\ifnum0=`{\fi}% -\cr\noalign{\if@IEEEeqnarrayboxnojot\else\vskip\jot\fi\vskip#1\relax}} - - - -% usage: \@IEEEbuildpreamble{column specifiers} -% starts the halign preamble build -% the assembled preamble is put in \@IEEEtrantmptoksA -\def\@IEEEbuildpreamble#1{\@IEEEtrantmptoksA={}% clear token register -\let\@IEEEBPcurtype=u%current column type is not yet known -\let\@IEEEBPprevtype=s%the previous column type was the start -\let\@IEEEBPnexttype=u%next column type is not yet known -% ensure these are valid -\def\@IEEEBPcurglue={0pt plus 0pt minus 0pt}% -\def\@IEEEBPcurcolname{@IEEEdefault}% name of current column definition -% currently acquired numerically referenced glue -% use a name that is easier to remember -\let\@IEEEBPcurnum=\@IEEEtrantmpcountA% -\@IEEEBPcurnum=0% -% tracks number of columns in the preamble -\@IEEEeqnnumcols=0% -% record the default end glues -\edef\@IEEEBPstartglue{\@IEEEeqnarraycolSEPdefaultstart}% -\edef\@IEEEBPendglue{\@IEEEeqnarraycolSEPdefaultend}% -\edef\@IEEEedefMACRO{#1}\relax% fully expand the preamble to support macro containers -% now parse the user's column specifications -% \ignorespaces is used as a delimiter, need at least one trailing \relax because -% \@@IEEEbuildpreamble looks into the future -\expandafter\@@IEEEbuildpreamble\@IEEEedefMACRO\ignorespaces\relax\relax} - - -% usage: \@@IEEEbuildpreamble{current column}{next column} -% parses and builds the halign preamble -\def\@@IEEEbuildpreamble#1#2{\let\@@nextIEEEbuildpreamble=\@@IEEEbuildpreamble% -% use only the very first token to check the end -\@IEEEextracttokengroups{#1}\relax -\ifx\@IEEEextractedfirsttoken\ignorespaces\let\@@nextIEEEbuildpreamble=\@@IEEEfinishpreamble\else% -% identify current and next token type -\@IEEEgetcoltype{#1}{\@IEEEBPcurtype}{1}% current, error on invalid -\@IEEEgetcoltype{#2}{\@IEEEBPnexttype}{0}% next, no error on invalid next -% if curtype is a glue, get the glue def -\if\@IEEEBPcurtype g\@IEEEgetcurglue{#1}{\@IEEEBPcurglue}\fi% -% if curtype is a column, get the column def and set the current column name -\if\@IEEEBPcurtype c\@IEEEgetcurcol{#1}\fi% -% if curtype is a numeral, acquire the user defined glue -\if\@IEEEBPcurtype n\@IEEEprocessNcol{#1}\fi% -% process the acquired glue -\if\@IEEEBPcurtype g\@IEEEprocessGcol\fi% -% process the acquired col -\if\@IEEEBPcurtype c\@IEEEprocessCcol\fi% -% ready prevtype for next col spec. -\let\@IEEEBPprevtype=\@IEEEBPcurtype% -% be sure and put back the future token(s) as a group -\fi\@@nextIEEEbuildpreamble{#2}} - - -% usage: \@@IEEEfinishpreamble{discarded} -% executed just after preamble build is completed -% warn about zero cols, and if prevtype type = u, put in end tabskip glue -% argument is not used -\def\@@IEEEfinishpreamble#1{\ifnum\@IEEEeqnnumcols<1\relax -\@IEEEclspkgerror{No column specifiers declared for IEEEeqnarray}% -{At least one column type must be declared for each IEEEeqnarray.}% -\fi%num cols less than 1 -%if last type undefined, set default end tabskip glue -\if\@IEEEBPprevtype u\@IEEEappendtoksA{\tabskip=\@IEEEBPendglue}\fi} - - -% usage: \@IEEEgetcoltype{col specifier}{\output}{error more} -% Identify and return the column specifier's type code in the given -% \output macro: -% n = number -% g = glue (any other char in catagory 12) -% c = letter -% e = \ignorespaces (end of sequence) -% u = undefined -% error mode: 0 = no error message, 1 = error on invalid char -\def\@IEEEgetcoltype#1#2#3{% -% use only the very first token to determine the type -\@IEEEextracttoken{#1}\relax -% \@IEEEextractedtoken has the first token, the rest are discarded -\let#2=u\relax% assume invalid until know otherwise -\ifx\@IEEEextractedtoken\ignorespaces\let#2=e\else -\ifcat\@IEEEextractedtoken\relax\else% screen out control sequences -\if0\@IEEEextractedtoken\let#2=n\else -\if1\@IEEEextractedtoken\let#2=n\else -\if2\@IEEEextractedtoken\let#2=n\else -\if3\@IEEEextractedtoken\let#2=n\else -\if4\@IEEEextractedtoken\let#2=n\else -\if5\@IEEEextractedtoken\let#2=n\else -\if6\@IEEEextractedtoken\let#2=n\else -\if7\@IEEEextractedtoken\let#2=n\else -\if8\@IEEEextractedtoken\let#2=n\else -\if9\@IEEEextractedtoken\let#2=n\else -\ifcat,\@IEEEextractedtoken\let#2=g\relax -\else\ifcat a\@IEEEextractedtoken\let#2=c\relax\fi\fi\fi\fi\fi\fi\fi\fi\fi\fi\fi\fi\fi\fi -\if#2u\relax -\if0\noexpand#3\relax\else\@IEEEclspkgerror{Invalid character in column specifications}% -{Only letters, numerals and certain other symbols are allowed \MessageBreak -as IEEEeqnarray column specifiers.}\fi\fi} - - -% usage: \@IEEEgetcurcol{col specifier} -% verify the letter referenced column exists -% and return its name in \@IEEEBPcurcolname -% if column specifier is invalid, use the default column @IEEEdefault -\def\@IEEEgetcurcol#1{\expandafter\ifx\csname @IEEEeqnarraycolDEF#1\endcsname\@IEEEeqnarraycolisdefined% -\def\@IEEEBPcurcolname{#1}\else% invalid column name -\@IEEEclspkgerror{Invalid column type "#1" in column specifications.\MessageBreak -Using a default centering column instead}% -{You must define IEEEeqnarray column types before use.}% -\def\@IEEEBPcurcolname{@IEEEdefault}\fi} - - -% usage: \@IEEEgetcurglue{glue specifier}{\output} -% identify the predefined (punctuation) glue value -% and return it in the given output macro -\def\@IEEEgetcurglue#1#2{% -% ! = \! (neg small) -0.16667em (-3/18 em) -% , = \, (small) 0.16667em ( 3/18 em) -% : = \: (med) 0.22222em ( 4/18 em) -% ; = \; (large) 0.27778em ( 5/18 em) -% ' = \quad 1em -% " = \qquad 2em -% . = 0.5\arraycolsep -% / = \arraycolsep -% ? = 2\arraycolsep -% * = 1fil -% + = \@IEEEeqnarraycolSEPcenter -% - = \@IEEEeqnarraycolSEPzero -% Note that all em values are referenced to the math font (textfont2) fontdimen6 -% value for 1em. -% -% use only the very first token to determine the type -\@IEEEextracttoken{#1}\relax -\ifx\@IEEEextractedtokensdiscarded\@empty\else - \typeout{** WARNING: IEEEeqnarray predefined inter-column glue type specifiers after the first in `\@IEEEextracttokenarg' ignored (line \the\inputlineno).}\relax -\fi -% get the math font 1em value -% LaTeX2e's NFSS2 does not preload the fonts, but \IEEEeqnarray needs -% to gain access to the math (\textfont2) font's spacing parameters. -% So we create a bogus box here that uses the math font to ensure -% that \textfont2 is loaded and ready. If this is not done, -% the \textfont2 stuff here may not work. -% Thanks to Bernd Raichle for his 1997 post on this topic. -{\setbox0=\hbox{$\displaystyle\relax$}}% -% fontdimen6 has the width of 1em (a quad). -\@IEEEtrantmpdimenA=\fontdimen6\textfont2\relax% -% identify the glue value based on the first token -% we discard anything after the first -\if!\@IEEEextractedtoken\@IEEEtrantmpdimenA=-0.16667\@IEEEtrantmpdimenA\edef#2{\the\@IEEEtrantmpdimenA}\else -\if,\@IEEEextractedtoken\@IEEEtrantmpdimenA=0.16667\@IEEEtrantmpdimenA\edef#2{\the\@IEEEtrantmpdimenA}\else -\if:\@IEEEextractedtoken\@IEEEtrantmpdimenA=0.22222\@IEEEtrantmpdimenA\edef#2{\the\@IEEEtrantmpdimenA}\else -\if;\@IEEEextractedtoken\@IEEEtrantmpdimenA=0.27778\@IEEEtrantmpdimenA\edef#2{\the\@IEEEtrantmpdimenA}\else -\if'\@IEEEextractedtoken\@IEEEtrantmpdimenA=1\@IEEEtrantmpdimenA\edef#2{\the\@IEEEtrantmpdimenA}\else -\if"\@IEEEextractedtoken\@IEEEtrantmpdimenA=2\@IEEEtrantmpdimenA\edef#2{\the\@IEEEtrantmpdimenA}\else -\if.\@IEEEextractedtoken\@IEEEtrantmpdimenA=0.5\arraycolsep\edef#2{\the\@IEEEtrantmpdimenA}\else -\if/\@IEEEextractedtoken\edef#2{\the\arraycolsep}\else -\if?\@IEEEextractedtoken\@IEEEtrantmpdimenA=2\arraycolsep\edef#2{\the\@IEEEtrantmpdimenA}\else -\if *\@IEEEextractedtoken\edef#2{0pt plus 1fil minus 0pt}\else -\if+\@IEEEextractedtoken\edef#2{\@IEEEeqnarraycolSEPcenter}\else -\if-\@IEEEextractedtoken\edef#2{\@IEEEeqnarraycolSEPzero}\else -\edef#2{\@IEEEeqnarraycolSEPzero}% -\@IEEEclspkgerror{Invalid predefined inter-column glue type "#1" in\MessageBreak -column specifications. Using a default value of\MessageBreak -0pt instead}% -{Only !,:;'"./?*+ and - are valid predefined glue types in the\MessageBreak -IEEEeqnarray column specifications.}\fi\fi\fi\fi\fi\fi\fi\fi\fi\fi\fi\fi} - - -% usage: \@IEEEprocessNcol{digit} -% process a numerical digit from the column specification -% and look up the corresponding user defined glue value -% can transform current type from n to g or a as the user defined glue is acquired -\def\@IEEEprocessNcol#1{\if\@IEEEBPprevtype g% -\@IEEEclspkgerror{Back-to-back inter-column glue specifiers in column\MessageBreak -specifications. Ignoring consecutive glue specifiers\MessageBreak -after the first}% -{You cannot have two or more glue types next to each other\MessageBreak -in the IEEEeqnarray column specifications.}% -\let\@IEEEBPcurtype=a% abort this glue, future digits will be discarded -\@IEEEBPcurnum=0\relax% -\else% if we previously aborted a glue -\if\@IEEEBPprevtype a\@IEEEBPcurnum=0\let\@IEEEBPcurtype=a%maintain digit abortion -\else%acquire this number -% save the previous type before the numerical digits started -\if\@IEEEBPprevtype n\else\let\@IEEEBPprevsavedtype=\@IEEEBPprevtype\fi% -\multiply\@IEEEBPcurnum by 10\relax% -\advance\@IEEEBPcurnum by #1\relax% add in number, \relax is needed to stop TeX's number scan -\if\@IEEEBPnexttype n\else%close acquisition -\expandafter\ifx\csname @IEEEeqnarraycolSEPDEF\expandafter\romannumeral\number\@IEEEBPcurnum\endcsname\@IEEEeqnarraycolisdefined% -\edef\@IEEEBPcurglue{\csname @IEEEeqnarraycolSEP\expandafter\romannumeral\number\@IEEEBPcurnum\endcsname}% -\else%user glue not defined -\@IEEEclspkgerror{Invalid user defined inter-column glue type "\number\@IEEEBPcurnum" in\MessageBreak -column specifications. Using a default value of\MessageBreak -0pt instead}% -{You must define all IEEEeqnarray numerical inter-column glue types via\MessageBreak -\string\IEEEeqnarraydefcolsep \space before they are used in column specifications.}% -\edef\@IEEEBPcurglue{\@IEEEeqnarraycolSEPzero}% -\fi% glue defined or not -\let\@IEEEBPcurtype=g% change the type to reflect the acquired glue -\let\@IEEEBPprevtype=\@IEEEBPprevsavedtype% restore the prev type before this number glue -\@IEEEBPcurnum=0\relax%ready for next acquisition -\fi%close acquisition, get glue -\fi%discard or acquire number -\fi%prevtype glue or not -} - - -% process an acquired glue -% add any acquired column/glue pair to the preamble -\def\@IEEEprocessGcol{\if\@IEEEBPprevtype a\let\@IEEEBPcurtype=a%maintain previous glue abortions -\else -% if this is the start glue, save it, but do nothing else -% as this is not used in the preamble, but before -\if\@IEEEBPprevtype s\edef\@IEEEBPstartglue{\@IEEEBPcurglue}% -\else%not the start glue -\if\@IEEEBPprevtype g%ignore if back to back glues -\@IEEEclspkgerror{Back-to-back inter-column glue specifiers in column\MessageBreak -specifications. Ignoring consecutive glue specifiers\MessageBreak -after the first}% -{You cannot have two or more glue types next to each other\MessageBreak -in the IEEEeqnarray column specifications.}% -\let\@IEEEBPcurtype=a% abort this glue -\else% not a back to back glue -\if\@IEEEBPprevtype c\relax% if the previoustype was a col, add column/glue pair to preamble -\ifnum\@IEEEeqnnumcols>0\relax\@IEEEappendtoksA{&}\fi -\toks0={##}% -% make preamble advance col counter if this environment needs this -\if@advanceIEEEeqncolcnt\@IEEEappendtoksA{\global\advance\@IEEEeqncolcnt by 1\relax}\fi -% insert the column defintion into the preamble, being careful not to expand -% the column definition -\@IEEEappendtoksA{\tabskip=\@IEEEBPcurglue}% -\@IEEEappendNOEXPANDtoksA{\begingroup\csname @IEEEeqnarraycolPRE}% -\@IEEEappendtoksA{\@IEEEBPcurcolname}% -\@IEEEappendNOEXPANDtoksA{\endcsname}% -\@IEEEappendtoksA{\the\toks0}% -\@IEEEappendNOEXPANDtoksA{\relax\relax\relax\relax\relax% -\relax\relax\relax\relax\relax\csname @IEEEeqnarraycolPOST}% -\@IEEEappendtoksA{\@IEEEBPcurcolname}% -\@IEEEappendNOEXPANDtoksA{\endcsname\relax\relax\relax\relax\relax% -\relax\relax\relax\relax\relax\endgroup}% -\advance\@IEEEeqnnumcols by 1\relax%one more column in the preamble -\else% error: non-start glue with no pending column -\@IEEEclspkgerror{Inter-column glue specifier without a prior column\MessageBreak -type in the column specifications. Ignoring this glue\MessageBreak -specifier}% -{Except for the first and last positions, glue can be placed only\MessageBreak -between column types.}% -\let\@IEEEBPcurtype=a% abort this glue -\fi% previous was a column -\fi% back-to-back glues -\fi% is start column glue -\fi% prev type not a -} - - -% process an acquired letter referenced column and, if necessary, add it to the preamble -\def\@IEEEprocessCcol{\if\@IEEEBPnexttype g\else -\if\@IEEEBPnexttype n\else -% we have a column followed by something other than a glue (or numeral glue) -% so we must add this column to the preamble now -\ifnum\@IEEEeqnnumcols>0\relax\@IEEEappendtoksA{&}\fi%col separator for those after the first -\if\@IEEEBPnexttype e\@IEEEappendtoksA{\tabskip=\@IEEEBPendglue\relax}\else%put in end glue -\@IEEEappendtoksA{\tabskip=\@IEEEeqnarraycolSEPdefaultmid\relax}\fi% or default mid glue -\toks0={##}% -% make preamble advance col counter if this environment needs this -\if@advanceIEEEeqncolcnt\@IEEEappendtoksA{\global\advance\@IEEEeqncolcnt by 1\relax}\fi -% insert the column definition into the preamble, being careful not to expand -% the column definition -\@IEEEappendNOEXPANDtoksA{\begingroup\csname @IEEEeqnarraycolPRE}% -\@IEEEappendtoksA{\@IEEEBPcurcolname}% -\@IEEEappendNOEXPANDtoksA{\endcsname}% -\@IEEEappendtoksA{\the\toks0}% -\@IEEEappendNOEXPANDtoksA{\relax\relax\relax\relax\relax% -\relax\relax\relax\relax\relax\csname @IEEEeqnarraycolPOST}% -\@IEEEappendtoksA{\@IEEEBPcurcolname}% -\@IEEEappendNOEXPANDtoksA{\endcsname\relax\relax\relax\relax\relax% -\relax\relax\relax\relax\relax\endgroup}% -\advance\@IEEEeqnnumcols by 1\relax%one more column in the preamble -\fi%next type not numeral -\fi%next type not glue -} - - -%% -%% END OF IEEEeqnarray DEFINITIONS -%% - - - - - -% set up the running headers and footers -% -% header and footer font and size specifications -\def\@IEEEheaderstyle{\normalfont\scriptsize} -\def\@IEEEfooterstyle{\normalfont\scriptsize} -% -% compsoc uses sans-serif headers and footers -\ifCLASSOPTIONcompsoc - \def\@IEEEheaderstyle{\normalfont\sffamily\scriptsize} - \def\@IEEEfooterstyle{\normalfont\sffamily\scriptsize} -\fi - - -% standard page style, ps@headings -\def\ps@headings{% default to standard twoside headers, no footers -% will change later if the mode requires otherwise -\def\@oddhead{\hbox{}\@IEEEheaderstyle\rightmark\hfil\thepage}\relax -\def\@evenhead{\@IEEEheaderstyle\thepage\hfil\leftmark\hbox{}}\relax -\let\@oddfoot\@empty -\let\@evenfoot\@empty -\ifCLASSOPTIONtechnote - % technote twoside - \def\@oddhead{\hbox{}\@IEEEheaderstyle\leftmark\hfil\thepage}\relax - \def\@evenhead{\@IEEEheaderstyle\thepage\hfil\leftmark\hbox{}}\relax -\fi -\ifCLASSOPTIONdraftcls - % draft footers - \def\@oddfoot{\@IEEEfooterstyle\@date\hfil DRAFT}\relax - \def\@evenfoot{\@IEEEfooterstyle DRAFT\hfil\@date}\relax -\fi -% oneside -\if@twoside\else - % standard one side headers - \def\@oddhead{\hbox{}\@IEEEheaderstyle\leftmark\hfil\thepage}\relax - \let\@evenhead\@empty - \ifCLASSOPTIONdraftcls - % oneside draft footers - \def\@oddfoot{\@IEEEfooterstyle\@date\hfil DRAFT}\relax - \let\@evenfoot\@empty - \fi -\fi -% turn off headers for conferences -\ifCLASSOPTIONconference - \let\@oddhead\@empty - \let\@evenhead\@empty -\fi -% turn off footers for draftclsnofoot -\ifCLASSOPTIONdraftclsnofoot - \let\@oddfoot\@empty - \let\@evenfoot\@empty -\fi} - - -% title page style, ps@IEEEtitlepagestyle -\def\ps@IEEEtitlepagestyle{% default title page headers, no footers -\def\@oddhead{\hbox{}\@IEEEheaderstyle\leftmark\hfil\thepage}\relax -\def\@evenhead{\@IEEEheaderstyle\thepage\hfil\leftmark\hbox{}}\relax -\let\@oddfoot\@empty -\let\@evenfoot\@empty -% will change later if the mode requires otherwise -\ifCLASSOPTIONdraftcls - % draft footers - \ifCLASSOPTIONdraftclsnofoot\else - % but only if not draftclsnofoot - \def\@oddfoot{\@IEEEfooterstyle\@date\hfil DRAFT}\relax - \def\@evenfoot{\@IEEEfooterstyle DRAFT\hfil\@date}\relax - \fi -\else - % all nondraft mode footers - \if@IEEEusingpubid - % for title pages that are using a pubid - % do not repeat pubid on the title page if using a peer review cover page - \ifCLASSOPTIONpeerreview\else - % for noncompsoc papers, the pubid uses footnotesize and - % is at the same vertical position as where the last baseline would normally be - \def\@oddfoot{\hbox{}\hss\@IEEEfooterstyle\footnotesize\raisebox{\footskip}[0pt][0pt]{\@IEEEpubid}\hss\hbox{}}\relax - \def\@evenfoot{\hbox{}\hss\@IEEEfooterstyle\footnotesize\raisebox{\footskip}[0pt][0pt]{\@IEEEpubid}\hss\hbox{}}\relax - \ifCLASSOPTIONcompsoc - % for compsoc papers, the pubid is at the same vertical position as the normal footer - \def\@oddfoot{\hbox{}\hss\@IEEEfooterstyle\raisebox{0pt}[0pt][0pt]{\@IEEEpubid}\hss\hbox{}}\relax - \def\@evenfoot{\hbox{}\hss\@IEEEfooterstyle\raisebox{0pt}[0pt][0pt]{\@IEEEpubid}\hss\hbox{}}\relax - \fi - \fi - \fi -\fi -% turn off headers for conferences -\ifCLASSOPTIONconference - \let\@oddhead\@empty - \let\@evenhead\@empty -\fi} - - -% peer review cover page style, ps@IEEEpeerreviewcoverpagestyle -\def\ps@IEEEpeerreviewcoverpagestyle{% default peer review cover no headers, no footers -\let\@oddhead\@empty -\let\@evenhead\@empty -\let\@oddfoot\@empty -\let\@evenfoot\@empty -% will change later if the mode requires otherwise -\ifCLASSOPTIONdraftcls - % draft footers - \ifCLASSOPTIONdraftclsnofoot\else - % but only if not draftclsnofoot - \def\@oddfoot{\@IEEEfooterstyle\@date\hfil DRAFT}\relax - \def\@evenfoot{\@IEEEfooterstyle DRAFT\hfil\@date}\relax - \fi -\else - % all nondraft mode footers - \if@IEEEusingpubid - % for peer review cover pages that are using a pubid - % for noncompsoc papers, the pubid uses footnotesize and - % is at the same vertical position as where the last baseline would normally be - \def\@oddfoot{\hbox{}\hss\@IEEEfooterstyle\footnotesize\raisebox{\footskip}[0pt][0pt]{\@IEEEpubid}\hss\hbox{}}\relax - \def\@evenfoot{\hbox{}\hss\@IEEEfooterstyle\footnotesize\raisebox{\footskip}[0pt][0pt]{\@IEEEpubid}\hss\hbox{}}\relax - \ifCLASSOPTIONcompsoc - % for compsoc papers, the pubid is at the same vertical position as the normal footer - \def\@oddfoot{\hbox{}\hss\@IEEEfooterstyle\raisebox{0pt}[0pt][0pt]{\@IEEEpubid}\hss\hbox{}}\relax - \def\@evenfoot{\hbox{}\hss\@IEEEfooterstyle\raisebox{0pt}[0pt][0pt]{\@IEEEpubid}\hss\hbox{}}\relax - \fi - \fi -\fi} - - - -%% Defines the command for putting the header. -%% Note that all the text is forced into uppercase, if you have some text -%% that needs to be in lower case, for instance et. al., then either manually -%% set \leftmark and \rightmark or use \MakeLowercase{et. al.} within the -%% arguments to \markboth. -%% V1.7b add \protect to work with Babel -\def\markboth#1#2{\def\leftmark{\MakeUppercase{\protect#1}}% -\def\rightmark{\MakeUppercase{\protect#2}}} - -\def\today{\ifcase\month\or - January\or February\or March\or April\or May\or June\or - July\or August\or September\or October\or November\or December\fi - \space\number\day, \number\year} - - - - -%% CITATION AND BIBLIOGRAPHY COMMANDS -%% -%% V1.6 no longer supports the older, nonstandard \shortcite and \citename setup stuff -% -% -% Modify Latex2e \@citex to separate citations with "], [" -\def\@citex[#1]#2{% - \let\@citea\@empty - \@cite{\@for\@citeb:=#2\do - {\@citea\def\@citea{], [}% - \edef\@citeb{\expandafter\@firstofone\@citeb\@empty}% - \if@filesw\immediate\write\@auxout{\string\citation{\@citeb}}\fi - \@ifundefined{b@\@citeb}{\mbox{\reset@font\bfseries ?}% - \G@refundefinedtrue - \@latex@warning - {Citation `\@citeb' on page \thepage \space undefined}}% - {\hbox{\csname b@\@citeb\endcsname}}}}{#1}} - -% V1.6 we create hooks for the optional use of Donald Arseneau's -% cite.sty package. cite.sty is "smart" and will notice that the -% following format controls are already defined and will not -% redefine them. The result will be the proper sorting of the -% citation numbers and auto detection of 3 or more entry "ranges" - -% all in IEEE style: [1], [2], [5]--[7], [12] -% This also allows for an optional note, i.e., \cite[mynote]{..}. -% If the \cite with note has more than one reference, the note will -% be applied to the last of the listed references. It is generally -% desired that if a note is given, only one reference is listed in -% that \cite. -% Thanks to Mr. Arseneau for providing the required format arguments -% to produce the IEEE style. -\def\citepunct{], [} -\def\citedash{]--[} - -% V1.7 default to using same font for urls made by url.sty -\AtBeginDocument{\csname url@samestyle\endcsname} - -% V1.6 class files should always provide these -\def\newblock{\hskip .11em\@plus.33em\@minus.07em} -\let\@openbib@code\@empty -% V1.8b article.cls is now providing these too -% we do not use \@mkboth, nor alter the page style -\newenvironment{theindex} - {\if@twocolumn - \@restonecolfalse - \else - \@restonecoltrue - \fi - \twocolumn[\section*{\indexname}]% - \parindent\z@ - \parskip\z@ \@plus .3\p@\relax - \columnseprule \z@ - \columnsep 35\p@ - \let\item\@idxitem} - {\if@restonecol\onecolumn\else\clearpage\fi} -\newcommand\@idxitem{\par\hangindent 40\p@} -\newcommand\subitem{\@idxitem \hspace*{20\p@}} -\newcommand\subsubitem{\@idxitem \hspace*{30\p@}} -\newcommand\indexspace{\par \vskip 10\p@ \@plus5\p@ \@minus3\p@\relax} - - - -% Provide support for the control entries of IEEEtran.bst V1.00 and later. -% V1.7 optional argument allows for a different aux file to be specified in -% order to handle multiple bibliographies. For example, with multibib.sty: -% \newcites{sec}{Secondary Literature} -% \bstctlcite[@auxoutsec]{BSTcontrolhak} -\def\bstctlcite{\@ifnextchar[{\@bstctlcite}{\@bstctlcite[@auxout]}} -\def\@bstctlcite[#1]#2{\@bsphack - \@for\@citeb:=#2\do{% - \edef\@citeb{\expandafter\@firstofone\@citeb}% - \if@filesw\immediate\write\csname #1\endcsname{\string\citation{\@citeb}}\fi}% - \@esphack} - -% \IEEEnoauxwrite{} allows for citations that do not add to or affect -% the order of the existing citation list. Can be useful for \cite -% within \thanks{}. -\DeclareRobustCommand{\IEEEnoauxwrite}[1]{\relax -\if@filesw -\@fileswfalse -#1\relax\relax\relax\relax\relax -\@fileswtrue -\else -#1\relax\relax\relax\relax\relax -\fi} - -% V1.6 provide a way for a user to execute a command just before -% a given reference number - used to insert a \newpage to balance -% the columns on the last page -\edef\@IEEEtriggerrefnum{0} % the default of zero means that - % the command is not executed -\def\@IEEEtriggercmd{\newpage} - -% allow the user to alter the triggered command -\long\def\IEEEtriggercmd#1{\long\def\@IEEEtriggercmd{#1}} - -% allow user a way to specify the reference number just before the -% command is executed -\def\IEEEtriggeratref#1{\@IEEEtrantmpcountA=#1% -\edef\@IEEEtriggerrefnum{\the\@IEEEtrantmpcountA}}% - -% trigger command at the given reference -\def\@IEEEbibitemprefix{\@IEEEtrantmpcountA=\@IEEEtriggerrefnum\relax% -\advance\@IEEEtrantmpcountA by -1\relax% -\ifnum\c@enumiv=\@IEEEtrantmpcountA\relax\@IEEEtriggercmd\relax\fi} - - -\def\@biblabel#1{[#1]} - -% compsoc journals and conferences left align the reference numbers -\@IEEEcompsoconly{\def\@biblabel#1{[#1]\hfill}} - -% controls bib item spacing -\def\IEEEbibitemsep{0pt plus .5pt} - -\@IEEEcompsocconfonly{\def\IEEEbibitemsep{0.5\baselineskip plus 0.25\baselineskip minus 0.25\baselineskip}} - - -\def\thebibliography#1{\section*{\refname}% - \addcontentsline{toc}{section}{\refname}% - % V1.6 add some rubber space here and provide a command trigger - \footnotesize\vskip 0.3\baselineskip plus 0.1\baselineskip minus 0.1\baselineskip% - \list{\@biblabel{\@arabic\c@enumiv}}% - {\settowidth\labelwidth{\@biblabel{#1}}% - \leftmargin\labelwidth - \advance\leftmargin\labelsep\relax - \itemsep \IEEEbibitemsep\relax - \usecounter{enumiv}% - \let\p@enumiv\@empty - \renewcommand\theenumiv{\@arabic\c@enumiv}}% - \let\@IEEElatexbibitem\bibitem% - \def\bibitem{\@IEEEbibitemprefix\@IEEElatexbibitem}% -\def\newblock{\hskip .11em plus .33em minus .07em}% -% originally: -% \sloppy\clubpenalty4000\widowpenalty4000% -% by adding the \interlinepenalty here, we make it more -% difficult, but not impossible, for LaTeX to break within a reference. -% The IEEE almost never breaks a reference (but they do it more often with -% technotes). You may get an underfull vbox warning around the bibliography, -% but the final result will be much more like what the IEEE will publish. -% MDS 11/2000 -\ifCLASSOPTIONtechnote\sloppy\clubpenalty4000\widowpenalty4000\interlinepenalty100% -\else\sloppy\clubpenalty4000\widowpenalty4000\interlinepenalty500\fi% - \sfcode`\.=1000\relax} -\let\endthebibliography=\endlist - - - - -% TITLE PAGE COMMANDS -% -% -% \IEEEmembership is used to produce the sublargesize italic font used to indicate author -% IEEE membership. compsoc uses a large size sans slant font -\def\IEEEmembership#1{{\@IEEEnotcompsoconly{\sublargesize}\normalfont\@IEEEcompsoconly{\sffamily}\textit{#1}}} - - -% \IEEEauthorrefmark{} produces a footnote type symbol to indicate author affiliation. -% When given an argument of 1 to 9, \IEEEauthorrefmark{} follows the standard LaTeX footnote -% symbol sequence convention. However, for arguments 10 and above, \IEEEauthorrefmark{} -% reverts to using lower case roman numerals, so it cannot overflow. Do note that you -% cannot use \footnotemark[] in place of \IEEEauthorrefmark{} within \author as the footnote -% symbols will have been turned off to prevent \thanks from creating footnote marks. -% \IEEEauthorrefmark{} produces a symbol that appears to LaTeX as having zero vertical -% height - this allows for a more compact line packing, but the user must ensure that -% the interline spacing is large enough to prevent \IEEEauthorrefmark{} from colliding -% with the text above. -% V1.7 make this a robust command -% V1.8 transmag uses an arabic author affiliation symbol -\ifCLASSOPTIONtransmag -\DeclareRobustCommand*{\IEEEauthorrefmark}[1]{\raisebox{0pt}[0pt][0pt]{\textsuperscript{\footnotesize #1}}} -\else -\DeclareRobustCommand*{\IEEEauthorrefmark}[1]{\raisebox{0pt}[0pt][0pt]{\textsuperscript{\footnotesize\ensuremath{\ifcase#1\or *\or \dagger\or \ddagger\or% - \mathsection\or \mathparagraph\or \|\or **\or \dagger\dagger% - \or \ddagger\ddagger \else\textsuperscript{\expandafter\romannumeral#1}\fi}}}} -\fi - - -% FONT CONTROLS AND SPACINGS FOR CONFERENCE MODE AUTHOR NAME AND AFFILIATION BLOCKS -% -% The default font styles for the author name and affiliation blocks (confmode) -\def\@IEEEauthorblockNstyle{\normalfont\@IEEEcompsocnotconfonly{\sffamily}\sublargesize} -\def\@IEEEauthorblockAstyle{\normalfont\@IEEEcompsocnotconfonly{\sffamily}\@IEEEcompsocconfonly{\itshape}\normalsize} -% The default if the user does not use an author block -\def\@IEEEauthordefaulttextstyle{\normalfont\@IEEEcompsocnotconfonly{\sffamily}\sublargesize} - -% adjustment spacing from title (or special paper notice) to author name blocks (confmode) -% can be negative -\def\@IEEEauthorblockconfadjspace{-0.25em} -% compsoc conferences need more space here -\@IEEEcompsocconfonly{\def\@IEEEauthorblockconfadjspace{0.75\@IEEEnormalsizeunitybaselineskip}} - -% spacing between name and affiliation blocks (confmode) -% This can be negative. -% The IEEE doesn't want any added spacing here, but I will leave these -% controls in place in case they ever change their mind. -% Personally, I like 0.75ex. -%\def\@IEEEauthorblockNtopspace{0.75ex} -%\def\@IEEEauthorblockAtopspace{0.75ex} -\def\@IEEEauthorblockNtopspace{0.0ex} -\def\@IEEEauthorblockAtopspace{0.0ex} -\ifCLASSOPTIONtransmag -% transmag uses one line of space above first affiliation block -\def\@IEEEauthorblockAtopspace{1\@IEEEnormalsizeunitybaselineskip} -\fi - -% baseline spacing within name and affiliation blocks (confmode) -% must be positive, spacings below certain values will make -% the position of line of text sensitive to the contents of the -% line above it i.e., whether or not the prior line has descenders, -% subscripts, etc. For this reason it is a good idea to keep -% these above 2.6ex -\def\@IEEEauthorblockNinterlinespace{2.6ex} -\def\@IEEEauthorblockAinterlinespace{2.75ex} - -% This tracks the required strut size. -% See the \@IEEEauthorhalign command for the actual default value used. -\def\@IEEEauthorblockXinterlinespace{2.7ex} - -% variables to retain font size and style across groups -% values given here have no effect as they will be overwritten later -\gdef\@IEEESAVESTATEfontsize{10} -\gdef\@IEEESAVESTATEfontbaselineskip{12} -\gdef\@IEEESAVESTATEfontencoding{OT1} -\gdef\@IEEESAVESTATEfontfamily{ptm} -\gdef\@IEEESAVESTATEfontseries{m} -\gdef\@IEEESAVESTATEfontshape{n} - -% saves the current font attributes -\def\@IEEEcurfontSAVE{\global\let\@IEEESAVESTATEfontsize\f@size% -\global\let\@IEEESAVESTATEfontbaselineskip\f@baselineskip% -\global\let\@IEEESAVESTATEfontencoding\f@encoding% -\global\let\@IEEESAVESTATEfontfamily\f@family% -\global\let\@IEEESAVESTATEfontseries\f@series% -\global\let\@IEEESAVESTATEfontshape\f@shape} - -% restores the saved font attributes -\def\@IEEEcurfontRESTORE{\fontsize{\@IEEESAVESTATEfontsize}{\@IEEESAVESTATEfontbaselineskip}% -\fontencoding{\@IEEESAVESTATEfontencoding}% -\fontfamily{\@IEEESAVESTATEfontfamily}% -\fontseries{\@IEEESAVESTATEfontseries}% -\fontshape{\@IEEESAVESTATEfontshape}% -\selectfont} - - -% variable to indicate if the current block is the first block in the column -\newif\if@IEEEprevauthorblockincol \@IEEEprevauthorblockincolfalse - - -% the command places a strut with height and depth = \@IEEEauthorblockXinterlinespace -% we use this technique to have complete manual control over the spacing of the lines -% within the halign environment. -% We set the below baseline portion at 30%, the above -% baseline portion at 70% of the total length. -% Responds to changes in the document's \baselinestretch -\def\@IEEEauthorstrutrule{\@IEEEtrantmpdimenA\@IEEEauthorblockXinterlinespace% -\@IEEEtrantmpdimenA=\baselinestretch\@IEEEtrantmpdimenA% -\rule[-0.3\@IEEEtrantmpdimenA]{0pt}{\@IEEEtrantmpdimenA}} - - -% blocks to hold the authors' names and affilations. -% Makes formatting easy for conferences -% -% use real definitions in conference mode -% name block -\def\IEEEauthorblockN#1{\relax\@IEEEauthorblockNstyle% set the default text style -\gdef\@IEEEauthorblockXinterlinespace{0pt}% disable strut for spacer row -% the \expandafter hides the \cr in conditional tex, see the array.sty docs -% for details, probably not needed here as the \cr is in a macro -% do a spacer row if needed -\if@IEEEprevauthorblockincol\expandafter\@IEEEauthorblockNtopspaceline\fi -\global\@IEEEprevauthorblockincoltrue% we now have a block in this column -%restore the correct strut value -\gdef\@IEEEauthorblockXinterlinespace{\@IEEEauthorblockNinterlinespace}% -% input the author names -#1% -% end the row if the user did not already -\crcr} -% spacer row for names -\def\@IEEEauthorblockNtopspaceline{\cr\noalign{\vskip\@IEEEauthorblockNtopspace}} -% -% affiliation block -\def\IEEEauthorblockA#1{\relax\@IEEEauthorblockAstyle% set the default text style -\gdef\@IEEEauthorblockXinterlinespace{0pt}%disable strut for spacer row -% the \expandafter hides the \cr in conditional tex, see the array.sty docs -% for details, probably not needed here as the \cr is in a macro -% do a spacer row if needed -\if@IEEEprevauthorblockincol\expandafter\@IEEEauthorblockAtopspaceline\fi -\global\@IEEEprevauthorblockincoltrue% we now have a block in this column -%restore the correct strut value -\gdef\@IEEEauthorblockXinterlinespace{\@IEEEauthorblockAinterlinespace}% -% input the author affiliations -#1% -% end the row if the user did not already -\crcr -% V1.8 transmag does not use any additional affiliation spacing after the first author -\ifCLASSOPTIONtransmag\gdef\@IEEEauthorblockAtopspace{0pt}\fi} - -% spacer row for affiliations -\def\@IEEEauthorblockAtopspaceline{\cr\noalign{\vskip\@IEEEauthorblockAtopspace}} - - -% allow papers to compile even if author blocks are used in modes other -% than conference or peerreviewca. For such cases, we provide dummy blocks. -\ifCLASSOPTIONconference -\else - \ifCLASSOPTIONpeerreviewca\else - % not conference, peerreviewca or transmag mode - \ifCLASSOPTIONtransmag\else - \def\IEEEauthorblockN#1{#1}% - \def\IEEEauthorblockA#1{#1}% - \fi - \fi -\fi - - - -% we provide our own halign so as not to have to depend on tabular -\def\@IEEEauthorhalign{\@IEEEauthordefaulttextstyle% default text style - \lineskip=0pt\relax% disable line spacing - \lineskiplimit=0pt\relax% - \baselineskip=0pt\relax% - \@IEEEcurfontSAVE% save the current font - \mathsurround\z@\relax% no extra spacing around math - \let\\\@IEEEauthorhaligncr% replace newline with halign friendly one - \tabskip=0pt\relax% no column spacing - \everycr{}% ensure no problems here - \@IEEEprevauthorblockincolfalse% no author blocks yet - \def\@IEEEauthorblockXinterlinespace{2.7ex}% default interline space - \vtop\bgroup%vtop box - \halign\bgroup&\relax\hfil\@IEEEcurfontRESTORE\relax ##\relax - \hfil\@IEEEcurfontSAVE\@IEEEauthorstrutrule\cr} - -% ensure last line, exit from halign, close vbox -\def\end@IEEEauthorhalign{\crcr\egroup\egroup} - -% handle bogus star form -\def\@IEEEauthorhaligncr{{\ifnum0=`}\fi\@ifstar{\@@IEEEauthorhaligncr}{\@@IEEEauthorhaligncr}} - -% test and setup the optional argument to \\[] -\def\@@IEEEauthorhaligncr{\@testopt\@@@IEEEauthorhaligncr\z@skip} - -% end the line and do the optional spacer -\def\@@@IEEEauthorhaligncr[#1]{\ifnum0=`{\fi}\cr\noalign{\vskip#1\relax}} - - - -% flag to prevent multiple \and warning messages -\newif\if@IEEEWARNand -\@IEEEWARNandtrue - -% if in conference or peerreviewca modes, we support the use of \and as \author is a -% tabular environment, otherwise we warn the user that \and is invalid -% outside of conference or peerreviewca modes. -\def\and{\relax} % provide a bogus \and that we will then override - -\renewcommand{\and}[1][\relax]{\if@IEEEWARNand\typeout{** WARNING: \noexpand\and is valid only - when in conference or peerreviewca}\typeout{modes (line \the\inputlineno).}\fi\global\@IEEEWARNandfalse} - -\ifCLASSOPTIONconference% -\renewcommand{\and}[1][\hfill]{\end{@IEEEauthorhalign}#1\begin{@IEEEauthorhalign}}% -\fi -\ifCLASSOPTIONpeerreviewca -\renewcommand{\and}[1][\hfill]{\end{@IEEEauthorhalign}#1\begin{@IEEEauthorhalign}}% -\fi -% V1.8 transmag uses conference author format -\ifCLASSOPTIONtransmag -\renewcommand{\and}[1][\hfill]{\end{@IEEEauthorhalign}#1\begin{@IEEEauthorhalign}}% -\fi - -% page clearing command -% based on LaTeX2e's \cleardoublepage, but allows different page styles -% for the inserted blank pages -\def\@IEEEcleardoublepage#1{\clearpage\if@twoside\ifodd\c@page\else -\hbox{}\thispagestyle{#1}\newpage\if@twocolumn\hbox{}\thispagestyle{#1}\newpage\fi\fi\fi} - -% V1.8b hooks to allow adjustment of space above title -\def\IEEEtitletopspace{0.5\baselineskip} -% an added extra amount to allow for adjustment/offset -\def\IEEEtitletopspaceextra{0pt} - -% user command to invoke the title page -\def\maketitle{\par% - \begingroup% - \normalfont% - \def\thefootnote{}% the \thanks{} mark type is empty - \def\footnotemark{}% and kill space from \thanks within author - \let\@makefnmark\relax% V1.7, must *really* kill footnotemark to remove all \textsuperscript spacing as well. - \footnotesize% equal spacing between thanks lines - \footnotesep 0.7\baselineskip%see global setting of \footnotesep for more info - % V1.7 disable \thanks note indention for compsoc - \@IEEEcompsoconly{\long\def\@makefntext##1{\parindent 1em\noindent\hbox{\@makefnmark}##1}}% - \normalsize% - \ifCLASSOPTIONpeerreview - \newpage\global\@topnum\z@ \@maketitle\@IEEEstatictitlevskip\@IEEEaftertitletext% - \thispagestyle{IEEEpeerreviewcoverpagestyle}\@thanks% - \else - \if@twocolumn% - \ifCLASSOPTIONtechnote% - \newpage\global\@topnum\z@ \@maketitle\@IEEEstatictitlevskip\@IEEEaftertitletext% - \else - \twocolumn[{\IEEEquantizevspace{\@maketitle}[\IEEEquantizedisabletitlecmds]{0pt}[-\topskip]{\baselineskip}{\@IEEENORMtitlevspace}{\@IEEEMINtitlevspace}\@IEEEaftertitletext}]% - \fi - \else - \newpage\global\@topnum\z@ \@maketitle\@IEEEstatictitlevskip\@IEEEaftertitletext% - \fi - \thispagestyle{IEEEtitlepagestyle}\@thanks% - \fi - % pullup page for pubid if used. - \if@IEEEusingpubid - \enlargethispage{-\@IEEEpubidpullup}% - \fi - \endgroup - \setcounter{footnote}{0}\let\maketitle\relax\let\@maketitle\relax - \gdef\@thanks{}% - % v1.6b do not clear these as we will need the title again for peer review papers - % \gdef\@author{}\gdef\@title{}% - \let\thanks\relax} - - -% V1.8 parbox to format \@IEEEtitleabstractindextext -\long\def\@IEEEtitleabstractindextextbox#1{\parbox{1\textwidth}{#1}} -% V1.8 compsoc is partial width -\ifCLASSOPTIONcompsoc -% comparison with proofs suggests it's in the range of 92.1-92.3% -\long\def\@IEEEtitleabstractindextextbox#1{\parbox{0.922\textwidth}{\@IEEEcompsocnotconfonly{\rightskip\@flushglue\leftskip\z@skip}#1}} -\fi - -% formats the Title, authors names, affiliations and special paper notice -% THIS IS A CONTROLLED SPACING COMMAND! Do not allow blank lines or unintentional -% spaces to enter the definition - use % at the end of each line -\def\@maketitle{\newpage -\bgroup\par\vskip\IEEEtitletopspace\vskip\IEEEtitletopspaceextra\centering% -\ifCLASSOPTIONtechnote% technotes, V1.8a abstract and index terms are not treated differently for compsoc technotes - {\bfseries\large\@IEEEcompsoconly{\Large\sffamily}\@title\par}\vskip 1.3em{\lineskip .5em\@IEEEcompsoconly{\large\sffamily}\@author - \@IEEEspecialpapernotice\par}\relax -\else% not a technote - \vskip0.2em{\Huge\ifCLASSOPTIONtransmag\bfseries\LARGE\fi\@IEEEcompsoconly{\sffamily}\@IEEEcompsocconfonly{\normalfont\normalsize\vskip 2\@IEEEnormalsizeunitybaselineskip - \bfseries\Large}\@IEEEcompsocnotconfonly{\vskip 0.75\@IEEEnormalsizeunitybaselineskip}\@title\par}\relax - \@IEEEcompsocnotconfonly{\vskip 0.5\@IEEEnormalsizeunitybaselineskip}\vskip1.0em\par% - % V1.6 handle \author differently if in conference mode - \ifCLASSOPTIONconference% - {\@IEEEspecialpapernotice\mbox{}\vskip\@IEEEauthorblockconfadjspace% - \mbox{}\hfill\begin{@IEEEauthorhalign}\@author\end{@IEEEauthorhalign}\hfill\mbox{}\par}\relax - \else% peerreviewca, peerreview or journal - \ifCLASSOPTIONpeerreviewca - % peerreviewca handles author names just like conference mode - {\@IEEEcompsoconly{\sffamily}\@IEEEspecialpapernotice\mbox{}\vskip\@IEEEauthorblockconfadjspace% - \mbox{}\hfill\begin{@IEEEauthorhalign}\@author\end{@IEEEauthorhalign}\hfill\mbox{}\par - {\@IEEEcompsoconly{\vskip 1.5em\relax - \@IEEEtitleabstractindextextbox{\@IEEEtitleabstractindextext}\par\noindent\hfill - \IEEEcompsocdiamondline\hfill\hbox{}\par}}}\relax - \else% journal, peerreview or transmag - \ifCLASSOPTIONtransmag - % transmag also handles author names just like conference mode - % it also uses \@IEEEtitleabstractindextex, but with one line less - % space above, and one more below - {\@IEEEspecialpapernotice\mbox{}\vskip\@IEEEauthorblockconfadjspace% - \mbox{}\hfill\begin{@IEEEauthorhalign}\@author\end{@IEEEauthorhalign}\hfill\mbox{}\par - {\vspace{0.5\baselineskip}\relax\@IEEEtitleabstractindextextbox{\@IEEEtitleabstractindextext}\vspace{-1\baselineskip}\par}}\relax - \else% journal or peerreview - {\lineskip.5em\@IEEEcompsoconly{\sffamily}\sublargesize\@author\@IEEEspecialpapernotice\par - {\@IEEEcompsoconly{\vskip 1.5em\relax - \@IEEEtitleabstractindextextbox{\@IEEEtitleabstractindextext}\par\noindent\hfill - \IEEEcompsocdiamondline\hfill\hbox{}\par}}}\relax - \fi - \fi - \fi -\fi\par\addvspace{0.5\baselineskip}\egroup} - - -% V1.7 Computer Society "diamond line" which follows index terms for nonconference papers -% V1.8a full width diamond line for single column use -\def\@IEEEcompsocdiamondlinei{\vrule depth 0pt height 0.5pt width 4cm\nobreak\hspace{7.5pt}\nobreak -\raisebox{-3.5pt}{\fontfamily{pzd}\fontencoding{U}\fontseries{m}\fontshape{n}\fontsize{11}{12}\selectfont\char70}\nobreak -\hspace{7.5pt}\nobreak\vrule depth 0pt height 0.5pt width 4cm\relax} -% V1.8a narrower width diamond line for double column use -\def\@IEEEcompsocdiamondlineii{\vrule depth 0pt height 0.5pt width 2.5cm\nobreak\hspace{7.5pt}\nobreak -\raisebox{-3.5pt}{\fontfamily{pzd}\fontencoding{U}\fontseries{m}\fontshape{n}\fontsize{11}{12}\selectfont\char70}\nobreak -\hspace{7.5pt}\nobreak\vrule depth 0pt height 0.5pt width 2.5cm\relax} -% V1.8a bare core without rules to base a last resort on for very narrow linewidths -\def\@IEEEcompsocdiamondlineiii{\mbox{}\nobreak\hspace{7.5pt}\nobreak -\raisebox{-3.5pt}{\fontfamily{pzd}\fontencoding{U}\fontseries{m}\fontshape{n}\fontsize{11}{12}\selectfont\char70}\nobreak -\hspace{7.5pt}\nobreak\mbox{}\relax} - -% V1.8a allow \IEEEcompsocdiamondline to adjust for different linewidths. -% Use \@IEEEcompsocdiamondlinei if its width is less than 0.66\linewidth (0.487 nominal for single column) -% if not, fall back to \@IEEEcompsocdiamondlineii if its width is less than 0.75\linewidth (0.659 nominal for double column) -% if all else fails, try to make a custom diamondline based on the abnormally narrow linewidth -\def\IEEEcompsocdiamondline{\settowidth{\@IEEEtrantmpdimenA}{\@IEEEcompsocdiamondlinei}\relax -\ifdim\@IEEEtrantmpdimenA<0.66\linewidth\relax\@IEEEcompsocdiamondlinei\relax -\else -\settowidth{\@IEEEtrantmpdimenA}{\@IEEEcompsocdiamondlineii}\relax -\ifdim\@IEEEtrantmpdimenA<0.75\linewidth\relax\@IEEEcompsocdiamondlineii\relax -\else -\settowidth{\@IEEEtrantmpdimenA}{\@IEEEcompsocdiamondlineiii}\relax -\@IEEEtrantmpdimenB=\linewidth\relax -\addtolength{\@IEEEtrantmpdimenB}{-1\@IEEEtrantmpdimenA}\relax -\vrule depth 0pt height 0.5pt width 0.33\@IEEEtrantmpdimenB\@IEEEcompsocdiamondlineiii\vrule depth 0pt height 0.5pt width 0.33\@IEEEtrantmpdimenB\relax -\fi\fi} - - -% V1.7 standard LateX2e \thanks, but with \itshape under compsoc. Also make it a \long\def -% We also need to trigger the one-shot footnote rule -\def\@IEEEtriggeroneshotfootnoterule{\global\@IEEEenableoneshotfootnoteruletrue} - - -\long\def\thanks#1{\footnotemark - \protected@xdef\@thanks{\@thanks - \protect\footnotetext[\the\c@footnote]{\@IEEEcompsoconly{\itshape - \protect\@IEEEtriggeroneshotfootnoterule\relax}\ignorespaces#1}}} -\let\@thanks\@empty - - -% V1.7 allow \author to contain \par's. This is needed to allow \thanks to contain \par. -\long\def\author#1{\gdef\@author{#1}} - - -% in addition to setting up IEEEitemize, we need to remove a baselineskip space above and -% below it because \list's \pars introduce blank lines because of the footnote struts. -\def\@IEEEsetupcompsocitemizelist{\def\labelitemi{$\bullet$}% -\setlength{\IEEElabelindent}{0pt}\setlength{\labelsep}{1.2em}\setlength{\parskip}{0pt}% -\setlength{\partopsep}{0pt}\setlength{\topsep}{0.5\baselineskip}\vspace{-1\baselineskip}\relax} - - -% flag for fake non-compsoc \IEEEcompsocthanksitem - prevents line break on very first item -\newif\if@IEEEbreakcompsocthanksitem \@IEEEbreakcompsocthanksitemfalse - -\ifCLASSOPTIONcompsoc -% V1.7 compsoc bullet item \thanks -% also, we need to redefine this to destroy the argument in \IEEEquantizevspace -\long\def\IEEEcompsocitemizethanks#1{\relax\@IEEEbreakcompsocthanksitemfalse\footnotemark - \protected@xdef\@thanks{\@thanks - \protect\footnotetext[\the\c@footnote]{\itshape\protect\@IEEEtriggeroneshotfootnoterule - {\let\IEEEiedlistdecl\relax\protect\begin{IEEEitemize}[\protect\@IEEEsetupcompsocitemizelist]\ignorespaces#1\relax - \protect\end{IEEEitemize}}\protect\vspace{-1\baselineskip}}}} -\DeclareRobustCommand*{\IEEEcompsocthanksitem}{\item} -\else -% non-compsoc, allow for dual compilation via rerouting to normal \thanks -\long\def\IEEEcompsocitemizethanks#1{\thanks{#1}} -% redirect to "pseudo-par" \hfil\break\indent after swallowing [] from \IEEEcompsocthanksitem[] -\DeclareRobustCommand{\IEEEcompsocthanksitem}{\@ifnextchar [{\@IEEEthanksswallowoptionalarg}% -{\@IEEEthanksswallowoptionalarg[\relax]}} -% be sure and break only after first item, be sure and ignore spaces after optional argument -\def\@IEEEthanksswallowoptionalarg[#1]{\relax\if@IEEEbreakcompsocthanksitem\hfil\break -\indent\fi\@IEEEbreakcompsocthanksitemtrue\ignorespaces} -\fi - - -% V1.6b define the \IEEEpeerreviewmaketitle as needed -\ifCLASSOPTIONpeerreview -\def\IEEEpeerreviewmaketitle{\@IEEEcleardoublepage{empty}% -\ifCLASSOPTIONtwocolumn -\twocolumn[{\IEEEquantizevspace{\@IEEEpeerreviewmaketitle}[\IEEEquantizedisabletitlecmds]{0pt}[-\topskip]{\baselineskip}{\@IEEENORMtitlevspace}{\@IEEEMINtitlevspace}}] -\else -\newpage\@IEEEpeerreviewmaketitle\@IEEEstatictitlevskip -\fi -\thispagestyle{IEEEtitlepagestyle}} -\else -% \IEEEpeerreviewmaketitle does nothing if peer review option has not been selected -\def\IEEEpeerreviewmaketitle{\relax} -\fi - -% peerreview formats the repeated title like the title in journal papers. -\def\@IEEEpeerreviewmaketitle{\bgroup\par\addvspace{0.5\baselineskip}\centering\@IEEEcompsoconly{\sffamily}% -\normalfont\normalsize\vskip0.2em{\Huge\@title\par}\vskip1.0em\par -\par\addvspace{0.5\baselineskip}\egroup} - - - -% V1.6 -% this is a static rubber spacer between the title/authors and the main text -% used for single column text, or when the title appears in the first column -% of two column text (technotes). -\def\@IEEEstatictitlevskip{{\normalfont\normalsize -% adjust spacing to next text -% v1.6b handle peer review papers -\ifCLASSOPTIONpeerreview -% for peer review papers, the same value is used for both title pages -% regardless of the other paper modes - \vskip 1\baselineskip plus 0.375\baselineskip minus 0.1875\baselineskip -\else - \ifCLASSOPTIONconference% conference - \vskip 1\baselineskip plus 0.375\baselineskip minus 0.1875\baselineskip% - \else% - \ifCLASSOPTIONtechnote% technote - \vskip 1\baselineskip plus 0.375\baselineskip minus 0.1875\baselineskip% - \else% journal uses more space - \vskip 2.5\baselineskip plus 0.75\baselineskip minus 0.375\baselineskip% - \fi - \fi -\fi}} - - -% set the nominal and minimum values for the quantized title spacer -% the quantization algorithm will not allow the spacer size to -% become less than \@IEEEMINtitlevspace - instead it will be lengthened -% default to journal values -\def\@IEEENORMtitlevspace{2.5\baselineskip} -\def\@IEEEMINtitlevspace{2\baselineskip} -% conferences and technotes need tighter spacing -\ifCLASSOPTIONconference% conference - \def\@IEEENORMtitlevspace{1\baselineskip} - \def\@IEEEMINtitlevspace{0.75\baselineskip} -\fi -\ifCLASSOPTIONtechnote% technote - \def\@IEEENORMtitlevspace{1\baselineskip} - \def\@IEEEMINtitlevspace{0.75\baselineskip} -\fi - - -% V1.8a -\def\IEEEquantizevspace{\begingroup\@ifstar{\@IEEEquantizevspacestarformtrue\@IEEEquantizevspace}{\@IEEEquantizevspacestarformfalse\@IEEEquantizevspace}} -% \IEEEquantizevspace[output dimen register]{object}[object decl] -% {top baselineskip} -% [offset][prevdepth][lineskip limit][lineskip] -% {unit height}{nominal vspace}{minimum vspace} -% -% Calculates and creates the vspace needed to make the combined height with -% the given object an integer multiple of the given unit height. This command -% is more general than the older \@IEEEdynamictitlevspace it replaces. -% -% The star form has no effect at present, but is reserved for future use. -% -% If the optional argument [output dimen register] is given, the calculated -% vspace height is stored in the given output dimen (or skip) register -% and no other action is taken, otherwise the object followed by a vspace* -% of the appropriate height is evaluated/output. -% -% The optional object decl (declarations) is code that is evaluated just -% before the object's height is evaluated. Its intented purpose is to allow -% for the alteration or disabling of code within the object during internal -% height evaluation (e.g., \long\def\thanks#1{\relax} ). -% This special code is not invoked if/when the object is rendered at the end. -% -% The nominal vspace is the target value of the added vspace and the minimum -% vspace is the lower allowed limit. The vspacer will be the value that achieves -% integral overall height, in terms of the given unit height, that is closest -% to the nominal vspace and that is not less than the specified minimum vspace. -% -% The line spacing algorithm of TeX is somewhat involved and requires special -% care with regard to the first line of a vertical list (which is indicated -% when \prevdepth is -1000pt or less). top baselineskip specifies the -% baselineskip or topskip used prior to the object. If the height of the -% first line of the object is greater than the given top baselineskip, then -% the top baselineskip is subtracted from the height of the first line and -% that difference is considered along with the rest of the object height -% (because the object will be shifted down by an amount = -% top line height - top baselineskip). Otherwise, the height of the first line -% of the object is ignored as far as the calculations are concerned. -% This algorithm is adequate for objects that appear at the top of a page -% (e.g., titles) where \topskip spacing is used. -% -% However, as explained on page 78 of the TeXbook, interline spacing is more -% complex when \baselineskip is being used (indicated by \prevdepth > -% -1000pt). The four optional parameters offset, prevdepth, lineskip limit and -% lineskip are assumed to be equal to be 0pt, \prevdepth, \lineskiplimit and -% \lineskip, respectively, if they are omitted. -% -% The prevdepth is the depth of the line before the object, the lineskip limit -% specifies how close the top of the object can come to the bottom of the -% previous line before \baselineskip is ignored and \lineskip is inserted -% between the object and the line above it. Lineskip does not come into -% play unless the first line of the object is high enough to "get too close" -% (as specified by lineskiplimit) to the line before it. The the prevdepth, -% lineskip limit, and lineskip optional parameters are not needed for the -% first object/line on a page (i.e., prevdepth <= -1000pt) where the simplier -% \topskip spacing rules are in effect. -% -% Offset is a manual adjustment that is added to the height calculations of -% object irrespective of the value of \prevdepth. It is useful when the top -% baselineskip will result in a noninteger unit height object placement even -% if the object itself has integral height. e.g., a footnotesize baselineskip -% is used before the object, thus an offset of, say -3pt, can be given as a -% correction. - -% Common combinations of these parameters include: -% -% top baselineskip: (and default values for offset, prevdepth, etc.) -% \topskip % for objects that appear at the top of a page -% \maxdimen % always ignore the height of the top line -% 0pt % always consider any positive height of the top line -% -% for objects to appear inline in normal text: -% top baselineskip = \baselineskip -% -% set prevdepth = -1000pt and top baselineskip = 0pt to consider the -% overall height of the object without any other external skip -% consideration - -\newif\if@IEEEquantizevspacestarform % flag to indicate star form -\newif\if@IEEEquantizevspaceuseoutdimenreg % flag to indicate output dimen register is to be used -% Use our own private registers because the object could contain a -% structure that uses the existing tmp scratch pad registers -\newdimen\@IEEEquantizeheightA -\newdimen\@IEEEquantizeheightB -\newdimen\@IEEEquantizeheightC -\newdimen\@IEEEquantizeprevdepth % need to save this early as can change -\newcount\@IEEEquantizemultiple -\newbox\@IEEEquantizeboxA - - -\def\@IEEEquantizevspace{\@ifnextchar [{\@IEEEquantizevspaceuseoutdimenregtrue\@@IEEEquantizevspace}{\@IEEEquantizevspaceuseoutdimenregfalse\@@IEEEquantizevspace[]}} - - -\long\def\@@IEEEquantizevspace[#1]#2{\relax -% acquire and store -% #1 optional output dimen register -% #2 object -\edef\@IEEEquantizeoutdimenreg{#1}\relax -% allow for object specifications that contain parameters -\@IEEEtrantmptoksA={#2}\relax -\long\edef\@IEEEquantizeobject{\the\@IEEEtrantmptoksA}\relax -\@ifnextchar [{\@@@IEEEquantizevspace}{\@@@IEEEquantizevspace[\relax]}} - -\long\def\@@@IEEEquantizevspace[#1]#2{\relax -% acquire and store -% [#1] optional object decl, is \relax if not given by user -% #2 top baselineskip -% allow for object decl specifications that have parameters -\@IEEEtrantmptoksA={#1}\relax -\long\edef\@IEEEquantizeobjectdecl{\the\@IEEEtrantmptoksA}\relax -\edef\@IEEEquantizetopbaselineskip{#2}\ivIEEEquantizevspace} - -% acquire optional argument set and store -% [offset][prevdepth][lineskip limit][lineskip] -\def\ivIEEEquantizevspace{\@ifnextchar [{\@vIEEEquantizevspace}{\@vIEEEquantizevspace[0pt]}} -\def\@vIEEEquantizevspace[#1]{\edef\@IEEEquantizeoffset{#1}\@ifnextchar [{\@viIEEEquantizevspace}{\@viIEEEquantizevspace[\prevdepth]}} -\def\@viIEEEquantizevspace[#1]{\@IEEEquantizeprevdepth=#1\relax\@ifnextchar [{\@viiIEEEquantizevspace}{\@viiIEEEquantizevspace[\lineskiplimit]}} -\def\@viiIEEEquantizevspace[#1]{\edef\@IEEEquantizelineskiplimit{#1}\@ifnextchar [{\@viiiIEEEquantizevspace}{\@viiiIEEEquantizevspace[\lineskip]}} -\def\@viiiIEEEquantizevspace[#1]{\edef\@IEEEquantizelineskip{#1}\@ixIEEEquantizevspace} - -% main routine -\def\@ixIEEEquantizevspace#1#2#3{\relax -\edef\@IEEEquantizeunitheight{#1}\relax -\edef\@IEEEquantizenomvspace{#2}\relax -\edef\@IEEEquantizeminvspace{#3}\relax -% \@IEEEquantizeoutdimenreg -% \@IEEEquantizeobject -% \@IEEEquantizeobjectdecl -% \@IEEEquantizetopbaselineskip -% \@IEEEquantizeoffset -% \@IEEEquantizeprevdepth -% \@IEEEquantizelineskiplimit -% \@IEEEquantizelineskip -% \@IEEEquantizeunitheight -% \@IEEEquantizenomvspace -% \@IEEEquantizeminvspace -% get overall height of object -\setbox\@IEEEquantizeboxA\vbox{\begingroup\@IEEEquantizeobjectdecl\@IEEEquantizeobject\relax\endgroup}\relax -\@IEEEquantizeheightA\ht\@IEEEquantizeboxA\relax -% get height of first line of object -\setbox\@IEEEquantizeboxA\vtop{\begingroup\@IEEEquantizeobjectdecl\@IEEEquantizeobject\relax\endgroup}\relax -\@IEEEquantizeheightB\ht\@IEEEquantizeboxA\relax -\ifdim\@IEEEquantizeprevdepth>-1000pt\relax % prevdepth > -1000pf means full baselineskip\lineskip rules in effect -% lineskip spacing rule takes effect if height of top line > baselineskip - prevdepth - lineskiplimit, -% otherwise the baselineskip rule is in effect and the height of the first line does not matter at all. -\@IEEEquantizeheightC=\@IEEEquantizetopbaselineskip\relax -\advance\@IEEEquantizeheightC-\@IEEEquantizeprevdepth\relax -\advance\@IEEEquantizeheightC-\@IEEEquantizelineskiplimit\relax % this works even though \@IEEEquantizelineskiplimit is a macro because TeX allows --10pt notation -\ifdim\@IEEEquantizeheightB>\@IEEEquantizeheightC\relax -% lineskip spacing rule is in effect i.e., the object is going to be shifted down relative to the -% baselineskip set position by its top line height (already a part of the total height) + prevdepth + lineskip - baselineskip -\advance\@IEEEquantizeheightA\@IEEEquantizeprevdepth\relax -\advance\@IEEEquantizeheightA\@IEEEquantizelineskip\relax -\advance\@IEEEquantizeheightA-\@IEEEquantizetopbaselineskip\relax -\else -% height of first line <= \@IEEEquantizetopbaselineskip - \@IEEEquantizeprevdepth - \@IEEEquantizelineskiplimit -% standard baselineskip rules are in effect, so don't consider height of first line -\advance\@IEEEquantizeheightA-\@IEEEquantizeheightB\relax -\fi -% -\else % prevdepth <= -1000pt, simplier \topskip type rules in effect -\ifdim\@IEEEquantizeheightB>\@IEEEquantizetopbaselineskip -% height of top line (already included in the total height) in excess of -% baselineskip is the amount it will be downshifted -\advance\@IEEEquantizeheightA-\@IEEEquantizetopbaselineskip\relax -\else -% height of first line is irrelevant, remove it -\advance\@IEEEquantizeheightA-\@IEEEquantizeheightB\relax -\fi -\fi % prevdepth <= -1000pt -% -% adjust height for any manual offset -\advance\@IEEEquantizeheightA\@IEEEquantizeoffset\relax -% add in nominal spacer -\advance\@IEEEquantizeheightA\@IEEEquantizenomvspace\relax -% check for nonzero unitheight -\@IEEEquantizeheightB=\@IEEEquantizeunitheight\relax -\ifnum\@IEEEquantizeheightB=0\relax -\@IEEEclspkgerror{IEEEquantizevspace unit height cannot be zero. Assuming 10pt.}% -{Division by zero is not allowed.} -\@IEEEquantizeheightB=10pt\relax -\fi -% get integer number of lines -\@IEEEquantizemultiple=\@IEEEquantizeheightA\relax -\divide\@IEEEquantizemultiple\@IEEEquantizeheightB\relax -% set A to contain the excess height over the \@IEEEquantizemultiple of lines -% A = height - multiple*unitheight -\@IEEEquantizeheightC\@IEEEquantizeheightB\relax -\multiply\@IEEEquantizeheightC\@IEEEquantizemultiple\relax -\advance\@IEEEquantizeheightA-\@IEEEquantizeheightC\relax -% set B to contain the height short of \@IEEEquantizemultiple+1 of lines -% B = unitheight - A -\advance\@IEEEquantizeheightB-\@IEEEquantizeheightA\relax -% choose A or B based on which is closer -\@IEEEquantizeheightC\@IEEEquantizenomvspace\relax -\ifdim\@IEEEquantizeheightA<\@IEEEquantizeheightB\relax -% C = nomvspace - A, go with lower -\advance\@IEEEquantizeheightC-\@IEEEquantizeheightA\relax -\else -% C = nomvspace + B, go with upper -\advance\@IEEEquantizeheightC\@IEEEquantizeheightB\relax -\fi -% if violate lower bound, use next integer bound -\ifdim\@IEEEquantizeheightC<\@IEEEquantizeminvspace\relax -% A + B = unitheight -\advance\@IEEEquantizeheightC\@IEEEquantizeheightA\relax -\advance\@IEEEquantizeheightC\@IEEEquantizeheightB\relax -\fi -% export object and spacer outside of group -\global\let\@IEEEquantizeobjectout\@IEEEquantizeobject\relax -\global\@IEEEquantizeheightC\@IEEEquantizeheightC\relax -\endgroup -\if@IEEEquantizevspaceuseoutdimenreg -\@IEEEquantizeoutdimenreg=\@IEEEquantizeheightC\relax -\else -\@IEEEquantizeobjectout\relax -\vskip\@IEEEquantizeheightC\relax -\fi} - - -% user command to disable all global assignments, possible use within object decl -\def\IEEEquantizedisableglobal{\let\global\relax -\let\gdef\def -\let\xdef\edef} -% user command to allow for the disabling of \thanks and other commands, possible use within object decl -\def\IEEEquantizedisabletitlecmds{\long\def\thanks##1{\relax}\relax -\long\def\IEEEcompsocitemizethanks##1{\relax}\def\newpage{\relax}} - - - - - -% V1.6 -% we allow the user access to the last part of the title area -% useful in emergencies such as when a different spacing is needed -% This text is NOT compensated for in the dynamic sizer. -\let\@IEEEaftertitletext=\relax -\long\def\IEEEaftertitletext#1{\def\@IEEEaftertitletext{#1}} - - -% V1.7 provide a way for users to enter abstract and keywords -% into the onecolumn title are. This text is compensated for -% in the dynamic sizer. -\let\@IEEEtitleabstractindextext=\relax -\long\def\IEEEtitleabstractindextext#1{\def\@IEEEtitleabstractindextext{#1}} - -% V1.7 provide a way for users to get the \@IEEEtitleabstractindextext if -% not in compsoc or transmag journal mode - this way abstract and keywords -% can still be placed in their conventional position if not in those modes. -\def\IEEEdisplaynontitleabstractindextext{% -% display for all conference formats -\ifCLASSOPTIONconference\@IEEEtitleabstractindextext\relax -\else% non-conferences - % V1.8a display for all technotes - \ifCLASSOPTIONtechnote\@IEEEtitleabstractindextext\relax - % V1.8a add diamond line after abstract and index terms for compsoc technotes - \@IEEEcompsoconly{\noindent\hfill\IEEEcompsocdiamondline\hfill\hbox{}\par}\relax - \else % non-conferences and non-technotes - \ifCLASSOPTIONcompsoc% display if not compsoc and not transmag - \else - \ifCLASSOPTIONtransmag - \else% not compsoc journal nor transmag journal - \@IEEEtitleabstractindextext\relax - \fi - \fi - \fi -\fi} - - -% command to allow alteration of baselinestretch, but only if the current -% baselineskip is unity. Used to tweak the compsoc abstract and keywords line spacing. -\def\@IEEEtweakunitybaselinestretch#1{{\def\baselinestretch{1}\selectfont -\global\@tempskipa\baselineskip}\ifnum\@tempskipa=\baselineskip% -\def\baselinestretch{#1}\selectfont\fi\relax} - - -% abstract and keywords are in \small, except -% for 9pt docs in which they are in \footnotesize -% Because 9pt docs use an 8pt footnotesize, \small -% becomes a rather awkward 8.5pt -\def\@IEEEabskeysecsize{\small} -\ifx\CLASSOPTIONpt\@IEEEptsizenine - \def\@IEEEabskeysecsize{\footnotesize} -\fi - -% compsoc journals use \footnotesize, compsoc conferences use normalsize -\@IEEEcompsoconly{\def\@IEEEabskeysecsize{\footnotesize}} -\@IEEEcompsocconfonly{\def\@IEEEabskeysecsize{\small}} - - -% V1.6 have abstract and keywords strip leading spaces, pars and newlines -% so that spacing is more tightly controlled. -\def\abstract{\normalfont - \if@twocolumn - \@IEEEabskeysecsize\bfseries\textit{\abstractname}---\relax - \else - \bgroup\par\addvspace{0.5\baselineskip}\centering\vspace{-1.78ex}\@IEEEabskeysecsize\textbf{\abstractname}\par\addvspace{0.5\baselineskip}\egroup\quotation\@IEEEabskeysecsize - \fi\@IEEEgobbleleadPARNLSP} -% V1.6 The IEEE wants only 1 pica from end of abstract to introduction heading when in -% conference mode (the heading already has this much above it) -\def\endabstract{\relax\ifCLASSOPTIONconference\vspace{0ex}\else\vspace{1.34ex}\fi\par\if@twocolumn\else\endquotation\fi - \normalfont\normalsize} - -\def\IEEEkeywords{\normalfont - \if@twocolumn - \@IEEEabskeysecsize\bfseries\textit{\IEEEkeywordsname}---\relax - \else - \bgroup\par\addvspace{0.5\baselineskip}\centering\@IEEEabskeysecsize\textbf{\IEEEkeywordsname}\par\addvspace{0.5\baselineskip}\egroup\quotation\@IEEEabskeysecsize - \fi\@IEEEgobbleleadPARNLSP} -\def\endIEEEkeywords{\relax\ifCLASSOPTIONtechnote\vspace{1.34ex}\else\vspace{0.67ex}\fi - \par\if@twocolumn\else\endquotation\fi% - \normalfont\normalsize} - -% V1.7 compsoc keywords index terms -\ifCLASSOPTIONcompsoc - \ifCLASSOPTIONconference% compsoc conference -\def\abstract{\normalfont\@IEEEtweakunitybaselinestretch{1.15}\bfseries - \if@twocolumn - \@IEEEabskeysecsize\noindent\textit{\abstractname}---\relax - \else - \bgroup\par\addvspace{0.5\baselineskip}\centering\vspace{-1.78ex}\@IEEEabskeysecsize\textbf{\abstractname}\par\addvspace{0.5\baselineskip}\egroup\quotation\@IEEEabskeysecsize% - \fi\@IEEEgobbleleadPARNLSP} -\def\IEEEkeywords{\normalfont\@IEEEtweakunitybaselinestretch{1.15}\bfseries - \if@twocolumn - \@IEEEabskeysecsize\vskip 0.5\baselineskip plus 0.25\baselineskip minus 0.25\baselineskip\noindent - \textit{\IEEEkeywordsname}---\relax - \else - \bgroup\par\addvspace{0.5\baselineskip}\centering\@IEEEabskeysecsize\textbf{\IEEEkeywordsname}\par\addvspace{0.5\baselineskip}\egroup\quotation\@IEEEabskeysecsize% - \fi\@IEEEgobbleleadPARNLSP} - \else% compsoc not conference -\def\abstract{\normalfont\@IEEEtweakunitybaselinestretch{1.15}\sffamily - \if@twocolumn - \@IEEEabskeysecsize\noindent\textbf{\abstractname}---\relax - \else - \bgroup\par\addvspace{0.5\baselineskip}\centering\vspace{-1.78ex}\@IEEEabskeysecsize\textbf{\abstractname}\par\addvspace{0.5\baselineskip}\egroup\quotation\@IEEEabskeysecsize% - \fi\@IEEEgobbleleadPARNLSP} -\def\IEEEkeywords{\normalfont\@IEEEtweakunitybaselinestretch{1.15}\sffamily - \if@twocolumn - \@IEEEabskeysecsize\vskip 0.5\baselineskip plus 0.25\baselineskip minus 0.25\baselineskip\noindent - \textbf{\IEEEkeywordsname}---\relax - \else - \bgroup\par\addvspace{0.5\baselineskip}\centering\@IEEEabskeysecsize\textbf{\IEEEkeywordsname}\par\addvspace{0.5\baselineskip}\egroup\quotation\@IEEEabskeysecsize% - \fi\@IEEEgobbleleadPARNLSP} - \fi -\fi - -% V1.8 transmag keywords index terms -% no abstract name, use indentation -\ifCLASSOPTIONtransmag -\def\abstract{\normalfont\parindent 1em\relax - \if@twocolumn - \@IEEEabskeysecsize\bfseries\indent - \else - \bgroup\par\addvspace{0.5\baselineskip}\centering\vspace{-1.78ex}\@IEEEabskeysecsize - \textbf{\abstractname}\par\addvspace{0.5\baselineskip}\egroup\quotation\@IEEEabskeysecsize - \fi\@IEEEgobbleleadPARNLSP} - -\def\IEEEkeywords{\normalfont\parindent 1em\relax - \if@twocolumn - \@IEEEabskeysecsize\vspace{1\baselineskip}\bfseries\indent\textit{\IEEEkeywordsname}---\relax - \else - \bgroup\par\vspace{1\baselineskip}\centering\@IEEEabskeysecsize - \textbf{\IEEEkeywordsname}\par\addvspace{0.5\baselineskip}\egroup\quotation\@IEEEabskeysecsize - \fi\@IEEEgobbleleadPARNLSP} -\fi - - - -% gobbles all leading \, \\ and \par, upon finding first token that -% is not a \ , \\ or a \par, it ceases and returns that token -% -% used to strip leading \, \\ and \par from the input -% so that such things in the beginning of an environment will not -% affect the formatting of the text -\long\def\@IEEEgobbleleadPARNLSP#1{\let\@IEEEswallowthistoken=0% -\let\@IEEEgobbleleadPARNLSPtoken#1% -\let\@IEEEgobbleleadPARtoken=\par% -\let\@IEEEgobbleleadNLtoken=\\% -\let\@IEEEgobbleleadSPtoken=\ % -\def\@IEEEgobbleleadSPMACRO{\ }% -\ifx\@IEEEgobbleleadPARNLSPtoken\@IEEEgobbleleadPARtoken% -\let\@IEEEswallowthistoken=1% -\fi% -\ifx\@IEEEgobbleleadPARNLSPtoken\@IEEEgobbleleadNLtoken% -\let\@IEEEswallowthistoken=1% -\fi% -\ifx\@IEEEgobbleleadPARNLSPtoken\@IEEEgobbleleadSPtoken% -\let\@IEEEswallowthistoken=1% -\fi% -% a control space will come in as a macro -% when it is the last one on a line -\ifx\@IEEEgobbleleadPARNLSPtoken\@IEEEgobbleleadSPMACRO% -\let\@IEEEswallowthistoken=1% -\fi% -% if we have to swallow this token, do so and taste the next one -% else spit it out and stop gobbling -\ifx\@IEEEswallowthistoken 1\let\@IEEEnextgobbleleadPARNLSP=\@IEEEgobbleleadPARNLSP\else% -\let\@IEEEnextgobbleleadPARNLSP=#1\fi% -\@IEEEnextgobbleleadPARNLSP}% - - - - -% TITLING OF SECTIONS -\def\@IEEEsectpunct{:\ \,} % Punctuation after run-in section heading (headings which are - % part of the paragraphs), need little bit more than a single space - % spacing from section number to title -% compsoc conferences use regular period/space punctuation -\ifCLASSOPTIONcompsoc -\ifCLASSOPTIONconference -\def\@IEEEsectpunct{.\ } -\fi\fi - - -\def\@seccntformat#1{\csname the#1dis\endcsname\hskip 0.5em\relax} - -\ifCLASSOPTIONcompsoc -% compsoc journals need extra spacing -\ifCLASSOPTIONconference\else -\def\@seccntformat#1{\csname the#1dis\endcsname\hskip 1em\relax} -\fi\fi - -%v1.7 put {} after #6 to allow for some types of user font control -%and use \@@par rather than \par -\def\@sect#1#2#3#4#5#6[#7]#8{% - \ifnum #2>\c@secnumdepth - \let\@svsec\@empty - \else - \refstepcounter{#1}% - % load section label and spacer into \@svsec - \protected@edef\@svsec{\@seccntformat{#1}\relax}% - \fi% - \@tempskipa #5\relax - \ifdim \@tempskipa>\z@% tempskipa determines whether is treated as a high - \begingroup #6{\relax% or low level heading - \noindent % subsections are NOT indented - % print top level headings. \@svsec is label, #8 is heading title - % The IEEE does not block indent the section title text, it flows like normal - {\hskip #3\relax\@svsec}{\interlinepenalty \@M #8\@@par}}% - \endgroup - \addcontentsline{toc}{#1}{\ifnum #2>\c@secnumdepth\relax\else - \protect\numberline{\csname the#1\endcsname}\fi#7}% - \else % printout low level headings - % svsechd seems to swallow the trailing space, protect it with \mbox{} - % got rid of sectionmark stuff - \def\@svsechd{#6{\hskip #3\relax\@svsec #8\@IEEEsectpunct\mbox{}}% - \addcontentsline{toc}{#1}{\ifnum #2>\c@secnumdepth\relax\else - \protect\numberline{\csname the#1\endcsname}\fi#7}}% - \fi%skip down - \@xsect{#5}} - - -% section* handler -%v1.7 put {} after #4 to allow for some types of user font control -%and use \@@par rather than \par -\def\@ssect#1#2#3#4#5{\@tempskipa #3\relax - \ifdim \@tempskipa>\z@ - %\begingroup #4\@hangfrom{\hskip #1}{\interlinepenalty \@M #5\par}\endgroup - % The IEEE does not block indent the section title text, it flows like normal - \begingroup \noindent #4{\relax{\hskip #1}{\interlinepenalty \@M #5\@@par}}\endgroup - % svsechd swallows the trailing space, protect it with \mbox{} - \else \def\@svsechd{#4{\hskip #1\relax #5\@IEEEsectpunct\mbox{}}}\fi - \@xsect{#3}} - - -%% SECTION heading spacing and font -%% -% arguments are: #1 - sectiontype name -% (for \@sect) #2 - section level -% #3 - section heading indent -% #4 - top separation (absolute value used, neg indicates not to indent main text) -% If negative, make stretch parts negative too! -% #5 - (absolute value used) positive: bottom separation after heading, -% negative: amount to indent main text after heading -% Both #4 and #5 negative means to indent main text and use negative top separation -% #6 - font control -% You've got to have \normalfont\normalsize in the font specs below to prevent -% trouble when you do something like: -% \section{Note}{\ttfamily TT-TEXT} is known to ... -% The IEEE sometimes REALLY stretches the area before a section -% heading by up to about 0.5in. However, it may not be a good -% idea to let LaTeX have quite this much rubber. -\ifCLASSOPTIONconference% -% The IEEE wants section heading spacing to decrease for conference mode -\def\section{\@startsection{section}{1}{\z@}{1.5ex plus 1.5ex minus 0.5ex}% -{0.7ex plus 1ex minus 0ex}{\normalfont\normalsize\centering\scshape}}% -\def\subsection{\@startsection{subsection}{2}{\z@}{1.5ex plus 1.5ex minus 0.5ex}% -{0.7ex plus .5ex minus 0ex}{\normalfont\normalsize\itshape}}% -\else % for journals -\def\section{\@startsection{section}{1}{\z@}{3.0ex plus 1.5ex minus 1.5ex}% V1.6 3.0ex from 3.5ex -{0.7ex plus 1ex minus 0ex}{\normalfont\normalsize\centering\scshape}}% -\def\subsection{\@startsection{subsection}{2}{\z@}{3.5ex plus 1.5ex minus 1.5ex}% -{0.7ex plus .5ex minus 0ex}{\normalfont\normalsize\itshape}}% -\fi - -% for both journals and conferences -% decided to put in a little rubber above the section, might help somebody -\def\subsubsection{\@startsection{subsubsection}{3}{\parindent}{0ex plus 0.1ex minus 0.1ex}% -{0ex}{\normalfont\normalsize\itshape}}% -\def\paragraph{\@startsection{paragraph}{4}{2\parindent}{0ex plus 0.1ex minus 0.1ex}% -{0ex}{\normalfont\normalsize\itshape}}% - - -% compsoc -\ifCLASSOPTIONcompsoc -\ifCLASSOPTIONconference -% compsoc conference -\def\section{\@startsection{section}{1}{\z@}{1\baselineskip plus 0.25\baselineskip minus 0.25\baselineskip}% -{1\baselineskip plus 0.25\baselineskip minus 0.25\baselineskip}{\normalfont\large\bfseries}}% -\def\subsection{\@startsection{subsection}{2}{\z@}{1\baselineskip plus 0.25\baselineskip minus 0.25\baselineskip}% -{1\baselineskip plus 0.25\baselineskip minus 0.25\baselineskip}{\normalfont\sublargesize\bfseries}}% -\def\subsubsection{\@startsection{subsubsection}{3}{\z@}{1\baselineskip plus 0.25\baselineskip minus 0.25\baselineskip}% -{0ex}{\normalfont\normalsize\bfseries}}% -\def\paragraph{\@startsection{paragraph}{4}{2\parindent}{0ex plus 0.1ex minus 0.1ex}% -{0ex}{\normalfont\normalsize}}% -\else% compsoc journals -% use negative top separation as compsoc journals do not indent paragraphs after section titles -\def\section{\@startsection{section}{1}{\z@}{-3.5ex plus -2ex minus -1.5ex}% -{0.7ex plus 1ex minus 0ex}{\normalfont\sublargesize\sffamily\bfseries\scshape}}% -% Note that subsection and smaller may not be correct for the Computer Society, -% I have to look up an example. -\def\subsection{\@startsection{subsection}{2}{\z@}{-3.5ex plus -1.5ex minus -1.5ex}% -{0.7ex plus .5ex minus 0ex}{\normalfont\normalsize\sffamily\bfseries}}% -\def\subsubsection{\@startsection{subsubsection}{3}{\z@}{-2.5ex plus -1ex minus -1ex}% -{0.5ex plus 0.5ex minus 0ex}{\normalfont\normalsize\sffamily\itshape}}% -\def\paragraph{\@startsection{paragraph}{4}{2\parindent}{-0ex plus -0.1ex minus -0.1ex}% -{0ex}{\normalfont\normalsize}}% -\fi\fi - -% transmag -\ifCLASSOPTIONtransmag -\def\subsection{\@startsection{subsection}{2}{0.75\parindent}{3.5ex plus 1.5ex minus 1.5ex}% -{0.7ex plus .5ex minus 0ex}{\normalfont\normalsize\itshape}}% -\def\subsubsection{\@startsection{subsubsection}{3}{1.25\parindent}{0.1ex plus 0.1ex minus 0.1ex}% -{0.1ex}{\normalfont\normalsize\itshape}}% -\fi - - -% V1.8a provide for a raised line Introduction section for use with Computer -% Society papers. We have to remove any spacing glue after the section -% heading and then remove the blank line for the new paragraph after it. -% LaTeX's section handler alters \everypar and we need to propogate those -% changes outside of the \parbox lest there be spacing problems at the top -% of the next section. -\def\IEEEraisesectionheading#1{\noindent\raisebox{1.5\baselineskip}[0pt][0pt]{\parbox[b]{\columnwidth}{#1\unskip\global\everypar=\everypar}}\vspace{-1\baselineskip}\vspace{-\parskip}\par} - - - -%% ENVIRONMENTS -% "box" symbols at end of proofs -\def\IEEEQEDclosed{\mbox{\rule[0pt]{1.3ex}{1.3ex}}} % for a filled box -% V1.6 some journals use an open box instead that will just fit around a closed one -\def\IEEEQEDopen{{\setlength{\fboxsep}{0pt}\setlength{\fboxrule}{0.2pt}\fbox{\rule[0pt]{0pt}{1.3ex}\rule[0pt]{1.3ex}{0pt}}}} -\ifCLASSOPTIONcompsoc -\def\IEEEQED{\IEEEQEDopen} % default to open for compsoc -\else -\def\IEEEQED{\IEEEQEDclosed} % otherwise default to closed -\fi - -%V1.8 flag to indicate if QED symbol is to be shown -\newif\if@IEEEQEDshow \@IEEEQEDshowtrue -\def\IEEEproofindentspace{2\parindent}% V1.8 allow user to change indentation amount if desired -% v1.7 name change to avoid namespace collision with amsthm. Also add support -% for an optional argument. -\def\IEEEproof{\@ifnextchar[{\@IEEEproof}{\@IEEEproof[\IEEEproofname]}} -\def\@IEEEproof[#1]{\@IEEEQEDshowtrue\par\noindent\hspace{\IEEEproofindentspace}{\itshape #1: }} -\def\endIEEEproof{\if@IEEEQEDshow\hspace*{\fill}\nobreakspace\IEEEQED\fi\par} -% qedhere for equation environments, similar to AMS \qedhere -\def\IEEEQEDhereeqn{\global\@IEEEQEDshowfalse\eqno\let\eqno\relax\let\leqno\relax - \let\veqno\relax\hbox{\IEEEQED}} -% IEEE style qedhere for IEEEeqnarray and other environments -\def\IEEEQEDhere{\global\@IEEEQEDshowfalse\IEEEQED} -% command to disable QED at end of IEEEproof -\def\IEEEQEDoff{\global\@IEEEQEDshowfalse} - - -%\itemindent is set to \z@ by list, so define new temporary variable -\newdimen\@IEEEtmpitemindent - -\ifCLASSOPTIONcompsoc -% V1.8a compsoc uses bold theorem titles, a period instead of a colon, vertical spacing, and hanging indentation -% V1.8 allow long theorem names to break across lines. -% Thanks to Miquel Payaro for reporting this. -\def\@begintheorem#1#2{\@IEEEtmpitemindent\itemindent\relax - \topsep 0.2\@IEEEnormalsizeunitybaselineskip plus 0.26\@IEEEnormalsizeunitybaselineskip minus 0.05\@IEEEnormalsizeunitybaselineskip - \rmfamily\trivlist\hangindent\parindent% - \item[]\textit{\bfseries\noindent #1\ #2.} \itemindent\@IEEEtmpitemindent\relax} -\def\@opargbegintheorem#1#2#3{\@IEEEtmpitemindent\itemindent\relax -\topsep 0.2\@IEEEnormalsizeunitybaselineskip plus 0.26\@IEEEnormalsizeunitybaselineskip minus 0.05\@IEEEnormalsizeunitybaselineskip -\rmfamily\trivlist\hangindent\parindent% -% V1.6 The IEEE is back to using () around theorem names which are also in italics -% Thanks to Christian Peel for reporting this. - \item[]\textit{\bfseries\noindent #1\ #2\ (#3).} \itemindent\@IEEEtmpitemindent\relax} -% V1.7 remove bogus \unskip that caused equations in theorems to collide with -% lines below. -\def\@endtheorem{\endtrivlist\vskip 0.25\@IEEEnormalsizeunitybaselineskip plus 0.26\@IEEEnormalsizeunitybaselineskip minus 0.05\@IEEEnormalsizeunitybaselineskip} -\else -% -% noncompsoc -% -% V1.8 allow long theorem names to break across lines. -% Thanks to Miquel Payaro for reporting this. -\def\@begintheorem#1#2{\@IEEEtmpitemindent\itemindent\relax\topsep 0pt\rmfamily\trivlist% - \item[]\textit{\indent #1\ #2:} \itemindent\@IEEEtmpitemindent\relax} -\def\@opargbegintheorem#1#2#3{\@IEEEtmpitemindent\itemindent\relax\topsep 0pt\rmfamily \trivlist% -% V1.6 The IEEE is back to using () around theorem names which are also in italics -% Thanks to Christian Peel for reporting this. - \item[]\textit{\indent #1\ #2\ (#3):} \itemindent\@IEEEtmpitemindent\relax} -% V1.7 remove bogus \unskip that caused equations in theorems to collide with -% lines below. -\def\@endtheorem{\endtrivlist} -\fi - - - -% V1.6 -% display command for the section the theorem is in - so that \thesection -% is not used as this will be in Roman numerals when we want arabic. -% LaTeX2e uses \def\@thmcounter#1{\noexpand\arabic{#1}} for the theorem number -% (second part) display and \def\@thmcountersep{.} as a separator. -% V1.7 intercept calls to the section counter and reroute to \@IEEEthmcounterinsection -% to allow \appendix(ices} to override as needed. -% -% special handler for sections, allows appendix(ices) to override -\gdef\@IEEEthmcounterinsection#1{\arabic{#1}} -% string macro -\edef\@IEEEstringsection{section} - -% redefine the #1#2[#3] form of newtheorem to use a hook to \@IEEEthmcounterinsection -% if section in_counter is used -\def\@xnthm#1#2[#3]{% - \expandafter\@ifdefinable\csname #1\endcsname - {\@definecounter{#1}\@newctr{#1}[#3]% - \edef\@IEEEstringtmp{#3} - \ifx\@IEEEstringtmp\@IEEEstringsection - \expandafter\xdef\csname the#1\endcsname{% - \noexpand\@IEEEthmcounterinsection{#3}\@thmcountersep - \@thmcounter{#1}}% - \else - \expandafter\xdef\csname the#1\endcsname{% - \expandafter\noexpand\csname the#3\endcsname \@thmcountersep - \@thmcounter{#1}}% - \fi - \global\@namedef{#1}{\@thm{#1}{#2}}% - \global\@namedef{end#1}{\@endtheorem}}} - - - -%% SET UP THE DEFAULT PAGESTYLE -\pagestyle{headings} -\pagenumbering{arabic} - -% normally the page counter starts at 1 -\setcounter{page}{1} -% however, for peerreview the cover sheet is page 0 or page -1 -% (for duplex printing) -\ifCLASSOPTIONpeerreview - \if@twoside - \setcounter{page}{-1} - \else - \setcounter{page}{0} - \fi -\fi - -% standard book class behavior - let bottom line float up and down as -% needed when single sided -\ifCLASSOPTIONtwoside\else\raggedbottom\fi -% if two column - turn on twocolumn, allow word spacings to stretch more and -% enforce a rigid position for the last lines -\ifCLASSOPTIONtwocolumn -% the peer review option delays invoking twocolumn - \ifCLASSOPTIONpeerreview\else - \twocolumn - \fi -\sloppy -\flushbottom -\fi - - - - -% \APPENDIX and \APPENDICES definitions - -% This is the \@ifmtarg command from the LaTeX ifmtarg package -% by Peter Wilson (CUA) and Donald Arseneau -% \@ifmtarg is used to determine if an argument to a command -% is present or not. -% For instance: -% \@ifmtarg{#1}{\typeout{empty}}{\typeout{has something}} -% \@ifmtarg is used with our redefined \section command if -% \appendices is invoked. -% The command \section will behave slightly differently depending -% on whether the user specifies a title: -% \section{My appendix title} -% or not: -% \section{} -% This way, we can eliminate the blank lines where the title -% would be, and the unneeded : after Appendix in the table of -% contents -\begingroup -\catcode`\Q=3 -\long\gdef\@ifmtarg#1{\@xifmtarg#1QQ\@secondoftwo\@firstoftwo\@nil} -\long\gdef\@xifmtarg#1#2Q#3#4#5\@nil{#4} -\endgroup -% end of \@ifmtarg defs - - -% V1.7 -% command that allows the one time saving of the original definition -% of section to \@IEEEappendixsavesection for \appendix or \appendices -% we don't save \section here as it may be redefined later by other -% packages (hyperref.sty, etc.) -\def\@IEEEsaveoriginalsectiononce{\let\@IEEEappendixsavesection\section -\let\@IEEEsaveoriginalsectiononce\relax} - -% neat trick to grab and process the argument from \section{argument} -% we process differently if the user invoked \section{} with no -% argument (title) -% note we reroute the call to the old \section* -\def\@IEEEprocessthesectionargument#1{% -\@ifmtarg{#1}{% -\@IEEEappendixsavesection*{\appendixname\nobreakspace\thesectiondis}% -\addcontentsline{toc}{section}{\appendixname\nobreakspace\thesection}}{% -\@IEEEappendixsavesection*{\appendixname\nobreakspace\thesectiondis\\* #1}% -\addcontentsline{toc}{section}{\appendixname\nobreakspace\thesection: #1}}} - -% we use this if the user calls \section{} after -% \appendix-- which has no meaning. So, we ignore the -% command and its argument. Then, warn the user. -\def\@IEEEdestroythesectionargument#1{\typeout{** WARNING: Ignoring useless -\protect\section\space in Appendix (line \the\inputlineno).}} - - -% remember \thesection forms will be displayed in \ref calls -% and in the Table of Contents. -% The \sectiondis form is used in the actual heading itself - -% appendix command for one single appendix -% normally has no heading. However, if you want a -% heading, you can do so via the optional argument: -% \appendix[Optional Heading] -\def\appendix{\relax} -\renewcommand{\appendix}[1][]{\@IEEEsaveoriginalsectiononce\par - % v1.6 keep hyperref's identifiers unique - \gdef\theHsection{Appendix.A}% - % v1.6 adjust hyperref's string name for the section - \xdef\Hy@chapapp{appendix}% - \setcounter{section}{0}% - \setcounter{subsection}{0}% - \setcounter{subsubsection}{0}% - \setcounter{paragraph}{0}% - \gdef\thesection{A}% - \gdef\thesectiondis{}% - \gdef\thesubsection{\Alph{subsection}}% - \gdef\@IEEEthmcounterinsection##1{A} - \refstepcounter{section}% update the \ref counter - \@ifmtarg{#1}{\@IEEEappendixsavesection*{\appendixname}% - \addcontentsline{toc}{section}{\appendixname}}{% - \@IEEEappendixsavesection*{\appendixname\nobreakspace\\* #1}% - \addcontentsline{toc}{section}{\appendixname: #1}}% - % redefine \section command for appendix - % leave \section* as is - \def\section{\@ifstar{\@IEEEappendixsavesection*}{% - \@IEEEdestroythesectionargument}}% throw out the argument - % of the normal form -} - - - -% appendices command for multiple appendices -% user then calls \section with an argument (possibly empty) to -% declare the individual appendices -\def\appendices{\@IEEEsaveoriginalsectiononce\par - % v1.6 keep hyperref's identifiers unique - \gdef\theHsection{Appendix.\Alph{section}}% - % v1.6 adjust hyperref's string name for the section - \xdef\Hy@chapapp{appendix}% - \setcounter{section}{-1}% we want \refstepcounter to use section 0 - \setcounter{subsection}{0}% - \setcounter{subsubsection}{0}% - \setcounter{paragraph}{0}% - \ifCLASSOPTIONromanappendices% - \gdef\thesection{\Roman{section}}% - \gdef\thesectiondis{\Roman{section}}% - \@IEEEcompsocconfonly{\gdef\thesectiondis{\Roman{section}.}}% - \gdef\@IEEEthmcounterinsection##1{A\arabic{##1}} - \else% - \gdef\thesection{\Alph{section}}% - \gdef\thesectiondis{\Alph{section}}% - \@IEEEcompsocconfonly{\gdef\thesectiondis{\Alph{section}.}}% - \gdef\@IEEEthmcounterinsection##1{\Alph{##1}} - \fi% - \refstepcounter{section}% update the \ref counter - \setcounter{section}{0}% NEXT \section will be the FIRST appendix - % redefine \section command for appendices - % leave \section* as is - \def\section{\@ifstar{\@IEEEappendixsavesection*}{% process the *-form - \refstepcounter{section}% or is a new section so, - \@IEEEprocessthesectionargument}}% process the argument - % of the normal form -} - - - -% V1.7 compoc uses nonbold drop cap and small caps word style -\ifCLASSOPTIONcompsoc - \def\IEEEPARstartFONTSTYLE{\mdseries} - \def\IEEEPARstartWORDFONTSTYLE{\scshape} - \def\IEEEPARstartWORDCAPSTYLE{\relax} -\fi -% -% -% \IEEEPARstart -% Definition for the big two line drop cap letter at the beginning of the -% first paragraph of journal papers. The first argument is the first letter -% of the first word, the second argument is the remaining letters of the -% first word which will be rendered in upper case. -% In V1.6 this has been completely rewritten to: -% -% 1. no longer have problems when the user begins an environment -% within the paragraph that uses \IEEEPARstart. -% 2. auto-detect and use the current font family -% 3. revise handling of the space at the end of the first word so that -% interword glue will now work as normal. -% 4. produce correctly aligned edges for the (two) indented lines. -% -% We generalize things via control macros - playing with these is fun too. -% -% V1.7 added more control macros to make it easy for IEEEtrantools.sty users -% to change the font style. -% -% the number of lines that are indented to clear it -% may need to increase if using decenders -\providecommand{\IEEEPARstartDROPLINES}{2} -% minimum number of lines left on a page to allow a \@IEEEPARstart -% Does not take into consideration rubber shrink, so it tends to -% be overly cautious -\providecommand{\IEEEPARstartMINPAGELINES}{2} -% V1.7 the height of the drop cap is adjusted to match the height of this text -% in the current font (when \IEEEPARstart is called). -\providecommand{\IEEEPARstartHEIGHTTEXT}{T} -% the depth the letter is lowered below the baseline -% the height (and size) of the letter is determined by the sum -% of this value and the height of the \IEEEPARstartHEIGHTTEXT in the current -% font. It is a good idea to set this value in terms of the baselineskip -% so that it can respond to changes therein. -\providecommand{\IEEEPARstartDROPDEPTH}{1.1\baselineskip} -% V1.7 the font the drop cap will be rendered in, -% can take zero or one argument. -\providecommand{\IEEEPARstartFONTSTYLE}{\bfseries} -% V1.7 any additional, non-font related commands needed to modify -% the drop cap letter, can take zero or one argument. -\providecommand{\IEEEPARstartCAPSTYLE}{\MakeUppercase} -% V1.7 the font that will be used to render the rest of the word, -% can take zero or one argument. -\providecommand{\IEEEPARstartWORDFONTSTYLE}{\relax} -% V1.7 any additional, non-font related commands needed to modify -% the rest of the word, can take zero or one argument. -\providecommand{\IEEEPARstartWORDCAPSTYLE}{\MakeUppercase} -% This is the horizontal separation distance from the drop letter to the main text. -% Lengths that depend on the font (e.g., ex, em, etc.) will be referenced -% to the font that is active when \IEEEPARstart is called. -\providecommand{\IEEEPARstartSEP}{0.15em} -% V1.7 horizontal offset applied to the left of the drop cap. -\providecommand{\IEEEPARstartHOFFSET}{0em} -% V1.7 Italic correction command applied at the end of the drop cap. -\providecommand{\IEEEPARstartITLCORRECT}{\/} - -% width of the letter output, set globally. Can be used in \IEEEPARstartSEP -% or \IEEEPARstartHOFFSET, but not the height lengths. -\newdimen\IEEEPARstartletwidth -\IEEEPARstartletwidth 0pt\relax - -% definition of \IEEEPARstart -% THIS IS A CONTROLLED SPACING AREA, DO NOT ALLOW SPACES WITHIN THESE LINES -% -% The token \@IEEEPARstartfont will be globally defined after the first use -% of \IEEEPARstart and will be a font command which creates the big letter -% The first argument is the first letter of the first word and the second -% argument is the rest of the first word(s). -\def\IEEEPARstart#1#2{\par{% -% if this page does not have enough space, break it and lets start -% on a new one -\@IEEEtranneedspace{\IEEEPARstartMINPAGELINES\baselineskip}{\relax}% -% V1.7 move this up here in case user uses \textbf for \IEEEPARstartFONTSTYLE -% which uses command \leavevmode which causes an unwanted \indent to be issued -\noindent -% calculate the desired height of the big letter -% it extends from the top of \IEEEPARstartHEIGHTTEXT in the current font -% down to \IEEEPARstartDROPDEPTH below the current baseline -\settoheight{\@IEEEtrantmpdimenA}{\IEEEPARstartHEIGHTTEXT}% -\addtolength{\@IEEEtrantmpdimenA}{\IEEEPARstartDROPDEPTH}% -% extract the name of the current font in bold -% and place it in \@IEEEPARstartFONTNAME -\def\@IEEEPARstartGETFIRSTWORD##1 ##2\relax{##1}% -{\IEEEPARstartFONTSTYLE{\selectfont\edef\@IEEEPARstartFONTNAMESPACE{\fontname\font\space}% -\xdef\@IEEEPARstartFONTNAME{\expandafter\@IEEEPARstartGETFIRSTWORD\@IEEEPARstartFONTNAMESPACE\relax}}}% -% define a font based on this name with a point size equal to the desired -% height of the drop letter -\font\@IEEEPARstartsubfont\@IEEEPARstartFONTNAME\space at \@IEEEtrantmpdimenA\relax% -% save this value as a counter (integer) value (sp points) -\@IEEEtrantmpcountA=\@IEEEtrantmpdimenA% -% now get the height of the actual letter produced by this font size -\settoheight{\@IEEEtrantmpdimenB}{\@IEEEPARstartsubfont\IEEEPARstartCAPSTYLE{#1}}% -% If something bogus happens like the first argument is empty or the -% current font is strange, do not allow a zero height. -\ifdim\@IEEEtrantmpdimenB=0pt\relax% -\typeout{** WARNING: IEEEPARstart drop letter has zero height! (line \the\inputlineno)}% -\typeout{ Forcing the drop letter font size to 10pt.}% -\@IEEEtrantmpdimenB=10pt% -\fi% -% and store it as a counter -\@IEEEtrantmpcountB=\@IEEEtrantmpdimenB% -% Since a font size doesn't exactly correspond to the height of the capital -% letters in that font, the actual height of the letter, \@IEEEtrantmpcountB, -% will be less than that desired, \@IEEEtrantmpcountA -% we need to raise the font size, \@IEEEtrantmpdimenA -% by \@IEEEtrantmpcountA / \@IEEEtrantmpcountB -% But, TeX doesn't have floating point division, so we have to use integer -% division. Hence the use of the counters. -% We need to reduce the denominator so that the loss of the remainder will -% have minimal affect on the accuracy of the result -\divide\@IEEEtrantmpcountB by 200% -\divide\@IEEEtrantmpcountA by \@IEEEtrantmpcountB% -% Then reequalize things when we use TeX's ability to multiply by -% floating point values -\@IEEEtrantmpdimenB=0.005\@IEEEtrantmpdimenA% -\multiply\@IEEEtrantmpdimenB by \@IEEEtrantmpcountA% -% \@IEEEPARstartfont is globaly set to the calculated font of the big letter -% We need to carry this out of the local calculation area to to create the -% big letter. -\global\font\@IEEEPARstartfont\@IEEEPARstartFONTNAME\space at \@IEEEtrantmpdimenB% -% Now set \@IEEEtrantmpdimenA to the width of the big letter -% We need to carry this out of the local calculation area to set the -% hanging indent -\settowidth{\global\@IEEEtrantmpdimenA}{\@IEEEPARstartfont -\IEEEPARstartCAPSTYLE{#1\IEEEPARstartITLCORRECT}}}% -% end of the isolated calculation environment -\global\IEEEPARstartletwidth\@IEEEtrantmpdimenA\relax% -% add in the extra clearance we want -\advance\@IEEEtrantmpdimenA by \IEEEPARstartSEP\relax% -% add in the optional offset -\advance\@IEEEtrantmpdimenA by \IEEEPARstartHOFFSET\relax% -% V1.7 don't allow negative offsets to produce negative hanging indents -\@IEEEtrantmpdimenB\@IEEEtrantmpdimenA -\ifnum\@IEEEtrantmpdimenB < 0 \@IEEEtrantmpdimenB 0pt\fi -% \@IEEEtrantmpdimenA has the width of the big letter plus the -% separation space and \@IEEEPARstartfont is the font we need to use -% Now, we make the letter and issue the hanging indent command -% The letter is placed in a box of zero width and height so that other -% text won't be displaced by it. -\hangindent\@IEEEtrantmpdimenB\hangafter=-\IEEEPARstartDROPLINES% -\makebox[0pt][l]{\hspace{-\@IEEEtrantmpdimenA}% -\raisebox{-\IEEEPARstartDROPDEPTH}[0pt][0pt]{\hspace{\IEEEPARstartHOFFSET}% -\@IEEEPARstartfont\IEEEPARstartCAPSTYLE{#1\IEEEPARstartITLCORRECT}% -\hspace{\IEEEPARstartSEP}}}% -{\IEEEPARstartWORDFONTSTYLE{\IEEEPARstartWORDCAPSTYLE{\selectfont#2}}}} - - - - -% determines if the space remaining on a given page is equal to or greater -% than the specified space of argument one -% if not, execute argument two (only if the remaining space is greater than zero) -% and issue a \newpage -% -% example: \@IEEEtranneedspace{2in}{\vfill} -% -% Does not take into consideration rubber shrinkage, so it tends to -% be overly cautious -% Based on an example posted by Donald Arseneau -% Note this macro uses \@IEEEtrantmpdimenB internally for calculations, -% so DO NOT PASS \@IEEEtrantmpdimenB to this routine -% if you need a dimen register, import with \@IEEEtrantmpdimenA instead -\def\@IEEEtranneedspace#1#2{\penalty-100\begingroup%shield temp variable -\@IEEEtrantmpdimenB\pagegoal\advance\@IEEEtrantmpdimenB-\pagetotal% space left -\ifdim #1>\@IEEEtrantmpdimenB\relax% not enough space left -\ifdim\@IEEEtrantmpdimenB>\z@\relax #2\fi% -\newpage% -\fi\endgroup} - - - -% IEEEbiography ENVIRONMENT -% Allows user to enter biography leaving place for picture (adapts to font size) -% As of V1.5, a new optional argument allows you to have a real graphic! -% V1.5 and later also fixes the "colliding biographies" which could happen when a -% biography's text was shorter than the space for the photo. -% MDS 7/2001 -% V1.6 prevent multiple biographies from making multiple TOC entries -\newif\if@IEEEbiographyTOCentrynotmade -\global\@IEEEbiographyTOCentrynotmadetrue - -% biography counter so hyperref can jump directly to the biographies -% and not just the previous section -\newcounter{IEEEbiography} -\setcounter{IEEEbiography}{0} - -% photo area size -\def\@IEEEBIOphotowidth{1.0in} % width of the biography photo area -\def\@IEEEBIOphotodepth{1.25in} % depth (height) of the biography photo area -% area cleared for photo -\def\@IEEEBIOhangwidth{1.14in} % width cleared for the biography photo area -\def\@IEEEBIOhangdepth{1.25in} % depth cleared for the biography photo area - % actual depth will be a multiple of - % \baselineskip, rounded up -\def\@IEEEBIOskipN{4\baselineskip}% nominal value of the vskip above the biography - -\newenvironment{IEEEbiography}[2][]{\normalfont\@IEEEcompsoconly{\sffamily}\footnotesize% -\unitlength 1in\parskip=0pt\par\parindent 1em\interlinepenalty500% -% we need enough space to support the hanging indent -% the nominal value of the spacer -% and one extra line for good measure -\@IEEEtrantmpdimenA=\@IEEEBIOhangdepth% -\advance\@IEEEtrantmpdimenA by \@IEEEBIOskipN% -\advance\@IEEEtrantmpdimenA by 1\baselineskip% -% if this page does not have enough space, break it and lets start -% with a new one -\@IEEEtranneedspace{\@IEEEtrantmpdimenA}{\relax}% -% nominal spacer can strech, not shrink use 1fil so user can out stretch with \vfill -\vskip \@IEEEBIOskipN plus 1fil minus 0\baselineskip% -% the default box for where the photo goes -\def\@IEEEtempbiographybox{{\setlength{\fboxsep}{0pt}\framebox{% -\begin{minipage}[b][\@IEEEBIOphotodepth][c]{\@IEEEBIOphotowidth}\centering PLACE\\ PHOTO\\ HERE \end{minipage}}}}% -% -% detect if the optional argument was supplied, this requires the -% \@ifmtarg command as defined in the appendix section above -% and if so, override the default box with what they want -\@ifmtarg{#1}{\relax}{\def\@IEEEtempbiographybox{\mbox{\begin{minipage}[b][\@IEEEBIOphotodepth][c]{\@IEEEBIOphotowidth}% -\centering% -#1% -\end{minipage}}}}% end if optional argument supplied -% Make an entry into the table of contents only if we have not done so before -\if@IEEEbiographyTOCentrynotmade% -% link labels to the biography counter so hyperref will jump -% to the biography, not the previous section -\setcounter{IEEEbiography}{-1}% -\refstepcounter{IEEEbiography}% -\addcontentsline{toc}{section}{Biographies}% -\global\@IEEEbiographyTOCentrynotmadefalse% -\fi% -% one more biography -\refstepcounter{IEEEbiography}% -% Make an entry for this name into the table of contents -\addcontentsline{toc}{subsection}{#2}% -% V1.6 properly handle if a new paragraph should occur while the -% hanging indent is still active. Do this by redefining \par so -% that it will not start a new paragraph. (But it will appear to the -% user as if it did.) Also, strip any leading pars, newlines, or spaces. -\let\@IEEEBIOORGparCMD=\par% save the original \par command -\edef\par{\hfil\break\indent}% the new \par will not be a "real" \par -\settoheight{\@IEEEtrantmpdimenA}{\@IEEEtempbiographybox}% get height of biography box -\@IEEEtrantmpdimenB=\@IEEEBIOhangdepth% -\@IEEEtrantmpcountA=\@IEEEtrantmpdimenB% countA has the hang depth -\divide\@IEEEtrantmpcountA by \baselineskip% calculates lines needed to produce the hang depth -\advance\@IEEEtrantmpcountA by 1% ensure we overestimate -% set the hanging indent -\hangindent\@IEEEBIOhangwidth% -\hangafter-\@IEEEtrantmpcountA% -% reference the top of the photo area to the top of a capital T -\settoheight{\@IEEEtrantmpdimenB}{\mbox{T}}% -% set the photo box, give it zero width and height so as not to disturb anything -\noindent\makebox[0pt][l]{\hspace{-\@IEEEBIOhangwidth}\raisebox{\@IEEEtrantmpdimenB}[0pt][0pt]{% -\raisebox{-\@IEEEBIOphotodepth}[0pt][0pt]{\@IEEEtempbiographybox}}}% -% now place the author name and begin the bio text -\noindent\textbf{#2\ }\@IEEEgobbleleadPARNLSP}{\relax\let\par=\@IEEEBIOORGparCMD\par% -% 7/2001 V1.5 detect when the biography text is shorter than the photo area -% and pad the unused area - preventing a collision from the next biography entry -% MDS -\ifnum \prevgraf <\@IEEEtrantmpcountA\relax% detect when the biography text is shorter than the photo - \advance\@IEEEtrantmpcountA by -\prevgraf% calculate how many lines we need to pad - \advance\@IEEEtrantmpcountA by -1\relax% we compensate for the fact that we indented an extra line - \@IEEEtrantmpdimenA=\baselineskip% calculate the length of the padding - \multiply\@IEEEtrantmpdimenA by \@IEEEtrantmpcountA% - \noindent\rule{0pt}{\@IEEEtrantmpdimenA}% insert an invisible support strut -\fi% -\par\normalfont} - - - -% V1.6 -% added biography without a photo environment -\newenvironment{IEEEbiographynophoto}[1]{% -% Make an entry into the table of contents only if we have not done so before -\if@IEEEbiographyTOCentrynotmade% -% link labels to the biography counter so hyperref will jump -% to the biography, not the previous section -\setcounter{IEEEbiography}{-1}% -\refstepcounter{IEEEbiography}% -\addcontentsline{toc}{section}{Biographies}% -\global\@IEEEbiographyTOCentrynotmadefalse% -\fi% -% one more biography -\refstepcounter{IEEEbiography}% -% Make an entry for this name into the table of contents -\addcontentsline{toc}{subsection}{#1}% -\normalfont\@IEEEcompsoconly{\sffamily}\footnotesize\interlinepenalty500% -\vskip 4\baselineskip plus 1fil minus 0\baselineskip% -\parskip=0pt\par% -\noindent\textbf{#1\ }\@IEEEgobbleleadPARNLSP}{\relax\par\normalfont} - - -% provide the user with some old font commands -% got this from article.cls -\DeclareOldFontCommand{\rm}{\normalfont\rmfamily}{\mathrm} -\DeclareOldFontCommand{\sf}{\normalfont\sffamily}{\mathsf} -\DeclareOldFontCommand{\tt}{\normalfont\ttfamily}{\mathtt} -\DeclareOldFontCommand{\bf}{\normalfont\bfseries}{\mathbf} -\DeclareOldFontCommand{\it}{\normalfont\itshape}{\mathit} -\DeclareOldFontCommand{\sl}{\normalfont\slshape}{\@nomath\sl} -\DeclareOldFontCommand{\sc}{\normalfont\scshape}{\@nomath\sc} -\DeclareRobustCommand*\cal{\@fontswitch\relax\mathcal} -\DeclareRobustCommand*\mit{\@fontswitch\relax\mathnormal} - - -% SPECIAL PAPER NOTICE COMMANDS -% -% holds the special notice text -\def\@IEEEspecialpapernotice{\relax} - -% for special papers, like invited papers, the user can do: -% \IEEEspecialpapernotice{(Invited Paper)} before \maketitle -\def\IEEEspecialpapernotice#1{\ifCLASSOPTIONconference% -\def\@IEEEspecialpapernotice{{\sublargesize\textit{#1}\vspace*{1em}}}% -\else% -\def\@IEEEspecialpapernotice{{\\*[1.5ex]\sublargesize\textit{#1}}\vspace*{-2ex}}% -\fi} - - - - -% PUBLISHER ID COMMANDS -% to insert a publisher's ID footer -% V1.6 \IEEEpubid has been changed so that the change in page size and style -% occurs in \maketitle. \IEEEpubid must now be issued prior to \maketitle -% use \IEEEpubidadjcol as before - in the second column of the title page -% These changes allow \maketitle to take the reduced page height into -% consideration when dynamically setting the space between the author -% names and the maintext. -% -% the amount the main text is pulled up to make room for the -% publisher's ID footer -% The IEEE uses about 1.3\baselineskip for journals, -% dynamic title spacing will clean up the fraction -\def\@IEEEpubidpullup{1.3\baselineskip} -\ifCLASSOPTIONtechnote -% for technotes it must be an integer of baselineskip as there can be no -% dynamic title spacing for two column mode technotes (the title is in the -% in first column) and we should maintain an integer number of lines in the -% second column -% There are some examples (such as older issues of "Transactions on -% Information Theory") in which the IEEE really pulls the text off the ID for -% technotes - about 0.55in (or 4\baselineskip). We'll use 2\baselineskip -% and call it even. -\def\@IEEEpubidpullup{2\baselineskip} -\fi - -% V1.7 compsoc does not use a pullup -\ifCLASSOPTIONcompsoc -\def\@IEEEpubidpullup{0pt} -\fi - -% holds the ID text -\def\@IEEEpubid{\relax} - -% flag so \maketitle can tell if \IEEEpubid was called -\newif\if@IEEEusingpubid -\global\@IEEEusingpubidfalse -% issue this command in the page to have the ID at the bottom -% V1.6 use before \maketitle -\def\IEEEpubid#1{\def\@IEEEpubid{#1}\global\@IEEEusingpubidtrue} - - -% command which will pull up (shorten) the column it is executed in -% to make room for the publisher ID. Place in the second column of -% the title page when using \IEEEpubid -% Is smart enough not to do anything when in single column text or -% if the user hasn't called \IEEEpubid -% currently needed in for the second column of a page with the -% publisher ID. If not needed in future releases, please provide this -% command and define it as \relax for backward compatibility -% v1.6b do not allow command to operate if the peer review option has been -% selected because \IEEEpubidadjcol will not be on the cover page. -% V1.7 do nothing if compsoc -\def\IEEEpubidadjcol{\ifCLASSOPTIONcompsoc\else\ifCLASSOPTIONpeerreview\else -\if@twocolumn\if@IEEEusingpubid\enlargethispage{-\@IEEEpubidpullup}\fi\fi\fi\fi} - -% Special thanks to Peter Wilson, Daniel Luecking, and the other -% gurus at comp.text.tex, for helping me to understand how best to -% implement the IEEEpubid command in LaTeX. - - - -%% Lockout some commands under various conditions - -% general purpose bit bucket -\newsavebox{\@IEEEtranrubishbin} - -% flags to prevent multiple warning messages -\newif\if@IEEEWARNthanks -\newif\if@IEEEWARNIEEEPARstart -\newif\if@IEEEWARNIEEEbiography -\newif\if@IEEEWARNIEEEbiographynophoto -\newif\if@IEEEWARNIEEEpubid -\newif\if@IEEEWARNIEEEpubidadjcol -\newif\if@IEEEWARNIEEEmembership -\newif\if@IEEEWARNIEEEaftertitletext -\@IEEEWARNthankstrue -\@IEEEWARNIEEEPARstarttrue -\@IEEEWARNIEEEbiographytrue -\@IEEEWARNIEEEbiographynophototrue -\@IEEEWARNIEEEpubidtrue -\@IEEEWARNIEEEpubidadjcoltrue -\@IEEEWARNIEEEmembershiptrue -\@IEEEWARNIEEEaftertitletexttrue - - -%% Lockout some commands when in various modes, but allow them to be restored if needed -%% -% save commands which might be locked out -% so that the user can later restore them if needed -\let\@IEEESAVECMDthanks\thanks -\let\@IEEESAVECMDIEEEPARstart\IEEEPARstart -\let\@IEEESAVECMDIEEEbiography\IEEEbiography -\let\@IEEESAVECMDendIEEEbiography\endIEEEbiography -\let\@IEEESAVECMDIEEEbiographynophoto\IEEEbiographynophoto -\let\@IEEESAVECMDendIEEEbiographynophoto\endIEEEbiographynophoto -\let\@IEEESAVECMDIEEEpubid\IEEEpubid -\let\@IEEESAVECMDIEEEpubidadjcol\IEEEpubidadjcol -\let\@IEEESAVECMDIEEEmembership\IEEEmembership -\let\@IEEESAVECMDIEEEaftertitletext\IEEEaftertitletext - - -% disable \IEEEPARstart when in draft mode -% This may have originally been done because the pre-V1.6 drop letter -% algorithm had problems with a non-unity baselinestretch -% At any rate, it seems too formal to have a drop letter in a draft -% paper. -\ifCLASSOPTIONdraftcls -\def\IEEEPARstart#1#2{#1#2\if@IEEEWARNIEEEPARstart\typeout{** ATTENTION: \noexpand\IEEEPARstart - is disabled in draft mode (line \the\inputlineno).}\fi\global\@IEEEWARNIEEEPARstartfalse} -\fi -% and for technotes -\ifCLASSOPTIONtechnote -\def\IEEEPARstart#1#2{#1#2\if@IEEEWARNIEEEPARstart\typeout{** WARNING: \noexpand\IEEEPARstart - is locked out for technotes (line \the\inputlineno).}\fi\global\@IEEEWARNIEEEPARstartfalse} -\fi - - -% lockout unneeded commands when in conference mode -\ifCLASSOPTIONconference -% when locked out, \thanks, \IEEEbiography, \IEEEbiographynophoto, \IEEEpubid, -% \IEEEmembership and \IEEEaftertitletext will all swallow their given text. -% \IEEEPARstart will output a normal character instead -% warn the user about these commands only once to prevent the console screen -% from filling up with redundant messages -\def\thanks#1{\if@IEEEWARNthanks\typeout{** WARNING: \noexpand\thanks - is locked out when in conference mode (line \the\inputlineno).}\fi\global\@IEEEWARNthanksfalse} -\def\IEEEPARstart#1#2{#1#2\if@IEEEWARNIEEEPARstart\typeout{** WARNING: \noexpand\IEEEPARstart - is locked out when in conference mode (line \the\inputlineno).}\fi\global\@IEEEWARNIEEEPARstartfalse} - - -% LaTeX treats environments and commands with optional arguments differently. -% the actual ("internal") command is stored as \\commandname -% (accessed via \csname\string\commandname\endcsname ) -% the "external" command \commandname is a macro with code to determine -% whether or not the optional argument is presented and to provide the -% default if it is absent. So, in order to save and restore such a command -% we would have to save and restore \\commandname as well. But, if LaTeX -% ever changes the way it names the internal names, the trick would break. -% Instead let us just define a new environment so that the internal -% name can be left undisturbed. -\newenvironment{@IEEEbogusbiography}[2][]{\if@IEEEWARNIEEEbiography\typeout{** WARNING: \noexpand\IEEEbiography - is locked out when in conference mode (line \the\inputlineno).}\fi\global\@IEEEWARNIEEEbiographyfalse% -\setbox\@IEEEtranrubishbin\vbox\bgroup}{\egroup\relax} -% and make biography point to our bogus biography -\let\IEEEbiography=\@IEEEbogusbiography -\let\endIEEEbiography=\end@IEEEbogusbiography - -\renewenvironment{IEEEbiographynophoto}[1]{\if@IEEEWARNIEEEbiographynophoto\typeout{** WARNING: \noexpand\IEEEbiographynophoto - is locked out when in conference mode (line \the\inputlineno).}\fi\global\@IEEEWARNIEEEbiographynophotofalse% -\setbox\@IEEEtranrubishbin\vbox\bgroup}{\egroup\relax} - -\def\IEEEpubid#1{\if@IEEEWARNIEEEpubid\typeout{** WARNING: \noexpand\IEEEpubid - is locked out when in conference mode (line \the\inputlineno).}\fi\global\@IEEEWARNIEEEpubidfalse} -\def\IEEEpubidadjcol{\if@IEEEWARNIEEEpubidadjcol\typeout{** WARNING: \noexpand\IEEEpubidadjcol - is locked out when in conference mode (line \the\inputlineno).}\fi\global\@IEEEWARNIEEEpubidadjcolfalse} -\def\IEEEmembership#1{\if@IEEEWARNIEEEmembership\typeout{** WARNING: \noexpand\IEEEmembership - is locked out when in conference mode (line \the\inputlineno).}\fi\global\@IEEEWARNIEEEmembershipfalse} -\def\IEEEaftertitletext#1{\if@IEEEWARNIEEEaftertitletext\typeout{** WARNING: \noexpand\IEEEaftertitletext - is locked out when in conference mode (line \the\inputlineno).}\fi\global\@IEEEWARNIEEEaftertitletextfalse} -\fi - - -% provide a way to restore the commands that are locked out -\def\IEEEoverridecommandlockouts{% -\typeout{** ATTENTION: Overriding command lockouts (line \the\inputlineno).}% -\let\thanks\@IEEESAVECMDthanks% -\let\IEEEPARstart\@IEEESAVECMDIEEEPARstart% -\let\IEEEbiography\@IEEESAVECMDIEEEbiography% -\let\endIEEEbiography\@IEEESAVECMDendIEEEbiography% -\let\IEEEbiographynophoto\@IEEESAVECMDIEEEbiographynophoto% -\let\endIEEEbiographynophoto\@IEEESAVECMDendIEEEbiographynophoto% -\let\IEEEpubid\@IEEESAVECMDIEEEpubid% -\let\IEEEpubidadjcol\@IEEESAVECMDIEEEpubidadjcol% -\let\IEEEmembership\@IEEESAVECMDIEEEmembership% -\let\IEEEaftertitletext\@IEEESAVECMDIEEEaftertitletext} - - - -% need a backslash character for typeout output -{\catcode`\|=0 \catcode`\\=12 -|xdef|@IEEEbackslash{\}} - - -% hook to allow easy disabling of all legacy warnings -\def\@IEEElegacywarn#1#2{\typeout{** ATTENTION: \@IEEEbackslash #1 is deprecated (line \the\inputlineno). -Use \@IEEEbackslash #2 instead.}} - - -% provide some legacy IEEEtran commands -\def\IEEEcompsoctitleabstractindextext{\@IEEElegacywarn{IEEEcompsoctitleabstractindextext}{IEEEtitleabstractindextext}\IEEEtitleabstractindextext} -\def\IEEEdisplaynotcompsoctitleabstractindextext{\@IEEElegacywarn{IEEEdisplaynotcompsoctitleabstractindextext}{IEEEdisplaynontitleabstractindextext}\IEEEdisplaynontitleabstractindextext} -% provide some legacy IEEEtran environments - - -% V1.8a no more support for these legacy commands -%\def\authorblockA{\@IEEElegacywarn{authorblockA}{IEEEauthorblockA}\IEEEauthorblockA} -%\def\authorblockN{\@IEEElegacywarn{authorblockN}{IEEEauthorblockN}\IEEEauthorblockN} -%\def\authorrefmark{\@IEEElegacywarn{authorrefmark}{IEEEauthorrefmark}\IEEEauthorrefmark} -%\def\PARstart{\@IEEElegacywarn{PARstart}{IEEEPARstart}\IEEEPARstart} -%\def\pubid{\@IEEElegacywarn{pubid}{IEEEpubid}\IEEEpubid} -%\def\pubidadjcol{\@IEEElegacywarn{pubidadjcol}{IEEEpubidadjcol}\IEEEpubidadjcol} -%\def\specialpapernotice{\@IEEElegacywarn{specialpapernotice}{IEEEspecialpapernotice}\IEEEspecialpapernotice} -% and environments -%\def\keywords{\@IEEElegacywarn{keywords}{IEEEkeywords}\IEEEkeywords} -%\def\endkeywords{\endIEEEkeywords} -% V1.8 no more support for legacy IED list commands -%\let\labelindent\IEEElabelindent -%\def\calcleftmargin{\@IEEElegacywarn{calcleftmargin}{IEEEcalcleftmargin}\IEEEcalcleftmargin} -%\def\setlabelwidth{\@IEEElegacywarn{setlabelwidth}{IEEEsetlabelwidth}\IEEEsetlabelwidth} -%\def\usemathlabelsep{\@IEEElegacywarn{usemathlabelsep}{IEEEusemathlabelsep}\IEEEusemathlabelsep} -%\def\iedlabeljustifyc{\@IEEElegacywarn{iedlabeljustifyc}{IEEEiedlabeljustifyc}\IEEEiedlabeljustifyc} -%\def\iedlabeljustifyl{\@IEEElegacywarn{iedlabeljustifyl}{IEEEiedlabeljustifyl}\IEEEiedlabeljustifyl} -%\def\iedlabeljustifyr{\@IEEElegacywarn{iedlabeljustifyr}{IEEEiedlabeljustifyr}\IEEEiedlabeljustifyr} -% V1.8 no more support for QED and proof stuff -%\def\QED{\@IEEElegacywarn{QED}{IEEEQED}\IEEEQED} -%\def\QEDclosed{\@IEEElegacywarn{QEDclosed}{IEEEQEDclosed}\IEEEQEDclosed} -%\def\QEDopen{\@IEEElegacywarn{QEDopen}{IEEEQEDopen}\IEEEQEDopen} -%\AtBeginDocument{\def\proof{\@IEEElegacywarn{proof}{IEEEproof}\IEEEproof}\def\endproof{\endIEEEproof}} -% V1.8 no longer support biography or biographynophoto -%\def\biography{\@IEEElegacywarn{biography}{IEEEbiography}\IEEEbiography} -%\def\biographynophoto{\@IEEElegacywarn{biographynophoto}{IEEEbiographynophoto}\IEEEbiographynophoto} -%\def\endbiography{\endIEEEbiography} -%\def\endbiographynophoto{\endIEEEbiographynophoto} -% V1.7 and later no longer supports \overrideIEEEmargins -%\def\overrideIEEEmargins{% -%\typeout{** WARNING: \string\overrideIEEEmargins \space no longer supported (line \the\inputlineno).}% -%\typeout{** Use the \string\CLASSINPUTinnersidemargin, \string\CLASSINPUToutersidemargin \space controls instead.}} - -\endinput - -%%%%%%%%%%%%%%%%%%%%%%%%%%%%% End of IEEEtran.cls %%%%%%%%%%%%%%%%%%%%%%%%%%%% -% That's all folks! - diff --git a/SAT_package_paper/Conference-LaTeX-template_10-17-19/bibliography.bib b/SAT_package_paper/Conference-LaTeX-template_10-17-19/bibliography.bib deleted file mode 100644 index f077ef7..0000000 --- a/SAT_package_paper/Conference-LaTeX-template_10-17-19/bibliography.bib +++ /dev/null @@ -1,150 +0,0 @@ -@article{convexjl, - title = {Convex Optimization in {J}ulia}, - author = {Udell, Madeleine and Mohan, Karanveer and Zeng, David and Hong, Jenny and Diamond, Steven and Boyd, Stephen}, - year = {2014}, - journal = {SC14 Workshop on High Performance Technical Computing in Dynamic Languages}, - archivePrefix = "arXiv", - eprint = {1410.4821}, - primaryClass = "math-oc", -} - -@article{Lubin2023, - author = {Miles Lubin and Oscar Dowson and Joaquim Dias Garcia and Joey Huchette and Beno{\^i}t Legat and Juan Pablo Vielma}, - title = {JuMP 1.0: Recent improvements to a modeling language for mathematical optimization}, - journal = {Mathematical Programming Computation}, - year = {2023}, - doi = {10.1007/s12532-023-00239-3} -} - -@book{bradley2007calculus, - title={The calculus of computation: decision procedures with applications to verification}, - author={Bradley, Aaron R and Manna, Zohar}, - year={2007}, - publisher={Springer Science \& Business Media} -} - -@book{kroening2016decision, - title={Decision procedures}, - author={Kroening, Daniel and Strichman, Ofer}, - year={2016}, - publisher={Springer} -} - -@article{de2011satisfiabilityintro, - title={Satisfiability modulo theories: introduction and applications}, - author={De Moura, Leonardo and Bj{\o}rner, Nikolaj}, - journal={Communications of the ACM}, - volume={54}, - number={9}, - pages={69--77}, - year={2011}, - publisher={ACM New York, NY, USA} -} - -@inproceedings{pysmt2015, - title={PySMT: a solver-agnostic library for fast prototyping of SMT-based algorithms}, - author={Gario, Marco and Micheli, Andrea}, - booktitle={SMT Workshop 2015}, - year={2015} -} - - -@inproceedings{z3, - title={Z3: An Efficient SMT Solver}, - author={Leonardo Mendonça de Moura and Nikolaj S. Bj{\o}rner}, - booktitle={International Conference on Tools and Algorithms for Construction and Analysis of Systems}, - year={2008} -} - -@inproceedings{cvc5, - author = {Haniel Barbosa and - Clark W. Barrett and - Martin Brain and - Gereon Kremer and - Hanna Lachnitt and - Makai Mann and - Abdalrhman Mohamed and - Mudathir Mohamed and - Aina Niemetz and - Andres N{\"{o}}tzli and - Alex Ozdemir and - Mathias Preiner and - Andrew Reynolds and - Ying Sheng and - Cesare Tinelli and - Yoni Zohar}, - editor = {Dana Fisman and - Grigore Rosu}, - title = {cvc5: {A} Versatile and Industrial-Strength {SMT} Solver}, - booktitle = {Tools and Algorithms for the Construction and Analysis of Systems - - 28th International Conference, {TACAS} 2022, Held as Part of the - European Joint Conferences on Theory and Practice of Software, {ETAPS} - 2022, Munich, Germany, April 2-7, 2022, Proceedings, Part {I}}, - series = {Lecture Notes in Computer Science}, - volume = {13243}, - pages = {415--442}, - publisher = {Springer}, - year = {2022}, - url = {https://doi.org/10.1007/978-3-030-99524-9\_24}, - doi = {10.1007/978-3-030-99524-9\_24}, - timestamp = {Fri, 01 Apr 2022 15:49:27 +0200}, - biburl = {https://dblp.org/rec/conf/tacas/BarbosaBBKLMMMN22.bib}, - bibsource = {dblp computer science bibliography, https://dblp.org}, -} - -@TECHREPORT{smtlib2, - author = {Clark Barrett and Pascal Fontaine and Cesare Tinelli}, - title = {{The SMT-LIB Standard: Version 2.6}}, - institution = {Department of Computer Science, The University of Iowa}, - year = 2017, - note = {Available at {\tt www.SMT-LIB.org}} -} - -@article{bezanson2017julia, - title={Julia: A fresh approach to numerical computing}, - author={Bezanson, Jeff and Edelman, Alan and Karpinski, Stefan and Shah, Viral B}, - journal={SIAM review}, - volume={59}, - number={1}, - pages={65--98}, - year={2017}, - publisher={SIAM}, - url={https://doi.org/10.1137/141000671} -} - -@article{perkel2019juliaspeed, - title={Julia: come for the syntax, stay for the speed}, - author={Perkel, Jeffrey M and others}, - journal={Nature}, - volume={572}, - number={7767}, - pages={141--142}, - year={2019}, - publisher={Springer Science and Business Media LLC} -} - -@article{besard2018juliagpu, - title={Effective extensible programming: unleashing Julia on GPUs}, - author={Besard, Tim and Foket, Christophe and De Sutter, Bjorn}, - journal={IEEE Transactions on Parallel and Distributed Systems}, - volume={30}, - number={4}, - pages={827--841}, - year={2018}, - publisher={IEEE} -} -@article{GAO2020juliaml, - title = {Julia language in machine learning: Algorithms, applications, and open issues}, - journal = {Computer Science Review}, - volume = {37}, - pages = {100254}, - year = {2020}, - issn = {1574-0137}, - doi = {https://doi.org/10.1016/j.cosrev.2020.100254}, - url = {https://www.sciencedirect.com/science/article/pii/S157401372030071X}, - author = {Kaifeng Gao and Gang Mei and Francesco Piccialli and Salvatore Cuomo and Jingzhi Tu and Zenan Huo}, - keywords = {Julia language, Machine learning, Supervised learning, Unsupervised learning, Deep learning, Artificial neural networks}, - abstract = {Machine learning is driving development across many fields in science and engineering. A simple and efficient programming language could accelerate applications of machine learning in various fields. Currently, the programming languages most commonly used to develop machine learning algorithms include Python, MATLAB, and C/C ++. However, none of these languages well balance both efficiency and simplicity. The Julia language is a fast, easy-to-use, and open-source programming language that was originally designed for high-performance computing, which can well balance the efficiency and simplicity. This paper summarizes the related research work and developments in the applications of the Julia language in machine learning. It first surveys the popular machine learning algorithms that are developed in the Julia language. Then, it investigates applications of the machine learning algorithms implemented with the Julia language. Finally, it discusses the open issues and the potential future directions that arise in the use of the Julia language in machine learning.} -} - -@misc{Julia_documentation_2023, url={https://docs.julialang.org/en/v1/manual/mathematical-operations/#Operator-Precedence-and-Associativity}, journal={Julia documentation}, publisher={julialang.org}, year={2023}, month={Jul}} \ No newline at end of file diff --git a/SAT_package_paper/Conference-LaTeX-template_10-17-19/conference_101719.tex b/SAT_package_paper/Conference-LaTeX-template_10-17-19/conference_101719.tex deleted file mode 100644 index 09d7398..0000000 --- a/SAT_package_paper/Conference-LaTeX-template_10-17-19/conference_101719.tex +++ /dev/null @@ -1,288 +0,0 @@ -\documentclass[conference]{IEEEtran} -\IEEEoverridecommandlockouts -% The preceding line is only needed to identify funding in the first footnote. If that is unneeded, please comment it out. -\usepackage{cite} -\usepackage{amsmath,amssymb,amsfonts} -\usepackage{algorithmic} -\usepackage{graphicx} -\usepackage{textcomp} -\usepackage{xcolor} -\def\BibTeX{{\rm B\kern-.05em{\sc i\kern-.025em b}\kern-.08em - T\kern-.1667em\lower.7ex\hbox{E}\kern-.125emX}} -\begin{document} - -\title{Conference Paper Title*\\ -{\footnotesize \textsuperscript{*}Note: Sub-titles are not captured in Xplore and -should not be used} -\thanks{Identify applicable funding agency here. If none, delete this.} -} - -\author{\IEEEauthorblockN{1\textsuperscript{st} Given Name Surname} -\IEEEauthorblockA{\textit{dept. name of organization (of Aff.)} \\ -\textit{name of organization (of Aff.)}\\ -City, Country \\ -email address or ORCID} -\and -\IEEEauthorblockN{2\textsuperscript{nd} Given Name Surname} -\IEEEauthorblockA{\textit{dept. name of organization (of Aff.)} \\ -\textit{name of organization (of Aff.)}\\ -City, Country \\ -email address or ORCID} -\and -\IEEEauthorblockN{3\textsuperscript{rd} Given Name Surname} -\IEEEauthorblockA{\textit{dept. name of organization (of Aff.)} \\ -\textit{name of organization (of Aff.)}\\ -City, Country \\ -email address or ORCID} -\and -\IEEEauthorblockN{4\textsuperscript{th} Given Name Surname} -\IEEEauthorblockA{\textit{dept. name of organization (of Aff.)} \\ -\textit{name of organization (of Aff.)}\\ -City, Country \\ -email address or ORCID} -\and -\IEEEauthorblockN{5\textsuperscript{th} Given Name Surname} -\IEEEauthorblockA{\textit{dept. name of organization (of Aff.)} \\ -\textit{name of organization (of Aff.)}\\ -City, Country \\ -email address or ORCID} -\and -\IEEEauthorblockN{6\textsuperscript{th} Given Name Surname} -\IEEEauthorblockA{\textit{dept. name of organization (of Aff.)} \\ -\textit{name of organization (of Aff.)}\\ -City, Country \\ -email address or ORCID} -} - -\maketitle - -\begin{abstract} -This document is a model and instructions for \LaTeX. -This and the IEEEtran.cls file define the components of your paper [title, text, heads, etc.]. *CRITICAL: Do Not Use Symbols, Special Characters, Footnotes, -or Math in Paper Title or Abstract. -\end{abstract} - -\begin{IEEEkeywords} -component, formatting, style, styling, insert -\end{IEEEkeywords} - -\section{Introduction} -This document is a model and instructions for \LaTeX. -Please observe the conference page limits. - -\section{Ease of Use} - -\subsection{Maintaining the Integrity of the Specifications} - -The IEEEtran class file is used to format your paper and style the text. All margins, -column widths, line spaces, and text fonts are prescribed; please do not -alter them. You may note peculiarities. For example, the head margin -measures proportionately more than is customary. This measurement -and others are deliberate, using specifications that anticipate your paper -as one part of the entire proceedings, and not as an independent document. -Please do not revise any of the current designations. - -\section{Prepare Your Paper Before Styling} -Before you begin to format your paper, first write and save the content as a -separate text file. Complete all content and organizational editing before -formatting. Please note sections \ref{AA}--\ref{SCM} below for more information on -proofreading, spelling and grammar. - -Keep your text and graphic files separate until after the text has been -formatted and styled. Do not number text heads---{\LaTeX} will do that -for you. - -\subsection{Abbreviations and Acronyms}\label{AA} -Define abbreviations and acronyms the first time they are used in the text, -even after they have been defined in the abstract. Abbreviations such as -IEEE, SI, MKS, CGS, ac, dc, and rms do not have to be defined. Do not use -abbreviations in the title or heads unless they are unavoidable. - -\subsection{Units} -\begin{itemize} -\item Use either SI (MKS) or CGS as primary units. (SI units are encouraged.) English units may be used as secondary units (in parentheses). An exception would be the use of English units as identifiers in trade, such as ``3.5-inch disk drive''. -\item Avoid combining SI and CGS units, such as current in amperes and magnetic field in oersteds. This often leads to confusion because equations do not balance dimensionally. If you must use mixed units, clearly state the units for each quantity that you use in an equation. -\item Do not mix complete spellings and abbreviations of units: ``Wb/m\textsuperscript{2}'' or ``webers per square meter'', not ``webers/m\textsuperscript{2}''. Spell out units when they appear in text: ``. . . a few henries'', not ``. . . a few H''. -\item Use a zero before decimal points: ``0.25'', not ``.25''. Use ``cm\textsuperscript{3}'', not ``cc''.) -\end{itemize} - -\subsection{Equations} -Number equations consecutively. To make your -equations more compact, you may use the solidus (~/~), the exp function, or -appropriate exponents. Italicize Roman symbols for quantities and variables, -but not Greek symbols. Use a long dash rather than a hyphen for a minus -sign. Punctuate equations with commas or periods when they are part of a -sentence, as in: -\begin{equation} -a+b=\gamma\label{eq} -\end{equation} - -Be sure that the -symbols in your equation have been defined before or immediately following -the equation. Use ``\eqref{eq}'', not ``Eq.~\eqref{eq}'' or ``equation \eqref{eq}'', except at -the beginning of a sentence: ``Equation \eqref{eq} is . . .'' - -\subsection{\LaTeX-Specific Advice} - -Please use ``soft'' (e.g., \verb|\eqref{Eq}|) cross references instead -of ``hard'' references (e.g., \verb|(1)|). That will make it possible -to combine sections, add equations, or change the order of figures or -citations without having to go through the file line by line. - -Please don't use the \verb|{eqnarray}| equation environment. Use -\verb|{align}| or \verb|{IEEEeqnarray}| instead. The \verb|{eqnarray}| -environment leaves unsightly spaces around relation symbols. - -Please note that the \verb|{subequations}| environment in {\LaTeX} -will increment the main equation counter even when there are no -equation numbers displayed. If you forget that, you might write an -article in which the equation numbers skip from (17) to (20), causing -the copy editors to wonder if you've discovered a new method of -counting. - -{\BibTeX} does not work by magic. It doesn't get the bibliographic -data from thin air but from .bib files. If you use {\BibTeX} to produce a -bibliography you must send the .bib files. - -{\LaTeX} can't read your mind. If you assign the same label to a -subsubsection and a table, you might find that Table I has been cross -referenced as Table IV-B3. - -{\LaTeX} does not have precognitive abilities. If you put a -\verb|\label| command before the command that updates the counter it's -supposed to be using, the label will pick up the last counter to be -cross referenced instead. In particular, a \verb|\label| command -should not go before the caption of a figure or a table. - -Do not use \verb|\nonumber| inside the \verb|{array}| environment. It -will not stop equation numbers inside \verb|{array}| (there won't be -any anyway) and it might stop a wanted equation number in the -surrounding equation. - -\subsection{Some Common Mistakes}\label{SCM} -\begin{itemize} -\item The word ``data'' is plural, not singular. -\item The subscript for the permeability of vacuum $\mu_{0}$, and other common scientific constants, is zero with subscript formatting, not a lowercase letter ``o''. -\item In American English, commas, semicolons, periods, question and exclamation marks are located within quotation marks only when a complete thought or name is cited, such as a title or full quotation. When quotation marks are used, instead of a bold or italic typeface, to highlight a word or phrase, punctuation should appear outside of the quotation marks. A parenthetical phrase or statement at the end of a sentence is punctuated outside of the closing parenthesis (like this). (A parenthetical sentence is punctuated within the parentheses.) -\item A graph within a graph is an ``inset'', not an ``insert''. The word alternatively is preferred to the word ``alternately'' (unless you really mean something that alternates). -\item Do not use the word ``essentially'' to mean ``approximately'' or ``effectively''. -\item In your paper title, if the words ``that uses'' can accurately replace the word ``using'', capitalize the ``u''; if not, keep using lower-cased. -\item Be aware of the different meanings of the homophones ``affect'' and ``effect'', ``complement'' and ``compliment'', ``discreet'' and ``discrete'', ``principal'' and ``principle''. -\item Do not confuse ``imply'' and ``infer''. -\item The prefix ``non'' is not a word; it should be joined to the word it modifies, usually without a hyphen. -\item There is no period after the ``et'' in the Latin abbreviation ``et al.''. -\item The abbreviation ``i.e.'' means ``that is'', and the abbreviation ``e.g.'' means ``for example''. -\end{itemize} -An excellent style manual for science writers is \cite{b7}. - -\subsection{Authors and Affiliations} -\textbf{The class file is designed for, but not limited to, six authors.} A -minimum of one author is required for all conference articles. Author names -should be listed starting from left to right and then moving down to the -next line. This is the author sequence that will be used in future citations -and by indexing services. Names should not be listed in columns nor group by -affiliation. Please keep your affiliations as succinct as possible (for -example, do not differentiate among departments of the same organization). - -\subsection{Identify the Headings} -Headings, or heads, are organizational devices that guide the reader through -your paper. There are two types: component heads and text heads. - -Component heads identify the different components of your paper and are not -topically subordinate to each other. Examples include Acknowledgments and -References and, for these, the correct style to use is ``Heading 5''. Use -``figure caption'' for your Figure captions, and ``table head'' for your -table title. Run-in heads, such as ``Abstract'', will require you to apply a -style (in this case, italic) in addition to the style provided by the drop -down menu to differentiate the head from the text. - -Text heads organize the topics on a relational, hierarchical basis. For -example, the paper title is the primary text head because all subsequent -material relates and elaborates on this one topic. If there are two or more -sub-topics, the next level head (uppercase Roman numerals) should be used -and, conversely, if there are not at least two sub-topics, then no subheads -should be introduced. - -\subsection{Figures and Tables} -\paragraph{Positioning Figures and Tables} Place figures and tables at the top and -bottom of columns. Avoid placing them in the middle of columns. Large -figures and tables may span across both columns. Figure captions should be -below the figures; table heads should appear above the tables. Insert -figures and tables after they are cited in the text. Use the abbreviation -``Fig.~\ref{fig}'', even at the beginning of a sentence. - -\begin{table}[htbp] -\caption{Table Type Styles} -\begin{center} -\begin{tabular}{|c|c|c|c|} -\hline -\textbf{Table}&\multicolumn{3}{|c|}{\textbf{Table Column Head}} \\ -\cline{2-4} -\textbf{Head} & \textbf{\textit{Table column subhead}}& \textbf{\textit{Subhead}}& \textbf{\textit{Subhead}} \\ -\hline -copy& More table copy$^{\mathrm{a}}$& & \\ -\hline -\multicolumn{4}{l}{$^{\mathrm{a}}$Sample of a Table footnote.} -\end{tabular} -\label{tab1} -\end{center} -\end{table} - -\begin{figure}[htbp] -\centerline{\includegraphics{fig1.png}} -\caption{Example of a figure caption.} -\label{fig} -\end{figure} - -Figure Labels: Use 8 point Times New Roman for Figure labels. Use words -rather than symbols or abbreviations when writing Figure axis labels to -avoid confusing the reader. As an example, write the quantity -``Magnetization'', or ``Magnetization, M'', not just ``M''. If including -units in the label, present them within parentheses. Do not label axes only -with units. In the example, write ``Magnetization (A/m)'' or ``Magnetization -\{A[m(1)]\}'', not just ``A/m''. Do not label axes with a ratio of -quantities and units. For example, write ``Temperature (K)'', not -``Temperature/K''. - -\section*{Acknowledgment} - -The preferred spelling of the word ``acknowledgment'' in America is without -an ``e'' after the ``g''. Avoid the stilted expression ``one of us (R. B. -G.) thanks $\ldots$''. Instead, try ``R. B. G. thanks$\ldots$''. Put sponsor -acknowledgments in the unnumbered footnote on the first page. - -\section*{References} - -Please number citations consecutively within brackets \cite{b1}. The -sentence punctuation follows the bracket \cite{b2}. Refer simply to the reference -number, as in \cite{b3}---do not use ``Ref. \cite{b3}'' or ``reference \cite{b3}'' except at -the beginning of a sentence: ``Reference \cite{b3} was the first $\ldots$'' - -Number footnotes separately in superscripts. Place the actual footnote at -the bottom of the column in which it was cited. Do not put footnotes in the -abstract or reference list. Use letters for table footnotes. - -Unless there are six authors or more give all authors' names; do not use -``et al.''. Papers that have not been published, even if they have been -submitted for publication, should be cited as ``unpublished'' \cite{b4}. Papers -that have been accepted for publication should be cited as ``in press'' \cite{b5}. -Capitalize only the first word in a paper title, except for proper nouns and -element symbols. - -For papers published in translation journals, please give the English -citation first, followed by the original foreign-language citation \cite{b6}. - -\begin{thebibliography}{00} -\bibitem{b1} G. Eason, B. Noble, and I. N. Sneddon, ``On certain integrals of Lipschitz-Hankel type involving products of Bessel functions,'' Phil. Trans. Roy. Soc. London, vol. A247, pp. 529--551, April 1955. -\bibitem{b2} J. Clerk Maxwell, A Treatise on Electricity and Magnetism, 3rd ed., vol. 2. Oxford: Clarendon, 1892, pp.68--73. -\bibitem{b3} I. S. Jacobs and C. P. Bean, ``Fine particles, thin films and exchange anisotropy,'' in Magnetism, vol. III, G. T. Rado and H. Suhl, Eds. New York: Academic, 1963, pp. 271--350. -\bibitem{b4} K. Elissa, ``Title of paper if known,'' unpublished. -\bibitem{b5} R. Nicole, ``Title of paper with only first word capitalized,'' J. Name Stand. Abbrev., in press. -\bibitem{b6} Y. Yorozu, M. Hirano, K. Oka, and Y. Tagawa, ``Electron spectroscopy studies on magneto-optical media and plastic substrate interface,'' IEEE Transl. J. Magn. Japan, vol. 2, pp. 740--741, August 1987 [Digests 9th Annual Conf. Magnetics Japan, p. 301, 1982]. -\bibitem{b7} M. Young, The Technical Writer's Handbook. Mill Valley, CA: University Science, 1989. -\end{thebibliography} -\vspace{12pt} -\color{red} -IEEE conference templates contain guidance text for composing and formatting conference papers. Please ensure that all template text is removed from your conference paper prior to submission to the conference. Failure to remove the template text from your paper may result in your paper not being published. - -\end{document} diff --git a/SAT_package_paper/Conference-LaTeX-template_10-17-19/figures/expr-tree.tex b/SAT_package_paper/Conference-LaTeX-template_10-17-19/figures/expr-tree.tex deleted file mode 100644 index 520861a..0000000 --- a/SAT_package_paper/Conference-LaTeX-template_10-17-19/figures/expr-tree.tex +++ /dev/null @@ -1,16 +0,0 @@ - \begin{tikzpicture}[level distance=3em, - level 1/.style={sibling distance=6em}, - level 2/.style={sibling distance=3em}] - \node[rectangle, draw] {and} - child {node[rectangle, draw] {>} - child{node[rectangle, draw] {a}} - child{node[rectangle, draw] {+} - child{node[rectangle, draw] {1}} - child{node[rectangle, draw] {b}} - } - } - child {node[rectangle, draw] {>=} - child {node[rectangle, draw] {b}} - child {node[rectangle, draw] {0}} - }; - \end{tikzpicture} \ No newline at end of file diff --git a/SAT_package_paper/Conference-LaTeX-template_10-17-19/figures/smt-lib.tex b/SAT_package_paper/Conference-LaTeX-template_10-17-19/figures/smt-lib.tex deleted file mode 100644 index 0e5d2a4..0000000 --- a/SAT_package_paper/Conference-LaTeX-template_10-17-19/figures/smt-lib.tex +++ /dev/null @@ -1,21 +0,0 @@ -\begin{tikzpicture} -\node[rectangle, draw, align=center, text width=2cm] (a) {Solver\\(start mode)}; -\node[align=left, above=4.5mm of a.north east] (in1) {(set-logic ...)}; - -\node[rectangle, draw, align=center, text width=2.6cm] (b) [right=5mm of a] {Solver\\(assert mode)}; -\node at (b) [align=left, above right = 14mm and -10mm] (in2) {(declare-const ...)\\(define-fun ...)\\(assert ...)}; - -\node at (b) [align=left, above right=9mm and 6mm] (in2) {(check-sat)}; - -\node[rectangle, draw, align=center, text width=2cm, ] (c) [right=5mm of b] {Solver\\(sat mode)}; -\node at (c) [align=left, above right=13mm and -8mm] (in2) {(get-model)}; -% https://tikz.dev/tikz-arrows#sec-16.3.3 -\draw [draw = blue, thick, -arrows={ - -> [bend,]}] -(a) edge [bend left=45] (b) -(b) edge [in=70, out=110,looseness=8] (b) -(b) edge [bend left=45] (c) -(c) edge [in=70, out=110,looseness=8] (c); - -\end{tikzpicture} \ No newline at end of file diff --git a/SAT_package_paper/Conference-LaTeX-template_10-17-19/paper-blx.bib b/SAT_package_paper/Conference-LaTeX-template_10-17-19/paper-blx.bib deleted file mode 100644 index 880a27d..0000000 --- a/SAT_package_paper/Conference-LaTeX-template_10-17-19/paper-blx.bib +++ /dev/null @@ -1,11 +0,0 @@ -@Comment{$ biblatex control file $} -@Comment{$ biblatex version 2.9 $} -Do not modify this file! - -This is an auxiliary file used by the 'biblatex' package. -This file may safely be deleted. It will be recreated as -required. - -@Control{biblatex-control, - options = {2.9:0:0:1:0:1:1:0:0:0:0:0:3:3:79:+:none}, -} diff --git a/SAT_package_paper/Conference-LaTeX-template_10-17-19/paper.tex b/SAT_package_paper/Conference-LaTeX-template_10-17-19/paper.tex deleted file mode 100644 index 53aff3d..0000000 --- a/SAT_package_paper/Conference-LaTeX-template_10-17-19/paper.tex +++ /dev/null @@ -1,501 +0,0 @@ -\documentclass[conference]{IEEEtran} -\IEEEoverridecommandlockouts -% The preceding line is only needed to identify funding in the first footnote. If that is unneeded, please comment it out. -%\usepackage{cite} -\usepackage[utf8]{inputenc} -\usepackage{amsmath,amssymb,amsfonts} -\usepackage{algorithmic} -\usepackage{graphicx} -\usepackage{tablefootnote} -\usepackage{textcomp} -\usepackage{tikz} -\usetikzlibrary {positioning, bending} -\usepackage{fontspec} -\setmonofont{FreeMono} % has unicode symbols https://tex.stackexchange.com/questions/581407/how-can-i-get-both-greek-and-unicode-characters-to-render-in-a-verbatim-environm -% \setmonofont{DejaVu Mono} -\usepackage{xcolor} -%\def\BibTeX{{\rm B\kern-.05em{\sc i\kern-.025em b}\kern-.08em -% T\kern-.1667em\lower.7ex\hbox{E}\kern-.125emX}} -\usepackage[ -backend=bibtex, -style=ieee, -]{biblatex} -\bibliography{bibliography.bib} - -\begin{document} - -\title{BooleanSatisfiability.jl: Satisfiability Modulo Theories in Julia\\ -\thanks{This work was supported by a grant from Ford Motor Company.} %TODO grant #? -} - -\author{\IEEEauthorblockN{1\textsuperscript{st} Emiko Soroka} -\IEEEauthorblockA{\textit{Aeronautics and Astronautics} \\ -\textit{Stanford University}\\ -Stanford, USA \\ -esoroka@stanford.edu} -\and -\IEEEauthorblockN{2\textsuperscript{nd} Sanjay Lall} -\IEEEauthorblockA{\textit{Electrical Engineering} \\ -\textit{Stanford University}\\ -Stanford, USA \\ -lall@stanford.edu} -\and -\IEEEauthorblockN{3\textsuperscript{rd} Mykel Kochenderfer} -\IEEEauthorblockA{\textit{Aeronautics and Astronautics} \\ - \textit{Stanford University}\\ - Stanford, USA \\ - mykel@stanford.edu} -} - -\maketitle - -\begin{abstract} -Automated theorem provers such as Z3 and CVC5 can check the satisfiability or validity of a logical formula stated in one or more theories. These provers, and the satisfiability modulo theories (SMT) problems they solve, have applications in formal verification including practical tasks such as proving the security of firewall configurations or the correctness of safety-critical software. While the SMT-LIB specification language can be used to interact with theorem proving software, a high-level interface allows for faster and easier specifications of complex SMT formulae. In this paper we present such an interface for the Julia programming language. -\end{abstract} - -\begin{IEEEkeywords} -automated reasoning, theorem prover, satisfiability modulo theories, julia package, smtlib -\end{IEEEkeywords} - -\section{Introduction} -Satisfiability modulo theories (SMT) is a general framework for computational theorem proving, in which the goal is to algorithmically find a satisfying assignment of variables such that one or more logical statements hold true. SMT encompasses a broad class of problems including the theories of propositional logic, integer arithmetic, floating-point arithmetic, and data structures. SMT formulae are used in formal verification and model checking to prove or disprove the correctness of a system \cite{de2011satisfiabilityintro}. - -A decision procedure for an SMT problem is an algorithm that either finds such an assignment or determines that the given formula is unsatisfiable. Theorem proving software such as Z3 or CVC5 \cite{z3, cvc5} uses decision procedures to check SMT formulae and find satisfying assignments where possible. However, theorem provers themselves are low-level tools intended to be integrated into other software. - -This paper introduces \verb|BooleanSatisfiability.jl|, a Julia package providing a high-level representation for SMT formulae including propositional logic, integer and real-valued arithmetic.% TODO, and IEEE floating-point numbers. -The Julia programming language is ideal for scientific computing due to its use of type inference, multiple dispatch, and just-in-time compilation to improve performance \cite{bezanson2017julia, perkel2019juliaspeed}. Although Julia has a smaller software ecosystem compared to Matlab or scientific Python, it has successfully been used in high-performance applications including machine learning \cite{GAO2020juliaml} and GPU programming \cite{besard2018juliagpu}. -\verb|BooleanSatisfiability.jl| is the first package to provide an interface for SMT solving in Julia. - -\section{Prior Work} -Two popular theorem provers are Z3, developed by Microsoft Research, and the open-source prover CVC5. Both provers including bindings for multiple programming languages, allowing access to some or all functionality with varying levels of abstraction. Additionally, both Z3 and CVC5 accept commands in the SMT-LIB specification language \cite{smtlib2}. - -Similar packages are available in other languages; for example, \verb|PySMT| provides a high-level SAT interface using the same strategy of translation to SMT-LIB commands \cite{pysmt2015}. -To our knowledge, \verb|BooleanSatisfiability.jl| is the first Julia package to use the SMT-LIB format for interactions with solvers, allowing compatibility with any theorem prover that supports SMT-LIB. - -\section{Introduction to SMT} -(TO DO) - -For an in-depth treatment of computational logic and the associated decision procedures, readers are referred to \cite{bradley2007calculus, kroening2016decision}. A shorter overview of SMT is available in \cite{de2011satisfiabilityintro}. -% TODO a section on SMT here? - -\section{The SMT-LIB specification language} -SMT-LIB is a low-level specification language designed to standardize interactions with theorem provers. At time of writing, the current SMT-LIB standard is V2.6; we used this version of the language specification when implementing our software. To disambiguate between SMT (satisfiability modulo theories) and this specification language, we always refer to the language as SMT-LIB. - -SMT-LIB uses a Lisp-like syntax designed to simplify input parsing. It is intended to provide an interactive interface for theorem proving similar to Julia's REPL. SMT-LIB supports declaring variables, defining functions, making assertions (e.g. requiring that a Boolean formula be true), and issuing solver commands. Figure ? % TODO \ref{fig:smtbasic} -provides an example of an SMT solver moving between modes. - -SMT expressions have an associated \textit{sort}, which constrains what functions or operations are valid for a given expression. For example, the SMT-LIB variable declaration \verb|(declare-const a Int)| declares a symbol \verb|a| with sort \verb|Int|, and the function definition \verb|(define-fun f () Bool (> a 1))| defines a function \verb|a > 1| with sort \verb|Bool|. The concept of SMT sorts maps cleanly onto Julia's type system. - -%(TO DO should we discuss SMT-LIB more here?) %TODO - -Figure \ref{fig:smt-lib} shows a simple example of a solver moving between modes as statements are received. -One limitation of SMT-LIB is that many commands are only valid in specific solver modes. -For example, the command \verb|(get-model)| retrieves the satisfying assignment for a formula and is only valid in \verb|sat| mode, while \verb|(get-unsat-core)| is only valid in \verb|unsat| mode. Issuing a command in the wrong mode yields an error, thus many useful sequences of SMT-LIB commands cannot be scripted in advance. - -\begin{figure}[h] - \centering - \input{figures/smt-lib.tex} - \caption{A simple interaction with an SMT-LIB standard solver. If the formula \texttt{assert}ed in assert mode was unsatisfiable, the solver would instead enter unsat mode and a different set of commands would be valid.} - \label{fig:smt-lib} -\end{figure} - -For a full description of SMT-LIB, readers are referred to \cite{smtlib2}. As the purpose of our software is to provide an abstraction on top of SMT-LIB, we refrain from an in-depth description of the language. Knowledge of SMT-LIB is not required to understand and use the basic functionality of \verb|BooleanSatisfiability.jl|. - -In this section we make use of Julia's type notation \verb|f(x::Type)| to disambiguate the types of function arguments when necessary. - -\section{Package Design} - -Our software facilitates the construction and SMT-LIB representation of SMT formulae, along with providing a simple interface to SMT-LIB compliant theorem provers. - -The basic unit of a formula in our software is the expression (Figure \ref{fig:expr-tree}). - -\begin{figure}[h] - \centering - \input{figures/expr-tree.tex} - \caption{The expression \texttt{and(a > b + 1, b >= 0)}.} - \label{fig:expr-tree} -\end{figure} - -Expressions may represent single variables or operators combining expressions. An abstract type \verb|AbstractExpr| is provided. Concrete types inheriting from \verb|AbstractExpr| implement a tree structure capable of representing arbitrarily complex nested expressions. Julia's type system prevents expressions from being incorrectly combined operators. For example, $\neg\verb|x|$ is only valid if \verb|x| is of type \verb|BoolExpr|. - -Output types of operations follow type compatibility and promotion rules; for example, if \verb|x| is a \verb|BoolExpr| and \verb|a| is an \verb|IntExpr|, \verb|x + a| is an \verb|IntExpr|. - -\subsection{Expressions} -Variables are declared using \verb|@satvariable|. Vector- and matrix-valued variables are arrays of single-valued expressions; thus, Julia's built in array functionality allows operators to be broadcast across said variables. - -Elements of vector and matrix expressions are assigned human-readable names of the form \verb|name_i_j|. -\begin{verbatim} -@satvariable(x[1:2], Bool) -# x is an array of BoolExprs -# with names x_1, x_2 - -@satvariable(y[1:2, 1:3], Bool) -# y is an array of BoolExprs -# with names y_1_1, y_1_2, ... y_2_3 -\end{verbatim} - -Expressions constructed from operators and variables take names of the format \verb|OP_HASH| where \verb|OP| is the operator name and \verb|HASH| is computed from the names of child expressions using Julia's deterministic hash function. This ensures all expressions have unique names and allows components of nested expressions to be re-used when generating the SMT-LIB representation of an expression. In future versions of our software, this could also allow for optimization by memoizing large expressions with repeated smaller components. - -Expressions are simplified where possible: specifically, \verb|not(not(expr))| simplifies to \verb|expr|, and nested conjunctions or disjunctions are flattened. - -\subsection{Constants} -Constants are automatically wrapped. Julia's native \verb|Bool|, \verb|Int|, and \verb|Float64| types interoperate with our \verb|BoolExpr|, \verb|IntExpr| and \verb|RealExpr| types as expected, following type promotion rules. - -Numeric constants are combined when possible: for example, \verb|true + 2| will be stored as integer \verb|3| and \verb|1 + 2.5| is promoted to \verb|3.5|. Logical expressions involving constants can often be simplified. The following examples are provided. -\begin{verbatim} -@satvariable(z, Bool) -and(false, z) # returns false -implies(false, z) # returns true -iff(z, false) # returns not(z) -\end{verbatim} - -\subsection{SMT-LIB representation} - -While SMT-LIB permits expressions of arbitrary complexity, our software limits the depth of nested expressions by generating sub-expressions using SMT-LIB's \verb|(define-fun)| to define sub-expressions without \verb|assert|ing them. % TODO clean up this part -A representative example is provided below, with hashed names shortened for readability. -\begin{verbatim} -@satvariable(x, Bool) -@satvariable(y, Bool) -expr = or(¬x, and(¬x, y)) -print(smt(expr)) -> (declare-const x Bool) -> (declare-const y Bool) -> (define-fun NOT_53b20e () Bool (not x)) -> (define-fun AND_eb3b71 () Bool - (and NOT_53b20e y)) -> (define-fun OR_90de3d - () Bool (or AND_eb3b71 NOT_53b20e)) -> (assert OR_90de3d) -\end{verbatim} -Note that although \verb|not(x)| appears twice in \verb|expr|, it is defined once and reused. - -\subsection{Interacting with Solvers} -Internally, our package uses Julia's \verb|Process| library to interact with a solver via input and output pipes. This supports the interactive nature of SMT-LIB, which necessitates a two-way connection with the solver. -%TODO diagram of this process thing -This design provides several benefits. By transparently documenting how our software manages sessions with solvers, we eliminate many of the difficulties that arise when calling software dependencies. The process to make solvers available for \verb|BooleanSatisfiability.jl| on any system is fundamentally the same: the user must install the solver and ensure it can be invoked from their machine's command line. Users can customize the command used to invoke a solver. This provides a single mechanism for interacting with SMT-LIB compatible solvers that aren't explicitly supported; customizing options using command line flags; and working around machine-specific issues such as a solver being available under a different name or at a specific path. - -\section{Using The Package} -\subsection{Working with formulae}. -The function \verb|smt(e::AbstractExpr)| returns the SMT-LIB representation of expression \verb|e| as a string. If \verb|e| is a Boolean expression, \verb|smt| will assert \verb|e|; otherwise \verb|smt| will simply generate the SMT-LIB statements defining \verb|e|. This behavior can be controlled using the optional keyword argument \texttt{assert=true|false}. The related function \verb|save(e::AbstractExpr, filename="out")| writes the output of \verb|smt(e)| to the text file \verb|out.smt|. - -The function \verb|sat!(e::BoolExpr, solver::solver)| calls the given solver on \verb|e| and returns either \verb|:SAT|, \verb|:UNSAT|, or \verb|:ERROR|. If \verb|e| is \verb|:SAT|, the values of all nested expressions in \verb|e| are updated to allow easy retrieval of the satisfying assignment. If \verb|e| is \verb|:UNSAT|, the values of all nested expressions are set to \verb|nothing|. - -Note that \verb|sat!| can only be called on Boolean expressions, because the purpose of a theorem prover is to determine whether a Boolean statement is \verb|true| or \verb|false|. In comparison, one can generate the SMT-LIB representation of any \verb|AbstractExpr|, including non-Boolean expressions that do not represent valid SMT problems. Tables \ref{tab:bool_ops} and \ref{tab:arithmetic_ops} provide an overview of which operators return Boolean expressions. - -\section{Specifying an SMT Problem} -\subsection{Variables} -New variables are declared using the \verb|@satvariable| macro, which behaves similarly to the \verb|@variable| macro in JuMP \cite{Lubin2023}. -The \verb|@satvariable| macro takes two arguments: a variable name with optional size and shape (for creating vector-valued and matrix-valued variables), and the variable type. - -\begin{verbatim} -# Single BoolExpr -@satvariable(x, Bool) - -# n-vector of BoolExpr -@satvariable(y[1:n], Bool) - -# m x n vector of IntExpr -@satvariable(z[1:n], Int) -\end{verbatim} - -Variables may be combined using operations, which we distinguish by return type. -Boolean operations \verb|and|, \verb|or|, \verb|not|, \verb|xor|, \verb|implies|, \verb|iff|, and \verb|ite| (if-then-else) return Boolean expressions. - - -\subsection{Type Promotion} -Integer or real-valued operations \verb|+|, \verb|-|, \verb|*| return integer or real expressions using Julia type promotion rules. Division (\verb|/|) is only valid over real-valued expressions\footnote{Readers familiar with gradient-based or iterative optimization over real-valued variables should be aware that although SMT provides mechanisms to represent arithmetic over real values, decision procedures for the theory of real arithmetic are incomplete and often require an impractical amount of computation time. SMT is primarily used for representing problems involving discrete-valued variables and logical statements over said variables. -}. -\begin{verbatim} -@satvariable(a, Bool) -@satvariable(b, Int) -@satvariable(c, Real) - -a + b # returns IntExpr -b + c # returns RealExpr -a + b > 1 # returns BoolExpr -\end{verbatim} - -Type promotion also applies to constants. Continuing the above example: -\begin{verbatim} -b + true # IntExpr + Bool returns IntExpr -b + 1.0 # IntExpr + Real returns RealExpr -c + 1 # RealExpr + Int returns RealExpr -\end{verbatim} - -\subsection{Operators} -We define the following operators. -\begin{table}[h!] - \centering - \begin{tabular}{|c|c|c|c|c|} - %\hline - %\multicolumn{5}{1}{Boolean Operators}\\ - \hline - Operator & \# Inputs & Input Type(s) & Return Type & Symbol\\ - \hline - \verb|or| & $n\geq 2$ & \verb|BoolExpr| & \verb|BoolExpr| & \verb|any|, \verb|∨|\\ - \hline - \verb|and| & $n\geq 2$ & \verb|BoolExpr| & \verb|BoolExpr| & \verb|all|, \verb|∧|\\ - \hline - \verb|not| & 1 & \verb|BoolExpr| & \verb|BoolExpr| & \verb|¬|\\ - \hline - \verb|implies| & 2 & \verb|BoolExpr| & \verb|BoolExpr| & \verb|⟹|\\ - \hline - \verb|xor| & $n\geq 2$ & \verb|BoolExpr| & \verb|BoolExpr| & \verb|⊻|\\ - \hline - \verb|iff| & 2 & \verb|BoolExpr| & \verb|BoolExpr| & \verb|⟺|\\ - \hline - \verb|ite|\tablefootnote{The operator \texttt{ite} refers to ``if-then-else". \texttt{ite(x, y, z)} is equivalent to \texttt{(x ⟹ y) ∧ (¬x ⟹ z)}.} - & 3 & \verb|BoolExpr| & \verb|BoolExpr| & ~\\ - \hline - \end{tabular} -\caption{Boolean operators.} -\label{tab:bool_ops} -\end{table} - -\begin{table}[h!] - \centering - \begin{tabular}{|c|c|c|c|} - %\hline - %\multicolumn{5}{|1|}{Arithmetic Operators}\\ - \hline - Operator & Input Type(s) & Return Type\\ - \hline - \verb|>| & Any numeric expr. & \verb|BoolExpr| \\ - \hline - \verb|>=| & Any numeric expr. & \verb|BoolExpr| \\ - \hline - \verb|<| & Any numeric expr. & \verb|BoolExpr| \\ - \hline - \verb|<=| & Any numeric expr. & \verb|BoolExpr| \\ - \hline - \verb|==|\tablefootnote{To check whether two \texttt{AbstractExpr} are equivalent, use \texttt{isequal}.} - & Any numeric expr. & \verb|BoolExpr| \\ - \hline - \verb|-| (unary) & \verb|IntExpr|, \verb|RealExpr| & \verb|IntExpr|, \verb|RealExpr|\\ - \hline - \verb|+| & Any numeric expr. & \verb|IntExpr|, \verb|RealExpr| \\ - \hline - \verb|-| & Any numeric expr.& \verb|IntExpr|, \verb|RealExpr| \\ - \hline - \verb|*| & Any numeric expr. & \verb|IntExpr|, \verb|RealExpr| \\ - \hline - \verb|/| & \verb|RealExpr|& \verb|RealExpr| \\ - \hline -\end{tabular} -\caption{Comparison and arithmetic operators. Where ``Any numeric expr" is listed, this refers to \texttt{BoolExpr}, \texttt{IntExpr}, \texttt{RealExpr}, or a \texttt{Bool}, \texttt{Int}, or \texttt{Float} constant. The return type of an arithmetic operator is determined by Julia's \texttt{Int} and \texttt{Float} type promotion rules.} -\label{tab:arithmetic_ops} -\end{table} - -\subsection{Operator Precedence} -Julia defines the operator precedence and associativity for all symbolic operators defined in this package. -For the most up-to-date description of Julia's operator precedence rules, see \cite{Julia_documentation_2023}. -One can also determine operator precedence using the call \verb|Base.operator_precedence(s)| where \verb|s| is a symbol (e.g. \verb|:+| or \verb|:*|). Higher numbers indicate greater precedence. - -Precedence and associativity rules can yield misleading expressions or unexpected type errors. Readers are encouraged to parenthesize expressions, avoiding potential sources of confusion. The following illustrative examples are provided. - -\begin{verbatim} -@satvariable(x, Bool) -@satvariable(y, Bool) -@satvariable(z, Bool) - -x⟹y ∧ y⟹z -# this is implies(x, implies(and(y, y), z)) -# it is not (x⟹y) ∧ (y⟹z) - -x ∧ y + z # equivalent to (x ∧ y) + z - -@satvariable(a, Int) -@satvariable(b, Int) - -a >= 1 ∨ b >= 1 # yields a type error -(a >= 1) ∨ (b >= 1) # valid expression -\end{verbatim} - -\section{Examples} -% TODO - -\subsection*{Custom solver interactions} -We expose the low-level interface, allowing advanced users to send SMT commands and receive prover responses. Users are responsible for ensuring the correctness of these commands, as well as interpreting the results. In this use case, \verb|BooleanSatisfiability.jl| can be used to automate generation of the SMT problem and programmatically interact with solvers, extending the usability of the SMT interface. - -\section{Conclusions} -We have successfully developed a Julia package providing a simple, high-level interface to SMT-LIB compatible solvers. Our package takes advantage of Julia's functionality to construct a simple and extensible interface; we use multiple dispatch to optimize and simplify operations over constants, the type system to enforce the correctness of SMT expressions, and \verb|Base.Process| to interact with SMT-LIB solvers. - -\section{Acknowledgements} -The software architecture of \verb|BooleanSatisfiability.jl| was inspired by \verb|Convex.jl|, \verb|JuMP|, and \verb|PySMT| \cite{convexjl, Lubin2023, pysmt2015}. Ideas, suggestions and feedback on the package's user interface were provided by Prof. Mykel Kochenderfer. - -\section{Future Work} - -\printbibliography - - -%\subsection{Maintaining the Integrity of the Specifications} - -%\subsection{Abbreviations and Acronyms}\label{AA} -%Define abbreviations and acronyms the first time they are used in the text, -%even after they have been defined in the abstract. Abbreviations such as -%IEEE, SI, MKS, CGS, ac, dc, and rms do not have to be defined. Do not use -%abbreviations in the title or heads unless they are unavoidable. - -%\subsection{Equations} -%Number equations consecutively. To make your -%equations more compact, you may use the solidus (~/~), the exp function, or -%appropriate exponents. Italicize Roman symbols for quantities and variables, -%but not Greek symbols. Use a long dash rather than a hyphen for a minus -%sign. Punctuate equations with commas or periods when they are part of a -%sentence, as in: -%\begin{equation} -%a+b=\gamma\label{eq} -%\end{equation} - -%Be sure that the -%symbols in your equation have been defined before or immediately following -%the equation. Use ``\eqref{eq}'', not ``Eq.~\eqref{eq}'' or ``equation \eqref{eq}'', except at -%the beginning of a sentence: ``Equation \eqref{eq} is . . .'' - -%\subsection{\LaTeX-Specific Advice} - -%Please note that the \verb|{subequations}| environment in {\LaTeX} -%will increment the main equation counter even when there are no -%equation numbers displayed. If you forget that, you might write an -%article in which the equation numbers skip from (17) to (20), causing -%the copy editors to wonder if you've discovered a new method of -%counting. - -%{\BibTeX} does not work by magic. It doesn't get the bibliographic -%data from thin air but from .bib files. If you use {\BibTeX} to produce a -%bibliography you must send the .bib files. - -%{\LaTeX} can't read your mind. If you assign the same label to a -%subsubsection and a table, you might find that Table I has been cross -%referenced as Table IV-B3. - -%{\LaTeX} does not have precognitive abilities. If you put a -%\verb|\label| command before the command that updates the counter it's -%supposed to be using, the label will pick up the last counter to be -%cross referenced instead. In particular, a \verb|\label| command -%should not go before the caption of a figure or a table. - -%Do not use \verb|\nonumber| inside the \verb|{array}| environment. It -%will not stop equation numbers inside \verb|{array}| (there won't be -%any anyway) and it might stop a wanted equation number in the -%surrounding equation. - -%\subsection{Some Common Mistakes}\label{SCM} -%\begin{itemize} -%\item The word ``data'' is plural, not singular. -%\item The subscript for the permeability of vacuum $\mu_{0}$, and other common scientific constants, is zero with subscript formatting, not a lowercase letter ``o''. -%\item In American English, commas, semicolons, periods, question and exclamation marks are located within quotation marks only when a complete thought or name is cited, such as a title or full quotation. When quotation marks are used, instead of a bold or italic typeface, to highlight a word or phrase, punctuation should appear outside of the quotation marks. A parenthetical phrase or statement at the end of a sentence is punctuated outside of the closing parenthesis (like this). (A parenthetical sentence is punctuated within the parentheses.) -%\item A graph within a graph is an ``inset'', not an ``insert''. The word alternatively is preferred to the word ``alternately'' (unless you really mean something that alternates). -%\item Do not use the word ``essentially'' to mean ``approximately'' or ``effectively''. -%\item In your paper title, if the words ``that uses'' can accurately replace the word ``using'', capitalize the ``u''; if not, keep using lower-cased. -%\item Be aware of the different meanings of the homophones ``affect'' and ``effect'', ``complement'' and ``compliment'', ``discreet'' and ``discrete'', ``principal'' and ``principle''. -%\item Do not confuse ``imply'' and ``infer''. -%\item The prefix ``non'' is not a word; it should be joined to the word it modifies, usually without a hyphen. -%\item There is no period after the ``et'' in the Latin abbreviation ``et al.''. -%\item The abbreviation ``i.e.'' means ``that is'', and the abbreviation ``e.g.'' means ``for example''. -%\end{itemize} -%An excellent style manual for science writers is \cite{b7}. - - -%\subsection{Identify the Headings} -%Headings, or heads, are organizational devices that guide the reader through -%your paper. There are two types: component heads and text heads. -% -%Component heads identify the different components of your paper and are not -%topically subordinate to each other. Examples include Acknowledgments and -%References and, for these, the correct style to use is ``Heading 5''. Use -%``figure caption'' for your Figure captions, and ``table head'' for your -%table title. Run-in heads, such as ``Abstract'', will require you to apply a -%style (in this case, italic) in addition to the style provided by the drop -%down menu to differentiate the head from the text. -% -%Text heads organize the topics on a relational, hierarchical basis. For -%example, the paper title is the primary text head because all subsequent -%material relates and elaborates on this one topic. If there are two or more -%sub-topics, the next level head (uppercase Roman numerals) should be used -%and, conversely, if there are not at least two sub-topics, then no subheads -%should be introduced. -% -%\subsection{Figures and Tables} -%\paragraph{Positioning Figures and Tables} Place figures and tables at the top and -%bottom of columns. Avoid placing them in the middle of columns. Large -%figures and tables may span across both columns. Figure captions should be -%below the figures; table heads should appear above the tables. Insert -%figures and tables after they are cited in the text. Use the abbreviation -%``Fig.~\ref{fig}'', even at the beginning of a sentence. -% -%\begin{table}[htbp] -%\caption{Table Type Styles} -%\begin{center} -%\begin{tabular}{|c|c|c|c|} -%\hline -%\textbf{Table}&\multicolumn{3}{|c|}{\textbf{Table Column Head}} \\ -%\cline{2-4} -%\textbf{Head} & \textbf{\textit{Table column subhead}}& \textbf{\textit{Subhead}}& \textbf{\textit{Subhead}} \\ -%\hline -%copy& More table copy$^{\mathrm{a}}$& & \\ -%\hline -%\multicolumn{4}{l}{$^{\mathrm{a}}$Sample of a Table footnote.} -%\end{tabular} -%\label{tab1} -%\end{center} -%\end{table} -% -%\begin{figure}[htbp] -%\centerline{\includegraphics{fig1.png}} -%\caption{Example of a figure caption.} -%\label{fig} -%\end{figure} -% -%Figure Labels: Use 8 point Times New Roman for Figure labels. Use words -%rather than symbols or abbreviations when writing Figure axis labels to -%avoid confusing the reader. As an example, write the quantity -%``Magnetization'', or ``Magnetization, M'', not just ``M''. If including -%units in the label, present them within parentheses. Do not label axes only -%with units. In the example, write ``Magnetization (A/m)'' or ``Magnetization -%\{A[m(1)]\}'', not just ``A/m''. Do not label axes with a ratio of -%quantities and units. For example, write ``Temperature (K)'', not -%``Temperature/K''. -% -%\section*{Acknowledgment} -% -%The preferred spelling of the word ``acknowledgment'' in America is without -%an ``e'' after the ``g''. Avoid the stilted expression ``one of us (R. B. -%G.) thanks $\ldots$''. Instead, try ``R. B. G. thanks$\ldots$''. Put sponsor -%acknowledgments in the unnumbered footnote on the first page. -% -%\section*{References} -% -%Please number citations consecutively within brackets \cite{b1}. The -%sentence punctuation follows the bracket \cite{b2}. Refer simply to the reference -%number, as in \cite{b3}---do not use ``Ref. \cite{b3}'' or ``reference \cite{b3}'' except at -%the beginning of a sentence: ``Reference \cite{b3} was the first $\ldots$'' -% -%Number footnotes separately in superscripts. Place the actual footnote at -%the bottom of the column in which it was cited. Do not put footnotes in the -%abstract or reference list. Use letters for table footnotes. -% -%Unless there are six authors or more give all authors' names; do not use -%``et al.''. Papers that have not been published, even if they have been -%submitted for publication, should be cited as ``unpublished'' \cite{b4}. Papers -%that have been accepted for publication should be cited as ``in press'' \cite{b5}. -%Capitalize only the first word in a paper title, except for proper nouns and -%element symbols. -% -%For papers published in translation journals, please give the English -%citation first, followed by the original foreign-language citation \cite{b6}. -% -%\begin{thebibliography}{00} -%\bibitem{b1} G. Eason, B. Noble, and I. N. Sneddon, ``On certain integrals of Lipschitz-Hankel type involving products of Bessel functions,'' Phil. Trans. Roy. Soc. London, vol. A247, pp. 529--551, April 1955. -%\bibitem{b2} J. Clerk Maxwell, A Treatise on Electricity and Magnetism, 3rd ed., vol. 2. Oxford: Clarendon, 1892, pp.68--73. -%\bibitem{b3} I. S. Jacobs and C. P. Bean, ``Fine particles, thin films and exchange anisotropy,'' in Magnetism, vol. III, G. T. Rado and H. Suhl, Eds. New York: Academic, 1963, pp. 271--350. -%\bibitem{b4} K. Elissa, ``Title of paper if known,'' unpublished. -%\bibitem{b5} R. Nicole, ``Title of paper with only first word capitalized,'' J. Name Stand. Abbrev., in press. -%\bibitem{b6} Y. Yorozu, M. Hirano, K. Oka, and Y. Tagawa, ``Electron spectroscopy studies on magneto-optical media and plastic substrate interface,'' IEEE Transl. J. Magn. Japan, vol. 2, pp. 740--741, August 1987 [Digests 9th Annual Conf. Magnetics Japan, p. 301, 1982]. -%\bibitem{b7} M. Young, The Technical Writer's Handbook. Mill Valley, CA: University Science, 1989. -%\end{thebibliography} -%\vspace{12pt} -%\color{red} -%IEEE conference templates contain guidance text for composing and formatting conference papers. Please ensure that all template text is removed from your conference paper prior to submission to the conference. Failure to remove the template text from your paper may result in your paper not being published. - -\end{document} From fb88fa25b7d586a30b4a57a66d05989c05ed5204 Mon Sep 17 00:00:00 2001 From: Emiko Soroka Date: Wed, 9 Aug 2023 22:30:17 -0700 Subject: [PATCH 16/36] working on BitVector, added all ops in SMT-LIB + some specific to z3. No docstrings, tests, SMT generation or parsing yet. --- src/BitVectorExpr.jl | 204 +++++++++++++++++++++++++++++++++++ src/BooleanOperations.jl | 14 +++ src/BooleanSatisfiability.jl | 3 +- src/IntExpr.jl | 8 +- 4 files changed, 224 insertions(+), 5 deletions(-) create mode 100644 src/BitVectorExpr.jl diff --git a/src/BitVectorExpr.jl b/src/BitVectorExpr.jl new file mode 100644 index 0000000..810237b --- /dev/null +++ b/src/BitVectorExpr.jl @@ -0,0 +1,204 @@ +import Base.BitVector, Base.length, Base.cat, Base.getindex +import Base.+, Base.-, Base.*, Base.<<, Base.>>, Base.>>>, Base.div +import Base.>, Base.>=, Base.<, Base.<= +# >>> is arithmetic shift right, corresponding to bvashr in SMT-LIB +# >> is logical shift right, bvlshr in SMT-LIB +# << is logical shift left, bvshl in SMT-LIB +# where operators exist (or, and, not, xor) +# Base.rem and Base.% both implement the remainder in integer division. + +mutable struct BitVectorExpr{T<:Integer} <: AbstractExpr + op :: Symbol + children :: Array{AbstractExpr} + value :: Union{T, Nothing, Missing} + name :: String + length :: Int +end + +""" + BitVector("a", n) + + Construct a single BitVector variable with name "a" and length n. Note that unlike Bool, Int, and Real, one cannot construct an array of BitVectors. + The length n may be any positive integer. +""" +function BitVector(name::String, length::Int) + global GLOBAL_VARNAMES + global WARN_DUPLICATE_NAMES + if name ∈ GLOBAL_VARNAMES[BitVectorExpr] + if WARN_DUPLICATE_NAMES @warn("Duplicate variable name $name of type BitVector") end + else + push!(GLOBAL_VARNAMES[BitVectorExpr], name) + end + return BitVectorExpr{nextsize(length)}(:IDENTITY, Array{AbstractExpr}[], nothing, "$name", length) +end + +# Constants, to match Julia conventions, may be specified in binary, hex, or octal. +# Constants may be specified in base 10 as long as they are explicitly constructed to be of type Unsigned or BigInt. +# Examples: 0xDEADBEEF (UInt32), 0b0101 (UInt8), 0o7700 (UInt16), big"123456789012345678901234567890" (BigInt) +function __wrap_const(c::Union{Unsigned, BigInt}) + nbits = bitcount(c) + rettype = nextsize(nbits) + return BitVectorExpr{rettype}(:CONST, AbstractExpr[], rettype(c), "const_0x$(string(c, base = 16, pad=sizeof(rettype)*2))", nbits) +end +# Consts can be padded, so for example you can add 0x01 (UInt8) to (_ BitVec 16) +# Variables cannot be padded! For example, 0x0101 (Uint16) cannot be added to (_ BitVec 8). + +# Note that we don't have to define == because it's defined for AbstractExpr. + +function nextsize(n::Integer) :: Type # works on BigInt and UInt + if sign(n) == -1 + @error("Constants must be unsigned or positive BigInts!") + end + sz = 2^Integer((round(log2(n), RoundUp, digits=0))) + sz = max(sz, 8) # sizes smaller than 8 get 8 bits + if sz > 128 + return BigInt + else + return eval(Symbol("UInt$sz")) # returns the correct size of int + end +end + +function bitcount(a::Integer) # works on BigInt and UInt + if sign(a) == -1 + @error("Constants must be unsigned or positive BigInts!") + end + return findlast((x) -> x != 0, a .>> collect(0:8*sizeof(a))) +end + +function hexstr(a::Integer) + if sign(a) == -1 + @error("Constants must be unsigned or positive BigInts!") + end + return string(a, base=16, pad=sizeof(a)*2) +end + + +function __bv2op(e1::BitVectorExpr, e2::BitVectorExpr, op::Function, opname::Symbol) + if e1.length != e2.length + @error "BitVectors have mismatched lengths $(e1.length) and $(e2.length)." + end + # This expression comes about because while SMT-LIB supports any length bit vector, + # we store the value in Julia as a standard size. So you have to mask any extra bits away. + value = nothing + if !isnothing(e1.value) && !isnothing(e2.value) + valtype = typeof(e1.value) + mask = typemax(valtype) >> (8*sizeof(valtype) - e1.length) + value = valtype(op(e1.value, e2.value) & mask) + end + name = __get_hash_name(opname, [e1.name, e2.name]) + return BitVectorExpr{nextsize(e1.length)}(opname, [e1, e2], value, name, e1.length) +end + +function __bv1op(e::BitVectorExpr, op::Function, opname::Symbol) + value = nothing + if !isnothing(e.value) + valtype = typeof(e.value) + mask = typemax(valtype) >> (8*sizeof(valtype) - e.length) + value = valtype(op(e.value) & mask) + end + name = __get_hash_name(opname, [e.name,]) + return BitVectorExpr{nextsize(e.length)}(opname, [e,], value, name, e.length) +end + +##### Integer arithmetic ##### + ++(e1::BitVectorExpr, e2::BitVectorExpr) = __bv2op(e1, e2, +, :bvadd) +-(e1::BitVectorExpr, e2::BitVectorExpr) = __bv2op(e1, e2, -, :bvsub) +*(e1::BitVectorExpr, e2::BitVectorExpr) = __bv2op(e1, e2, *, :bvmul) +div(e1::BitVectorExpr, e2::BitVectorExpr) = __bv2op(e1, e2, div, :bvudiv) + +# unary minus +-(e::BitVectorExpr) = __bv1op(e, -, :bvneg) + +# NOTE: Julia rem(a, b) and a%b return the unsigned remainder when a and b are unsigned +# the signed arithmetic is done when a and b are signed +# We do not implement % (modulus) because it could result in confusion +# The reason is Julia naturally prints unsigned integers in hex notation +# This matches how people usually think of BitVectors. So we store values as unsigned +# and cast to signed when necessary. +# But Julia decides whether to the unsigned or signed arithmetic based on the variable type +# while SMT-LIB defines only signed modulo, bvsmod. Thus it is confusing to implement Base.% or Base.rem +# We define urem and srem for the unsigned and signed things, respectively. + +# Yikes! A function that returns a function. +__signfix(f::Function) = (a, b) -> unsigned(f(signed(a), signed(b))) + +urem(e1::BitVectorExpr, e2::BitVectorExpr) = __bv2op(e1, e2, rem, :bvurem) +<<(e1::BitVectorExpr, e2::BitVectorExpr) = __bv2op(e1, e2, <<, :bvshl) # shift left +>>(e1::BitVectorExpr, e2::BitVectorExpr) = __bv2op(e1, e2, >>>, :bvlshr) # logical shift right + +# Extra arithmetic operators supported by Z3 but not part of the SMT-LIB standard. +srem(e1::BitVectorExpr, e2::BitVectorExpr) = __bv2op(e1, e2, __signfix(rem), :bvsrem) # unique to z3 +smod(e1::BitVectorExpr, e2::BitVectorExpr) = __bv2op(e1, e2, __signfix(mod), :bvsmod) # unique to z3 +>>>(e1::BitVectorExpr, e2::BitVectorExpr) = __bv2op(e1, e2, __signfix(>>), :bvashr) # arithmetic shift right - unique to Z3 + + +##### Bitwise logical operations ##### +∨(e1::BitVectorExpr, e2::BitVectorExpr) = __bv2op(e1, e2, (a,b) -> a | b, :bvor) +∧(e1::BitVectorExpr, e2::BitVectorExpr) = __bv2op(e1, e2, (a,b) -> a & b, :bvand) + +# Extra logical operators supported by Z3 but not part of the SMT-LIB standard. +nor(e1::BitVectorExpr, e2::BitVectorExpr) = __bv2op(e1, e2, (a,b) -> ~(a | b), :bvnor) +nand(e1::BitVectorExpr, e2::BitVectorExpr) = __bv2op(e1, e2, (a,b) -> ~(a & b), :bvnand) +xnor(e1::BitVectorExpr, e2::BitVectorExpr) = __bv2op(e1, e2, (a,b) -> (a & b) | (~a & ~b), :bvxnor) +# TODO operations with arity n +# note that bvxnor is left-accumulating, so bvxnor(a, b, c) = bvxnor(bvxnor(a, b), c) +# bvnor and bvnand have arity 2 + +¬(e::BitVectorExpr) = __bv1op(e, ~, :bvnot) + +##### Bitwise predicates ##### +>(e1::BitVectorExpr, e2::BitVectorExpr) = __bv2op(e1, e2, >, :bvult) +>=(e1::BitVectorExpr, e2::BitVectorExpr) = __bv2op(e1, e2, >=, :bvule) +<(e1::BitVectorExpr, e2::BitVectorExpr) = __bv2op(e1, e2, >, :bvugt) +<=(e1::BitVectorExpr, e2::BitVectorExpr) = __bv2op(e1, e2, >=, :bvuge) + +# Signed comparisons are supported by Z3 but not part of the SMT-LIB standard. +slt(e1::BitVectorExpr, e2::BitVectorExpr) = __bv2op(e1, e2, __signfix(>), :bvslt) +sle(e1::BitVectorExpr, e2::BitVectorExpr) = __bv2op(e1, e2, __signfix(>=), :bvsle) +sgt(e1::BitVectorExpr, e2::BitVectorExpr) = __bv2op(e1, e2, __signfix(>), :bvsgt) +sge(e1::BitVectorExpr, e2::BitVectorExpr) = __bv2op(e1, e2, __signfix(>=), :bvsge) + + +##### Word-level operations ##### +# concat and extract are the only SMT-LIB standard operations +# z3 adds some more +function cat(es::Array{T}) where T <: BitVectorExpr + length = sum(getproperty.(es, :length)) + valtype = nextsize(length) + if any(isnothing.(getproperty.(es, :value))) + value = nothing + else + value = valtype(0) # this generates an unsigned int or BigInt of the appropriate size + acc = 0 + for e in es + value |= valtype(e.value) << acc + acc += e.length + end + end + name = __get_hash_name(:concat, getproperty.(es, :name)) + return BitVectorExpr{nextsize(length)}(:concat, es, value, name, length) +end + +getindex(e::BitVectorExpr, ind::UnitRange{Int64}) = getindex(e, first(ind), last(ind)) +getindex(e::BitVectorExpr, ind::Int64) = getindex(e, ind, ind) + +function getindex(e::BitVectorExpr, ind_1::Int64, ind_2::Int64) + if ind_1 > ind_2 || ind_1 < 1 || ind_2 > e.length + @error "Cannot extract sequence $ind_1 to $ind_2 from BitVector!" + end + return __bv1op(e, identity, Symbol("(_ extract $ind_2 $ind_1)")) +end + +##### Translation to/from integer ##### +# Be aware these have high overhead +bv2int(e::BitVectorExpr) = IntExpr(:bv2int, [e,], isnothing(e.value) ? nothing : Int(e.value), "int_$(e.name)") +int2bv(e::IntExpr, size::Int) = __bv1op(e, unsigned, Symbol("(_ int2bv $size)")) + + +##### INTEROPERABILITY WITH CONSTANTS ##### +# RULE +# Given a variable with sort (_ BitVec n) and a const with sort (_ BitVec m) +# as long as m ≤ n any operation with the same size output is valid +# Short constants will be padded with zeros because this matches Julia's behavior. +# eg any operation except concat \ No newline at end of file diff --git a/src/BooleanOperations.jl b/src/BooleanOperations.jl index b0897cf..e6f950d 100644 --- a/src/BooleanOperations.jl +++ b/src/BooleanOperations.jl @@ -33,6 +33,20 @@ function __get_hash_name(op::Symbol, zs::Array{T}) where T <: AbstractExpr return "$(op)_$(string(hash(combined_name), base=16))" end +# new version - switch to this +function __get_combined_name(names::Array{String}; max_items=3) + names = sort(vec(names)) + if length(names) > max_items + return "$(names[1])_to_$(names[end])" + else + return join(names, "__") + end +end + +function __get_hash_name(op::Symbol, names::Array{String}) + combined_name = __get_combined_name(names, max_items=Inf) + return "$(op)_$(string(hash(combined_name), base=16))" +end ##### LOGICAL OPERATIONS ##### diff --git a/src/BooleanSatisfiability.jl b/src/BooleanSatisfiability.jl index 625215e..6471e0e 100644 --- a/src/BooleanSatisfiability.jl +++ b/src/BooleanSatisfiability.jl @@ -55,8 +55,9 @@ include("BooleanOperations.jl") =# include("IntExpr.jl") +include("BitVectorExpr.jl") -__EXPR_TYPES = [BoolExpr, RealExpr, IntExpr] +__EXPR_TYPES = [BoolExpr, RealExpr, IntExpr, BitVectorExpr] # Track the user-declared BoolExpr names so the user doesn't make duplicates. # This will NOT contain hash names. If the user declares x = Bool("x"); y = Bool("y"); xy = and(x,y) diff --git a/src/IntExpr.jl b/src/IntExpr.jl index f8c9e1f..c758285 100644 --- a/src/IntExpr.jl +++ b/src/IntExpr.jl @@ -102,7 +102,7 @@ a .< b a .< z ``` """ -function Base.:<(e1::AbstractExpr, e2::AbstractExpr) +function Base.:<(e1::NumericInteroperableExpr, e2::NumericInteroperableExpr) value = isnothing(e1.value) || isnothing(e2.value) ? nothing : e1.value < e2.value name = __get_hash_name(:LT, [e1, e2]) return BoolExpr(:LT, [e1, e2], value, name) @@ -122,7 +122,7 @@ a .<= b a .<= z ``` """ -function Base.:<=(e1::AbstractExpr, e2::AbstractExpr) +function Base.:<=(e1::NumericInteroperableExpr, e2::NumericInteroperableExpr) value = isnothing(e1.value) || isnothing(e2.value) ? nothing : e1.value <= e2.value name = __get_hash_name(:LEQ, [e1, e2]) return BoolExpr(:LEQ, [e1, e2], value, name) @@ -142,7 +142,7 @@ a .>= b a .>= z ``` """ -function Base.:>=(e1::AbstractExpr, e2::AbstractExpr) +function Base.:>=(e1::NumericInteroperableExpr, e2::NumericInteroperableExpr) value = isnothing(e1.value) || isnothing(e2.value) ? nothing : e1.value >= e2.value name = __get_hash_name(:GEQ, [e1, e2]) return BoolExpr(:GEQ, [e1, e2], value, name) @@ -162,7 +162,7 @@ a .> b a .> z ``` """ -function Base.:>(e1::AbstractExpr, e2::AbstractExpr) +function Base.:>(e1::NumericInteroperableExpr, e2::NumericInteroperableExpr) value = isnothing(e1.value) || isnothing(e2.value) ? nothing : e1.value > e2.value name = __get_hash_name(:GT, [e1, e2]) return BoolExpr(:GT, [e1, e2], value, name) From 5c67f6ceac8d47bc89f9ac4b73263a4d3aaa5d40 Mon Sep 17 00:00:00 2001 From: Emiko Soroka Date: Thu, 10 Aug 2023 17:37:21 -0700 Subject: [PATCH 17/36] Moved @satvariable macro to its own file. Added support for BitVector in @satvariable. --- src/BoolExpr.jl | 43 ----------------------------- src/BooleanSatisfiability.jl | 3 ++ src/smt_macros.jl | 53 ++++++++++++++++++++++++++++++++++++ src/smt_representation.jl | 13 ++++----- 4 files changed, 62 insertions(+), 50 deletions(-) create mode 100644 src/smt_macros.jl diff --git a/src/BoolExpr.jl b/src/BoolExpr.jl index 2ebbddb..28220b2 100644 --- a/src/BoolExpr.jl +++ b/src/BoolExpr.jl @@ -51,49 +51,6 @@ Bool(n::Int, name::String) :: Vector{BoolExpr} = BoolExpr[Bool("$(name)_ Bool(m::Int, n::Int, name::String) :: Matrix{BoolExpr} = BoolExpr[Bool("$(name)_$(i)_$(j)") for i=1:m, j=1:n] - -__valid_vartypes = [:Bool, :Int, :Real] -""" - @satvariable(z, Bool) - @satvariable(a[1:n], Int) - -Construct a SAT variable with name z, optional array dimensions, and specified type (`Bool`, `Int` or `Real`). - -One and two-dimensional variables can be constructed with the following syntax. -```julia -@satvariable(a[1:n], Int) # an Int vector of length n -@satvariable(x[1:m, 1:n], Real) # an m x n Int matrix -``` -""" -macro satvariable(expr, typename) - # check typename - if !isa(typename, Symbol) || !(typename ∈ __valid_vartypes) # unknown - @error "Unknown expression type $typename" - end - - # inside here name and t are exprs - if isa(expr, Symbol) # one variable, eg @Bool(x) - name = string(expr) - # this line resolves to something like x = Bool("x") - return esc(:($expr = $(typename)($name))) - - elseif length(expr.args) == 2 && isa(expr.args[1], Symbol) - stem = expr.args[1] - name = string(stem) - iterable = expr.args[2] - - return esc(:($stem = [$(typename)("$(:($$name))_$(i)") for i in $iterable])) - elseif length(expr.args) == 3 - stem = expr.args[1] - name = string(stem) - iterable1, iterable2 = expr.args[2], expr.args[3] - return esc(:($stem = [$(typename)("$(:($$name))_$(i)_$(j)") for i in $iterable1, j in $iterable2])) - else - @error "Unable to create variable from expression $expr. Recommended usage: \"@satvariable(x, Bool)\", \"@satvariable(x[1:n], Int)\", or \"@satvariable(x[1:m, 1:n], Bool)\"." - end -end - - ##### BASE FUNCTIONS ##### # Base calls diff --git a/src/BooleanSatisfiability.jl b/src/BooleanSatisfiability.jl index 6471e0e..f0151ee 100644 --- a/src/BooleanSatisfiability.jl +++ b/src/BooleanSatisfiability.jl @@ -57,6 +57,9 @@ include("IntExpr.jl") include("BitVectorExpr.jl") +# include @satvariable later because we need some functions from BitVector to declare that type +include("smt_macros.jl") + __EXPR_TYPES = [BoolExpr, RealExpr, IntExpr, BitVectorExpr] # Track the user-declared BoolExpr names so the user doesn't make duplicates. diff --git a/src/smt_macros.jl b/src/smt_macros.jl new file mode 100644 index 0000000..84add68 --- /dev/null +++ b/src/smt_macros.jl @@ -0,0 +1,53 @@ +# SMT-LIB theories http://smtlib.cs.uiowa.edu/theories.shtml +__valid_vartypes = [:Bool, :Int, :Real, :BitVector, :FloatingPoint, :String, :Array] +""" + @satvariable(z, Bool) + @satvariable(a[1:n], Int) + +Construct a SAT variable with name z, optional array dimensions, and specified type (`Bool`, `Int` or `Real`). + +One and two-dimensional variables can be constructed with the following syntax. +```julia +@satvariable(a[1:n], Int) # an Int vector of length n +@satvariable(x[1:m, 1:n], Real) # an m x n Int matrix +``` +""" +macro satvariable(expr, typename, arrsize=1) + # check typename + if !isa(typename, Symbol) || !(typename ∈ __valid_vartypes) # unknown + @error "Unknown expression type $typename" + end + + # inside here name and t are exprs + if isa(expr, Symbol) # one variable, eg @Bool(x) + name = string(expr) + # this line resolves to something like x = Bool("x") + # special handling of parametric BitVector + if typename == :BitVector + return esc(:($expr = $(typename)($(name),$(arrsize)))) + else + return esc(:($expr = $(typename)($name))) + end + + elseif length(expr.args) == 2 && isa(expr.args[1], Symbol) + stem = expr.args[1] + name = string(stem) + iterable = expr.args[2] + if typename == :BitVector + return esc(:($stem = [$(typename)("$(:($$name))_$(i)",$(arrsize)) for i in $iterable])) + else + return esc(:($stem = [$(typename)("$(:($$name))_$(i)") for i in $iterable])) + end + elseif length(expr.args) == 3 + stem = expr.args[1] + name = string(stem) + iterable1, iterable2 = expr.args[2], expr.args[3] + if typename == :BitVector + return esc(:($stem = [$(typename)("$(:($$name))_$(i)_$(j)",$(arrsize)) for i in $iterable1, j in $iterable2])) + else + return esc(:($stem = [$(typename)("$(:($$name))_$(i)_$(j)") for i in $iterable1, j in $iterable2])) + end + else + @error "Unable to create variable from expression $expr. Recommended usage: \"@satvariable(x, Bool)\", \"@satvariable(x[1:n], Int)\", or \"@satvariable(x[1:m, 1:n], Bool)\"." + end +end diff --git a/src/smt_representation.jl b/src/smt_representation.jl index 6497d93..551ac11 100644 --- a/src/smt_representation.jl +++ b/src/smt_representation.jl @@ -1,11 +1,10 @@ include("ops.jl") # Mapping of Julia Expr types to SMT names. This is necessary because to distinguish from native types Bool, Int, Real, etc, we call ours BoolExpr, IntExpr, RealExpr, etc. -__smt_typenames = Dict( - BoolExpr => "Bool", - IntExpr => "Int", - RealExpr => "Real", -) +__smt_typestr(e::BoolExpr) = "Bool" +__smt_typestr(e::IntExpr) = "Int" +__smt_typestr(e::RealExpr) = "Real" +__smt_typestr(e::BitVectorExpr) = "(_ BitVec $(e.length))" ##### GENERATING SMTLIB REPRESENTATION ##### @@ -20,7 +19,7 @@ Examples: """ function declare(z::AbstractExpr; line_ending='\n') # There is only one variable - vartype = __smt_typenames[typeof(z)] + vartype = __smt_typestr(z) if length(z) == 1 return "(declare-const $(z.name) $vartype)$line_ending" # Variable is 1D @@ -67,7 +66,7 @@ function __get_smt_name(z::AbstractExpr) global GLOBAL_VARNAMES appears_in = map( (t) -> z.name ∈ GLOBAL_VARNAMES[t], __EXPR_TYPES) if sum(appears_in) > 1 - return "(as $(z.name) $(__smt_typenames[typeof(z)]))" + return "(as $(z.name) $(__smt_typestr(z)))" else # easy case, one variable with z.name is defined return z.name end From 43ece7c142b6167e733d225a004db4173c9e5633 Mon Sep 17 00:00:00 2001 From: Emiko Soroka Date: Fri, 11 Aug 2023 18:11:57 -0700 Subject: [PATCH 18/36] ARCHITECTURE UPDATE to support adding many theories: 1. Cleaned up how plaintext operator names (:add, :lt, etc) are mapped to symbols. 2. Cleaned up functions in smt_representation.jl 3. Cleaned up hacks to determine whether an operator is commutative or what its return type is by adding two new fields to concrete types of AbstractExpr: __is_commutative and __ret_type. Cleaned up SMT statement generation logic to use these types, which are carried within the SMT expressions, vs looking up operators in a dumb lookup table that was getting too long. All tests pass! --- src/BitVectorExpr.jl | 11 ++- src/BoolExpr.jl | 44 +++++----- src/BooleanOperations.jl | 24 +++--- src/IntExpr.jl | 136 ++++++++++++++++--------------- src/ops.jl | 30 ------- src/sat.jl | 38 ++++----- src/smt_macros.jl | 2 + src/smt_representation.jl | 119 +++++++++++++++------------ test/boolean_operation_tests.jl | 25 +++--- test/int_parse_tests.jl | 53 ++++++------ test/int_real_tests.jl | 24 +++--- test/runtests.jl | 7 +- test/smt_representation_tests.jl | 30 +++---- test/solver_interface_tests.jl | 40 +++++---- 14 files changed, 291 insertions(+), 292 deletions(-) delete mode 100644 src/ops.jl diff --git a/src/BitVectorExpr.jl b/src/BitVectorExpr.jl index 810237b..0cad93d 100644 --- a/src/BitVectorExpr.jl +++ b/src/BitVectorExpr.jl @@ -29,7 +29,7 @@ function BitVector(name::String, length::Int) else push!(GLOBAL_VARNAMES[BitVectorExpr], name) end - return BitVectorExpr{nextsize(length)}(:IDENTITY, Array{AbstractExpr}[], nothing, "$name", length) + return BitVectorExpr{nextsize(length)}(:identity, Array{AbstractExpr}[], nothing, "$name", length) end # Constants, to match Julia conventions, may be specified in binary, hex, or octal. @@ -38,7 +38,7 @@ end function __wrap_const(c::Union{Unsigned, BigInt}) nbits = bitcount(c) rettype = nextsize(nbits) - return BitVectorExpr{rettype}(:CONST, AbstractExpr[], rettype(c), "const_0x$(string(c, base = 16, pad=sizeof(rettype)*2))", nbits) + return BitVectorExpr{rettype}(:const, AbstractExpr[], rettype(c), "const_0x$(string(c, base = 16, pad=sizeof(rettype)*2))", nbits) end # Consts can be padded, so for example you can add 0x01 (UInt8) to (_ BitVec 16) # Variables cannot be padded! For example, 0x0101 (Uint16) cannot be added to (_ BitVec 8). @@ -86,7 +86,11 @@ function __bv2op(e1::BitVectorExpr, e2::BitVectorExpr, op::Function, opname::Sym value = valtype(op(e1.value, e2.value) & mask) end name = __get_hash_name(opname, [e1.name, e2.name]) - return BitVectorExpr{nextsize(e1.length)}(opname, [e1, e2], value, name, e1.length) + if opname in [:bvule, :bvult, :bvuge, :bvugt, :bvsle, :bvslt, :bvsgt, :bvsge] + return BoolExpr(opname, [e1, e2], value, name) + else + return BitVectorExpr{nextsize(e1.length)}(opname, [e1, e2], value, name, e1.length) + end end function __bv1op(e::BitVectorExpr, op::Function, opname::Symbol) @@ -100,6 +104,7 @@ function __bv1op(e::BitVectorExpr, op::Function, opname::Symbol) return BitVectorExpr{nextsize(e.length)}(opname, [e,], value, name, e.length) end + ##### Integer arithmetic ##### +(e1::BitVectorExpr, e2::BitVectorExpr) = __bv2op(e1, e2, +, :bvadd) diff --git a/src/BoolExpr.jl b/src/BoolExpr.jl index 28220b2..aa88e94 100644 --- a/src/BoolExpr.jl +++ b/src/BoolExpr.jl @@ -5,37 +5,38 @@ import Base.length, Base.size, Base.show, Base.string, Base.isequal, Base.hash, # Define the Variable object abstract type AbstractExpr end -# op: :IDENTITY (variable only, no operation), :NOT, :AND, :OR, :XOR, :IFF, :IMPLIES, :ITE (if-then-else) +# op: :identity (variable only, no operation), :not, :and, :or, :xor, :iff, :implies, :ite (if-then-else) # children: BoolExpr children for an expression. And(z1, z2) has children [z1, z2] # value: Bool array or nothing if result not computed -# name: String name of variable / expression. Can get long, we're working on that. +# name: String name of variable / expression. +# __ret_type : Corresponds to the sort of an operator in SMT-LIB. Necessitated because Julia has a dynamic type system so the compiler can't easily infer return type of an operator. +# __is_commutative: true if AbstractExpr is a commutative operator, false if not. mutable struct BoolExpr <: AbstractExpr op :: Symbol children :: Array{AbstractExpr} value :: Union{Bool, Nothing, Missing} name :: String + __ret_type :: Type + __is_commutative :: Bool + + # for convenience + BoolExpr(op::Symbol, + children::Array{T}, + value::Union{Bool, Nothing, Missing}, + name::String; + __ret_type = BoolExpr, + __is_commutative = false) where T <: AbstractExpr = new(op, children, value, name, __ret_type, __is_commutative) end -# define a type that accepts Array{T, Bool}, Array{Bool}, and Array{T} -# ExprArray{T} = Union{Array{Union{T, Bool}}, Array{T}, Array{Bool}} ##### CONSTRUCTORS ##### """ - Bool("z") +BoolExpr("z") Construct a single Boolean variable with name "z". - -```julia - Bool(n, "z") - Bool(m, n, "z") -``` - -Construct a vector-valued or matrix-valued Boolean variable with name "z". - -Vector and matrix-valued Booleans use Julia's built-in array functionality: calling `Bool(n,"z")` returns a `Vector{BoolExpr}`, while calling `Bool(m, n, "z")` returns a `Matrix{BoolExpr}`. """ -function Bool(name::String) :: BoolExpr +function BoolExpr(name::String) :: BoolExpr # This unsightly bit enables warning when users define two variables with the same string name. global GLOBAL_VARNAMES global WARN_DUPLICATE_NAMES @@ -44,11 +45,11 @@ function Bool(name::String) :: BoolExpr else push!(GLOBAL_VARNAMES[BoolExpr], name) end - return BoolExpr(:IDENTITY, Array{AbstractExpr}[], nothing, "$(name)") + return BoolExpr(:identity, AbstractExpr[], nothing, "$(name)") end # may eventually be removed in favor of macros -Bool(n::Int, name::String) :: Vector{BoolExpr} = BoolExpr[Bool("$(name)_$(i)") for i=1:n] -Bool(m::Int, n::Int, name::String) :: Matrix{BoolExpr} = BoolExpr[Bool("$(name)_$(i)_$(j)") for i=1:m, j=1:n] +#Bool(n::Int, name::String) :: Vector{BoolExpr} = BoolExpr[Bool("$(name)_$(i)") for i=1:n] +#Bool(m::Int, n::Int, name::String) :: Matrix{BoolExpr} = BoolExpr[Bool("$(name)_$(i)_$(j)") for i=1:m, j=1:n] ##### BASE FUNCTIONS ##### @@ -63,7 +64,7 @@ Base.show(io::IO, expr::AbstractExpr) = print(io, string(expr)) # This helps us print nested exprs function Base.string(expr::AbstractExpr, indent=0)::String - if expr.op == :IDENTITY + if expr.op == :identity return "$(repeat(" | ", indent))$(expr.name)$(isnothing(expr.value) ? "" : " = $(expr.value)")\n" else res = "$(repeat(" | ", indent))$(expr.name)$(isnothing(expr.value) ? "" : " = $(expr.value)")\n" @@ -74,15 +75,12 @@ function Base.string(expr::AbstractExpr, indent=0)::String end end -# Utility functions -include("ops.jl") - "Test equality of two AbstractExprs. To construct an equality constraint, use `==`." function Base.isequal(expr1::AbstractExpr, expr2::AbstractExpr) return (expr1.op == expr2.op) && all(expr1.value .== expr2.value) && (expr1.name == expr2.name) && - (expr1.op ∈ __commutative_ops ? __is_permutation(expr1.children, expr2.children) : ((length(expr1.children) == length(expr2.children)) && all(isequal.(expr1.children, expr2.children)))) + (expr1.__is_commutative ? __is_permutation(expr1.children, expr2.children) : ((length(expr1.children) == length(expr2.children)) && all(isequal.(expr1.children, expr2.children)))) end # Required for isequal apparently, since isequal(expr1, expr2) implies hash(expr1) == hash(expr2). diff --git a/src/BooleanOperations.jl b/src/BooleanOperations.jl index e6f950d..5889876 100644 --- a/src/BooleanOperations.jl +++ b/src/BooleanOperations.jl @@ -65,7 +65,7 @@ Note: Broacasting a unary operator requires the syntax `.¬z` which can be confu ``` """ -not(z::BoolExpr) = BoolExpr(:NOT, [z], isnothing(z.value) ? nothing : !(z.value), __get_hash_name(:NOT, [z])) +not(z::BoolExpr) = BoolExpr(:not, [z], isnothing(z.value) ? nothing : !(z.value), __get_hash_name(:not, [z])) not(zs::Array{T}) where T <: BoolExpr = map(not, zs) ¬(z::BoolExpr) = not(z) ¬(zs::Array{T}) where T <: BoolExpr = not(zs) @@ -93,7 +93,7 @@ function and(zs_mixed::Array{T}; broadcast_type=:Elementwise) where T end # now the remaining are BoolExpr - expr = __combine(zs, :AND) + expr = __combine(zs, :and, BoolExpr) values = getproperty.(expr.children, :value) expr.value = length(values) > 0 && !any(isnothing.(values)) ? reduce(&, values) : nothing return expr @@ -138,7 +138,7 @@ function or(zs_mixed::Array{T}; broadcast_type=:Elementwise) where T return zs[1] end - expr = __combine(zs, :OR) + expr = __combine(zs, :or, BoolExpr) values = getproperty.(expr.children, :value) expr.value = length(values) > 0 && !any(isnothing.(values)) ? reduce(|, values) : nothing return expr @@ -202,10 +202,10 @@ function xor(zs_mixed::Array{T}; broadcast_type=:Elementwise) where T return zs[1] end - name = __get_hash_name(:XOR, zs) + name = __get_hash_name(:xor, zs) child_values = getproperty.(zs, :value) value = any(isnothing.(child_values)) ? nothing : reduce(xor, child_values) - return BoolExpr(:XOR, zs, value, name) + return BoolExpr(:xor, zs, value, name, __is_commutative=true) end # We need this extra line to enable the syntax xor.([z1, z2,...,zn]) where z1, z2,...,z are broadcast-compatible @@ -220,7 +220,7 @@ Returns the expression z1 IMPLIES z2. Use dot broadcasting for vector-valued and function implies(z1::BoolExpr, z2::BoolExpr) zs = BoolExpr[z1, z2] value = isnothing(z1.value) || isnothing(z2.value) ? nothing : !(z1.value) | z2.value - return BoolExpr(:IMPLIES, zs, value, __get_hash_name(:IMPLIES, zs)) + return BoolExpr(:implies, zs, value, __get_hash_name(:implies, zs)) end """ @@ -232,7 +232,7 @@ Bidirectional implication between z1 and z2. Equivalent to `and(z1 ⟹ z2, z2 function iff(z1::BoolExpr, z2::BoolExpr) zs = BoolExpr[z1, z2] value = isnothing(z1.value) || isnothing(z2.value) ? nothing : z1.value == z2.value - return BoolExpr(:IFF, zs, value, __get_hash_name(:IFF, zs)) + return BoolExpr(:iff, zs, value, __get_hash_name(:iff, zs), __is_commutative=true) end ⟺(z1::Union{BoolExpr, Bool}, z2::Union{BoolExpr, Bool}) = iff(z1, z2) @@ -249,7 +249,7 @@ function ite(x::Union{BoolExpr, Bool}, y::Union{BoolExpr, Bool}, z::Union{BoolEx end value = any(isnothing.([x.value, y.value, z.value])) ? nothing : (x.value & y.value) | (!(x.value) & z.value) - return BoolExpr(:ITE, zs, value, __get_hash_name(:ITE, zs)) + return BoolExpr(:ite, zs, value, __get_hash_name(:ite, zs)) end @@ -289,7 +289,7 @@ iff(z1::Bool, z2::Bool) = z1 == z2 ##### ADDITIONAL OPERATIONS ##### "combine is used for both and() and or() since those are fundamentally the same with different operations." -function __combine(zs::Array{T}, op::Symbol) where T <: BoolExpr +function __combine(zs::Array{T}, op::Symbol, ret_type::Type) where T <: BoolExpr if length(zs) == 0 error("Cannot iterate over zero-length array.") elseif length(zs) == 1 @@ -297,7 +297,7 @@ function __combine(zs::Array{T}, op::Symbol) where T <: BoolExpr end # Now we need to take an array of statements and decide how to combine them - if all(getproperty.(zs, :op) .== :IDENTITY) + if all(getproperty.(zs, :op) .== :identity) children = flatten(zs) name = __get_hash_name(op, zs) elseif all(getproperty.(zs, :op) .== op) @@ -311,12 +311,12 @@ function __combine(zs::Array{T}, op::Symbol) where T <: BoolExpr children = flatten(zs) end - return BoolExpr(op, children, nothing, name) + return BoolExpr(op, children, nothing, name, __is_commutative=true) end "combine(z, op) where z is an n x m matrix of BoolExprs first flattens z, then combines it with op. combine([z1 z2; z3 z4], or) = or([z1; z2; z3; z4])." -__combine(zs::Matrix{T}, op::Symbol) where T <: BoolExpr = __combine(flatten(zs), op) +__combine(zs::Matrix{T}, op::Symbol, ret_type::Type) where T <: BoolExpr = __combine(flatten(zs), op, ret_type) """ all([z1,...,zn]) diff --git a/src/IntExpr.jl b/src/IntExpr.jl index c758285..c77b557 100644 --- a/src/IntExpr.jl +++ b/src/IntExpr.jl @@ -1,4 +1,3 @@ -import Base.Int, Base.Real import Base.<, Base.<=, Base.>, Base.<=, Base.+, Base.-, Base.*, Base./, Base.== abstract type NumericExpr <: AbstractExpr end @@ -9,23 +8,25 @@ mutable struct IntExpr <: NumericExpr children :: Array{AbstractExpr} value :: Union{Int, Bool, Nothing, Missing} name :: String + __ret_type :: Type + __is_commutative :: Bool + + # for convenience + IntExpr(op::Symbol, + children::Array{T}, + value::Union{Int, Bool, Nothing, Missing}, + name::String; + __ret_type = IntExpr, + __is_commutative = false) where T <: AbstractExpr = new(op, children, value, name, __ret_type, __is_commutative) end -""" - Int("a") - -Construct a single Int variable with name "a". - -```julia - Int(n, "a") - Int(m, n, "a") -``` -Construct a vector-valued or matrix-valued Int variable with name "a". +""" +IntExpr("a") -Vector and matrix-valued Ints use Julia's built-in array functionality: calling `Int(n,"a")` returns a `Vector{IntExpr}`, while calling `Int(m, n, "a")` returns a `Matrix{IntExpr}`. +Construct a single IntExpr variable with name "a". """ -function Base.Int(name::String) :: IntExpr +function IntExpr(name::String) :: IntExpr # This unsightly bit enables warning when users define two variables with the same string name. global GLOBAL_VARNAMES global WARN_DUPLICATE_NAMES @@ -34,34 +35,35 @@ function Base.Int(name::String) :: IntExpr else push!(GLOBAL_VARNAMES[IntExpr], name) end - return IntExpr(:IDENTITY, Array{AbstractExpr}[], nothing, "$(name)") + return IntExpr(:identity, AbstractExpr[], nothing, "$(name)") end -Int(n::Int, name::String) :: Vector{IntExpr} = IntExpr[Int("$(name)_$(i)") for i=1:n] -Int(m::Int, n::Int, name::String) :: Matrix{IntExpr} = IntExpr[Int("$(name)_$(i)_$(j)") for i=1:m, j=1:n] +#Int(n::Int, name::String) :: Vector{IntExpr} = IntExpr[Int("$(name)_$(i)") for i=1:n] +#Int(m::Int, n::Int, name::String) :: Matrix{IntExpr} = IntExpr[Int("$(name)_$(i)_$(j)") for i=1:m, j=1:n] mutable struct RealExpr <: NumericExpr op :: Symbol children :: Array{AbstractExpr} - value :: Union{Float64, Bool, Nothing, Missing} + value :: Union{Float64, Nothing, Missing} name :: String + __ret_type :: Type + __is_commutative :: Bool + + # for convenience + RealExpr(op::Symbol, + children::Array{T}, + value::Union{Float64, Nothing, Missing}, + name::String; + __ret_type = RealExpr, + __is_commutative = false) where T <: AbstractExpr = new(op, children, value, name, __ret_type, __is_commutative) end """ - Real("r") - -Construct a single Int variable with name "r". - -```julia - Real(n, "r") - Real(m, n, "r") -``` - -Construct a vector-valued or matrix-valued Real variable with name "r". +RealExpr("r") -Vector and matrix-valued Reals use Julia's built-in array functionality: calling `Real(n,"a")` returns a `Vector{RealExpr}`, while calling `Real(m, n, "r")` returns a `Matrix{RealExpr}`. +Construct a single Real variable with name "r". """ -function Base.Real(name::String) :: RealExpr +function RealExpr(name::String) :: RealExpr # This unsightly bit enables warning when users define two variables with the same string name. global GLOBAL_VARNAMES global WARN_DUPLICATE_NAMES @@ -70,10 +72,10 @@ function Base.Real(name::String) :: RealExpr else push!(GLOBAL_VARNAMES[RealExpr], name) end - return RealExpr(:IDENTITY, Array{AbstractExpr}[], nothing, "$(name)") + return RealExpr(:identity, AbstractExpr[], nothing, "$(name)") end -Real(n::Int, name::String) :: Vector{RealExpr} = RealExpr[Real("$(name)_$(i)") for i=1:n] -Real(m::Int, n::Int, name::String) :: Matrix{RealExpr} = RealExpr[Real("$(name)_$(i)_$(j)") for i=1:m, j=1:n] +#Real(n::Int, name::String) :: Vector{RealExpr} = RealExpr[Real("$(name)_$(i)") for i=1:n] +#Real(m::Int, n::Int, name::String) :: Matrix{RealExpr} = RealExpr[Real("$(name)_$(i)_$(j)") for i=1:m, j=1:n] # These are necessary for defining interoperability between IntExpr, RealExpr, BoolExpr and built-in types such as Int, Bool, and Float. @@ -81,8 +83,8 @@ NumericInteroperableExpr = Union{NumericExpr, BoolExpr} NumericInteroperableConst = Union{Bool, Int, Float64} NumericInteroperable = Union{NumericInteroperableExpr, NumericInteroperableConst} -__wrap_const(c::Float64) = RealExpr(:CONST, AbstractExpr[], c, "const_$c") -__wrap_const(c::Union{Int, Bool}) = IntExpr(:CONST, AbstractExpr[], c, "const_$c") +__wrap_const(c::Float64) = RealExpr(:const, AbstractExpr[], c, "const_$c") +__wrap_const(c::Union{Int, Bool}) = IntExpr(:const, AbstractExpr[], c, "const_$c") ##### COMPARISON OPERATIONS #### @@ -104,8 +106,8 @@ a .< z """ function Base.:<(e1::NumericInteroperableExpr, e2::NumericInteroperableExpr) value = isnothing(e1.value) || isnothing(e2.value) ? nothing : e1.value < e2.value - name = __get_hash_name(:LT, [e1, e2]) - return BoolExpr(:LT, [e1, e2], value, name) + name = __get_hash_name(:lt, [e1, e2]) + return BoolExpr(:lt, [e1, e2], value, name, __ret_type=BoolExpr) end """ @@ -124,8 +126,8 @@ a .<= z """ function Base.:<=(e1::NumericInteroperableExpr, e2::NumericInteroperableExpr) value = isnothing(e1.value) || isnothing(e2.value) ? nothing : e1.value <= e2.value - name = __get_hash_name(:LEQ, [e1, e2]) - return BoolExpr(:LEQ, [e1, e2], value, name) + name = __get_hash_name(:leq, [e1, e2]) + return BoolExpr(:leq, [e1, e2], value, name, __ret_type=BoolExpr) end """ @@ -144,8 +146,8 @@ a .>= z """ function Base.:>=(e1::NumericInteroperableExpr, e2::NumericInteroperableExpr) value = isnothing(e1.value) || isnothing(e2.value) ? nothing : e1.value >= e2.value - name = __get_hash_name(:GEQ, [e1, e2]) - return BoolExpr(:GEQ, [e1, e2], value, name) + name = __get_hash_name(:geq, [e1, e2]) + return BoolExpr(:geq, [e1, e2], value, name, __ret_type=BoolExpr) end """ @@ -164,8 +166,8 @@ a .> z """ function Base.:>(e1::NumericInteroperableExpr, e2::NumericInteroperableExpr) value = isnothing(e1.value) || isnothing(e2.value) ? nothing : e1.value > e2.value - name = __get_hash_name(:GT, [e1, e2]) - return BoolExpr(:GT, [e1, e2], value, name) + name = __get_hash_name(:gt, [e1, e2]) + return BoolExpr(:gt, [e1, e2], value, name, __ret_type=BoolExpr) end # IMPORTANT NOTE @@ -189,8 +191,8 @@ a .== b """ function Base.:(==)(e1::AbstractExpr, e2::AbstractExpr) value = isnothing(e1.value) || isnothing(e2.value) ? nothing : e1.value == e2.value - name = __get_hash_name(:EQ, [e1, e2]) - return BoolExpr(:EQ, [e1, e2], value, name) + name = __get_hash_name(:eq, [e1, e2]) + return BoolExpr(:eq, [e1, e2], value, name, __ret_type=BoolExpr, __is_commutative=true) end # INTEROPERABILITY FOR COMPARISON OPERATIONS @@ -221,8 +223,8 @@ Return the negative of an Int or Real expression. ``` """ -Base.:-(e::IntExpr) = IntExpr(:NEG, IntExpr[e,], isnothing(e.value) ? nothing : -e.value, __get_hash_name(:NEG, [e,])) -Base.:-(e::RealExpr) = RealExpr(:NEG, RealExpr[e,], isnothing(e.value) ? nothing : -e.value, __get_hash_name(:NEG, [e,])) +Base.:-(e::IntExpr) = IntExpr(:neg, IntExpr[e,], isnothing(e.value) ? nothing : -e.value, __get_hash_name(:neg, [e,])) +Base.:-(e::RealExpr) = RealExpr(:neg, RealExpr[e,], isnothing(e.value) ? nothing : -e.value, __get_hash_name(:neg, [e,])) # Define array version for convenience because the syntax .- for unary operators is confusing. Base.:-(es::Array{T}) where T <: NumericExpr = .-es @@ -232,27 +234,27 @@ Base.:-(es::Array{T}) where T <: NumericExpr = .-es # These return Int values. We would say they have sort Int. # See figure 3.3 in the SMT-LIB standard. -# If literal is != 0, add a :CONST expr to es representing literal +# If literal is != 0, add a :const expr to es representing literal function __add_const!(es::Array{T}, literal::Real) where T <: AbstractExpr if literal != 0 - const_expr = isa(literal, Float64) ? RealExpr(:CONST, AbstractExpr[], literal, "const_$literal") : IntExpr(:CONST, AbstractExpr[], literal, "const_$literal") + const_expr = isa(literal, Float64) ? RealExpr(:const, AbstractExpr[], literal, "const_$literal") : IntExpr(:const, AbstractExpr[], literal, "const_$literal") push!(es, const_expr) end end -# If there is more than one :CONST expr in es, merge them into one +# If there is more than one :const expr in es, merge them into one function __merge_const!(es::Array{T}) where T <: AbstractExpr - const_exprs = filter( (e) -> e.op == :CONST, es) + const_exprs = filter( (e) -> e.op == :const, es) if length(const_exprs) > 1 - filter!( (e) -> e.op != :CONST, es) + filter!( (e) -> e.op != :const, es) __add_const!(es, sum(getproperty.(const_exprs, :value))) end end # This is NOT a recursive function. It will only unnest one level. function __unnest(es::Array{T}, op::Symbol) where T <: AbstractExpr - # this is all the child operators that aren't CONST or IDENTITY - child_operators = filter( (op) -> op != :IDENTITY && op != :CONST, getproperty.(es, :op)) + # this is all the child operators that aren't const or IDENTITY + child_operators = filter( (op) -> op != :identity && op != :const, getproperty.(es, :op)) if length(child_operators) > 0 && all(child_operators .== op) children = AbstractExpr[] @@ -263,8 +265,8 @@ function __unnest(es::Array{T}, op::Symbol) where T <: AbstractExpr end end -# This works for any n_ary op that takes as input NumericInteroperable arguments. -function __numeric_n_ary_op(es_mixed::Array, op::Symbol) +# This works for any n_ary op that takes as input NumericInteroperable arguments +function __numeric_n_ary_op(es_mixed::Array, op::Symbol; __is_commutative=true) # clean up types! This guarantees es::Array{AbstractExpr} es, literals = __check_inputs_nary_op(es_mixed, const_type=NumericInteroperableConst, expr_type=NumericInteroperableExpr) literal = length(literals) > 0 ? sum(literals) : 0 @@ -281,10 +283,10 @@ function __numeric_n_ary_op(es_mixed::Array, op::Symbol) # Now everything is in es and we are all cleaned up. # Determine return expr type. Note that / promotes to RealExpr because the SMT theory of integers doesn't include it - ReturnExpr = any(isa.(es, RealExpr)) || op == :DIV ? RealExpr : IntExpr + ReturnExpr = any(isa.(es, RealExpr)) || op == :div ? RealExpr : IntExpr value = any(isnothing.(getproperty.(es, :value))) ? nothing : sum(getproperty.(es, :value)) - return ReturnExpr(op, es, value, __get_hash_name(op, es)) + return ReturnExpr(op, es, value, __get_hash_name(op, es), __ret_type=ReturnExpr, __is_commutative=__is_commutative) end @@ -315,8 +317,8 @@ println("typeof a+z: \$(typeof(a[1] + z))") ``` """ -Base.:+(e1::Union{NumericInteroperableExpr}, e2::NumericInteroperableExpr) = __numeric_n_ary_op([e1, e2], :ADD) -Base.:+(e1::Union{NumericInteroperableExpr}, e2::NumericInteroperableConst) = __numeric_n_ary_op([e1, e2], :ADD) +Base.:+(e1::Union{NumericInteroperableExpr}, e2::NumericInteroperableExpr) = __numeric_n_ary_op([e1, e2], :add, __is_commutative=true) +Base.:+(e1::Union{NumericInteroperableExpr}, e2::NumericInteroperableConst) = __numeric_n_ary_op([e1, e2], :add, __is_commutative=true) Base.:+(e1::Union{NumericInteroperableConst}, e2::NumericInteroperableExpr) = e2 + e1 """ @@ -339,9 +341,9 @@ a .- z println("typeof a-z: \$(typeof(a[1] - z))") ``` """ -Base.:-(e1::Union{NumericInteroperableExpr}, e2::NumericInteroperableExpr) = __numeric_n_ary_op([e1, e2], :SUB) -Base.:-(e1::Union{NumericInteroperableExpr}, e2::NumericInteroperableConst) = __numeric_n_ary_op([e1, e2], :SUB) -Base.:-(e1::Union{NumericInteroperableConst}, e2::NumericInteroperableExpr) = __numeric_n_ary_op([e1, e2], :SUB) +Base.:-(e1::Union{NumericInteroperableExpr}, e2::NumericInteroperableExpr) = __numeric_n_ary_op([e1, e2], :sub) +Base.:-(e1::Union{NumericInteroperableExpr}, e2::NumericInteroperableConst) = __numeric_n_ary_op([e1, e2], :sub) +Base.:-(e1::Union{NumericInteroperableConst}, e2::NumericInteroperableExpr) = __numeric_n_ary_op([e1, e2], :sub) """ a * b @@ -363,8 +365,8 @@ a .- z println("typeof a*z: \$(typeof(a[1]*z))") ``` """ -Base.:*(e1::Union{NumericInteroperableExpr}, e2::NumericInteroperableExpr) = __numeric_n_ary_op([e1, e2], :MUL) -Base.:*(e1::Union{NumericInteroperableExpr}, e2::NumericInteroperableConst) = __numeric_n_ary_op([e1, e2], :MUL) +Base.:*(e1::Union{NumericInteroperableExpr}, e2::NumericInteroperableExpr) = __numeric_n_ary_op([e1, e2], :mul, __is_commutative=true) +Base.:*(e1::Union{NumericInteroperableExpr}, e2::NumericInteroperableConst) = __numeric_n_ary_op([e1, e2], :mul, __is_commutative=true) Base.:*(e1::Union{NumericInteroperableConst}, e2::NumericInteroperableExpr) = e2 * e1 """ @@ -380,6 +382,6 @@ a ./ b println("typeof a/b: \$(typeof(a[1]/b[1]))") ``` """ -Base.:/(e1::Union{NumericInteroperableExpr}, e2::NumericInteroperableExpr) = __numeric_n_ary_op([e1, e2], :DIV) -Base.:/(e1::Union{NumericInteroperableExpr}, e2::NumericInteroperableConst) = __numeric_n_ary_op([e1, e2], :DIV) -Base.:/(e1::Union{NumericInteroperableConst}, e2::NumericInteroperableExpr) = __numeric_n_ary_op([e1, e2], :DIV) \ No newline at end of file +Base.:/(e1::Union{NumericInteroperableExpr}, e2::NumericInteroperableExpr) = __numeric_n_ary_op([e1, e2], :div) +Base.:/(e1::Union{NumericInteroperableExpr}, e2::NumericInteroperableConst) = __numeric_n_ary_op([e1, e2], :div) +Base.:/(e1::Union{NumericInteroperableConst}, e2::NumericInteroperableExpr) = __numeric_n_ary_op([e1, e2], :div) \ No newline at end of file diff --git a/src/ops.jl b/src/ops.jl deleted file mode 100644 index 4a8c776..0000000 --- a/src/ops.jl +++ /dev/null @@ -1,30 +0,0 @@ -##### CONSTANTS FOR USE IN THIS FILE ##### -# Dictionary of opnames with n>=2 operands. This is necessary because not all opnames are valid symbols -# For example, iff is = and := is an invalid symbol. -__smt_n_opnames = Dict( - :AND => "and", - :OR => "or", - :XOR => "xor", - :IMPLIES => "=>", - :IFF => "=", - :ITE => "ite", - :LT => "<", - :LEQ => "<=", - :GT => ">", - :GEQ => ">=", - :EQ => "=", - :ADD => "+", - :SUB => "-", - :MUL => "*", - :DIV => "/", -) - -__commutative_ops = [:AND, :OR, :XOR, :IFF, :EQ, :ADD, :MUL] - -# Dictionary of opnames with 1 operand. -__smt_1_opnames = Dict( - :NOT => "not", - :NEG => "neg", -) - -__boolean_ops = [:AND, :OR, :XOR, :IMPLIES, :IFF, :ITE, :LT, :LEQ, :GT, :GEQ, :EQ, :NOT] diff --git a/src/sat.jl b/src/sat.jl index 8ee5fa7..9635c7d 100644 --- a/src/sat.jl +++ b/src/sat.jl @@ -40,33 +40,33 @@ sat!(zs::Array, solver::Solver) = sat!(zs...; solver=Solver) # https://docs.julialang.org/en/v1/manual/performance-tips/#The-dangers-of-abusing-multiple-dispatch-(aka,-more-on-types-with-values-as-parameters) # https://groups.google.com/forum/#!msg/julia-users/jUMu9A3QKQQ/qjgVWr7vAwAJ __reductions = Dict( - :NOT => (values) -> !(values[1]), - :AND => (values) -> reduce(&, values), - :OR => (values) -> reduce(|, values), - :XOR => (values) -> sum(values) == 1, - :IMPLIES => (values) -> !(values[1]) | values[2], - :IFF => (values) -> values[1] == values[2], - :ITE => (values) -> (values[1] & values[2]) | (values[1] & values[3]), - :EQ => (values) -> values[1] == values[2], - :LT => (values) -> values[1] < values[2], - :LEQ => (values) -> values[1] <= values[2], - :GT => (values) -> values[1] > values[2], - :GEQ => (values) -> values[1] >= values[2], - :ADD => (values) -> sum(values), - :SUB => (values) -> values[1] - sum(values[2:end]) , - :MUL => (values) -> prod(values), - :DIV => (values) -> values[1] / prod(values[2:end]), + :not => (values) -> !(values[1]), + :and => (values) -> reduce(&, values), + :or => (values) -> reduce(|, values), + :xor => (values) -> sum(values) == 1, + :implies => (values) -> !(values[1]) | values[2], + :iff => (values) -> values[1] == values[2], + :ite => (values) -> (values[1] & values[2]) | (values[1] & values[3]), + :eq => (values) -> values[1] == values[2], + :lt => (values) -> values[1] < values[2], + :leq => (values) -> values[1] <= values[2], + :gt => (values) -> values[1] > values[2], + :geq => (values) -> values[1] >= values[2], + :add => (values) -> sum(values), + :sub => (values) -> values[1] - sum(values[2:end]) , + :mul => (values) -> prod(values), + :div => (values) -> values[1] / prod(values[2:end]), ) function __assign!(z::T, values::Dict) where T <: AbstractExpr - if z.op == :IDENTITY + if z.op == :identity if z.name ∈ keys(values) z.value = values[z.name] else z.value = missing # this is better than nothing because & and | automatically skip it (three-valued logic). end - elseif z.op == :CONST - ; # CONST already has .value set so do nothing + elseif z.op == :const + ; # const already has .value set so do nothing else map( (z) -> __assign!(z, values), z.children) values = getproperty.(z.children, :value) diff --git a/src/smt_macros.jl b/src/smt_macros.jl index 84add68..9d9dadf 100644 --- a/src/smt_macros.jl +++ b/src/smt_macros.jl @@ -17,6 +17,8 @@ macro satvariable(expr, typename, arrsize=1) if !isa(typename, Symbol) || !(typename ∈ __valid_vartypes) # unknown @error "Unknown expression type $typename" end + # append Expr to typename + typename = Symbol(typename, "Expr") # inside here name and t are exprs if isa(expr, Symbol) # one variable, eg @Bool(x) diff --git a/src/smt_representation.jl b/src/smt_representation.jl index 551ac11..b9f6885 100644 --- a/src/smt_representation.jl +++ b/src/smt_representation.jl @@ -1,17 +1,43 @@ -include("ops.jl") - # Mapping of Julia Expr types to SMT names. This is necessary because to distinguish from native types Bool, Int, Real, etc, we call ours BoolExpr, IntExpr, RealExpr, etc. __smt_typestr(e::BoolExpr) = "Bool" __smt_typestr(e::IntExpr) = "Int" __smt_typestr(e::RealExpr) = "Real" __smt_typestr(e::BitVectorExpr) = "(_ BitVec $(e.length))" +# Dictionary of opnames with n>=2 operands. This is necessary because not all opnames are valid symbols +# For example, iff is = and := is an invalid symbol. +function __smt_opnames(op::Symbol) + if op ∈ keys(__special_cases) + return __special_cases[op] + else + return op + end +end +# These special cases arise because the SMT-LIB specification requires names to be ASCII +# thus we have to name these to successfully name things in (define-fun ) +# but the SMT-LIB operators are symbolic. +__special_cases = Dict( + :implies => "=>", + :iff => "=", + :eq => "=", + :add => "+", + :sub => "-", + :mul => "*", + :div => "/", + :neg => "-", + :lt => "<", + :leq => "<=", + :geq => ">=", + :gt => ">", +) + + ##### GENERATING SMTLIB REPRESENTATION ##### """ declare(z; line_ending='\n') -Generate SMT variable declarations for a BoolExpr variable (operation = :IDENTITY). +Generate SMT variable declarations for a BoolExpr variable (operation = :identity). Examples: * `declare(a::IntExpr)` returns `"(declare-const a Int)\\n"` @@ -43,24 +69,11 @@ end declare(zs::Array{T}; line_ending='\n') where T <: AbstractExpr = reduce(*, declare.(zs; line_ending=line_ending)) -# Determine the return type of an expression with operation op and children zs -function __return_type(op::Symbol, zs::Array{T}) where T <: AbstractExpr - if op ∈ __boolean_ops - return "Bool" - else - if any(typeof.(zs) .== RealExpr) - return "Real" - else # all are IntExpr - return "Int" - end - end -end - # Return either z.name or the correct (as z.name Type) if z.name is defined for multiple types # This multiple name misbehavior is allowed in SMT2; the expression (as z.name Type) is called a fully qualified name. # It would arise if someone wrote something like @satvariable(x, Bool); x = xb; @satvariable(x, Int) function __get_smt_name(z::AbstractExpr) - if z.op == :CONST + if z.op == :const return string(z.value) end global GLOBAL_VARNAMES @@ -76,33 +89,34 @@ end cache is a Dict where each value is an SMT statement and its key is the hash of the statement. This allows us to avoid two things: 1. Redeclaring SMT statements, which causes the solver to emit errors. 2. Re-using named functions. For example if we \"(define-fun FUNC_NAME or(z1, z2))\" and then the expression or(z1, z2) re-appears later in the expression \"and(or(z1, z2), z3)\", we can write and(FUNC_NAME, z3)." -function __define_n_op!(zs::Array{T}, op::Symbol, cache::Dict{UInt64, String}, depth::Int; assert=true, line_ending='\n') where T <: AbstractExpr - if length(zs) == 0 # silly case but we should handle it +function __define_n_op!(z::T, cache::Dict{UInt64, String}, depth::Int; assert=true, line_ending='\n') where T <: AbstractExpr + children = z.children + if length(children) == 0 # silly case but we should handle it return "" end - if assert && depth == 0 && !isa(zs[1], BoolExpr) - @warn("Cannot assert non-Boolean expression $op($zs)") + if assert && depth == 0 && z.__ret_type != BoolExpr + @warn("Cannot assert non-Boolean expression $z") end # done error checking - if length(zs) == 1 - return assert && depth == 0 ? "(assert ($(zs[1].name)))$line_ending" : "" - else - fname = __get_hash_name(op, zs) - # if the expr is a :CONST it will have a value (e.g. 2 or 1.5), otherwise use its name + #if length(children) == 1 + # return assert && depth == 0 ? "(assert ($(children[1].name)))$line_ending" : "" + #else + fname = __get_hash_name(z.op, children) + # if the expr is a :const it will have a value (e.g. 2 or 1.5), otherwise use its name # This yields a list like String["z_1", "z_2", "1"]. - varnames = __get_smt_name.(zs) - outname = __return_type(op, zs) - if op ∈ __commutative_ops + varnames = __get_smt_name.(children) + outname = __smt_typestr(z) + if z.__is_commutative varnames = sort(varnames) end - declaration = "(define-fun $fname () $outname ($(__smt_n_opnames[op]) $(join(varnames, " "))))$line_ending" + declaration = "(define-fun $fname () $outname ($(__smt_opnames(z.op)) $(join(varnames, " "))))$line_ending" cache_key = hash(declaration) # we use this to find out if we already declared this item prop = "" if cache_key in keys(cache) prop = depth == 0 ? cache[cache_key] : "" else - if assert && op ∈ __boolean_ops && depth == 0 + if assert && z.__ret_type == BoolExpr && depth == 0 prop = declaration*"(assert $fname)$line_ending" # the proposition is generated and cached now. cache[cache_key] = "(assert $fname)$line_ending" @@ -111,19 +125,19 @@ function __define_n_op!(zs::Array{T}, op::Symbol, cache::Dict{UInt64, String}, d end end return prop - end + # end end -function __define_1_op!(z::AbstractExpr, op::Symbol, cache::Dict{UInt64, String}, depth::Int; assert=true, line_ending='\n') - fname = __get_hash_name(op, z.children) - outname = __return_type(op, [z]) +function __define_1_op!(z::AbstractExpr, cache::Dict{UInt64, String}, depth::Int; assert=true, line_ending='\n') + fname = __get_hash_name(z.op, z.children) + outname = __smt_typestr(z) prop = "" - declaration = "(define-fun $fname () $outname ($(__smt_1_opnames[op]) $(__get_smt_name(z.children[1]))))$line_ending" + declaration = "(define-fun $fname () $outname ($(__smt_opnames(z.op)) $(__get_smt_name(z.children[1]))))$line_ending" cache_key = hash(declaration) - if assert && depth == 0 && !isa(z, BoolExpr) - @warn("Cannot assert non-Boolean expression $op($z)") + if assert && depth == 0 && z.__ret_type != BoolExpr + @warn("Cannot assert non-Boolean expression $z") end if cache_key in keys(cache) && depth == 0 @@ -131,7 +145,7 @@ function __define_1_op!(z::AbstractExpr, op::Symbol, cache::Dict{UInt64, String} else # if depth = 0 that means we are at the top-level of a nested expression. # thus, if the expr is Boolean we should assert it. - if assert && op ∈ __boolean_ops && depth == 0 + if assert && z.__ret_type == BoolExpr && depth == 0 prop = declaration*"(assert $fname)$line_ending" # the proposition is generated and cached now. cache[cache_key] = "(assert $fname)$line_ending" @@ -148,31 +162,34 @@ end We use it to iteratively build a list of declarations and propositions. Users should call smt(prob, line_ending)." function smt!(z::AbstractExpr, declarations::Array{T}, propositions::Array{T}, cache::Dict{UInt64, String}, depth::Int; assert=true, line_ending='\n') :: Tuple{Array{T}, Array{T}} where T <: String - if z.op == :IDENTITY # a single variable + if z.op == :identity # a single variable n = length(declarations) push_unique!(declarations, declare(z; line_ending=line_ending)) if assert && depth == 0 - push_unique!(propositions, "(assert $(z.name))$line_ending") + if z.__ret_type != BoolExpr + @warn("Cannot assert non-Boolean expression $z") + else + push_unique!(propositions, "(assert $(z.name))$line_ending") + end end - elseif z.op == :CONST + elseif z.op == :const ; # do nothing, constants don't need declarations else # an expression with operators and children map( (c) -> smt!(c, declarations, propositions, cache, depth+1, assert=assert, line_ending=line_ending) , z.children) - if z.op ∈ keys(__smt_1_opnames) - props = [__define_1_op!(z, z.op, cache, depth, assert=assert, line_ending=line_ending),] + if length(z.children) == 1 + prop = __define_1_op!(z, cache, depth, assert=assert, line_ending=line_ending) - elseif z.op ∈ keys(__smt_n_opnames) # all n-ary ops where n >= 2 - props = broadcast((zs::Vararg{AbstractExpr}) -> __define_n_op!(collect(zs), z.op, cache, depth, assert=assert, line_ending=line_ending), z.children...) + else # all n-ary ops where n >= 2 + prop = __define_n_op!(z, cache, depth, assert=assert, line_ending=line_ending) #n = length(propositions) - props = collect(props) - else - error("Unknown operation $(z.op)!") + #else + # error("Unknown operation $(z.op)!") end - append_unique!(propositions, props) + push_unique!(propositions, prop) end return declarations, propositions end @@ -223,7 +240,7 @@ function save(prob::AbstractExpr, filename="out"; assert=true, check_sat=true, l line_ending = Sys.iswindows() ? "\r\n" : '\n' end - if assert && !isa(prob, BoolExpr) + if assert && prob.__ret_type != BoolExpr @warn "Top-level expression must be Boolean to produce a valid SMT program." end open("$filename.smt", "w") do io diff --git a/test/boolean_operation_tests.jl b/test/boolean_operation_tests.jl index 7922deb..5e8477e 100644 --- a/test/boolean_operation_tests.jl +++ b/test/boolean_operation_tests.jl @@ -44,11 +44,10 @@ end @test string(z1) == "z1 = true\n" end -@testset "Logical operations" begin - # ensures test coverage of Bool() syntax - z1 = Bool(1, "z1") - z12 = Bool(1,2, "z12") - z32 = Bool(3,2, "z32") +@testset "Logical operations" begin + @satvariable(z1[1:1], Bool) + @satvariable(z12[1:1, 1:2], Bool) + @satvariable(z32[1:3, 1:2], Bool) # 1 and 0 cases @test isequal(and([z1[1]]), z1[1]) @@ -56,19 +55,19 @@ end # Can construct with 2 exprs @test all( isequal.((z1 .∧ z32)[1].children, [z1[1], z32[1]] )) - @test (z1 .∧ z32)[1].name == BooleanSatisfiability.__get_hash_name(:AND, [z1[1], z32[1]]) + @test (z1 .∧ z32)[1].name == BooleanSatisfiability.__get_hash_name(:and, [z1[1], z32[1]]) @test all( isequal.((z1 .∨ z32)[2,1].children, [z1[1], z32[2,1]] )) - @test (z1 .∨ z32)[1].name == BooleanSatisfiability.__get_hash_name(:OR, [z1[1], z32[1]]) + @test (z1 .∨ z32)[1].name == BooleanSatisfiability.__get_hash_name(:or, [z1[1], z32[1]]) # Can construct with N>2 exprs or_N = or.(z1, z12, z32) and_N = and.(z1, z12, z32) @test all( isequal.(or_N[3,2].children, [z1[1], z12[1,2], z32[3,2]] )) - @test and_N[1].name == BooleanSatisfiability.__get_hash_name(:AND, and_N[1].children) + @test and_N[1].name == BooleanSatisfiability.__get_hash_name(:and, and_N[1].children) @test all( isequal.(or_N[1].children, [z1[1], z12[1], z32[1]] )) - @test or_N[1].name == BooleanSatisfiability.__get_hash_name(:OR, and_N[1].children) + @test or_N[1].name == BooleanSatisfiability.__get_hash_name(:or, and_N[1].children) # Can construct negation @test isequal((¬z32)[1].children, [z32[1]]) @@ -78,12 +77,12 @@ end # Can construct all() and any() statements @test isequal(any(z1), z1[1]) - @test isequal(any(z1 .∨ z12), BoolExpr(:OR, [z12[1,1], z1[1], z12[1,2]], nothing, BooleanSatisfiability.__get_hash_name(:OR, [z1 z12]))) - @test isequal(all(z1 .∧ z12), BoolExpr(:AND, [z12[1,1], z1[1], z12[1,2]], nothing, BooleanSatisfiability.__get_hash_name(:AND, [z1 z12]))) + @test isequal(any(z1 .∨ z12), BoolExpr(:or, [z12[1,1], z1[1], z12[1,2]], nothing, BooleanSatisfiability.__get_hash_name(:or, [z1 z12]))) + @test isequal(all(z1 .∧ z12), BoolExpr(:and, [z12[1,1], z1[1], z12[1,2]], nothing, BooleanSatisfiability.__get_hash_name(:and, [z1 z12]))) # mismatched all() and any() - @test isequal(any(z1 .∧ z12), BoolExpr(:OR, [z1[1] ∧ z12[1,1], z1[1] ∧ z12[1,2]], nothing, BooleanSatisfiability.__get_hash_name(:OR, z1.∧ z12))) - @test isequal(and(z12 .∨ z1), BoolExpr(:AND, [z1[1] ∨ z12[1,1], z1[1] ∨ z12[1,2]], nothing, BooleanSatisfiability.__get_hash_name(:AND, z1.∨ z12))) + @test isequal(any(z1 .∧ z12), BoolExpr(:or, [z1[1] ∧ z12[1,1], z1[1] ∧ z12[1,2]], nothing, BooleanSatisfiability.__get_hash_name(:or, z1.∧ z12))) + @test isequal(and(z12 .∨ z1), BoolExpr(:and, [z1[1] ∨ z12[1,1], z1[1] ∨ z12[1,2]], nothing, BooleanSatisfiability.__get_hash_name(:and, z1.∨ z12))) end @testset "Additional operations" begin diff --git a/test/int_parse_tests.jl b/test/int_parse_tests.jl index 2bc49cd..7016f9e 100644 --- a/test/int_parse_tests.jl +++ b/test/int_parse_tests.jl @@ -6,19 +6,19 @@ CLEAR_VARNAMES!() @satvariable(a, Int) @satvariable(b, Int) expr1 = a + b + 2 -@test smt(expr1) == "(declare-const a Int) +@test smt(expr1, assert=false) == "(declare-const a Int) (declare-const b Int) -(define-fun ADD_99dce5c325207b7 () Int (+ 2 a b))\n" +(define-fun add_99dce5c325207b7 () Int (+ 2 a b))\n" expr = and(expr1 <= a, b + 1 >= b) result = "(declare-const a Int) (declare-const b Int) -(define-fun ADD_99dce5c325207b7 () Int (+ 2 a b)) -(define-fun LEQ_d476c845a7be63a () Bool (<= ADD_99dce5c325207b7 a)) -(define-fun ADD_f0a93f0b97da1ab2 () Int (+ 1 b)) -(define-fun GEQ_d3e5e06dff9812ca () Bool (>= ADD_f0a93f0b97da1ab2 b)) -(define-fun AND_20084a5e2cc43534 () Bool (and GEQ_d3e5e06dff9812ca LEQ_d476c845a7be63a)) -(assert AND_20084a5e2cc43534)\n" +(define-fun add_99dce5c325207b7 () Int (+ 2 a b)) +(define-fun leq_8df5432ee845c9e8 () Bool (<= add_99dce5c325207b7 a)) +(define-fun add_f0a93f0b97da1ab2 () Int (+ 1 b)) +(define-fun geq_e1bd460e008a4d8b () Bool (>= add_f0a93f0b97da1ab2 b)) +(define-fun and_8014e2e143374eea () Bool (and geq_e1bd460e008a4d8b leq_8df5432ee845c9e8)) +(assert and_8014e2e143374eea)\n" @test smt(expr) == result status = sat!(expr) @@ -30,26 +30,27 @@ end @testset "Parse some z3 output with ints and floats" begin output = "( - (define-fun GEQ_d3e5e06dff9812ca () Bool - (>= (+ 1 b) b)) - (define-fun ADD_f0a93f0b97da1ab2 () Int - (+ 1 b)) - (define-fun LEQ_d476c845a7be63a () Bool - (<= (+ 2 a b) a)) - (define-fun AND_20084a5e2cc43534 () Bool - (and (>= (+ 1 b) b) (<= (+ 2 a b) a))) - (define-fun b () Int - (- 2)) - (define-fun ADD_99dce5c325207b7 () Int - (+ 2 a b)) - (define-fun a () Int - 0) -)" +(define-fun b () Int + (- 2)) +(define-fun a () Int + 0) +(define-fun geq_e1bd460e008a4d8b () Bool + (>= (+ 1 b) b)) +(define-fun and_8014e2e143374eea () Bool + (and (>= (+ 1 b) b) (<= (+ 2 a b) a))) +(define-fun add_99dce5c325207b7 () Int + (+ 2 a b)) +(define-fun add_f0a93f0b97da1ab2 () Int + (+ 1 b)) +(define-fun leq_8df5432ee845c9e8 () Bool + (<= (+ 2 a b) a)) +) + " result = BooleanSatisfiability.parse_smt_output(output) @test result == Dict("b" => -2, "a" => 0) output = "((define-fun b () Real (- 2.5)) -(define-fun ADD_99dce5c325207b7 () Real +(define-fun add_99dce5c325207b7 () Real (+ 2 a b)) (define-fun a () Real 0.0) @@ -63,8 +64,8 @@ end @satvariable(a, Int) b = a @satvariable(a, Real) - hashname = BooleanSatisfiability.__get_hash_name(:ADD, [b, a]) - @test smt(b+a) == "(declare-const a Int) + hashname = BooleanSatisfiability.__get_hash_name(:add, [b, a]) + @test smt(b+a, assert=false) == "(declare-const a Int) (declare-const a Real) (define-fun $hashname () Real (+ (as a Int) (as a Real))) " diff --git a/test/int_real_tests.jl b/test/int_real_tests.jl index 0703c47..4b1c41d 100644 --- a/test/int_real_tests.jl +++ b/test/int_real_tests.jl @@ -11,15 +11,15 @@ using Test @satvariable(cr[1:1,1:2], Real) a.value = 2; b[1].value = 1 - @test isequal((a .< b)[1], BoolExpr(:LT, AbstractExpr[a, b[1]], false, BooleanSatisfiability.__get_hash_name(:LT, [a,b[1]]))) - @test isequal((a .>= b)[1], BoolExpr(:GEQ, AbstractExpr[a, b[1]], true, BooleanSatisfiability.__get_hash_name(:GEQ, [a,b[1]]))) + @test isequal((a .< b)[1], BoolExpr(:lt, AbstractExpr[a, b[1]], false, BooleanSatisfiability.__get_hash_name(:lt, [a,b[1]]))) + @test isequal((a .>= b)[1], BoolExpr(:geq, AbstractExpr[a, b[1]], true, BooleanSatisfiability.__get_hash_name(:geq, [a,b[1]]))) ar.value = 2.1; br[1].value = 0.9 - @test isequal((ar .> br)[1], BoolExpr(:GT, AbstractExpr[ar, br[1]], true, BooleanSatisfiability.__get_hash_name(:GT, [ar,br[1]]))) - @test isequal((ar .<= br)[1], BoolExpr(:LEQ, AbstractExpr[ar, br[1]], false, BooleanSatisfiability.__get_hash_name(:LEQ, [ar,br[1]]))) + @test isequal((ar .> br)[1], BoolExpr(:gt, AbstractExpr[ar, br[1]], true, BooleanSatisfiability.__get_hash_name(:gt, [ar,br[1]]))) + @test isequal((ar .<= br)[1], BoolExpr(:leq, AbstractExpr[ar, br[1]], false, BooleanSatisfiability.__get_hash_name(:leq, [ar,br[1]]))) - @test isequal((-c)[1,2], IntExpr(:NEG, [c[1,2]], nothing, BooleanSatisfiability.__get_hash_name(:NEG, [c[1,2]]))) - @test isequal((-cr)[1,2], RealExpr(:NEG, [cr[1,2]], nothing, BooleanSatisfiability.__get_hash_name(:NEG, [cr[1,2]]))) + @test isequal((-c)[1,2], IntExpr(:neg, [c[1,2]], nothing, BooleanSatisfiability.__get_hash_name(:neg, [c[1,2]]))) + @test isequal((-cr)[1,2], RealExpr(:neg, [cr[1,2]], nothing, BooleanSatisfiability.__get_hash_name(:neg, [cr[1,2]]))) # Construct with constants on RHS c[1,2].value = 1 @@ -51,16 +51,16 @@ end # Operations with mixed constants and type promotion # Adding Int and Bool types results in an IntExpr - children = [a, IntExpr(:CONST, AbstractExpr[], 2, "const_2")] - @test isequal(sum([a, 1, true]), IntExpr(:ADD, children, nothing, BooleanSatisfiability.__get_hash_name(:ADD, children))) + children = [a, IntExpr(:const, AbstractExpr[], 2, "const_2")] + @test isequal(sum([a, 1, true]), IntExpr(:add, children, nothing, BooleanSatisfiability.__get_hash_name(:add, children))) # Type promotion to RealExpr works when we add a float-valued literal - children = [a, RealExpr(:CONST, AbstractExpr[], 3., "const_3.0")] - @test isequal(sum([1.0, a, true, 1]), RealExpr(:ADD, children, nothing, BooleanSatisfiability.__get_hash_name(:ADD, children))) + children = [a, RealExpr(:const, AbstractExpr[], 3., "const_3.0")] + @test isequal(sum([1.0, a, true, 1]), RealExpr(:add, children, nothing, BooleanSatisfiability.__get_hash_name(:add, children))) # Type promotion to RealExpr works when we add a real-valued expr - children = [a, b[1], IntExpr(:CONST, AbstractExpr[], 2, "const_2.0")] - @test isequal(sum([a, 1.0, 1, false, b[1]]), RealExpr(:ADD, children, nothing, BooleanSatisfiability.__get_hash_name(:ADD, children))) + children = [a, b[1], IntExpr(:const, AbstractExpr[], 2, "const_2.0")] + @test isequal(sum([a, 1.0, 1, false, b[1]]), RealExpr(:add, children, nothing, BooleanSatisfiability.__get_hash_name(:add, children))) # Sum works automatically @test isequal(1 + a + b[1] + true, sum([1, a, b[1], true])) diff --git a/test/runtests.jl b/test/runtests.jl index 998b551..d2020b2 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -2,6 +2,7 @@ push!(LOAD_PATH, "../src") push!(LOAD_PATH, "./") using BooleanSatisfiability using Test, Logging +SET_DUPLICATE_NAME_WARNING!(false) # Constructing Boolean expressions include("boolean_operation_tests.jl") @@ -22,14 +23,14 @@ include("int_parse_tests.jl") @testset "Duplicate variable warning" begin SET_DUPLICATE_NAME_WARNING!(true) @satvariable(z, Bool) - @test_logs (:warn, "Duplicate variable name z of type Bool") Bool("z") + @test_logs (:warn, "Duplicate variable name z of type Bool") @satvariable(z, Bool) # now we should have no warnings SET_DUPLICATE_NAME_WARNING!(false) - @test_logs min_level=Logging.Warn Bool("z") + @test_logs min_level=Logging.Warn @satvariable(z, Bool) # we can also clear the list SET_DUPLICATE_NAME_WARNING!(true) CLEAR_VARNAMES!() - @test_logs min_level=Logging.Warn Bool("z") + @test_logs min_level=Logging.Warn @satvariable(z, Bool) end \ No newline at end of file diff --git a/test/smt_representation_tests.jl b/test/smt_representation_tests.jl index e95bafe..6ad2573 100644 --- a/test/smt_representation_tests.jl +++ b/test/smt_representation_tests.jl @@ -15,20 +15,20 @@ using Test # idea from https://microsoft.github.io/z3guide/docs/logic/propositional-logic # broadcast expression correctly generated - hashname = BooleanSatisfiability.__get_hash_name(:AND, [z1, z2[1]]) + hashname = BooleanSatisfiability.__get_hash_name(:and, [z1, z2[1]]) @test smt(z1 .∧ z2) == smt(z1, assert=false)*smt(z2, assert=false)*"(define-fun $hashname () Bool (and z1 z2_1))\n(assert $hashname)\n" # indexing creates a 1d expression - hashname = BooleanSatisfiability.__get_hash_name(:AND, [z1, z12[1,2]]) + hashname = BooleanSatisfiability.__get_hash_name(:and, [z1, z12[1,2]]) @test smt(z1 ∧ z12[1,2]) == smt(z1, assert=false)*smt(z12[1,2], assert=false)*"(define-fun $hashname () Bool (and z1 z12_1_2))\n(assert $hashname)\n" - hashname = BooleanSatisfiability.__get_hash_name(:AND, z12) + hashname = BooleanSatisfiability.__get_hash_name(:and, z12) @test smt(z12[1,1] ∧ z12[1,2]) == smt(z12[1,1], assert=false)*smt(z12[1,2], assert=false)*"(define-fun $hashname () Bool (and z12_1_1 z12_1_2))\n(assert $hashname)\n" # all() and any() work - hashname = BooleanSatisfiability.__get_hash_name(:OR, [z1 z12]) + hashname = BooleanSatisfiability.__get_hash_name(:or, [z1 z12]) @test smt(any(z1 .∨ z12)) == smt(z1, assert=false)*smt(z12, assert=false)*"(define-fun $hashname () Bool (or z1 z12_1_1 z12_1_2))\n(assert $hashname)\n" - hashname = BooleanSatisfiability.__get_hash_name(:AND, [z1 z12]) + hashname = BooleanSatisfiability.__get_hash_name(:and, [z1 z12]) @test smt(all(z1 .∧ z12)) == smt(z1, assert=false)*smt(z12, assert=false)*"(define-fun $hashname () Bool (and z1 z12_1_1 z12_1_2))\n(assert $hashname)\n" # cross all() and any() terms @@ -47,22 +47,22 @@ end @satvariable(z12[1:1, 1:2], Bool) # implies, also tests \r\n - hashname = BooleanSatisfiability.__get_hash_name(:IMPLIES, [z1, z12[1,2]]) + hashname = BooleanSatisfiability.__get_hash_name(:implies, [z1, z12[1,2]]) @test smt(z1 ⟹ z12[1,2], line_ending="\r\n") == "(declare-const z1 Bool)\r\n(declare-const z12_1_2 Bool)\r\n(define-fun $hashname () Bool (=> z1 z12_1_2))\r\n(assert $hashname)\r\n" # iff, also tests \r\n - hashname = BooleanSatisfiability.__get_hash_name(:IFF, [z1, z12[1,2]]) + hashname = BooleanSatisfiability.__get_hash_name(:iff, [z1, z12[1,2]]) @test smt(z1 ⟺ z12[1,2], line_ending="\r\n") == smt(z1, assert=false, line_ending="\r\n")*smt(z12[1,2], assert=false, line_ending="\r\n")*"(define-fun $hashname () Bool (= z1 z12_1_2))\r\n(assert $hashname)\r\n" # xor - hashname = BooleanSatisfiability.__get_hash_name(:XOR, z12) + hashname = BooleanSatisfiability.__get_hash_name(:xor, z12) @test smt(xor(z12[1,1], z12[1,2])) == smt(z12[1,1], assert=false)*smt(z12[1,2], assert=false)*"(define-fun $hashname () Bool (xor z12_1_1 z12_1_2))\n(assert $hashname)\n" # if-then-else @satvariable(x, Bool) @satvariable(y, Bool) @satvariable(z, Bool) - hashname = BooleanSatisfiability.__get_hash_name(:ITE, [x,y,z]) + hashname = BooleanSatisfiability.__get_hash_name(:ite, [x,y,z]) @test smt(ite(x,y,z)) == smt(x, assert=false)*smt(y, assert=false)*smt(z, assert=false)*"(define-fun $hashname () Bool (ite x y z))\n(assert $hashname)\n" end @@ -70,19 +70,19 @@ end @satvariable(x, Bool) @satvariable(y, Bool) - xyname = BooleanSatisfiability.__get_hash_name(:AND, [x,y]) + xyname = BooleanSatisfiability.__get_hash_name(:and, [x,y]) xy = and(x,y) yx = and(y,x) - topname = BooleanSatisfiability.__get_hash_name(:OR, [xy, yx]) + topname = BooleanSatisfiability.__get_hash_name(:or, [xy, yx]) @test smt(or(xy, yx)) == smt(x, assert=false)*smt(y, assert=false)* "(define-fun $xyname () Bool (and x y)) (define-fun $topname () Bool (or $xyname $xyname)) (assert $topname)\n" # Generate a nested expr with not (1-ary op) without duplicating statements - xname = BooleanSatisfiability.__get_hash_name(:NOT, [x]) + xname = BooleanSatisfiability.__get_hash_name(:not, [x]) nx = ¬x - xyname = BooleanSatisfiability.__get_hash_name(:AND, [nx, nx]) + xyname = BooleanSatisfiability.__get_hash_name(:and, [nx, nx]) @test smt(and(¬x, ¬x)) == smt(x, assert=false)* "(define-fun $xname () Bool (not x)) (define-fun $xyname () Bool (and $xname $xname)) @@ -96,6 +96,6 @@ end save(z1 .∧ z12, "outfile") text = read(open("outfile.smt", "r"), String) @test text == smt(all(z1 .∧ z12))*"(check-sat)\n" - a = Int("a") - @test_logs (:warn, "Top-level expression must be Boolean to produce a valid SMT program.") save(a) + @satvariable(a, Int) + @test_logs (:warn, "Top-level expression must be Boolean to produce a valid SMT program.") match_mode=:any save(a) end \ No newline at end of file diff --git a/test/solver_interface_tests.jl b/test/solver_interface_tests.jl index 61d49ec..c2c12ac 100644 --- a/test/solver_interface_tests.jl +++ b/test/solver_interface_tests.jl @@ -30,60 +30,64 @@ using Test, Logging # Test other assignments, especially reducing child values - test_expr = BoolExpr(:XOR, x, nothing, "test") + test_expr = BoolExpr(:xor, x, nothing, "test") BooleanSatisfiability.__assign!(test_expr, values) @test value(test_expr) == false - test_expr.op = :ITE + test_expr.op = :ite BooleanSatisfiability.__assign!(test_expr, values) @test value(test_expr) == true - test_expr = BoolExpr(:IMPLIES, y, nothing, "test") + test_expr = BoolExpr(:implies, y, nothing, "test") BooleanSatisfiability.__assign!(test_expr, values) @test value(test_expr) == true - test_expr.op = :IFF + test_expr.op = :iff BooleanSatisfiability.__assign!(test_expr, values) @test value(test_expr) == true # done with Booleans, now test Int assignments - values = Dict("a_1"=>1, "a_2"=>2, "a_3"=>3) - test_expr = IntExpr(:EQ, Int(2,"a"), nothing, "test") + values = Dict("a2_1"=>1, "a2_2"=>2, "a2_3"=>3) + @satvariable(a2[1:2], Int) + test_expr = IntExpr(:eq, a2, nothing, "test") BooleanSatisfiability.__assign!(test_expr, values) @test value(test_expr) == false - test_expr.op = :LT + test_expr.op = :lt BooleanSatisfiability.__assign!(test_expr, values) @test value(test_expr) == true - test_expr.op = :GT + test_expr.op = :gt BooleanSatisfiability.__assign!(test_expr, values) @test value(test_expr) == false - test_expr.op = :LEQ + test_expr.op = :leq BooleanSatisfiability.__assign!(test_expr, values) @test value(test_expr) == true - test_expr.op = :GEQ + test_expr.op = :geq BooleanSatisfiability.__assign!(test_expr, values) @test value(test_expr) == false # Arithmetic operations - test_expr = IntExpr(:ADD, Int(3,"a"), nothing, "test") + values = Dict("a3_1"=>1, "a3_2"=>2, "a3_3"=>3) + @satvariable(a3[1:3], Int) + test_expr = IntExpr(:add, a3, nothing, "test") BooleanSatisfiability.__assign!(test_expr, values) @test value(test_expr) == 6 - test_expr.op = :SUB + test_expr.op = :sub BooleanSatisfiability.__assign!(test_expr, values) @test value(test_expr) == -4 - test_expr.op = :MUL + test_expr.op = :mul BooleanSatisfiability.__assign!(test_expr, values) @test value(test_expr) == 6 - values = Dict("a_1"=>1., "a_2"=>2., "a_3"=>3., "a"=>0.) - test_expr = RealExpr(:DIV, Real(3,"a"), nothing, "test") + values = Dict("ar3_1"=>1., "ar3_2"=>2., "ar3_3"=>3., "a"=>0.) + @satvariable(ar3[1:3], Real) + test_expr = RealExpr(:div, ar3, nothing, "test") BooleanSatisfiability.__assign!(test_expr, values) @test value(test_expr) == (1. / 2. / 3.) # Can't assign nonexistent operator - test_expr = RealExpr(:fakeop, Real(1,"a"), nothing, "test") - @test_logs (:error, "Unknown operator fakeop") BooleanSatisfiability.__assign!(test_expr, values) + #test_expr = RealExpr(:fakeop, Real(1,"a"), nothing, "test") + #@test_logs (:error, "Unknown operator fakeop") BooleanSatisfiability.__assign!(test_expr, values) # Missing value assigned to missing - b = Int("b") + @satvariable(b, Int) @test ismissing(BooleanSatisfiability.__assign!(b, values)) end From 92b40bcb1b13b10c4b71b7231eaec30a64a8b3fe Mon Sep 17 00:00:00 2001 From: Emiko Soroka Date: Sat, 12 Aug 2023 14:50:54 -0700 Subject: [PATCH 19/36] Finished architecture fixes for adding new theories. --- src/BoolExpr.jl | 7 +-- src/BooleanOperations.jl | 76 ++++++++------------------------ src/IntExpr.jl | 60 ++++++++++++------------- src/smt_representation.jl | 12 ++--- src/utilities.jl | 29 ++++++++++++ test/boolean_operation_tests.jl | 8 ++-- test/int_real_tests.jl | 2 +- test/smt_representation_tests.jl | 8 ++-- 8 files changed, 95 insertions(+), 107 deletions(-) diff --git a/src/BoolExpr.jl b/src/BoolExpr.jl index aa88e94..03757fd 100644 --- a/src/BoolExpr.jl +++ b/src/BoolExpr.jl @@ -9,14 +9,12 @@ abstract type AbstractExpr end # children: BoolExpr children for an expression. And(z1, z2) has children [z1, z2] # value: Bool array or nothing if result not computed # name: String name of variable / expression. -# __ret_type : Corresponds to the sort of an operator in SMT-LIB. Necessitated because Julia has a dynamic type system so the compiler can't easily infer return type of an operator. # __is_commutative: true if AbstractExpr is a commutative operator, false if not. mutable struct BoolExpr <: AbstractExpr op :: Symbol children :: Array{AbstractExpr} value :: Union{Bool, Nothing, Missing} name :: String - __ret_type :: Type __is_commutative :: Bool # for convenience @@ -24,8 +22,7 @@ mutable struct BoolExpr <: AbstractExpr children::Array{T}, value::Union{Bool, Nothing, Missing}, name::String; - __ret_type = BoolExpr, - __is_commutative = false) where T <: AbstractExpr = new(op, children, value, name, __ret_type, __is_commutative) + __is_commutative = false) where T <: AbstractExpr = new(op, children, value, name, __is_commutative) end @@ -85,7 +82,7 @@ end # Required for isequal apparently, since isequal(expr1, expr2) implies hash(expr1) == hash(expr2). function Base.hash(expr::AbstractExpr) - return hash("$(show(expr))") + return hash("$(string(expr))") end # Overload because Base.in uses == which se used to construct equality expressions diff --git a/src/BooleanOperations.jl b/src/BooleanOperations.jl index 5889876..8a6d394 100644 --- a/src/BooleanOperations.jl +++ b/src/BooleanOperations.jl @@ -48,6 +48,17 @@ function __get_hash_name(op::Symbol, names::Array{String}) return "$(op)_$(string(hash(combined_name), base=16))" end +# combine children for Boolean n-ary ops +function __bool_nary_op(zs::Array{T}, op::Symbol, ReturnType::Type, __is_commutative=false, __try_flatten=false) where T <: BoolExpr + expr = __combine(zs, op, ReturnType, __is_commutative, __try_flatten) + if __is_commutative && length(expr.children)>0 # clear duplicates + expr.children = unique(expr.children) + expr.name = __get_hash_name(expr.op, expr.children) + end + return expr +end + + ##### LOGICAL OPERATIONS ##### """ @@ -85,15 +96,9 @@ function and(zs_mixed::Array{T}; broadcast_type=:Elementwise) where T return true end end - # having passed this processing of literals, we'll check for base cases - if length(zs) == 0 - return nothing - elseif length(zs) == 1 - return zs[1] - end - + # now the remaining are BoolExpr - expr = __combine(zs, :and, BoolExpr) + expr = __bool_nary_op(zs, :and, BoolExpr, true, true) values = getproperty.(expr.children, :value) expr.value = length(values) > 0 && !any(isnothing.(values)) ? reduce(&, values) : nothing return expr @@ -131,14 +136,8 @@ function or(zs_mixed::Array{T}; broadcast_type=:Elementwise) where T return false end end - # having passed this processing of literals, we'll check for base cases - if length(zs)== 0 - return nothing - elseif length(zs) == 1 - return zs[1] - end - expr = __combine(zs, :or, BoolExpr) + expr = __bool_nary_op(zs, :or, BoolExpr, true, true) values = getproperty.(expr.children, :value) expr.value = length(values) > 0 && !any(isnothing.(values)) ? reduce(|, values) : nothing return expr @@ -195,17 +194,11 @@ function xor(zs_mixed::Array{T}; broadcast_type=:Elementwise) where T return xor(literals...) end end - # having passed this processing of literals, we'll check for base cases - if length(zs)== 0 - return nothing - elseif length(zs) == 1 - return zs[1] - end - name = __get_hash_name(:xor, zs) + expr = __bool_nary_op(zs, :xor, BoolExpr, true, false) child_values = getproperty.(zs, :value) - value = any(isnothing.(child_values)) ? nothing : reduce(xor, child_values) - return BoolExpr(:xor, zs, value, name, __is_commutative=true) + expr.value = any(isnothing.(child_values)) ? nothing : reduce(xor, child_values) + return expr end # We need this extra line to enable the syntax xor.([z1, z2,...,zn]) where z1, z2,...,z are broadcast-compatible @@ -219,7 +212,7 @@ Returns the expression z1 IMPLIES z2. Use dot broadcasting for vector-valued and """ function implies(z1::BoolExpr, z2::BoolExpr) zs = BoolExpr[z1, z2] - value = isnothing(z1.value) || isnothing(z2.value) ? nothing : !(z1.value) | z2.value + value = isnothing(z1.value) || isnothing(z2.value) ? nothing : implies(z1.value, z2.value) return BoolExpr(:implies, zs, value, __get_hash_name(:implies, zs)) end @@ -231,7 +224,7 @@ Bidirectional implication between z1 and z2. Equivalent to `and(z1 ⟹ z2, z2 """ function iff(z1::BoolExpr, z2::BoolExpr) zs = BoolExpr[z1, z2] - value = isnothing(z1.value) || isnothing(z2.value) ? nothing : z1.value == z2.value + value = isnothing(z1.value) || isnothing(z2.value) ? nothing : iff(z1.value, z2.value) return BoolExpr(:iff, zs, value, __get_hash_name(:iff, zs), __is_commutative=true) end @@ -285,39 +278,8 @@ iff(z1::Bool, z2::BoolExpr) = z1 ? z2 : ¬z2 iff(z1::Bool, z2::Bool) = z1 == z2 - ##### ADDITIONAL OPERATIONS ##### -"combine is used for both and() and or() since those are fundamentally the same with different operations." -function __combine(zs::Array{T}, op::Symbol, ret_type::Type) where T <: BoolExpr - if length(zs) == 0 - error("Cannot iterate over zero-length array.") - elseif length(zs) == 1 - return zs[1] - end - - # Now we need to take an array of statements and decide how to combine them - if all(getproperty.(zs, :op) .== :identity) - children = flatten(zs) - name = __get_hash_name(op, zs) - elseif all(getproperty.(zs, :op) .== op) - # if op matches (e.g. any(or(z1, z2)) or all(and(z1, z2))) then flatten it. - # Returm a combined operator - # this line gets a list with no duplicates of all children - children = union(cat(map( (e) -> flatten(e.children), zs)..., dims=1)) - name = __get_hash_name(op, children) - else # op doesn't match, so we won't flatten it but will combine all the children - name = __get_hash_name(op, zs) - children = flatten(zs) - end - - return BoolExpr(op, children, nothing, name, __is_commutative=true) -end - -"combine(z, op) where z is an n x m matrix of BoolExprs first flattens z, then combines it with op. -combine([z1 z2; z3 z4], or) = or([z1; z2; z3; z4])." -__combine(zs::Matrix{T}, op::Symbol, ret_type::Type) where T <: BoolExpr = __combine(flatten(zs), op, ret_type) - """ all([z1,...,zn]) diff --git a/src/IntExpr.jl b/src/IntExpr.jl index c77b557..f80ef12 100644 --- a/src/IntExpr.jl +++ b/src/IntExpr.jl @@ -8,7 +8,6 @@ mutable struct IntExpr <: NumericExpr children :: Array{AbstractExpr} value :: Union{Int, Bool, Nothing, Missing} name :: String - __ret_type :: Type __is_commutative :: Bool # for convenience @@ -16,8 +15,7 @@ mutable struct IntExpr <: NumericExpr children::Array{T}, value::Union{Int, Bool, Nothing, Missing}, name::String; - __ret_type = IntExpr, - __is_commutative = false) where T <: AbstractExpr = new(op, children, value, name, __ret_type, __is_commutative) + __is_commutative = false) where T <: AbstractExpr = new(op, children, value, name, __is_commutative) end @@ -46,7 +44,6 @@ mutable struct RealExpr <: NumericExpr children :: Array{AbstractExpr} value :: Union{Float64, Nothing, Missing} name :: String - __ret_type :: Type __is_commutative :: Bool # for convenience @@ -54,8 +51,7 @@ mutable struct RealExpr <: NumericExpr children::Array{T}, value::Union{Float64, Nothing, Missing}, name::String; - __ret_type = RealExpr, - __is_commutative = false) where T <: AbstractExpr = new(op, children, value, name, __ret_type, __is_commutative) + __is_commutative = false) where T <: AbstractExpr = new(op, children, value, name, __is_commutative) end """ @@ -107,7 +103,7 @@ a .< z function Base.:<(e1::NumericInteroperableExpr, e2::NumericInteroperableExpr) value = isnothing(e1.value) || isnothing(e2.value) ? nothing : e1.value < e2.value name = __get_hash_name(:lt, [e1, e2]) - return BoolExpr(:lt, [e1, e2], value, name, __ret_type=BoolExpr) + return BoolExpr(:lt, [e1, e2], value, name) end """ @@ -127,7 +123,7 @@ a .<= z function Base.:<=(e1::NumericInteroperableExpr, e2::NumericInteroperableExpr) value = isnothing(e1.value) || isnothing(e2.value) ? nothing : e1.value <= e2.value name = __get_hash_name(:leq, [e1, e2]) - return BoolExpr(:leq, [e1, e2], value, name, __ret_type=BoolExpr) + return BoolExpr(:leq, [e1, e2], value, name) end """ @@ -147,7 +143,7 @@ a .>= z function Base.:>=(e1::NumericInteroperableExpr, e2::NumericInteroperableExpr) value = isnothing(e1.value) || isnothing(e2.value) ? nothing : e1.value >= e2.value name = __get_hash_name(:geq, [e1, e2]) - return BoolExpr(:geq, [e1, e2], value, name, __ret_type=BoolExpr) + return BoolExpr(:geq, [e1, e2], value, name) end """ @@ -167,7 +163,7 @@ a .> z function Base.:>(e1::NumericInteroperableExpr, e2::NumericInteroperableExpr) value = isnothing(e1.value) || isnothing(e2.value) ? nothing : e1.value > e2.value name = __get_hash_name(:gt, [e1, e2]) - return BoolExpr(:gt, [e1, e2], value, name, __ret_type=BoolExpr) + return BoolExpr(:gt, [e1, e2], value, name) end # IMPORTANT NOTE @@ -192,7 +188,7 @@ a .== b function Base.:(==)(e1::AbstractExpr, e2::AbstractExpr) value = isnothing(e1.value) || isnothing(e2.value) ? nothing : e1.value == e2.value name = __get_hash_name(:eq, [e1, e2]) - return BoolExpr(:eq, [e1, e2], value, name, __ret_type=BoolExpr, __is_commutative=true) + return BoolExpr(:eq, [e1, e2], value, name, __is_commutative=true) end # INTEROPERABILITY FOR COMPARISON OPERATIONS @@ -251,6 +247,7 @@ function __merge_const!(es::Array{T}) where T <: AbstractExpr end end +#= # This is NOT a recursive function. It will only unnest one level. function __unnest(es::Array{T}, op::Symbol) where T <: AbstractExpr # this is all the child operators that aren't const or IDENTITY @@ -264,29 +261,32 @@ function __unnest(es::Array{T}, op::Symbol) where T <: AbstractExpr return es end end +=# # This works for any n_ary op that takes as input NumericInteroperable arguments -function __numeric_n_ary_op(es_mixed::Array, op::Symbol; __is_commutative=true) +function __numeric_n_ary_op(es_mixed::Array, op::Symbol; __is_commutative=false, __try_flatten=false) # clean up types! This guarantees es::Array{AbstractExpr} es, literals = __check_inputs_nary_op(es_mixed, const_type=NumericInteroperableConst, expr_type=NumericInteroperableExpr) - literal = length(literals) > 0 ? sum(literals) : 0 + literals = __is_commutative && length(literals) > 0 ? [sum(literals)] : literals - # flatten nestings, this prevents unsightly things like and(x, and(y, and(z, true))) - es = __unnest(es, op) # now we are guaranteed all es are valid exprs and all literals have been condensed to one - # hack to store literals - __add_const!(es, literal) - - # Now it is possible we have several CONST exprs. This occurs if, for example, one writes 1 + a + true - # TO clean up, we should merge the CONST exprs - __merge_const!(es) - - # Now everything is in es and we are all cleaned up. + for l in literals + __add_const!(es, l) + end + # Determine return expr type. Note that / promotes to RealExpr because the SMT theory of integers doesn't include it - ReturnExpr = any(isa.(es, RealExpr)) || op == :div ? RealExpr : IntExpr + ReturnType = any(isa.(es, RealExpr)) || op == :div ? RealExpr : IntExpr + expr = __combine(es, op, ReturnType, __is_commutative, __try_flatten) + + # Now it is possible we have several CONST exprs. This occurs if, for example, one writes (a+1) + (b+1) which flattens to a+1+b+1 + # TO clean up, we should merge the CONST exprs + if __is_commutative + __merge_const!(expr.children) + expr.name = __get_hash_name(expr.op, expr.children) + end - value = any(isnothing.(getproperty.(es, :value))) ? nothing : sum(getproperty.(es, :value)) - return ReturnExpr(op, es, value, __get_hash_name(op, es), __ret_type=ReturnExpr, __is_commutative=__is_commutative) + expr.value = any(isnothing.(getproperty.(es, :value))) ? nothing : sum(getproperty.(es, :value)) + return expr end @@ -317,8 +317,8 @@ println("typeof a+z: \$(typeof(a[1] + z))") ``` """ -Base.:+(e1::Union{NumericInteroperableExpr}, e2::NumericInteroperableExpr) = __numeric_n_ary_op([e1, e2], :add, __is_commutative=true) -Base.:+(e1::Union{NumericInteroperableExpr}, e2::NumericInteroperableConst) = __numeric_n_ary_op([e1, e2], :add, __is_commutative=true) +Base.:+(e1::Union{NumericInteroperableExpr}, e2::NumericInteroperableExpr) = __numeric_n_ary_op([e1, e2], :add, __is_commutative=true, __try_flatten=true) +Base.:+(e1::Union{NumericInteroperableExpr}, e2::NumericInteroperableConst) = __numeric_n_ary_op([e1, e2], :add, __is_commutative=true, __try_flatten=true) Base.:+(e1::Union{NumericInteroperableConst}, e2::NumericInteroperableExpr) = e2 + e1 """ @@ -365,8 +365,8 @@ a .- z println("typeof a*z: \$(typeof(a[1]*z))") ``` """ -Base.:*(e1::Union{NumericInteroperableExpr}, e2::NumericInteroperableExpr) = __numeric_n_ary_op([e1, e2], :mul, __is_commutative=true) -Base.:*(e1::Union{NumericInteroperableExpr}, e2::NumericInteroperableConst) = __numeric_n_ary_op([e1, e2], :mul, __is_commutative=true) +Base.:*(e1::Union{NumericInteroperableExpr}, e2::NumericInteroperableExpr) = __numeric_n_ary_op([e1, e2], :mul, __is_commutative=true, __try_flatten=true) +Base.:*(e1::Union{NumericInteroperableExpr}, e2::NumericInteroperableConst) = __numeric_n_ary_op([e1, e2], :mul, __is_commutative=true, __try_flatten=true) Base.:*(e1::Union{NumericInteroperableConst}, e2::NumericInteroperableExpr) = e2 * e1 """ diff --git a/src/smt_representation.jl b/src/smt_representation.jl index b9f6885..c3d30fa 100644 --- a/src/smt_representation.jl +++ b/src/smt_representation.jl @@ -94,7 +94,7 @@ function __define_n_op!(z::T, cache::Dict{UInt64, String}, depth::Int; assert=tr if length(children) == 0 # silly case but we should handle it return "" end - if assert && depth == 0 && z.__ret_type != BoolExpr + if assert && depth == 0 && typeof(z) != BoolExpr @warn("Cannot assert non-Boolean expression $z") end @@ -116,7 +116,7 @@ function __define_n_op!(z::T, cache::Dict{UInt64, String}, depth::Int; assert=tr if cache_key in keys(cache) prop = depth == 0 ? cache[cache_key] : "" else - if assert && z.__ret_type == BoolExpr && depth == 0 + if assert && typeof(z) == BoolExpr && depth == 0 prop = declaration*"(assert $fname)$line_ending" # the proposition is generated and cached now. cache[cache_key] = "(assert $fname)$line_ending" @@ -136,7 +136,7 @@ function __define_1_op!(z::AbstractExpr, cache::Dict{UInt64, String}, depth::Int declaration = "(define-fun $fname () $outname ($(__smt_opnames(z.op)) $(__get_smt_name(z.children[1]))))$line_ending" cache_key = hash(declaration) - if assert && depth == 0 && z.__ret_type != BoolExpr + if assert && depth == 0 && typeof(z) != BoolExpr @warn("Cannot assert non-Boolean expression $z") end @@ -145,7 +145,7 @@ function __define_1_op!(z::AbstractExpr, cache::Dict{UInt64, String}, depth::Int else # if depth = 0 that means we are at the top-level of a nested expression. # thus, if the expr is Boolean we should assert it. - if assert && z.__ret_type == BoolExpr && depth == 0 + if assert && typeof(z) == BoolExpr && depth == 0 prop = declaration*"(assert $fname)$line_ending" # the proposition is generated and cached now. cache[cache_key] = "(assert $fname)$line_ending" @@ -166,7 +166,7 @@ function smt!(z::AbstractExpr, declarations::Array{T}, propositions::Array{T}, c n = length(declarations) push_unique!(declarations, declare(z; line_ending=line_ending)) if assert && depth == 0 - if z.__ret_type != BoolExpr + if typeof(z) != BoolExpr @warn("Cannot assert non-Boolean expression $z") else push_unique!(propositions, "(assert $(z.name))$line_ending") @@ -240,7 +240,7 @@ function save(prob::AbstractExpr, filename="out"; assert=true, check_sat=true, l line_ending = Sys.iswindows() ? "\r\n" : '\n' end - if assert && prob.__ret_type != BoolExpr + if assert && typeof(prob) != BoolExpr @warn "Top-level expression must be Boolean to produce a valid SMT program." end open("$filename.smt", "w") do io diff --git a/src/utilities.jl b/src/utilities.jl index 64691ad..d820c34 100644 --- a/src/utilities.jl +++ b/src/utilities.jl @@ -23,6 +23,35 @@ function __check_inputs_nary_op(zs_mixed::Array{T}; const_type=Bool, expr_type=A return zs, literals end + +function __combine(zs::Array{T}, op::Symbol, ReturnType::Type, __is_commutative=false, __try_flatten=false) where T <: AbstractExpr + if length(zs) == 0 + error("Cannot iterate over zero-length array.") + elseif length(zs) == 1 + return zs[1] + end + + # Now we need to take an array of statements and decide how to combine them + # if this is an op where it makes sense to flatten (eg, and(and(x,y), and(y,z)) then flatten it) + ops = getproperty.(zs, :op) + if __try_flatten && (all(ops .== op) || + (__is_commutative && all(map( (o) -> o in [:identity, :const, op], ops)))) + # Returm a combined operator + # this line merges childless operators and children, eg and(x, and(y,z)) yields [x, y, z] + children = cat(map( (e) -> length(e.children) > 0 ? e.children : [e], zs)..., dims=1) + else # op doesn't match, so we won't flatten it + children = zs + end + name = __get_hash_name(op, children) + + return ReturnType(op, children, nothing, name, __is_commutative=__is_commutative) +end + +"combine(z, op) where z is an n x m matrix of BoolExprs first flattens z, then combines it with op. +combine([z1 z2; z3 z4], or) = or([z1; z2; z3; z4])." +__combine(zs::Matrix{T}, op::Symbol, ReturnType::Type, __is_commutative=false, __try_flatten=false) where T <: BoolExpr = __combine(flatten(zs), op, ReturnType, __is_commutative, __try_flatten) + + "is_permutation(a::Array, b::Array) returns True if a is a permutation of b. is_permutation([1,2,3], [3,2,1]) == true is_permutation([1,2,3], [1,3]) == false" diff --git a/test/boolean_operation_tests.jl b/test/boolean_operation_tests.jl index 5e8477e..9dd951b 100644 --- a/test/boolean_operation_tests.jl +++ b/test/boolean_operation_tests.jl @@ -51,7 +51,7 @@ end # 1 and 0 cases @test isequal(and([z1[1]]), z1[1]) - @test isnothing(and(AbstractExpr[])) + @test_throws ErrorException and(AbstractExpr[]) # Can construct with 2 exprs @test all( isequal.((z1 .∧ z32)[1].children, [z1[1], z32[1]] )) @@ -77,8 +77,8 @@ end # Can construct all() and any() statements @test isequal(any(z1), z1[1]) - @test isequal(any(z1 .∨ z12), BoolExpr(:or, [z12[1,1], z1[1], z12[1,2]], nothing, BooleanSatisfiability.__get_hash_name(:or, [z1 z12]))) - @test isequal(all(z1 .∧ z12), BoolExpr(:and, [z12[1,1], z1[1], z12[1,2]], nothing, BooleanSatisfiability.__get_hash_name(:and, [z1 z12]))) + @test isequal(any(z1 .∨ z12), or(z1 .∨ z12)) + @test isequal(all(z1 .∧ z12), and(z1 .∧ z12)) # mismatched all() and any() @test isequal(any(z1 .∧ z12), BoolExpr(:or, [z1[1] ∧ z12[1,1], z1[1] ∧ z12[1,2]], nothing, BooleanSatisfiability.__get_hash_name(:or, z1.∧ z12))) @@ -93,7 +93,7 @@ end # xor @test all(isequal.(xor.(z1, z12), BoolExpr[xor(z12[1,1], z1[1]) xor(z12[1,2], z1[1])])) # weird cases - @test isnothing(xor(AbstractExpr[])) + @test_throws ErrorException xor(AbstractExpr[]) @test all(isequal.(xor(z1), z1)) @test xor(true, true, z) == false @test xor(true, false) == true diff --git a/test/int_real_tests.jl b/test/int_real_tests.jl index 4b1c41d..ee51ada 100644 --- a/test/int_real_tests.jl +++ b/test/int_real_tests.jl @@ -27,8 +27,8 @@ using Test @test isequal((c .>= 0)[1,1] , c[1,1] >= 0) && isequal((c .<= 0.0)[1,1] , c[1,1] <= 0.0) @test isequal((c .== 0)[1,1] , c[1,1] == 0) @test isequal((c .< 0)[1,1] , c[1,1] < 0) && isequal((c .> 0)[1,1] , c[1,1] > 0) - @test isequal((c .- 1)[1,1], c[1,1] - 1) && isequal((c .* 2)[1,1], 2 * c[1,1]) && isequal((br ./ 2)[1], br[1] / 2) + # Construct with constants on LHS @test isequal((0 .>= c)[1,1] , 0 >= c[1,1]) && isequal((0.0 .<= c)[1,1] , 0.0 <= c[1,1]) @test isequal((0 .== c)[1,1] , c[1,1] == 0) diff --git a/test/smt_representation_tests.jl b/test/smt_representation_tests.jl index 6ad2573..bc1328b 100644 --- a/test/smt_representation_tests.jl +++ b/test/smt_representation_tests.jl @@ -73,19 +73,19 @@ end xyname = BooleanSatisfiability.__get_hash_name(:and, [x,y]) xy = and(x,y) yx = and(y,x) - topname = BooleanSatisfiability.__get_hash_name(:or, [xy, yx]) + topname = BooleanSatisfiability.__get_hash_name(:or, [xy]) @test smt(or(xy, yx)) == smt(x, assert=false)*smt(y, assert=false)* "(define-fun $xyname () Bool (and x y)) -(define-fun $topname () Bool (or $xyname $xyname)) +(define-fun $topname () Bool (or $xyname)) (assert $topname)\n" # Generate a nested expr with not (1-ary op) without duplicating statements xname = BooleanSatisfiability.__get_hash_name(:not, [x]) nx = ¬x - xyname = BooleanSatisfiability.__get_hash_name(:and, [nx, nx]) + xyname = BooleanSatisfiability.__get_hash_name(:and, [nx]) @test smt(and(¬x, ¬x)) == smt(x, assert=false)* "(define-fun $xname () Bool (not x)) -(define-fun $xyname () Bool (and $xname $xname)) +(define-fun $xyname () Bool (and $xname)) (assert $xyname)\n" end From 50597a228cf28d3ff0ddb66bf122a866c8feb3ba Mon Sep 17 00:00:00 2001 From: Emiko Soroka Date: Sat, 12 Aug 2023 14:51:52 -0700 Subject: [PATCH 20/36] delete unused commented code, fix hash function for AbstractExpr and isequal to correctly handle commutative vs non commutative operations. All tests pass. --- src/BoolExpr.jl | 11 +++--- src/IntExpr.jl | 20 ---------- src/utilities.jl | 65 ++------------------------------- test/boolean_operation_tests.jl | 12 +++--- test/int_parse_tests.jl | 8 ++-- 5 files changed, 19 insertions(+), 97 deletions(-) diff --git a/src/BoolExpr.jl b/src/BoolExpr.jl index 03757fd..c95b4be 100644 --- a/src/BoolExpr.jl +++ b/src/BoolExpr.jl @@ -44,9 +44,6 @@ function BoolExpr(name::String) :: BoolExpr end return BoolExpr(:identity, AbstractExpr[], nothing, "$(name)") end -# may eventually be removed in favor of macros -#Bool(n::Int, name::String) :: Vector{BoolExpr} = BoolExpr[Bool("$(name)_$(i)") for i=1:n] -#Bool(m::Int, n::Int, name::String) :: Matrix{BoolExpr} = BoolExpr[Bool("$(name)_$(i)_$(j)") for i=1:m, j=1:n] ##### BASE FUNCTIONS ##### @@ -81,8 +78,12 @@ function Base.isequal(expr1::AbstractExpr, expr2::AbstractExpr) end # Required for isequal apparently, since isequal(expr1, expr2) implies hash(expr1) == hash(expr2). -function Base.hash(expr::AbstractExpr) - return hash("$(string(expr))") +function Base.hash(expr::AbstractExpr, h::UInt) + if length(expr.children)>0 + return hash(expr.op, hash(expr.__is_commutative, hash(hash(expr.children, h), h))) + else + return hash(expr.op, hash(expr.__is_commutative, hash(expr.name, h))) + end end # Overload because Base.in uses == which se used to construct equality expressions diff --git a/src/IntExpr.jl b/src/IntExpr.jl index f80ef12..574fc01 100644 --- a/src/IntExpr.jl +++ b/src/IntExpr.jl @@ -35,8 +35,6 @@ function IntExpr(name::String) :: IntExpr end return IntExpr(:identity, AbstractExpr[], nothing, "$(name)") end -#Int(n::Int, name::String) :: Vector{IntExpr} = IntExpr[Int("$(name)_$(i)") for i=1:n] -#Int(m::Int, n::Int, name::String) :: Matrix{IntExpr} = IntExpr[Int("$(name)_$(i)_$(j)") for i=1:m, j=1:n] mutable struct RealExpr <: NumericExpr @@ -70,8 +68,6 @@ function RealExpr(name::String) :: RealExpr end return RealExpr(:identity, AbstractExpr[], nothing, "$(name)") end -#Real(n::Int, name::String) :: Vector{RealExpr} = RealExpr[Real("$(name)_$(i)") for i=1:n] -#Real(m::Int, n::Int, name::String) :: Matrix{RealExpr} = RealExpr[Real("$(name)_$(i)_$(j)") for i=1:m, j=1:n] # These are necessary for defining interoperability between IntExpr, RealExpr, BoolExpr and built-in types such as Int, Bool, and Float. @@ -247,22 +243,6 @@ function __merge_const!(es::Array{T}) where T <: AbstractExpr end end -#= -# This is NOT a recursive function. It will only unnest one level. -function __unnest(es::Array{T}, op::Symbol) where T <: AbstractExpr - # this is all the child operators that aren't const or IDENTITY - child_operators = filter( (op) -> op != :identity && op != :const, getproperty.(es, :op)) - - if length(child_operators) > 0 && all(child_operators .== op) - children = AbstractExpr[] - map( (e) -> length(e.children) > 0 ? append!(children, e.children) : push!(children, e), es) - return children - else - return es - end -end -=# - # This works for any n_ary op that takes as input NumericInteroperable arguments function __numeric_n_ary_op(es_mixed::Array, op::Symbol; __is_commutative=false, __try_flatten=false) # clean up types! This guarantees es::Array{AbstractExpr} diff --git a/src/utilities.jl b/src/utilities.jl index d820c34..9863e77 100644 --- a/src/utilities.jl +++ b/src/utilities.jl @@ -42,6 +42,9 @@ function __combine(zs::Array{T}, op::Symbol, ReturnType::Type, __is_commutative= else # op doesn't match, so we won't flatten it children = zs end + if __is_commutative + children = sort(children, by=(c) -> c.name) + end name = __get_hash_name(op, children) return ReturnType(op, children, nothing, name, __is_commutative=__is_commutative) @@ -76,68 +79,6 @@ end ##### PARSING SMT OUTPUT ##### -#= -"Utility function for parsing SMT output. Split lines based on parentheses" -function __split_line(output, ptr) - stack = 0 - while ptr < length(output) - lp = findnext("(", output, ptr) - rp = findnext(")", output, ptr) - if isnothing(lp) || isnothing(rp) - return nothing - end - lp, rp = lp[1], rp[1] - if lp < rp - ptr = lp+1 # move past the next ( - stack += 1 - else - ptr = rp+1 # move past the next ) - stack -= 1 - end - if stack == 0 - return ptr - end - end -end - - -"Utility function for parsing SMT output. Read lines of the form '(define-fun x () Bool true)' -and extract the name (x) and the value (true)." -function __read_line!(line, values) - line = join(filter( (c) -> c != '\n', line),"") - line = split(line[1:end-1], " ") # strip ( and ) - name = line[4] # TODO fix - if line[end] == "true" - values[name] = true - elseif line[end] == "false" - values[name] = false - end -end - -"Utility function for parsing SMT output. Takes output of (get-model) and returns a dict of values like {'x' => true, 'y' => false}. -If a variable is not set to true or false by get-model, it will not appear in the dictionary keys." -function __parse_smt_output(output::String) - values = Dict{String, Bool}() - # there's one line with just ( - ptr = findnext("(\n", output, 1)[2] # skip it - # lines 3 - n-1 are the model definitions - next_ptr = ptr - - while ptr < length(output) - next_ptr = __split_line(output, ptr) - if isnothing(next_ptr) - break - end - #println(output[ptr:next_ptr]) - __read_line!(output[ptr:next_ptr], values) - ptr = next_ptr - end - # line n is the closing ) - return values -end -=# - -##### NEW OUTPUT PARSER ##### # Given a string consisting of a set of statements (statement-1) \n(statement-2) etc, split into an array of strings, stripping \n and (). # Split one level only, so "(a(b))(c)(d)" returns ["a(b)", "c", "d"] diff --git a/test/boolean_operation_tests.jl b/test/boolean_operation_tests.jl index 9dd951b..d74dcf6 100644 --- a/test/boolean_operation_tests.jl +++ b/test/boolean_operation_tests.jl @@ -54,19 +54,19 @@ end @test_throws ErrorException and(AbstractExpr[]) # Can construct with 2 exprs - @test all( isequal.((z1 .∧ z32)[1].children, [z1[1], z32[1]] )) + @test BooleanSatisfiability.__is_permutation((z1 .∧ z32)[1].children, [z1[1], z32[1]] ) @test (z1 .∧ z32)[1].name == BooleanSatisfiability.__get_hash_name(:and, [z1[1], z32[1]]) - @test all( isequal.((z1 .∨ z32)[2,1].children, [z1[1], z32[2,1]] )) + @test BooleanSatisfiability.__is_permutation((z1 .∨ z32)[2,1].children, [z1[1], z32[2,1]] ) @test (z1 .∨ z32)[1].name == BooleanSatisfiability.__get_hash_name(:or, [z1[1], z32[1]]) # Can construct with N>2 exprs or_N = or.(z1, z12, z32) and_N = and.(z1, z12, z32) - @test all( isequal.(or_N[3,2].children, [z1[1], z12[1,2], z32[3,2]] )) + @test BooleanSatisfiability.__is_permutation(or_N[3,2].children, [z1[1], z12[1,2], z32[3,2]] ) @test and_N[1].name == BooleanSatisfiability.__get_hash_name(:and, and_N[1].children) - @test all( isequal.(or_N[1].children, [z1[1], z12[1], z32[1]] )) + @test BooleanSatisfiability.__is_permutation(or_N[1].children, [z1[1], z12[1], z32[1]] ) @test or_N[1].name == BooleanSatisfiability.__get_hash_name(:or, and_N[1].children) # Can construct negation @@ -81,8 +81,8 @@ end @test isequal(all(z1 .∧ z12), and(z1 .∧ z12)) # mismatched all() and any() - @test isequal(any(z1 .∧ z12), BoolExpr(:or, [z1[1] ∧ z12[1,1], z1[1] ∧ z12[1,2]], nothing, BooleanSatisfiability.__get_hash_name(:or, z1.∧ z12))) - @test isequal(and(z12 .∨ z1), BoolExpr(:and, [z1[1] ∨ z12[1,1], z1[1] ∨ z12[1,2]], nothing, BooleanSatisfiability.__get_hash_name(:and, z1.∨ z12))) + @test isequal(any(z1 .∧ z12), BoolExpr(:or, [z1[1] ∧ z12[1,1], z1[1] ∧ z12[1,2]], nothing, BooleanSatisfiability.__get_hash_name(:or, z1.∧ z12), __is_commutative=true)) + @test isequal(and(z12 .∨ z1), BoolExpr(:and, [z1[1] ∨ z12[1,1], z1[1] ∨ z12[1,2]], nothing, BooleanSatisfiability.__get_hash_name(:and, z1.∨ z12), __is_commutative=true)) end @testset "Additional operations" begin diff --git a/test/int_parse_tests.jl b/test/int_parse_tests.jl index 7016f9e..699913e 100644 --- a/test/int_parse_tests.jl +++ b/test/int_parse_tests.jl @@ -11,12 +11,12 @@ expr1 = a + b + 2 (define-fun add_99dce5c325207b7 () Int (+ 2 a b))\n" expr = and(expr1 <= a, b + 1 >= b) -result = "(declare-const a Int) -(declare-const b Int) -(define-fun add_99dce5c325207b7 () Int (+ 2 a b)) -(define-fun leq_8df5432ee845c9e8 () Bool (<= add_99dce5c325207b7 a)) +result = "(declare-const b Int) +(declare-const a Int) (define-fun add_f0a93f0b97da1ab2 () Int (+ 1 b)) (define-fun geq_e1bd460e008a4d8b () Bool (>= add_f0a93f0b97da1ab2 b)) +(define-fun add_99dce5c325207b7 () Int (+ 2 a b)) +(define-fun leq_8df5432ee845c9e8 () Bool (<= add_99dce5c325207b7 a)) (define-fun and_8014e2e143374eea () Bool (and geq_e1bd460e008a4d8b leq_8df5432ee845c9e8)) (assert and_8014e2e143374eea)\n" @test smt(expr) == result From fbd0f0165402de9901b2c9d3ba6e54531fd54037 Mon Sep 17 00:00:00 2001 From: Emiko Soroka Date: Sat, 12 Aug 2023 16:51:58 -0700 Subject: [PATCH 21/36] Added BitVector tests. There are two broken for cat, because Base.cat is called instead. SMT generation works except for int2bv, bv2int, cat and indexing. --- src/BitVectorExpr.jl | 50 ++++++++++++++++++++++-------------- src/BooleanSatisfiability.jl | 21 +++++++++++++++ src/smt_macros.jl | 6 ++--- test/bitvector_tests.jl | 46 +++++++++++++++++++++++++++++++++ 4 files changed, 101 insertions(+), 22 deletions(-) create mode 100644 test/bitvector_tests.jl diff --git a/src/BitVectorExpr.jl b/src/BitVectorExpr.jl index 0cad93d..84b49f7 100644 --- a/src/BitVectorExpr.jl +++ b/src/BitVectorExpr.jl @@ -13,6 +13,14 @@ mutable struct BitVectorExpr{T<:Integer} <: AbstractExpr value :: Union{T, Nothing, Missing} name :: String length :: Int + __is_commutative :: Bool + + BitVectorExpr{T}(op::Symbol, + children::Array{C}, + value::Union{T, Nothing, Missing}, + name::String, + length::Int; + __is_commutative = false) where T <: Integer where C <: AbstractExpr = new(op, children, value, name, length, __is_commutative) end """ @@ -21,7 +29,7 @@ end Construct a single BitVector variable with name "a" and length n. Note that unlike Bool, Int, and Real, one cannot construct an array of BitVectors. The length n may be any positive integer. """ -function BitVector(name::String, length::Int) +function BitVectorExpr(name::String, length::Int) global GLOBAL_VARNAMES global WARN_DUPLICATE_NAMES if name ∈ GLOBAL_VARNAMES[BitVectorExpr] @@ -29,7 +37,7 @@ function BitVector(name::String, length::Int) else push!(GLOBAL_VARNAMES[BitVectorExpr], name) end - return BitVectorExpr{nextsize(length)}(:identity, Array{AbstractExpr}[], nothing, "$name", length) + return BitVectorExpr{nextsize(length)}(:identity, AbstractExpr[], nothing, "$name", length) end # Constants, to match Julia conventions, may be specified in binary, hex, or octal. @@ -93,7 +101,8 @@ function __bv2op(e1::BitVectorExpr, e2::BitVectorExpr, op::Function, opname::Sym end end -function __bv1op(e::BitVectorExpr, op::Function, opname::Symbol) +function __bv1op(e::BitVectorExpr, op::Function, opname::Symbol, length=nothing) + length = isnothing(length) ? e.length : length value = nothing if !isnothing(e.value) valtype = typeof(e.value) @@ -101,7 +110,7 @@ function __bv1op(e::BitVectorExpr, op::Function, opname::Symbol) value = valtype(op(e.value) & mask) end name = __get_hash_name(opname, [e.name,]) - return BitVectorExpr{nextsize(e.length)}(opname, [e,], value, name, e.length) + return BitVectorExpr{nextsize(e.length)}(opname, [e,], value, name, length) end @@ -153,10 +162,10 @@ xnor(e1::BitVectorExpr, e2::BitVectorExpr) = __bv2op(e1, e2, (a,b) -> (a & b ¬(e::BitVectorExpr) = __bv1op(e, ~, :bvnot) ##### Bitwise predicates ##### ->(e1::BitVectorExpr, e2::BitVectorExpr) = __bv2op(e1, e2, >, :bvult) ->=(e1::BitVectorExpr, e2::BitVectorExpr) = __bv2op(e1, e2, >=, :bvule) -<(e1::BitVectorExpr, e2::BitVectorExpr) = __bv2op(e1, e2, >, :bvugt) -<=(e1::BitVectorExpr, e2::BitVectorExpr) = __bv2op(e1, e2, >=, :bvuge) +<(e1::BitVectorExpr, e2::BitVectorExpr) = __bv2op(e1, e2, >, :bvult) +<=(e1::BitVectorExpr, e2::BitVectorExpr) = __bv2op(e1, e2, >=, :bvule) +>(e1::BitVectorExpr, e2::BitVectorExpr) = __bv2op(e1, e2, >, :bvugt) +>=(e1::BitVectorExpr, e2::BitVectorExpr) = __bv2op(e1, e2, >=, :bvuge) # Signed comparisons are supported by Z3 but not part of the SMT-LIB standard. slt(e1::BitVectorExpr, e2::BitVectorExpr) = __bv2op(e1, e2, __signfix(>), :bvslt) @@ -168,7 +177,7 @@ sge(e1::BitVectorExpr, e2::BitVectorExpr) = __bv2op(e1, e2, __signfix(>=), ##### Word-level operations ##### # concat and extract are the only SMT-LIB standard operations # z3 adds some more -function cat(es::Array{T}) where T <: BitVectorExpr +function Base.cat(es::Vararg{T}) where T <: BitVectorExpr length = sum(getproperty.(es, :length)) valtype = nextsize(length) if any(isnothing.(getproperty.(es, :value))) @@ -181,25 +190,28 @@ function cat(es::Array{T}) where T <: BitVectorExpr acc += e.length end end - name = __get_hash_name(:concat, getproperty.(es, :name)) - return BitVectorExpr{nextsize(length)}(:concat, es, value, name, length) + name = __get_hash_name(:concat, collect(getproperty.(es, :name))) + return BitVectorExpr{nextsize(length)}(:concat, collect(es), value, name, length) end -getindex(e::BitVectorExpr, ind::UnitRange{Int64}) = getindex(e, first(ind), last(ind)) -getindex(e::BitVectorExpr, ind::Int64) = getindex(e, ind, ind) +Base.getindex(e::BitVectorExpr, ind::UnitRange{Int64}) = getindex(e, first(ind), last(ind)) +Base.getindex(e::BitVectorExpr, ind::Int64) = getindex(e, ind, ind) -function getindex(e::BitVectorExpr, ind_1::Int64, ind_2::Int64) +function Base.getindex(e::BitVectorExpr, ind_1::Int64, ind_2::Int64) if ind_1 > ind_2 || ind_1 < 1 || ind_2 > e.length - @error "Cannot extract sequence $ind_1 to $ind_2 from BitVector!" + error("Cannot extract sequence $ind_1 to $ind_2 from BitVector!") end - return __bv1op(e, identity, Symbol("(_ extract $ind_2 $ind_1)")) + return __bv1op(e, identity, :extract)#Symbol("(_ extract $ind_2 $ind_1)")) end ##### Translation to/from integer ##### # Be aware these have high overhead -bv2int(e::BitVectorExpr) = IntExpr(:bv2int, [e,], isnothing(e.value) ? nothing : Int(e.value), "int_$(e.name)") -int2bv(e::IntExpr, size::Int) = __bv1op(e, unsigned, Symbol("(_ int2bv $size)")) - +bv2int(e::BitVectorExpr) = IntExpr(:bv2int, [e,], isnothing(e.value) ? nothing : Int(e.value), "bv2int_$(e.name)") +function int2bv(e::IntExpr, size::Int) + name = "int2bv_$(e.name)" + expr = BitVectorExpr{nextsize(size)}(:int2bv, [e], isnothing(e.value) ? nothing : unsigned(e.value), name, size)#Symbol("(_ int2bv $size)")) + return expr +end ##### INTEROPERABILITY WITH CONSTANTS ##### # RULE diff --git a/src/BooleanSatisfiability.jl b/src/BooleanSatisfiability.jl index f0151ee..3133695 100644 --- a/src/BooleanSatisfiability.jl +++ b/src/BooleanSatisfiability.jl @@ -5,6 +5,7 @@ export AbstractExpr, IntExpr, @satvariable, RealExpr, + BitVectorExpr, isequal, hash, # required by isequal (?) in # specialize to use isequal instead of == @@ -18,12 +19,32 @@ export iff, ⟺, ite, value + export ==, <, <=, >, >= export +, -, *, / +# BitVector specific functions +export + nextsize, + bitcount, + div, + urem, + <<, + >>, + >>>, + srem, + smod, + nor, + nand, + xnor, + slt, sle, + sgt, sge, + cat, + bv2int, int2bv + export smt, save diff --git a/src/smt_macros.jl b/src/smt_macros.jl index 9d9dadf..f3c2dae 100644 --- a/src/smt_macros.jl +++ b/src/smt_macros.jl @@ -25,7 +25,7 @@ macro satvariable(expr, typename, arrsize=1) name = string(expr) # this line resolves to something like x = Bool("x") # special handling of parametric BitVector - if typename == :BitVector + if typename == :BitVectorExpr return esc(:($expr = $(typename)($(name),$(arrsize)))) else return esc(:($expr = $(typename)($name))) @@ -35,7 +35,7 @@ macro satvariable(expr, typename, arrsize=1) stem = expr.args[1] name = string(stem) iterable = expr.args[2] - if typename == :BitVector + if typename == :BitVectorExpr return esc(:($stem = [$(typename)("$(:($$name))_$(i)",$(arrsize)) for i in $iterable])) else return esc(:($stem = [$(typename)("$(:($$name))_$(i)") for i in $iterable])) @@ -44,7 +44,7 @@ macro satvariable(expr, typename, arrsize=1) stem = expr.args[1] name = string(stem) iterable1, iterable2 = expr.args[2], expr.args[3] - if typename == :BitVector + if typename == :BitVectorExpr return esc(:($stem = [$(typename)("$(:($$name))_$(i)_$(j)",$(arrsize)) for i in $iterable1, j in $iterable2])) else return esc(:($stem = [$(typename)("$(:($$name))_$(i)_$(j)") for i in $iterable1, j in $iterable2])) diff --git a/test/bitvector_tests.jl b/test/bitvector_tests.jl new file mode 100644 index 0000000..4e0243c --- /dev/null +++ b/test/bitvector_tests.jl @@ -0,0 +1,46 @@ +using BooleanSatisfiability +using Test + +@testset "Construct variables and exprs" begin + # a few basics + @test nextsize(16) == UInt16 + @test nextsize(17) == UInt32 + @test nextsize(15) == UInt16 + @test bitcount(0x01) == 1 + @test bitcount(0b10010) == 5 + + @satvariable(a, BitVector, 16) + @satvariable(b, BitVector, 16) + @satvariable(c, BitVector, 12) + @satvariable(d, BitVector, 4) + + # unary minus + @test (-d).op == :bvneg + # combining ops + ops = [+, -, *, div, urem, <<, >>, srem, smod, >>>, nor, nand, xnor] + names = [:bvadd, :bvsub, :bvmul, :bvudiv, :bvurem, :bvshl, :bvlshr, :bvsrem, :bvsmod, :bvashr, :bvnor, :bvnand, :bvxnor] + for (op, name) in zip(ops, names) + @test isequal(op(a,b), BitVectorExpr{UInt16}(name, [a,b], nothing, BooleanSatisfiability.__get_hash_name(name, [a,b]), 16)) + end + + # logical ops + ops = [<, <=, >, >=, ==, slt, sle, sgt, sge] + names = [:bvult, :bvule, :bvugt, :bvuge, :eq, :bvslt, :bvsle, :bvsgt, :bvsge] + for (op, name) in zip(ops, names) + @test isequal(op(a,b), BoolExpr(name, [a,b], nothing, BooleanSatisfiability.__get_hash_name(name, [a,b]))) + end + + # concat + @test cat(c, d).length == 16 + @test (cat(c, d) + a).length == 16 + + # indexing + @test a[2:4].op == :extract + @test_throws ErrorException a[0:2] + @test_throws ErrorException a[15:30] + + # bv2int and int2bv + @test isequal(bv2int(a), IntExpr(:bv2int, [a], nothing, "bv2int_a")) + @satvariable(e, Int) + @test isequal(int2bv(e, 32), BitVectorExpr{UInt32}(:int2bv, [e], nothing, "int2bv_e", 32)) +end \ No newline at end of file From 0cb4a22944899c69185fc304f2687041c94210ba Mon Sep 17 00:00:00 2001 From: Emiko Soroka Date: Sat, 12 Aug 2023 19:20:06 -0700 Subject: [PATCH 22/36] fixed the cat issue by calling the function concat. All BitVector tests pass. Need to add interoperability with constants and a few special cases for SMT code generation. .# --- src/BitVectorExpr.jl | 7 +++++-- src/BooleanSatisfiability.jl | 2 +- test/bitvector_tests.jl | 4 ++-- 3 files changed, 8 insertions(+), 5 deletions(-) diff --git a/src/BitVectorExpr.jl b/src/BitVectorExpr.jl index 84b49f7..ec50de7 100644 --- a/src/BitVectorExpr.jl +++ b/src/BitVectorExpr.jl @@ -1,4 +1,4 @@ -import Base.BitVector, Base.length, Base.cat, Base.getindex +import Base.getindex import Base.+, Base.-, Base.*, Base.<<, Base.>>, Base.>>>, Base.div import Base.>, Base.>=, Base.<, Base.<= # >>> is arithmetic shift right, corresponding to bvashr in SMT-LIB @@ -177,7 +177,10 @@ sge(e1::BitVectorExpr, e2::BitVectorExpr) = __bv2op(e1, e2, __signfix(>=), ##### Word-level operations ##### # concat and extract are the only SMT-LIB standard operations # z3 adds some more -function Base.cat(es::Vararg{T}) where T <: BitVectorExpr +function concat(es::Vararg{Any}) + if !all(isa.(es, BitVector)) + @error("Only BitVectors can be concatenated!") + end length = sum(getproperty.(es, :length)) valtype = nextsize(length) if any(isnothing.(getproperty.(es, :value))) diff --git a/src/BooleanSatisfiability.jl b/src/BooleanSatisfiability.jl index 3133695..d976389 100644 --- a/src/BooleanSatisfiability.jl +++ b/src/BooleanSatisfiability.jl @@ -42,7 +42,7 @@ export xnor, slt, sle, sgt, sge, - cat, + concat, bv2int, int2bv export smt, diff --git a/test/bitvector_tests.jl b/test/bitvector_tests.jl index 4e0243c..b564c7b 100644 --- a/test/bitvector_tests.jl +++ b/test/bitvector_tests.jl @@ -31,8 +31,8 @@ using Test end # concat - @test cat(c, d).length == 16 - @test (cat(c, d) + a).length == 16 + @test concat(c, d).length == 16 + @test (concat(c, d) + a).length == 16 # indexing @test a[2:4].op == :extract From 15df2ef9ac165981356fac1f68216d7e0db86527 Mon Sep 17 00:00:00 2001 From: Emiko Soroka Date: Sun, 13 Aug 2023 00:25:18 -0700 Subject: [PATCH 23/36] worked on unifying how operators are constructed, and used this work to finish implementing construction of n-ary ops for BitVector. ALL TESTS PASS. --- src/BitVectorExpr.jl | 143 +++++++++++++++++++++++++---------- src/BooleanOperations.jl | 27 ++++--- src/BooleanSatisfiability.jl | 1 + src/IntExpr.jl | 16 ++-- src/multiple_dispatch_ops.jl | 17 +++++ src/utilities.jl | 18 +++-- test/bitvector_tests.jl | 12 ++- test/runtests.jl | 2 + 8 files changed, 166 insertions(+), 70 deletions(-) create mode 100644 src/multiple_dispatch_ops.jl diff --git a/src/BitVectorExpr.jl b/src/BitVectorExpr.jl index ec50de7..3a2ec99 100644 --- a/src/BitVectorExpr.jl +++ b/src/BitVectorExpr.jl @@ -70,7 +70,8 @@ function bitcount(a::Integer) # works on BigInt and UInt if sign(a) == -1 @error("Constants must be unsigned or positive BigInts!") end - return findlast((x) -> x != 0, a .>> collect(0:8*sizeof(a))) + result = findlast((x) -> x != 0, a .>> collect(0:8*sizeof(a))) + return !isnothing(result) ? result : 0 end function hexstr(a::Integer) @@ -81,23 +82,24 @@ function hexstr(a::Integer) end -function __bv2op(e1::BitVectorExpr, e2::BitVectorExpr, op::Function, opname::Symbol) - if e1.length != e2.length - @error "BitVectors have mismatched lengths $(e1.length) and $(e2.length)." - end +function __bvnop(op::Function, opname::Symbol, ReturnType::Type, es::Vararg{T}; __is_commutative=false, __try_flatten=false) where T <: BitVectorExpr # This expression comes about because while SMT-LIB supports any length bit vector, # we store the value in Julia as a standard size. So you have to mask any extra bits away. + es = collect(es) value = nothing - if !isnothing(e1.value) && !isnothing(e2.value) - valtype = typeof(e1.value) + values = getproperty.(es, :value) + if all(.!(isnothing.(values))) + # We are guaranteed es all have the same type by our type signature + valtype = typeof(es[1].value) mask = typemax(valtype) >> (8*sizeof(valtype) - e1.length) - value = valtype(op(e1.value, e2.value) & mask) + value = valtype(op(values...) & mask) end - name = __get_hash_name(opname, [e1.name, e2.name]) - if opname in [:bvule, :bvult, :bvuge, :bvugt, :bvsle, :bvslt, :bvsgt, :bvsge] - return BoolExpr(opname, [e1, e2], value, name) - else - return BitVectorExpr{nextsize(e1.length)}(opname, [e1, e2], value, name, e1.length) + + children, name = __combine(es, opname, __is_commutative, __try_flatten) + if ReturnType <: BitVectorExpr + return ReturnType{nextsize(es[1].length)}(opname, children, value, name, es[1].length, __is_commutative=__is_commutative) + else # it must be a BoolExpr or IntExpr + return ReturnType(opname, children, value, name) end end @@ -116,10 +118,10 @@ end ##### Integer arithmetic ##### -+(e1::BitVectorExpr, e2::BitVectorExpr) = __bv2op(e1, e2, +, :bvadd) --(e1::BitVectorExpr, e2::BitVectorExpr) = __bv2op(e1, e2, -, :bvsub) -*(e1::BitVectorExpr, e2::BitVectorExpr) = __bv2op(e1, e2, *, :bvmul) -div(e1::BitVectorExpr, e2::BitVectorExpr) = __bv2op(e1, e2, div, :bvudiv) ++(e1::BitVectorExpr, e2::BitVectorExpr) = __bvnop(+, :bvadd, BitVectorExpr, e1, e2, __is_commutative=true, __try_flatten=true) +-(e1::BitVectorExpr, e2::BitVectorExpr) = __bvnop(-, :bvsub, BitVectorExpr, e1, e2) +*(e1::BitVectorExpr, e2::BitVectorExpr) = __bvnop(*, :bvmul, BitVectorExpr, e1, e2,__is_commutative=true, __try_flatten=true) +div(e1::BitVectorExpr, e2::BitVectorExpr) = __bvnop(div, :bvudiv, BitVectorExpr, e1, e2) # unary minus -(e::BitVectorExpr) = __bv1op(e, -, :bvneg) @@ -137,24 +139,62 @@ div(e1::BitVectorExpr, e2::BitVectorExpr) = __bv2op(e1, e2, div, :bvudiv) # Yikes! A function that returns a function. __signfix(f::Function) = (a, b) -> unsigned(f(signed(a), signed(b))) -urem(e1::BitVectorExpr, e2::BitVectorExpr) = __bv2op(e1, e2, rem, :bvurem) -<<(e1::BitVectorExpr, e2::BitVectorExpr) = __bv2op(e1, e2, <<, :bvshl) # shift left ->>(e1::BitVectorExpr, e2::BitVectorExpr) = __bv2op(e1, e2, >>>, :bvlshr) # logical shift right +# these all have arity 2 +urem(e1::BitVectorExpr, e2::BitVectorExpr) = __bvnop(rem, :bvurem, BitVectorExpr, e1, e2) +<<(e1::BitVectorExpr, e2::BitVectorExpr) = __bvnop(<<, :bvshl, BitVectorExpr, e1, e2) # shift left +>>(e1::BitVectorExpr, e2::BitVectorExpr) = __bvnop(>>>, :bvlshr, BitVectorExpr, e1, e2) # logical shift right # Extra arithmetic operators supported by Z3 but not part of the SMT-LIB standard. -srem(e1::BitVectorExpr, e2::BitVectorExpr) = __bv2op(e1, e2, __signfix(rem), :bvsrem) # unique to z3 -smod(e1::BitVectorExpr, e2::BitVectorExpr) = __bv2op(e1, e2, __signfix(mod), :bvsmod) # unique to z3 ->>>(e1::BitVectorExpr, e2::BitVectorExpr) = __bv2op(e1, e2, __signfix(>>), :bvashr) # arithmetic shift right - unique to Z3 +srem(e1::BitVectorExpr, e2::BitVectorExpr) = __bvnop(__signfix(rem), :bvsrem, BitVectorExpr, e1, e2) # unique to z3 +smod(e1::BitVectorExpr, e2::BitVectorExpr) = __bvnop(__signfix(mod), :bvsmod, BitVectorExpr, e1, e2) # unique to z3 +>>>(e1::BitVectorExpr, e2::BitVectorExpr) = __bvnop(__signfix(>>), :bvashr, BitVectorExpr, e1, e2) # arithmetic shift right - unique to Z3 + + +##### Bitwise logical operations (arity n>=2) ##### +function or(es::Array{T}, consts=Integer[]) where T <: BitVectorExpr + if length(consts)>0 + push!(es, __wrap_bitvector_const(reduce(|, consts), es[1].length)) + end + expr = __bvnop((a,b) -> a | b, :bvor, BitVectorExpr, es..., __is_commutative=true, __try_flatten=true) + return expr +end + +or(zs::Vararg{Union{T, Integer}}) where T <: BitVectorExpr = or(collect(zs)) +# We need this declaration to enable the syntax and.([z1, z2,...,zn]) where z1, z2,...,zn are broadcast-compatible + +function and(es::Array{T}, consts=Integer[]) where T <: BitVectorExpr + if length(consts)>0 + push!(es, __wrap_bitvector_const(reduce(&, consts), es[1].length)) + end + expr = __bvnop((a,b) -> a & b, :bvand, BitVectorExpr, es..., __is_commutative=true, __try_flatten=true) + return expr +end +and(zs::Vararg{Union{T, Integer}}) where T <: BitVectorExpr = and(collect(zs)) +# We need this declaration to enable the syntax and.([z1, z2,...,zn]) where z1, z2,...,zn are broadcast-compatible -##### Bitwise logical operations ##### -∨(e1::BitVectorExpr, e2::BitVectorExpr) = __bv2op(e1, e2, (a,b) -> a | b, :bvor) -∧(e1::BitVectorExpr, e2::BitVectorExpr) = __bv2op(e1, e2, (a,b) -> a & b, :bvand) +∨(e1::BitVectorExpr, e2::BitVectorExpr) = or([e1, e2]) +∧(e1::BitVectorExpr, e2::BitVectorExpr) = and([e1, e2]) # Extra logical operators supported by Z3 but not part of the SMT-LIB standard. -nor(e1::BitVectorExpr, e2::BitVectorExpr) = __bv2op(e1, e2, (a,b) -> ~(a | b), :bvnor) -nand(e1::BitVectorExpr, e2::BitVectorExpr) = __bv2op(e1, e2, (a,b) -> ~(a & b), :bvnand) -xnor(e1::BitVectorExpr, e2::BitVectorExpr) = __bv2op(e1, e2, (a,b) -> (a & b) | (~a & ~b), :bvxnor) +nor(e1::BitVectorExpr, e2::BitVectorExpr) = __bvnop((a,b) -> ~(a | b), :bvnor, BitVectorExpr, e1, e2, __is_commutative=true) +nand(e1::BitVectorExpr, e2::BitVectorExpr) = __bvnop((a,b) -> ~(a & b), :bvnand, BitVectorExpr, e1, e2, __is_commutative=true) + +# TODO Probably all the "extra" operators should behave like this for constants +xnor(a::T,b::T) where T <: Integer = (a & b) | (~a & ~b) + +function xnor(es_mixed::Array{T}) where T + es, literals = __check_inputs_nary_op(es_mixed, const_type=Integer, expr_type=BitVectorExpr) + if length(literals)>0 + push!(es, __wrap_bitvector_const(reduce(xnor, literals), es[1].length)) + end + expr = __bvnop(xnor, :bvxnor, BitVectorExpr, es...) + return expr +end + +xnor(zs::Vararg{Union{T, Integer}}) where T <: BitVectorExpr = xnor(collect(zs)) +# We need this declaration to enable the syntax and.([z1, z2,...,zn]) where z1, z2,...,zn are broadcast-compatible + # TODO operations with arity n # note that bvxnor is left-accumulating, so bvxnor(a, b, c) = bvxnor(bvxnor(a, b), c) # bvnor and bvnand have arity 2 @@ -162,23 +202,23 @@ xnor(e1::BitVectorExpr, e2::BitVectorExpr) = __bv2op(e1, e2, (a,b) -> (a & b ¬(e::BitVectorExpr) = __bv1op(e, ~, :bvnot) ##### Bitwise predicates ##### -<(e1::BitVectorExpr, e2::BitVectorExpr) = __bv2op(e1, e2, >, :bvult) -<=(e1::BitVectorExpr, e2::BitVectorExpr) = __bv2op(e1, e2, >=, :bvule) ->(e1::BitVectorExpr, e2::BitVectorExpr) = __bv2op(e1, e2, >, :bvugt) ->=(e1::BitVectorExpr, e2::BitVectorExpr) = __bv2op(e1, e2, >=, :bvuge) +<(e1::BitVectorExpr, e2::BitVectorExpr) = __bvnop(>, :bvult, BoolExpr, e1, e2) +<=(e1::BitVectorExpr, e2::BitVectorExpr) = __bvnop(>=, :bvule, BoolExpr, e1, e2) +>(e1::BitVectorExpr, e2::BitVectorExpr) = __bvnop(>, :bvugt, BoolExpr, e1, e2) +>=(e1::BitVectorExpr, e2::BitVectorExpr) = __bvnop(>=, :bvuge, BoolExpr, e1, e2) # Signed comparisons are supported by Z3 but not part of the SMT-LIB standard. -slt(e1::BitVectorExpr, e2::BitVectorExpr) = __bv2op(e1, e2, __signfix(>), :bvslt) -sle(e1::BitVectorExpr, e2::BitVectorExpr) = __bv2op(e1, e2, __signfix(>=), :bvsle) -sgt(e1::BitVectorExpr, e2::BitVectorExpr) = __bv2op(e1, e2, __signfix(>), :bvsgt) -sge(e1::BitVectorExpr, e2::BitVectorExpr) = __bv2op(e1, e2, __signfix(>=), :bvsge) +slt(e1::BitVectorExpr, e2::BitVectorExpr) = __bvnop(__signfix(>), :bvslt, BoolExpr, e1, e2) +sle(e1::BitVectorExpr, e2::BitVectorExpr) = __bvnop(__signfix(>=), :bvsle, BoolExpr, e1, e2) +sgt(e1::BitVectorExpr, e2::BitVectorExpr) = __bvnop(__signfix(>), :bvsgt, BoolExpr, e1, e2) +sge(e1::BitVectorExpr, e2::BitVectorExpr) = __bvnop(__signfix(>=), :bvsge, BoolExpr, e1, e2) ##### Word-level operations ##### # concat and extract are the only SMT-LIB standard operations -# z3 adds some more +# z3 adds some more, note that concat can accept constants and has arity n >= 2 function concat(es::Vararg{Any}) - if !all(isa.(es, BitVector)) + if !all(isa.(es, BitVectorExpr)) @error("Only BitVectors can be concatenated!") end length = sum(getproperty.(es, :length)) @@ -221,4 +261,27 @@ end # Given a variable with sort (_ BitVec n) and a const with sort (_ BitVec m) # as long as m ≤ n any operation with the same size output is valid # Short constants will be padded with zeros because this matches Julia's behavior. -# eg any operation except concat \ No newline at end of file +# eg any operation except concat + +# size must be the SMT-LIB bitvector length, for example if you have a bitvector of length 12 pass in 12 NOT 16 +# this function returns c of the correct Unsigned type to interoperate with the bitvector.value +# which is the smallest Unsigned type that fits the SMT-LIB bitvector length. +function __wrap_bitvector_const(c::Union{Unsigned, BigInt}, size::Int) + minsize = bitcount(c) + # nextsize(size) returns the correct Unsigned type + ReturnType = nextsize(size) + if minsize > size + error("BitVector of size $size cannot be combined with constant of size $minisize") + elseif minsize == size + return BitVectorExpr{ReturnType}(:const, AbstractExpr[], c, "const_$c", size) + else # it's smaller and we need to pad it + return BitVectorExpr{ReturnType}(:const, AbstractExpr[], ReturnType(c), "const_$c", size) + end +end + +__2ops = [:+, :-, :*, :/, :<, :<=, :>, :>=, :sle, :slt, :sge, :sgt, :nand, :nor, :<<, :>>, :>>>, :srem, :urem, :smod] + +for op in __2ops + @eval $op(a::Union{Unsigned, BigInt}, b::BitVectorExpr) = $op(__wrap_bitvector_const(a, b.length), b) + @eval $op(a::BitVectorExpr, b::Union{Unsigned, BigInt}) = $op(a, __wrap_bitvector_const(b, a.length)) +end diff --git a/src/BooleanOperations.jl b/src/BooleanOperations.jl index 8a6d394..666aea9 100644 --- a/src/BooleanOperations.jl +++ b/src/BooleanOperations.jl @@ -50,12 +50,16 @@ end # combine children for Boolean n-ary ops function __bool_nary_op(zs::Array{T}, op::Symbol, ReturnType::Type, __is_commutative=false, __try_flatten=false) where T <: BoolExpr - expr = __combine(zs, op, ReturnType, __is_commutative, __try_flatten) - if __is_commutative && length(expr.children)>0 # clear duplicates - expr.children = unique(expr.children) - expr.name = __get_hash_name(expr.op, expr.children) + if length(zs) == 1 + return zs[1] end - return expr + children, name = __combine(zs, op, __is_commutative, __try_flatten) + if __is_commutative && length(children)>1 # clear duplicates + children = unique(children) + name = __get_hash_name(op, children) + end + # TODO here we should compute the value + return ReturnType(op, children, nothing, name, __is_commutative=__is_commutative) end @@ -85,10 +89,7 @@ not(zs::Array{T}) where T <: BoolExpr = map(not, zs) ∨(z1::BoolExpr, z2::BoolExpr) = or([z1, z2]) -function and(zs_mixed::Array{T}; broadcast_type=:Elementwise) where T - - zs, literals = __check_inputs_nary_op(zs_mixed, expr_type=BoolExpr) - +function and(zs::Array{T}, literals=Bool[]) where T <: BoolExpr if length(literals) > 0 if !all(literals) # if any literal is 0 return false @@ -123,12 +124,10 @@ Special cases: * `and(z, false)` returns `false`. * `and(z, true)` returns `z`. """ -and(zs::Vararg{Union{T, Bool}}; broadcast_type=:Elementwise) where T <: AbstractExpr = and(collect(zs)) +and(zs::Vararg{Union{T, Bool}}) where T <: BoolExpr = and(collect(zs)) # We need this declaration to enable the syntax and.([z1, z2,...,zn]) where z1, z2,...,zn are broadcast-compatible -function or(zs_mixed::Array{T}; broadcast_type=:Elementwise) where T - zs, literals = __check_inputs_nary_op(zs_mixed, expr_type=BoolExpr) - +function or(zs::Array{T}, literals=Bool[]) where T <: BoolExpr if length(literals) > 0 if any(literals) # if any literal is 1 return true @@ -164,7 +163,7 @@ Special cases: **Note that ∨ (`\\vee`) is NOT the ASCII character v.** """ -or(zs::Vararg{Union{T, Bool}}; broadcast_type=:Elementwise) where T <: AbstractExpr = or(collect(zs)) +or(zs::Vararg{Union{T, Bool}}) where T <: BoolExpr = or(collect(zs)) # We need this declaration to enable the syntax or.([z1, z2,...,zn]) where z1, z2,...,z are broadcast-compatible ##### ADDITIONAL OPERATORS IN THE SMT BOOL CORE SPEC ##### diff --git a/src/BooleanSatisfiability.jl b/src/BooleanSatisfiability.jl index d976389..780d7d5 100644 --- a/src/BooleanSatisfiability.jl +++ b/src/BooleanSatisfiability.jl @@ -80,6 +80,7 @@ include("BitVectorExpr.jl") # include @satvariable later because we need some functions from BitVector to declare that type include("smt_macros.jl") +include("multiple_dispatch_ops.jl") __EXPR_TYPES = [BoolExpr, RealExpr, IntExpr, BitVectorExpr] diff --git a/src/IntExpr.jl b/src/IntExpr.jl index 574fc01..d382e4c 100644 --- a/src/IntExpr.jl +++ b/src/IntExpr.jl @@ -256,17 +256,17 @@ function __numeric_n_ary_op(es_mixed::Array, op::Symbol; __is_commutative=false, # Determine return expr type. Note that / promotes to RealExpr because the SMT theory of integers doesn't include it ReturnType = any(isa.(es, RealExpr)) || op == :div ? RealExpr : IntExpr - expr = __combine(es, op, ReturnType, __is_commutative, __try_flatten) + children, name = __combine(es, op, __is_commutative, __try_flatten) # Now it is possible we have several CONST exprs. This occurs if, for example, one writes (a+1) + (b+1) which flattens to a+1+b+1 # TO clean up, we should merge the CONST exprs if __is_commutative - __merge_const!(expr.children) - expr.name = __get_hash_name(expr.op, expr.children) + __merge_const!(children) + name = __get_hash_name(op, children) end - - expr.value = any(isnothing.(getproperty.(es, :value))) ? nothing : sum(getproperty.(es, :value)) - return expr + # TODO should call a function indexed by op + value = any(isnothing.(getproperty.(es, :value))) ? nothing : sum(getproperty.(es, :value)) + return ReturnType(op, children, value, name, __is_commutative=__is_commutative) end @@ -299,7 +299,7 @@ println("typeof a+z: \$(typeof(a[1] + z))") """ Base.:+(e1::Union{NumericInteroperableExpr}, e2::NumericInteroperableExpr) = __numeric_n_ary_op([e1, e2], :add, __is_commutative=true, __try_flatten=true) Base.:+(e1::Union{NumericInteroperableExpr}, e2::NumericInteroperableConst) = __numeric_n_ary_op([e1, e2], :add, __is_commutative=true, __try_flatten=true) -Base.:+(e1::Union{NumericInteroperableConst}, e2::NumericInteroperableExpr) = e2 + e1 +Base.:+(e1::Union{NumericInteroperableConst}, e2::NumericInteroperableExpr) = __numeric_n_ary_op([e1, e2], :add, __is_commutative=true, __try_flatten=true) """ a - b @@ -347,7 +347,7 @@ println("typeof a*z: \$(typeof(a[1]*z))") """ Base.:*(e1::Union{NumericInteroperableExpr}, e2::NumericInteroperableExpr) = __numeric_n_ary_op([e1, e2], :mul, __is_commutative=true, __try_flatten=true) Base.:*(e1::Union{NumericInteroperableExpr}, e2::NumericInteroperableConst) = __numeric_n_ary_op([e1, e2], :mul, __is_commutative=true, __try_flatten=true) -Base.:*(e1::Union{NumericInteroperableConst}, e2::NumericInteroperableExpr) = e2 * e1 +Base.:*(e1::Union{NumericInteroperableConst}, e2::NumericInteroperableExpr) = __numeric_n_ary_op([e1, e2], :mul, __is_commutative=true, __try_flatten=true) """ a / b diff --git a/src/multiple_dispatch_ops.jl b/src/multiple_dispatch_ops.jl new file mode 100644 index 0000000..20e905a --- /dev/null +++ b/src/multiple_dispatch_ops.jl @@ -0,0 +1,17 @@ +# This allows and() to be used in multiple theories +# in a context-dependent manner + +and(es_mixed::Array{T}) where T = __multidispatch_op(and, es_mixed) +or(es_mixed::Array{T}) where T = __multidispatch_op(or, es_mixed) + +function __multidispatch_op(op::Function, es_mixed::Array{T}) where T + zs, literals = __check_inputs_nary_op(es_mixed, const_type=Bool, expr_type=BoolExpr) + if !isnothing(zs) # successfully found the type + return op(zs, literals) + end + zs, literals = __check_inputs_nary_op(es_mixed, const_type=Integer, expr_type=BitVectorExpr) + if !isnothing(zs) + return op(zs, literals) + end + @error("Unable to operate on mixed type inputs $es_mixed") +end \ No newline at end of file diff --git a/src/utilities.jl b/src/utilities.jl index 9863e77..9a9e493 100644 --- a/src/utilities.jl +++ b/src/utilities.jl @@ -15,7 +15,7 @@ end function __check_inputs_nary_op(zs_mixed::Array{T}; const_type=Bool, expr_type=AbstractExpr) where T # Check for wrong type inputs if any((z) -> !(isa(z, const_type) || isa(z, expr_type)), zs_mixed) - error("Unrecognized type in list") + return nothing, nothing end # separate literals and const_type literals = filter((z) -> isa(z, const_type), zs_mixed) @@ -23,12 +23,16 @@ function __check_inputs_nary_op(zs_mixed::Array{T}; const_type=Bool, expr_type=A return zs, literals end - -function __combine(zs::Array{T}, op::Symbol, ReturnType::Type, __is_commutative=false, __try_flatten=false) where T <: AbstractExpr +# this is a very generic function to combine children of operands in any theory +function __combine(zs::Array{T}, op::Symbol, __is_commutative=false, __try_flatten=false) where T <: AbstractExpr if length(zs) == 0 error("Cannot iterate over zero-length array.") elseif length(zs) == 1 - return zs[1] + if __try_flatten && zs[1].op == op + return zs[1].children, zs[1].name + else + return zs[1:1], zs[1].name + end end # Now we need to take an array of statements and decide how to combine them @@ -46,13 +50,13 @@ function __combine(zs::Array{T}, op::Symbol, ReturnType::Type, __is_commutative= children = sort(children, by=(c) -> c.name) end name = __get_hash_name(op, children) - - return ReturnType(op, children, nothing, name, __is_commutative=__is_commutative) + + return children, name end "combine(z, op) where z is an n x m matrix of BoolExprs first flattens z, then combines it with op. combine([z1 z2; z3 z4], or) = or([z1; z2; z3; z4])." -__combine(zs::Matrix{T}, op::Symbol, ReturnType::Type, __is_commutative=false, __try_flatten=false) where T <: BoolExpr = __combine(flatten(zs), op, ReturnType, __is_commutative, __try_flatten) +__combine(zs::Matrix{T}, op::Symbol, __is_commutative=false, __try_flatten=false) where T <: AbstractExpr = __combine(flatten(zs), op, __is_commutative, __try_flatten) "is_permutation(a::Array, b::Array) returns True if a is a permutation of b. diff --git a/test/bitvector_tests.jl b/test/bitvector_tests.jl index b564c7b..90c5092 100644 --- a/test/bitvector_tests.jl +++ b/test/bitvector_tests.jl @@ -1,7 +1,7 @@ using BooleanSatisfiability using Test -@testset "Construct variables and exprs" begin +@testset "Construct BitVector variables and exprs" begin # a few basics @test nextsize(16) == UInt16 @test nextsize(17) == UInt32 @@ -23,6 +23,16 @@ using Test @test isequal(op(a,b), BitVectorExpr{UInt16}(name, [a,b], nothing, BooleanSatisfiability.__get_hash_name(name, [a,b]), 16)) end + # n-ary ops + @satvariable(e, BitVector, 16) + ops = [+, *, and, or] + names = [:bvadd, :bvmul, :bvand, :bvor] + ct = BooleanSatisfiability.__wrap_bitvector_const(0x00ff, 16) + for (op, name) in zip(ops, names) + @test isequal(op(a,b,0x00ff,e), BitVectorExpr{UInt16}(name, [a,b,ct, e], nothing, BooleanSatisfiability.__get_hash_name(name, [a,b,ct,e]), 16)) + end + @test isequal(xnor(a,b,0x00ff,e), BitVectorExpr{UInt16}(:bvxnor, [a,b,e,ct], nothing, BooleanSatisfiability.__get_hash_name(:bvxnor, [a,b,e,ct]), 16)) + # logical ops ops = [<, <=, >, >=, ==, slt, sle, sgt, sge] names = [:bvult, :bvule, :bvugt, :bvuge, :eq, :bvslt, :bvsle, :bvsgt, :bvsge] diff --git a/test/runtests.jl b/test/runtests.jl index d2020b2..8eab829 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -19,6 +19,8 @@ include("solver_interface_tests.jl") # Test with int and real problems include("int_parse_tests.jl") +include("bitvector_tests.jl") + # Extra: Check that defining duplicate variables yields a warning @testset "Duplicate variable warning" begin SET_DUPLICATE_NAME_WARNING!(true) From 305aa63c05f5b32c992886f8924630d4b8bede16 Mon Sep 17 00:00:00 2001 From: Emiko Soroka Date: Sun, 13 Aug 2023 14:25:47 -0700 Subject: [PATCH 24/36] fixed BitVector extract (array slicing) --- src/BitVectorExpr.jl | 122 ++++++++++++++++++++++++---------------- test/bitvector_tests.jl | 2 +- 2 files changed, 75 insertions(+), 49 deletions(-) diff --git a/src/BitVectorExpr.jl b/src/BitVectorExpr.jl index 3a2ec99..2df6adf 100644 --- a/src/BitVectorExpr.jl +++ b/src/BitVectorExpr.jl @@ -7,7 +7,11 @@ import Base.>, Base.>=, Base.<, Base.<= # where operators exist (or, and, not, xor) # Base.rem and Base.% both implement the remainder in integer division. -mutable struct BitVectorExpr{T<:Integer} <: AbstractExpr +# This design decision supports subclasses of AbstractBitVectorExpr +# which is used to represent SMT-LIB extract (indexing) of BitVectors +abstract type AbstractBitVectorExpr <: AbstractExpr end + +mutable struct BitVectorExpr{T<:Integer} <: AbstractBitVectorExpr op :: Symbol children :: Array{AbstractExpr} value :: Union{T, Nothing, Missing} @@ -23,6 +27,16 @@ mutable struct BitVectorExpr{T<:Integer} <: AbstractExpr __is_commutative = false) where T <: Integer where C <: AbstractExpr = new(op, children, value, name, length, __is_commutative) end +mutable struct SlicedBitVectorExpr{T<:Integer} <: AbstractBitVectorExpr + op :: Symbol + children :: Array{AbstractExpr} + value :: Union{T, Nothing, Missing} + name :: String + length :: Int + __is_commutative :: Bool # this doesn't mean anything here and is always false + range :: Union{UnitRange{I}, I} where I <: Integer +end + """ BitVector("a", n) @@ -82,10 +96,9 @@ function hexstr(a::Integer) end -function __bvnop(op::Function, opname::Symbol, ReturnType::Type, es::Vararg{T}; __is_commutative=false, __try_flatten=false) where T <: BitVectorExpr +function __bvnop(op::Function, opname::Symbol, ReturnType::Type, es::Array{T}; __is_commutative=false, __try_flatten=false) where T <: AbstractBitVectorExpr # This expression comes about because while SMT-LIB supports any length bit vector, # we store the value in Julia as a standard size. So you have to mask any extra bits away. - es = collect(es) value = nothing values = getproperty.(es, :value) if all(.!(isnothing.(values))) @@ -96,14 +109,14 @@ function __bvnop(op::Function, opname::Symbol, ReturnType::Type, es::Vararg{T}; end children, name = __combine(es, opname, __is_commutative, __try_flatten) - if ReturnType <: BitVectorExpr + if ReturnType <: AbstractBitVectorExpr return ReturnType{nextsize(es[1].length)}(opname, children, value, name, es[1].length, __is_commutative=__is_commutative) else # it must be a BoolExpr or IntExpr return ReturnType(opname, children, value, name) end end -function __bv1op(e::BitVectorExpr, op::Function, opname::Symbol, length=nothing) +function __bv1op(e::AbstractBitVectorExpr, op::Function, opname::Symbol, length=nothing) length = isnothing(length) ? e.length : length value = nothing if !isnothing(e.value) @@ -118,10 +131,10 @@ end ##### Integer arithmetic ##### -+(e1::BitVectorExpr, e2::BitVectorExpr) = __bvnop(+, :bvadd, BitVectorExpr, e1, e2, __is_commutative=true, __try_flatten=true) --(e1::BitVectorExpr, e2::BitVectorExpr) = __bvnop(-, :bvsub, BitVectorExpr, e1, e2) -*(e1::BitVectorExpr, e2::BitVectorExpr) = __bvnop(*, :bvmul, BitVectorExpr, e1, e2,__is_commutative=true, __try_flatten=true) -div(e1::BitVectorExpr, e2::BitVectorExpr) = __bvnop(div, :bvudiv, BitVectorExpr, e1, e2) ++(e1::AbstractBitVectorExpr, e2::AbstractBitVectorExpr) = __bvnop(+, :bvadd, BitVectorExpr, [e1, e2], __is_commutative=true, __try_flatten=true) +-(e1::AbstractBitVectorExpr, e2::AbstractBitVectorExpr) = __bvnop(-, :bvsub, BitVectorExpr, [e1, e2]) +*(e1::AbstractBitVectorExpr, e2::AbstractBitVectorExpr) = __bvnop(*, :bvmul, BitVectorExpr, [e1, e2],__is_commutative=true, __try_flatten=true) +div(e1::AbstractBitVectorExpr, e2::AbstractBitVectorExpr) = __bvnop(div, :bvudiv, BitVectorExpr, [e1, e2]) # unary minus -(e::BitVectorExpr) = __bv1op(e, -, :bvneg) @@ -140,45 +153,45 @@ div(e1::BitVectorExpr, e2::BitVectorExpr) = __bvnop(div, :bvudiv, BitVectorExpr, __signfix(f::Function) = (a, b) -> unsigned(f(signed(a), signed(b))) # these all have arity 2 -urem(e1::BitVectorExpr, e2::BitVectorExpr) = __bvnop(rem, :bvurem, BitVectorExpr, e1, e2) -<<(e1::BitVectorExpr, e2::BitVectorExpr) = __bvnop(<<, :bvshl, BitVectorExpr, e1, e2) # shift left ->>(e1::BitVectorExpr, e2::BitVectorExpr) = __bvnop(>>>, :bvlshr, BitVectorExpr, e1, e2) # logical shift right +urem(e1::AbstractBitVectorExpr, e2::AbstractBitVectorExpr) = __bvnop(rem, :bvurem, BitVectorExpr, [e1, e2]) +<<(e1::AbstractBitVectorExpr, e2::AbstractBitVectorExpr) = __bvnop(<<, :bvshl, BitVectorExpr, [e1, e2]) # shift left +>>(e1::AbstractBitVectorExpr, e2::AbstractBitVectorExpr) = __bvnop(>>>, :bvlshr, BitVectorExpr, [e1, e2]) # logical shift right # Extra arithmetic operators supported by Z3 but not part of the SMT-LIB standard. -srem(e1::BitVectorExpr, e2::BitVectorExpr) = __bvnop(__signfix(rem), :bvsrem, BitVectorExpr, e1, e2) # unique to z3 -smod(e1::BitVectorExpr, e2::BitVectorExpr) = __bvnop(__signfix(mod), :bvsmod, BitVectorExpr, e1, e2) # unique to z3 ->>>(e1::BitVectorExpr, e2::BitVectorExpr) = __bvnop(__signfix(>>), :bvashr, BitVectorExpr, e1, e2) # arithmetic shift right - unique to Z3 +srem(e1::AbstractBitVectorExpr, e2::AbstractBitVectorExpr) = __bvnop(__signfix(rem), :bvsrem, BitVectorExpr, [e1, e2]) # unique to z3 +smod(e1::AbstractBitVectorExpr, e2::AbstractBitVectorExpr) = __bvnop(__signfix(mod), :bvsmod, BitVectorExpr, [e1, e2]) # unique to z3 +>>>(e1::AbstractBitVectorExpr, e2::AbstractBitVectorExpr) = __bvnop(__signfix(>>), :bvashr, BitVectorExpr, [e1, e2]) # arithmetic shift right - unique to Z3 ##### Bitwise logical operations (arity n>=2) ##### -function or(es::Array{T}, consts=Integer[]) where T <: BitVectorExpr +function or(es::Array{T}, consts=Integer[]) where T <: AbstractBitVectorExpr if length(consts)>0 push!(es, __wrap_bitvector_const(reduce(|, consts), es[1].length)) end - expr = __bvnop((a,b) -> a | b, :bvor, BitVectorExpr, es..., __is_commutative=true, __try_flatten=true) + expr = __bvnop((a,b) -> a | b, :bvor, BitVectorExpr, es, __is_commutative=true, __try_flatten=true) return expr end -or(zs::Vararg{Union{T, Integer}}) where T <: BitVectorExpr = or(collect(zs)) +or(zs::Vararg{Union{T, Integer}}) where T <: AbstractBitVectorExpr = or(collect(zs)) # We need this declaration to enable the syntax and.([z1, z2,...,zn]) where z1, z2,...,zn are broadcast-compatible -function and(es::Array{T}, consts=Integer[]) where T <: BitVectorExpr +function and(es::Array{T}, consts=Integer[]) where T <: AbstractBitVectorExpr if length(consts)>0 push!(es, __wrap_bitvector_const(reduce(&, consts), es[1].length)) end - expr = __bvnop((a,b) -> a & b, :bvand, BitVectorExpr, es..., __is_commutative=true, __try_flatten=true) + expr = __bvnop((a,b) -> a & b, :bvand, BitVectorExpr, es, __is_commutative=true, __try_flatten=true) return expr end -and(zs::Vararg{Union{T, Integer}}) where T <: BitVectorExpr = and(collect(zs)) +and(zs::Vararg{Union{T, Integer}}) where T <: AbstractBitVectorExpr = and(collect(zs)) # We need this declaration to enable the syntax and.([z1, z2,...,zn]) where z1, z2,...,zn are broadcast-compatible -∨(e1::BitVectorExpr, e2::BitVectorExpr) = or([e1, e2]) -∧(e1::BitVectorExpr, e2::BitVectorExpr) = and([e1, e2]) +∨(e1::AbstractBitVectorExpr, e2::AbstractBitVectorExpr) = or([e1, e2]) +∧(e1::AbstractBitVectorExpr, e2::AbstractBitVectorExpr) = and([e1, e2]) # Extra logical operators supported by Z3 but not part of the SMT-LIB standard. -nor(e1::BitVectorExpr, e2::BitVectorExpr) = __bvnop((a,b) -> ~(a | b), :bvnor, BitVectorExpr, e1, e2, __is_commutative=true) -nand(e1::BitVectorExpr, e2::BitVectorExpr) = __bvnop((a,b) -> ~(a & b), :bvnand, BitVectorExpr, e1, e2, __is_commutative=true) +nor(e1::AbstractBitVectorExpr, e2::AbstractBitVectorExpr) = __bvnop((a,b) -> ~(a | b), :bvnor, BitVectorExpr, [e1, e2], __is_commutative=true) +nand(e1::AbstractBitVectorExpr, e2::AbstractBitVectorExpr) = __bvnop((a,b) -> ~(a & b), :bvnand, BitVectorExpr, [e1, e2], __is_commutative=true) # TODO Probably all the "extra" operators should behave like this for constants xnor(a::T,b::T) where T <: Integer = (a & b) | (~a & ~b) @@ -188,11 +201,11 @@ function xnor(es_mixed::Array{T}) where T if length(literals)>0 push!(es, __wrap_bitvector_const(reduce(xnor, literals), es[1].length)) end - expr = __bvnop(xnor, :bvxnor, BitVectorExpr, es...) + expr = __bvnop(xnor, :bvxnor, BitVectorExpr, es) return expr end -xnor(zs::Vararg{Union{T, Integer}}) where T <: BitVectorExpr = xnor(collect(zs)) +xnor(zs::Vararg{Union{T, Integer}}) where T <: AbstractBitVectorExpr = xnor(collect(zs)) # We need this declaration to enable the syntax and.([z1, z2,...,zn]) where z1, z2,...,zn are broadcast-compatible # TODO operations with arity n @@ -202,23 +215,23 @@ xnor(zs::Vararg{Union{T, Integer}}) where T <: BitVectorExpr = xnor(collect(zs)) ¬(e::BitVectorExpr) = __bv1op(e, ~, :bvnot) ##### Bitwise predicates ##### -<(e1::BitVectorExpr, e2::BitVectorExpr) = __bvnop(>, :bvult, BoolExpr, e1, e2) -<=(e1::BitVectorExpr, e2::BitVectorExpr) = __bvnop(>=, :bvule, BoolExpr, e1, e2) ->(e1::BitVectorExpr, e2::BitVectorExpr) = __bvnop(>, :bvugt, BoolExpr, e1, e2) ->=(e1::BitVectorExpr, e2::BitVectorExpr) = __bvnop(>=, :bvuge, BoolExpr, e1, e2) +<(e1::AbstractBitVectorExpr, e2::AbstractBitVectorExpr) = __bvnop(>, :bvult, BoolExpr, [e1, e2]) +<=(e1::AbstractBitVectorExpr, e2::AbstractBitVectorExpr) = __bvnop(>=, :bvule, BoolExpr, [e1, e2]) +>(e1::AbstractBitVectorExpr, e2::AbstractBitVectorExpr) = __bvnop(>, :bvugt, BoolExpr, [e1, e2]) +>=(e1::AbstractBitVectorExpr, e2::AbstractBitVectorExpr) = __bvnop(>=, :bvuge, BoolExpr, [e1, e2]) # Signed comparisons are supported by Z3 but not part of the SMT-LIB standard. -slt(e1::BitVectorExpr, e2::BitVectorExpr) = __bvnop(__signfix(>), :bvslt, BoolExpr, e1, e2) -sle(e1::BitVectorExpr, e2::BitVectorExpr) = __bvnop(__signfix(>=), :bvsle, BoolExpr, e1, e2) -sgt(e1::BitVectorExpr, e2::BitVectorExpr) = __bvnop(__signfix(>), :bvsgt, BoolExpr, e1, e2) -sge(e1::BitVectorExpr, e2::BitVectorExpr) = __bvnop(__signfix(>=), :bvsge, BoolExpr, e1, e2) +slt(e1::AbstractBitVectorExpr, e2::AbstractBitVectorExpr) = __bvnop(__signfix(>), :bvslt, BoolExpr, [e1, e2]) +sle(e1::AbstractBitVectorExpr, e2::AbstractBitVectorExpr) = __bvnop(__signfix(>=), :bvsle, BoolExpr, [e1, e2]) +sgt(e1::AbstractBitVectorExpr, e2::AbstractBitVectorExpr) = __bvnop(__signfix(>), :bvsgt, BoolExpr, [e1, e2]) +sge(e1::AbstractBitVectorExpr, e2::AbstractBitVectorExpr) = __bvnop(__signfix(>=), :bvsge, BoolExpr, [e1, e2]) ##### Word-level operations ##### # concat and extract are the only SMT-LIB standard operations # z3 adds some more, note that concat can accept constants and has arity n >= 2 function concat(es::Vararg{Any}) - if !all(isa.(es, BitVectorExpr)) + if !all(isa.(es, AbstractBitVectorExpr)) @error("Only BitVectors can be concatenated!") end length = sum(getproperty.(es, :length)) @@ -237,25 +250,38 @@ function concat(es::Vararg{Any}) return BitVectorExpr{nextsize(length)}(:concat, collect(es), value, name, length) end -Base.getindex(e::BitVectorExpr, ind::UnitRange{Int64}) = getindex(e, first(ind), last(ind)) -Base.getindex(e::BitVectorExpr, ind::Int64) = getindex(e, ind, ind) -function Base.getindex(e::BitVectorExpr, ind_1::Int64, ind_2::Int64) - if ind_1 > ind_2 || ind_1 < 1 || ind_2 > e.length - error("Cannot extract sequence $ind_1 to $ind_2 from BitVector!") +##### INDEXING ##### +# SMT-LIB indexing is called extract and works in a slightly weird manner +# Here we enable indexing using the Julia slice operator. + +Base.getindex(e::AbstractBitVectorExpr, ind_1::Int64, ind_2::Int64) = getindex(e, UnitRange(ind_1, ind_2)) +Base.getindex(e::AbstractBitVectorExpr, ind::Int64) = getindex(e, ind, ind) + +function Base.getindex(e::AbstractBitVectorExpr, ind::UnitRange{Int64}) + if first(ind) > last(ind) || first(ind) < 1 || last(ind) > e.length + error("Cannot extract sequence $ind from BitVector!") end - return __bv1op(e, identity, :extract)#Symbol("(_ extract $ind_2 $ind_1)")) + + # typeof(e).parameters[1] returns the type of the first parameter to the parametric type of e + ReturnIntType = typeof(e).parameters[1] + v = isnothing(e.value) ? nothing : e.value & ReturnIntType(reduce(|, map((i) -> 2^(i-1), ind))) + + # the SMT-LIB operator is (_ extract $(last(ind)) $(first(ind))) + return SlicedBitVectorExpr{ReturnIntType}(:extract, [e], v, __get_hash_name(:extract, [e]), length(ind), false, ind) end + ##### Translation to/from integer ##### # Be aware these have high overhead -bv2int(e::BitVectorExpr) = IntExpr(:bv2int, [e,], isnothing(e.value) ? nothing : Int(e.value), "bv2int_$(e.name)") +bv2int(e::AbstractBitVectorExpr) = IntExpr(:bv2int, [e,], isnothing(e.value) ? nothing : Int(e.value), "bv2int_$(e.name)") function int2bv(e::IntExpr, size::Int) name = "int2bv_$(e.name)" expr = BitVectorExpr{nextsize(size)}(:int2bv, [e], isnothing(e.value) ? nothing : unsigned(e.value), name, size)#Symbol("(_ int2bv $size)")) return expr end + ##### INTEROPERABILITY WITH CONSTANTS ##### # RULE # Given a variable with sort (_ BitVec n) and a const with sort (_ BitVec m) @@ -271,17 +297,17 @@ function __wrap_bitvector_const(c::Union{Unsigned, BigInt}, size::Int) # nextsize(size) returns the correct Unsigned type ReturnType = nextsize(size) if minsize > size - error("BitVector of size $size cannot be combined with constant of size $minisize") + error("BitVector of size $size cannot be combined with constant of size $minsize") elseif minsize == size - return BitVectorExpr{ReturnType}(:const, AbstractExpr[], c, "const_$c", size) + return BitVectorExpr{ReturnType}(:const, AbstractExpr[], c, "const_$(hexstr(c))", size) else # it's smaller and we need to pad it - return BitVectorExpr{ReturnType}(:const, AbstractExpr[], ReturnType(c), "const_$c", size) + return BitVectorExpr{ReturnType}(:const, AbstractExpr[], ReturnType(c), "const_$(hexstr(c))", size) end end __2ops = [:+, :-, :*, :/, :<, :<=, :>, :>=, :sle, :slt, :sge, :sgt, :nand, :nor, :<<, :>>, :>>>, :srem, :urem, :smod] for op in __2ops - @eval $op(a::Union{Unsigned, BigInt}, b::BitVectorExpr) = $op(__wrap_bitvector_const(a, b.length), b) - @eval $op(a::BitVectorExpr, b::Union{Unsigned, BigInt}) = $op(a, __wrap_bitvector_const(b, a.length)) + @eval $op(a::Union{Unsigned, BigInt}, b::AbstractBitVectorExpr) = $op(__wrap_bitvector_const(a, b.length), b) + @eval $op(a::AbstractBitVectorExpr, b::Union{Unsigned, BigInt}) = $op(a, __wrap_bitvector_const(b, a.length)) end diff --git a/test/bitvector_tests.jl b/test/bitvector_tests.jl index 90c5092..7a763ab 100644 --- a/test/bitvector_tests.jl +++ b/test/bitvector_tests.jl @@ -45,7 +45,7 @@ using Test @test (concat(c, d) + a).length == 16 # indexing - @test a[2:4].op == :extract + @test (a[2:4]).range == UnitRange(2,4) @test_throws ErrorException a[0:2] @test_throws ErrorException a[15:30] From d1d80d0617c9d3712dcea453bee09d27918b999a Mon Sep 17 00:00:00 2001 From: Emiko Soroka Date: Sun, 13 Aug 2023 15:55:04 -0700 Subject: [PATCH 25/36] Fixed special cases for BitVector SMT statement generation and added unittests (this didn't take much work). Fixed parsing for BitVector generation. One outstanding issue is we need to revamp how values are propagated. --- src/BitVectorExpr.jl | 12 +++---- src/sat.jl | 3 +- src/smt_representation.jl | 39 ++++++++++++++++----- src/utilities.jl | 17 +++++++-- test/bitvector_tests.jl | 73 +++++++++++++++++++++++++++++++++++++-- 5 files changed, 123 insertions(+), 21 deletions(-) diff --git a/src/BitVectorExpr.jl b/src/BitVectorExpr.jl index 2df6adf..7e4e820 100644 --- a/src/BitVectorExpr.jl +++ b/src/BitVectorExpr.jl @@ -274,10 +274,11 @@ end ##### Translation to/from integer ##### # Be aware these have high overhead -bv2int(e::AbstractBitVectorExpr) = IntExpr(:bv2int, [e,], isnothing(e.value) ? nothing : Int(e.value), "bv2int_$(e.name)") +bv2int(e::AbstractBitVectorExpr) = IntExpr(:bv2int, [e,], isnothing(e.value) ? nothing : Int(e.value), __get_hash_name(:bv2int, [e.name])) + function int2bv(e::IntExpr, size::Int) - name = "int2bv_$(e.name)" - expr = BitVectorExpr{nextsize(size)}(:int2bv, [e], isnothing(e.value) ? nothing : unsigned(e.value), name, size)#Symbol("(_ int2bv $size)")) + name = __get_hash_name(:int2bv, [e.name]) + expr = BitVectorExpr{nextsize(size)}(:int2bv, [e], isnothing(e.value) ? nothing : unsigned(e.value), name, size) return expr end @@ -285,9 +286,8 @@ end ##### INTEROPERABILITY WITH CONSTANTS ##### # RULE # Given a variable with sort (_ BitVec n) and a const with sort (_ BitVec m) -# as long as m ≤ n any operation with the same size output is valid +# as long as m ≤ n any operation with the same size output is valid (except concat which adds them) # Short constants will be padded with zeros because this matches Julia's behavior. -# eg any operation except concat # size must be the SMT-LIB bitvector length, for example if you have a bitvector of length 12 pass in 12 NOT 16 # this function returns c of the correct Unsigned type to interoperate with the bitvector.value @@ -305,7 +305,7 @@ function __wrap_bitvector_const(c::Union{Unsigned, BigInt}, size::Int) end end -__2ops = [:+, :-, :*, :/, :<, :<=, :>, :>=, :sle, :slt, :sge, :sgt, :nand, :nor, :<<, :>>, :>>>, :srem, :urem, :smod] +__2ops = [:+, :-, :*, :/, :<, :<=, :>, :>=, :(==), :sle, :slt, :sge, :sgt, :nand, :nor, :<<, :>>, :>>>, :srem, :urem, :smod] for op in __2ops @eval $op(a::Union{Unsigned, BigInt}, b::AbstractBitVectorExpr) = $op(__wrap_bitvector_const(a, b.length), b) diff --git a/src/sat.jl b/src/sat.jl index 9635c7d..e942211 100644 --- a/src/sat.jl +++ b/src/sat.jl @@ -73,7 +73,8 @@ function __assign!(z::T, values::Dict) where T <: AbstractExpr if z.op ∈ keys(__reductions) z.value = __reductions[z.op](values) else - @error("Unknown operator $(z.op)") + z.value = missing + @error "Unable to propagate value in __assign! Unknown operator $(z.op)" end end end diff --git a/src/smt_representation.jl b/src/smt_representation.jl index c3d30fa..e040614 100644 --- a/src/smt_representation.jl +++ b/src/smt_representation.jl @@ -2,13 +2,16 @@ __smt_typestr(e::BoolExpr) = "Bool" __smt_typestr(e::IntExpr) = "Int" __smt_typestr(e::RealExpr) = "Real" -__smt_typestr(e::BitVectorExpr) = "(_ BitVec $(e.length))" +__smt_typestr(e::AbstractBitVectorExpr) = "(_ BitVec $(e.length))" # Dictionary of opnames with n>=2 operands. This is necessary because not all opnames are valid symbols # For example, iff is = and := is an invalid symbol. -function __smt_opnames(op::Symbol) - if op ∈ keys(__special_cases) - return __special_cases[op] +function __smt_opnames(e::AbstractExpr) + op = e.op + if op ∈ keys(__symbolic_ops) + return __symbolic_ops[op] + elseif op ∈ keys(__generated_ops) + return __generated_ops[op](e) else return op end @@ -16,7 +19,7 @@ end # These special cases arise because the SMT-LIB specification requires names to be ASCII # thus we have to name these to successfully name things in (define-fun ) # but the SMT-LIB operators are symbolic. -__special_cases = Dict( +__symbolic_ops = Dict( :implies => "=>", :iff => "=", :eq => "=", @@ -31,6 +34,24 @@ __special_cases = Dict( :gt => ">", ) +# These are extra-special cases where the operator name is not ASCII and has to be generated at runtime +__generated_ops = Dict( + :int2bv => (e::AbstractBitVectorExpr) -> "(_ int2bv $(e.length))", + :extract => (e::AbstractBitVectorExpr) -> "(_ extract $(last(e.range)-1) $(first(e.range)-1))", +) + +# Finally, we provide facilities for correct encoding of consts +function __format_smt_const(exprtype::Type, c) + # there's no such thing as a Bool const because all Bool consts are simplifiable + if exprtype <: IntExpr || exprtype <: RealExpr + return string(c) # automatically does the right thing for Ints and Reals + elseif exprtype <: AbstractBitVectorExpr + return "#x$(hexstr(c))" + else + error("Unable to encode constant $c for expression of type $exprtype.") + end +end + ##### GENERATING SMTLIB REPRESENTATION ##### @@ -74,7 +95,7 @@ declare(zs::Array{T}; line_ending='\n') where T <: AbstractExpr = reduce(*, decl # It would arise if someone wrote something like @satvariable(x, Bool); x = xb; @satvariable(x, Int) function __get_smt_name(z::AbstractExpr) if z.op == :const - return string(z.value) + return __format_smt_const(typeof(z), z.value) end global GLOBAL_VARNAMES appears_in = map( (t) -> z.name ∈ GLOBAL_VARNAMES[t], __EXPR_TYPES) @@ -110,7 +131,7 @@ function __define_n_op!(z::T, cache::Dict{UInt64, String}, depth::Int; assert=tr if z.__is_commutative varnames = sort(varnames) end - declaration = "(define-fun $fname () $outname ($(__smt_opnames(z.op)) $(join(varnames, " "))))$line_ending" + declaration = "(define-fun $fname () $outname ($(__smt_opnames(z)) $(join(varnames, " "))))$line_ending" cache_key = hash(declaration) # we use this to find out if we already declared this item prop = "" if cache_key in keys(cache) @@ -131,9 +152,9 @@ end function __define_1_op!(z::AbstractExpr, cache::Dict{UInt64, String}, depth::Int; assert=true, line_ending='\n') fname = __get_hash_name(z.op, z.children) - outname = __smt_typestr(z) + outtype = __smt_typestr(z) prop = "" - declaration = "(define-fun $fname () $outname ($(__smt_opnames(z.op)) $(__get_smt_name(z.children[1]))))$line_ending" + declaration = "(define-fun $fname () $outtype ($(__smt_opnames(z)) $(__get_smt_name(z.children[1]))))$line_ending" cache_key = hash(declaration) if assert && depth == 0 && typeof(z) != BoolExpr diff --git a/src/utilities.jl b/src/utilities.jl index 9a9e493..ebb5f36 100644 --- a/src/utilities.jl +++ b/src/utilities.jl @@ -138,6 +138,8 @@ function __parse_line(line::String) ptr = findnext(')', line, ptr+1) # skip the next part () # figure out what the return type is return_type = nothing + + #@debug "line = $(line[ptr+1:end])" if startswith(line[ptr+1:end], "Bool") return_type = Bool ptr += 4 @@ -147,6 +149,10 @@ function __parse_line(line::String) elseif startswith(line[ptr+1:end], "Real") return_type = Float64 ptr += 4 + elseif startswith(line[ptr+1:end], "(_BitVec") + tmp_ptr = ptr + length("(_BitVec") + ptr = findnext(')', line, tmp_ptr+1) # move past the type declaration (_ BitVec [0-9]+) + return_type = nextsize(parse(Int, line[tmp_ptr+1:ptr-1])) # this figures out the unsigned int type of the SMT-LIB BitVec size else @error "Unable to parse return type of \"$original_line\"" end @@ -155,6 +161,7 @@ function __parse_line(line::String) return name, value # value may be nothing if it's a function and not a variable catch @error "Unable to parse value of type $return_type in \"$original_line\"" + rethrow() end end @@ -172,16 +179,20 @@ function __parse_value(value_type::Type, line::String) # trim the () line = line[l+1:findlast(')', line)-1] end + if value_type <: Unsigned || value_type <: BigInt # these both correspond to BitVectors + # the dumb thing here is Z3 returns them with the syntax #x0f instead of 0x0f + line = "0"*line[2:end] + end return parse(value_type, line) end -function parse_smt_output(output::String) +function parse_smt_output(original_output::String) #println(output) assignments = Dict() # recall the whole output will be surrounded by () - output = __split_statements(output) + output = __split_statements(original_output) if length(output) > 1 # something is wrong! - @error "Unable to parse output\n\"$output\"" + @error "Unable to parse output\n\"$original_output\"" return assignments end # now we've cleared the outer (), so iterating will go over each line in the model diff --git a/test/bitvector_tests.jl b/test/bitvector_tests.jl index 7a763ab..ebc0d76 100644 --- a/test/bitvector_tests.jl +++ b/test/bitvector_tests.jl @@ -1,6 +1,8 @@ using BooleanSatisfiability using Test +CLEAR_VARNAMES!() + @testset "Construct BitVector variables and exprs" begin # a few basics @test nextsize(16) == UInt16 @@ -50,7 +52,74 @@ using Test @test_throws ErrorException a[15:30] # bv2int and int2bv - @test isequal(bv2int(a), IntExpr(:bv2int, [a], nothing, "bv2int_a")) + @test isequal(bv2int(a), IntExpr(:bv2int, [a], nothing, BooleanSatisfiability.__get_hash_name(:bv2int, [a.name]))) @satvariable(e, Int) - @test isequal(int2bv(e, 32), BitVectorExpr{UInt32}(:int2bv, [e], nothing, "int2bv_e", 32)) + @test isequal(int2bv(e, 32), BitVectorExpr{UInt32}(:int2bv, [e], nothing, BooleanSatisfiability.__get_hash_name(:int2bv, [e.name]), 32)) +end + +@testset "Spot checks for SMT generation" begin + @satvariable(a, BitVector, 8) + @satvariable(b, BitVector, 8) + + @test smt(concat(a, b, a), assert=false) == "(declare-const a (_ BitVec 8)) +(declare-const b (_ BitVec 8)) +(define-fun concat_aaa580f0c8a73d2a () (_ BitVec 24) (concat a b a))\n" + @test smt((a + b) << 0x2, assert=false) == "(declare-const a (_ BitVec 8)) +(declare-const b (_ BitVec 8)) +(define-fun bvadd_e2cecf976dd1f170 () (_ BitVec 8) (bvadd a b)) +(define-fun bvshl_c0674f1acfd5874d () (_ BitVec 8) (bvshl bvadd_e2cecf976dd1f170 #x02))\n" + + @test smt(0xff >= b) == "(declare-const b (_ BitVec 8)) +(define-fun bvuge_a5b290d10bcab80 () Bool (bvuge #xff b)) +(assert bvuge_a5b290d10bcab80)\n" + + @test smt(0xff == a) == "(declare-const a (_ BitVec 8)) +(define-fun eq_d6dd66c61541c411 () Bool (= #xff a)) +(assert eq_d6dd66c61541c411)\n" + +end + +@testset "BitVector special cases for SMT generation" begin + @satvariable(a, BitVector, 8) + @satvariable(b, BitVector, 8) + + @satvariable(c, Int) + @test smt(int2bv(c, 64), assert=false) == "(declare-const c Int) +(define-fun int2bv_1a6e7a9c3b2f1483 () (_ BitVec 64) ((_ int2bv 64) (as c Int)))\n" + + @test smt(bv2int(b) < 1) == "(declare-const b (_ BitVec 8)) +(define-fun bv2int_9551acae52440d48 () Int (bv2int b)) +(define-fun lt_6154633d9e26b5a1 () Bool (< bv2int_9551acae52440d48 1)) +(assert lt_6154633d9e26b5a1)\n" + + @test smt(a[1:8] == 0xff) == "(declare-const a (_ BitVec 8)) +(define-fun extract_fa232f94411b00cd () (_ BitVec 8) ((_ extract 7 0) a)) +(define-fun eq_b1e0ef160af6310 () Bool (= #xff extract_fa232f94411b00cd)) +(assert eq_b1e0ef160af6310)\n" +end + +@testset "BitVector result parsing" begin + # this output is the result of the two prior tests, bv2int(b) < 1 and a[1:8] == 0xff + output = "( + (define-fun b () (_ BitVec 8) + #x00) + (define-fun bv2int_9551acae52440d48 () Int + (bv2int b)) + (define-fun lt_6154633d9e26b5a1 () Bool + (< (bv2int b) 1)) + (define-fun extract_fa232f94411b00cd () (_ BitVec 8) + ((_ extract 7 0) a)) + (define-fun eq_b1e0ef160af6310 () Bool + (= #xff ((_ extract 7 0) a))) + (define-fun a () (_ BitVec 8) + #xff) + )" + @satvariable(a, BitVector, 8) + @satvariable(b, BitVector, 8) + expr = and(a[1:8] == 0xff, bv2int(b) < 1) + vals = BooleanSatisfiability.parse_smt_output(output) + BooleanSatisfiability.__assign!(expr, vals) + @test a.value == 0xff + @test b.value == 0x00 + end \ No newline at end of file From a16927bf63c200be94fea59b9ac8385703acee27 Mon Sep 17 00:00:00 2001 From: Emiko Soroka Date: Mon, 14 Aug 2023 14:21:48 -0700 Subject: [PATCH 26/36] committing before making the final architecture fix: unifying value propagation in sat.jl --- src/BitVectorExpr.jl | 47 ++++++++++++++++++++++------------ src/BooleanOperations.jl | 21 +++++++++------ src/sat.jl | 25 +++++++++++++++--- src/smt_representation.jl | 12 ++++----- test/solver_interface_tests.jl | 17 ++++++------ 5 files changed, 79 insertions(+), 43 deletions(-) diff --git a/src/BitVectorExpr.jl b/src/BitVectorExpr.jl index 7e4e820..655eeb4 100644 --- a/src/BitVectorExpr.jl +++ b/src/BitVectorExpr.jl @@ -1,4 +1,4 @@ -import Base.getindex +import Base.getindex, Base.setproperty! import Base.+, Base.-, Base.*, Base.<<, Base.>>, Base.>>>, Base.div import Base.>, Base.>=, Base.<, Base.<= # >>> is arithmetic shift right, corresponding to bvashr in SMT-LIB @@ -103,9 +103,7 @@ function __bvnop(op::Function, opname::Symbol, ReturnType::Type, es::Array{T}; _ values = getproperty.(es, :value) if all(.!(isnothing.(values))) # We are guaranteed es all have the same type by our type signature - valtype = typeof(es[1].value) - mask = typemax(valtype) >> (8*sizeof(valtype) - e1.length) - value = valtype(op(values...) & mask) + value = op(values...) end children, name = __combine(es, opname, __is_commutative, __try_flatten) @@ -234,20 +232,26 @@ function concat(es::Vararg{Any}) if !all(isa.(es, AbstractBitVectorExpr)) @error("Only BitVectors can be concatenated!") end - length = sum(getproperty.(es, :length)) - valtype = nextsize(length) - if any(isnothing.(getproperty.(es, :value))) - value = nothing - else - value = valtype(0) # this generates an unsigned int or BigInt of the appropriate size - acc = 0 - for e in es - value |= valtype(e.value) << acc - acc += e.length - end - end + lengths = getproperty.(es, :length) + length = sum(lengths) + ReturnType = nextsize(length) + + values = getproperty.(es, :value) + value = any(isnothing.(values)) ? nothing : concat(values, lengths, ReturnType) + name = __get_hash_name(:concat, collect(getproperty.(es, :name))) - return BitVectorExpr{nextsize(length)}(:concat, collect(es), value, name, length) + + return BitVectorExpr{ReturnType}(:concat, collect(es), value, name, length) +end + +function concat(vals::Array{T}, bitsizes::Array{Integer}, ReturnType::Type) where T <: Integer + value = ReturnType(0) # this generates an unsigned int or BigInt of the appropriate size + acc = 0 + for (v, s) in zip(vals, bitsizes) + value |= ReturnType(v) << acc + acc += s + end + return value end @@ -311,3 +315,12 @@ for op in __2ops @eval $op(a::Union{Unsigned, BigInt}, b::AbstractBitVectorExpr) = $op(__wrap_bitvector_const(a, b.length), b) @eval $op(a::AbstractBitVectorExpr, b::Union{Unsigned, BigInt}) = $op(a, __wrap_bitvector_const(b, a.length)) end + + +##### CONSTANT VERSIONS (for value propagation) ##### + +function __trim_bits!(e::AbstractBitVectorExpr) + mask = typemax(typeof(e.value)) >> (8*sizeof(typeof(e.value)) - e.length) + e.value = e.value & mask +end + diff --git a/src/BooleanOperations.jl b/src/BooleanOperations.jl index 666aea9..b3f6ecc 100644 --- a/src/BooleanOperations.jl +++ b/src/BooleanOperations.jl @@ -186,22 +186,27 @@ function xor(zs_mixed::Array{T}; broadcast_type=:Elementwise) where T if length(literals) > 0 if sum(literals)>1 # more than one literal is true, so xor automatically is false return false - elseif sum(literals) == 1 && length(zs) > 0 # exactly one literal is true and there are variables - # conversion is needed because zs has type Array{AbstractExpr} when it's returned from __check_inputs_nary_op - return and(¬convert(Array{BoolExpr}, zs)) # then all variables must be false - elseif length(zs) == 0 # only literals - return xor(literals...) + elseif sum(literals) == 1 + if length(zs) > 0 # exactly one literal is true and there are variables + # conversion is needed because zs has type Array{AbstractExpr} when it's returned from __check_inputs_nary_op + return and(¬convert(Array{BoolExpr}, zs)) # then all variables must be false + else # only literals + return true + end end + # if sum(literals) == 0 they're all false so we move on end expr = __bool_nary_op(zs, :xor, BoolExpr, true, false) child_values = getproperty.(zs, :value) - expr.value = any(isnothing.(child_values)) ? nothing : reduce(xor, child_values) + expr.value = any(isnothing.(child_values)) ? nothing : xor(child_values) return expr end # We need this extra line to enable the syntax xor.([z1, z2,...,zn]) where z1, z2,...,z are broadcast-compatible -xor(zs::Vararg{Union{T, Bool}}; broadcast_type=:Elementwise) where T <: AbstractExpr = xor(collect(zs)) +xor(zs::Vararg{Union{T, Bool}}) where T <: AbstractExpr = xor(collect(zs)) + # this is the const version +xor(values::Union{BitVector, Array{T}}) where T <: Bool = sum(values) == 1 """ z1 ⟹ z2 @@ -227,7 +232,6 @@ function iff(z1::BoolExpr, z2::BoolExpr) return BoolExpr(:iff, zs, value, __get_hash_name(:iff, zs), __is_commutative=true) end -⟺(z1::Union{BoolExpr, Bool}, z2::Union{BoolExpr, Bool}) = iff(z1, z2) """ ite(x::BoolExpr, y::BoolExpr, z::BoolExpr) @@ -272,6 +276,7 @@ implies(z1::Bool, z2::BoolExpr) = z1 ? z2 : true # not(z1) or z2 implies(z1::BoolExpr, z2::Bool) = z2 ? true : not(z1) # not(z1) or z2 implies(z1::Bool, z2::Bool) = !z1 | z2 +⟺(z1::Union{BoolExpr, Bool}, z2::Union{BoolExpr, Bool}) = iff(z1, z2) iff(z1::BoolExpr, z2::Bool) = z2 ? z1 : ¬z1 # if z2 is true z1 must be true and if z2 is false z1 must be false iff(z1::Bool, z2::BoolExpr) = z1 ? z2 : ¬z2 iff(z1::Bool, z2::Bool) = z1 == z2 diff --git a/src/sat.jl b/src/sat.jl index e942211..521f246 100644 --- a/src/sat.jl +++ b/src/sat.jl @@ -39,6 +39,7 @@ sat!(zs::Array, solver::Solver) = sat!(zs...; solver=Solver) # see discussion on why this is the way it is # https://docs.julialang.org/en/v1/manual/performance-tips/#The-dangers-of-abusing-multiple-dispatch-(aka,-more-on-types-with-values-as-parameters) # https://groups.google.com/forum/#!msg/julia-users/jUMu9A3QKQQ/qjgVWr7vAwAJ +#= __reductions = Dict( :not => (values) -> !(values[1]), :and => (values) -> reduce(&, values), @@ -57,12 +58,27 @@ __reductions = Dict( :mul => (values) -> prod(values), :div => (values) -> values[1] / prod(values[2:end]), ) +=# + +__julia_symbolic_ops = Dict( + :eq => ==, + :add => +, + :sub => -, + :mul => *, + :div => /, + :neg => -, + :lt => <, + :leq => <=, + :geq => >=, + :gt => >, +) function __assign!(z::T, values::Dict) where T <: AbstractExpr if z.op == :identity if z.name ∈ keys(values) z.value = values[z.name] else + @warn "Value not found for variable $(z.name)." z.value = missing # this is better than nothing because & and | automatically skip it (three-valued logic). end elseif z.op == :const @@ -70,11 +86,12 @@ function __assign!(z::T, values::Dict) where T <: AbstractExpr else map( (z) -> __assign!(z, values), z.children) values = getproperty.(z.children, :value) - if z.op ∈ keys(__reductions) - z.value = __reductions[z.op](values) - else + op = z.op ∈ keys(__julia_symbolic_ops) ? __julia_symbolic_ops[z.op] : eval(z.op) + try + z.value = op(values...) + catch z.value = missing - @error "Unable to propagate value in __assign! Unknown operator $(z.op)" + @warn "Unable to propagate value to $(z.name)." end end end diff --git a/src/smt_representation.jl b/src/smt_representation.jl index e040614..3b6ac0a 100644 --- a/src/smt_representation.jl +++ b/src/smt_representation.jl @@ -8,10 +8,10 @@ __smt_typestr(e::AbstractBitVectorExpr) = "(_ BitVec $(e.length))" # For example, iff is = and := is an invalid symbol. function __smt_opnames(e::AbstractExpr) op = e.op - if op ∈ keys(__symbolic_ops) - return __symbolic_ops[op] - elseif op ∈ keys(__generated_ops) - return __generated_ops[op](e) + if op ∈ keys(__smt_symbolic_ops) + return __smt_symbolic_ops[op] + elseif op ∈ keys(__smt_generated_ops) + return __smt_generated_ops[op](e) else return op end @@ -19,7 +19,7 @@ end # These special cases arise because the SMT-LIB specification requires names to be ASCII # thus we have to name these to successfully name things in (define-fun ) # but the SMT-LIB operators are symbolic. -__symbolic_ops = Dict( +__smt_symbolic_ops = Dict( :implies => "=>", :iff => "=", :eq => "=", @@ -35,7 +35,7 @@ __symbolic_ops = Dict( ) # These are extra-special cases where the operator name is not ASCII and has to be generated at runtime -__generated_ops = Dict( +__smt_generated_ops = Dict( :int2bv => (e::AbstractBitVectorExpr) -> "(_ int2bv $(e.length))", :extract => (e::AbstractBitVectorExpr) -> "(_ extract $(last(e.range)-1) $(first(e.range)-1))", ) diff --git a/test/solver_interface_tests.jl b/test/solver_interface_tests.jl index c2c12ac..e0e9176 100644 --- a/test/solver_interface_tests.jl +++ b/test/solver_interface_tests.jl @@ -68,19 +68,20 @@ using Test, Logging test_expr = IntExpr(:add, a3, nothing, "test") BooleanSatisfiability.__assign!(test_expr, values) @test value(test_expr) == 6 - test_expr.op = :sub - BooleanSatisfiability.__assign!(test_expr, values) - @test value(test_expr) == -4 - + test_expr.op = :mul BooleanSatisfiability.__assign!(test_expr, values) @test value(test_expr) == 6 - values = Dict("ar3_1"=>1., "ar3_2"=>2., "ar3_3"=>3., "a"=>0.) - @satvariable(ar3[1:3], Real) - test_expr = RealExpr(:div, ar3, nothing, "test") + test_expr.op = :sub; test_expr.children = test_expr.children[1:2] + BooleanSatisfiability.__assign!(test_expr, values) + @test value(test_expr) == -1 + + values = Dict("ar2_1"=>1., "ar2_2"=>2.) + @satvariable(ar2[1:2], Real) + test_expr = RealExpr(:div, ar2, nothing, "test") BooleanSatisfiability.__assign!(test_expr, values) - @test value(test_expr) == (1. / 2. / 3.) + @test value(test_expr) == (1. / 2.) # Can't assign nonexistent operator #test_expr = RealExpr(:fakeop, Real(1,"a"), nothing, "test") From f8aa6da86ede2179b1b42cfeda085c9fb108784f Mon Sep 17 00:00:00 2001 From: Emiko Soroka Date: Mon, 14 Aug 2023 15:26:21 -0700 Subject: [PATCH 27/36] fixed operator names to &, | and ~ --- src/BitVectorExpr.jl | 12 ++++++------ test/bitvector_tests.jl | 5 +++++ 2 files changed, 11 insertions(+), 6 deletions(-) diff --git a/src/BitVectorExpr.jl b/src/BitVectorExpr.jl index 655eeb4..2b7e2ff 100644 --- a/src/BitVectorExpr.jl +++ b/src/BitVectorExpr.jl @@ -1,5 +1,5 @@ import Base.getindex, Base.setproperty! -import Base.+, Base.-, Base.*, Base.<<, Base.>>, Base.>>>, Base.div +import Base.+, Base.-, Base.*, Base.<<, Base.>>, Base.>>>, Base.div, Base.&, Base.|, Base.~ import Base.>, Base.>=, Base.<, Base.<= # >>> is arithmetic shift right, corresponding to bvashr in SMT-LIB # >> is logical shift right, bvlshr in SMT-LIB @@ -134,7 +134,7 @@ end *(e1::AbstractBitVectorExpr, e2::AbstractBitVectorExpr) = __bvnop(*, :bvmul, BitVectorExpr, [e1, e2],__is_commutative=true, __try_flatten=true) div(e1::AbstractBitVectorExpr, e2::AbstractBitVectorExpr) = __bvnop(div, :bvudiv, BitVectorExpr, [e1, e2]) -# unary minus +# unary minus, this is an arithmetic minus not a bit flip. -(e::BitVectorExpr) = __bv1op(e, -, :bvneg) # NOTE: Julia rem(a, b) and a%b return the unsigned remainder when a and b are unsigned @@ -184,8 +184,8 @@ end and(zs::Vararg{Union{T, Integer}}) where T <: AbstractBitVectorExpr = and(collect(zs)) # We need this declaration to enable the syntax and.([z1, z2,...,zn]) where z1, z2,...,zn are broadcast-compatible -∨(e1::AbstractBitVectorExpr, e2::AbstractBitVectorExpr) = or([e1, e2]) -∧(e1::AbstractBitVectorExpr, e2::AbstractBitVectorExpr) = and([e1, e2]) +(|)(e1::AbstractBitVectorExpr, e2::AbstractBitVectorExpr) = or([e1, e2]) +(&)(e1::AbstractBitVectorExpr, e2::AbstractBitVectorExpr) = and([e1, e2]) # Extra logical operators supported by Z3 but not part of the SMT-LIB standard. nor(e1::AbstractBitVectorExpr, e2::AbstractBitVectorExpr) = __bvnop((a,b) -> ~(a | b), :bvnor, BitVectorExpr, [e1, e2], __is_commutative=true) @@ -210,7 +210,7 @@ xnor(zs::Vararg{Union{T, Integer}}) where T <: AbstractBitVectorExpr = xnor(coll # note that bvxnor is left-accumulating, so bvxnor(a, b, c) = bvxnor(bvxnor(a, b), c) # bvnor and bvnand have arity 2 -¬(e::BitVectorExpr) = __bv1op(e, ~, :bvnot) +~(e::BitVectorExpr) = __bv1op(e, ~, :bvnot) ##### Bitwise predicates ##### <(e1::AbstractBitVectorExpr, e2::AbstractBitVectorExpr) = __bvnop(>, :bvult, BoolExpr, [e1, e2]) @@ -309,7 +309,7 @@ function __wrap_bitvector_const(c::Union{Unsigned, BigInt}, size::Int) end end -__2ops = [:+, :-, :*, :/, :<, :<=, :>, :>=, :(==), :sle, :slt, :sge, :sgt, :nand, :nor, :<<, :>>, :>>>, :srem, :urem, :smod] +__2ops = [:+, :-, :*, :/, :<, :<=, :>, :>=, :(==), :sle, :slt, :sge, :sgt, :nand, :nor, :<<, :>>, :>>>, :&, :|, :~, :srem, :urem, :smod] for op in __2ops @eval $op(a::Union{Unsigned, BigInt}, b::AbstractBitVectorExpr) = $op(__wrap_bitvector_const(a, b.length), b) diff --git a/test/bitvector_tests.jl b/test/bitvector_tests.jl index ebc0d76..a618b21 100644 --- a/test/bitvector_tests.jl +++ b/test/bitvector_tests.jl @@ -25,6 +25,11 @@ CLEAR_VARNAMES!() @test isequal(op(a,b), BitVectorExpr{UInt16}(name, [a,b], nothing, BooleanSatisfiability.__get_hash_name(name, [a,b]), 16)) end + # three special cases! the native Julia bitwise ops have weird forms (&)(a,b) because they are short circuitable + @test isequal(a & b, BitVectorExpr{UInt16}(:bvand, [a,b], nothing, BooleanSatisfiability.__get_hash_name(:bvand, [a,b]), 16)) + @test isequal(a | b, BitVectorExpr{UInt16}(:bvor, [a,b], nothing, BooleanSatisfiability.__get_hash_name(:bvor, [a,b]), 16)) + @test isequal(~a, BitVectorExpr{UInt16}(:bvnot, [a], nothing, BooleanSatisfiability.__get_hash_name(:bvnot, [a]), 16)) + # n-ary ops @satvariable(e, BitVector, 16) ops = [+, *, and, or] From 425fd4ad7201b917a88929e6a9a4d0779c322bba Mon Sep 17 00:00:00 2001 From: Emiko Soroka Date: Mon, 14 Aug 2023 17:11:42 -0700 Subject: [PATCH 28/36] Fixed concat of constant values so that it makes sense, even if it doesn't fully match z3 which is not possible. Added unittest converage. --- src/BitVectorExpr.jl | 143 +++++++++++++++++++++++++---------- src/BooleanSatisfiability.jl | 4 +- src/sat.jl | 22 ++++-- test/bitvector_tests.jl | 23 +++++- 4 files changed, 143 insertions(+), 49 deletions(-) diff --git a/src/BitVectorExpr.jl b/src/BitVectorExpr.jl index 2b7e2ff..6b6e555 100644 --- a/src/BitVectorExpr.jl +++ b/src/BitVectorExpr.jl @@ -54,19 +54,10 @@ function BitVectorExpr(name::String, length::Int) return BitVectorExpr{nextsize(length)}(:identity, AbstractExpr[], nothing, "$name", length) end -# Constants, to match Julia conventions, may be specified in binary, hex, or octal. -# Constants may be specified in base 10 as long as they are explicitly constructed to be of type Unsigned or BigInt. -# Examples: 0xDEADBEEF (UInt32), 0b0101 (UInt8), 0o7700 (UInt16), big"123456789012345678901234567890" (BigInt) -function __wrap_const(c::Union{Unsigned, BigInt}) - nbits = bitcount(c) - rettype = nextsize(nbits) - return BitVectorExpr{rettype}(:const, AbstractExpr[], rettype(c), "const_0x$(string(c, base = 16, pad=sizeof(rettype)*2))", nbits) -end -# Consts can be padded, so for example you can add 0x01 (UInt8) to (_ BitVec 16) -# Variables cannot be padded! For example, 0x0101 (Uint16) cannot be added to (_ BitVec 8). # Note that we don't have to define == because it's defined for AbstractExpr. +# some utility functions function nextsize(n::Integer) :: Type # works on BigInt and UInt if sign(n) == -1 @error("Constants must be unsigned or positive BigInts!") @@ -81,18 +72,21 @@ function nextsize(n::Integer) :: Type # works on BigInt and UInt end function bitcount(a::Integer) # works on BigInt and UInt + if a == 0 + return 1 + end if sign(a) == -1 @error("Constants must be unsigned or positive BigInts!") end result = findlast((x) -> x != 0, a .>> collect(0:8*sizeof(a))) - return !isnothing(result) ? result : 0 + return result end -function hexstr(a::Integer) +function hexstr(a::Integer, ReturnType::Type) if sign(a) == -1 @error("Constants must be unsigned or positive BigInts!") end - return string(a, base=16, pad=sizeof(a)*2) + return string(a, base=16, pad=sizeof(ReturnType)*2) end @@ -114,8 +108,8 @@ function __bvnop(op::Function, opname::Symbol, ReturnType::Type, es::Array{T}; _ end end -function __bv1op(e::AbstractBitVectorExpr, op::Function, opname::Symbol, length=nothing) - length = isnothing(length) ? e.length : length +function __bv1op(e::AbstractBitVectorExpr, op::Function, opname::Symbol, l=nothing) + l = isnothing(l) ? e.length : l value = nothing if !isnothing(e.value) valtype = typeof(e.value) @@ -123,7 +117,7 @@ function __bv1op(e::AbstractBitVectorExpr, op::Function, opname::Symbol, length= value = valtype(op(e.value) & mask) end name = __get_hash_name(opname, [e.name,]) - return BitVectorExpr{nextsize(e.length)}(opname, [e,], value, name, length) + return BitVectorExpr{nextsize(e.length)}(opname, [e,], value, name, l) end @@ -153,18 +147,18 @@ __signfix(f::Function) = (a, b) -> unsigned(f(signed(a), signed(b))) # these all have arity 2 urem(e1::AbstractBitVectorExpr, e2::AbstractBitVectorExpr) = __bvnop(rem, :bvurem, BitVectorExpr, [e1, e2]) <<(e1::AbstractBitVectorExpr, e2::AbstractBitVectorExpr) = __bvnop(<<, :bvshl, BitVectorExpr, [e1, e2]) # shift left ->>(e1::AbstractBitVectorExpr, e2::AbstractBitVectorExpr) = __bvnop(>>>, :bvlshr, BitVectorExpr, [e1, e2]) # logical shift right +>>>(e1::AbstractBitVectorExpr, e2::AbstractBitVectorExpr) = __bvnop(>>>, :bvlshr, BitVectorExpr, [e1, e2]) # logical shift right # Extra arithmetic operators supported by Z3 but not part of the SMT-LIB standard. srem(e1::AbstractBitVectorExpr, e2::AbstractBitVectorExpr) = __bvnop(__signfix(rem), :bvsrem, BitVectorExpr, [e1, e2]) # unique to z3 smod(e1::AbstractBitVectorExpr, e2::AbstractBitVectorExpr) = __bvnop(__signfix(mod), :bvsmod, BitVectorExpr, [e1, e2]) # unique to z3 ->>>(e1::AbstractBitVectorExpr, e2::AbstractBitVectorExpr) = __bvnop(__signfix(>>), :bvashr, BitVectorExpr, [e1, e2]) # arithmetic shift right - unique to Z3 +>>(e1::AbstractBitVectorExpr, e2::AbstractBitVectorExpr) = __bvnop(__signfix(>>), :bvashr, BitVectorExpr, [e1, e2]) # arithmetic shift right - unique to Z3 ##### Bitwise logical operations (arity n>=2) ##### function or(es::Array{T}, consts=Integer[]) where T <: AbstractBitVectorExpr if length(consts)>0 - push!(es, __wrap_bitvector_const(reduce(|, consts), es[1].length)) + push!(es, bvconst(reduce(|, consts), es[1].length)) end expr = __bvnop((a,b) -> a | b, :bvor, BitVectorExpr, es, __is_commutative=true, __try_flatten=true) return expr @@ -175,7 +169,7 @@ or(zs::Vararg{Union{T, Integer}}) where T <: AbstractBitVectorExpr = or(collect( function and(es::Array{T}, consts=Integer[]) where T <: AbstractBitVectorExpr if length(consts)>0 - push!(es, __wrap_bitvector_const(reduce(&, consts), es[1].length)) + push!(es, bvconst(reduce(&, consts), es[1].length)) end expr = __bvnop((a,b) -> a & b, :bvand, BitVectorExpr, es, __is_commutative=true, __try_flatten=true) return expr @@ -189,16 +183,22 @@ and(zs::Vararg{Union{T, Integer}}) where T <: AbstractBitVectorExpr = and(collec # Extra logical operators supported by Z3 but not part of the SMT-LIB standard. nor(e1::AbstractBitVectorExpr, e2::AbstractBitVectorExpr) = __bvnop((a,b) -> ~(a | b), :bvnor, BitVectorExpr, [e1, e2], __is_commutative=true) +⊽(e1::AbstractBitVectorExpr, e2::AbstractBitVectorExpr) = nor(e1, e2) + nand(e1::AbstractBitVectorExpr, e2::AbstractBitVectorExpr) = __bvnop((a,b) -> ~(a & b), :bvnand, BitVectorExpr, [e1, e2], __is_commutative=true) +⊼(e1::AbstractBitVectorExpr, e2::AbstractBitVectorExpr) = nand(e1, e2) # TODO Probably all the "extra" operators should behave like this for constants xnor(a::T,b::T) where T <: Integer = (a & b) | (~a & ~b) function xnor(es_mixed::Array{T}) where T - es, literals = __check_inputs_nary_op(es_mixed, const_type=Integer, expr_type=BitVectorExpr) - if length(literals)>0 - push!(es, __wrap_bitvector_const(reduce(xnor, literals), es[1].length)) + es_mixed = collect(es_mixed) + vars, consts = __check_inputs_nary_op(es_mixed, const_type=Integer, expr_type=BitVectorExpr) + if isnothing(vars) || length(vars)==0 + return reduce(xnor, consts) end + + es = map((e) -> isa(e, Integer) ? bvconst(e, vars[1].length) : e, es_mixed) expr = __bvnop(xnor, :bvxnor, BitVectorExpr, es) return expr end @@ -228,28 +228,40 @@ sge(e1::AbstractBitVectorExpr, e2::AbstractBitVectorExpr) = __bvnop(__signf ##### Word-level operations ##### # concat and extract are the only SMT-LIB standard operations # z3 adds some more, note that concat can accept constants and has arity n >= 2 -function concat(es::Vararg{Any}) - if !all(isa.(es, AbstractBitVectorExpr)) - @error("Only BitVectors can be concatenated!") +function concat(es_mixed::Vararg{Any}) + es_mixed = collect(es_mixed) + vars, consts = __check_inputs_nary_op(es_mixed, const_type=Integer, expr_type=BitVectorExpr) + # only consts + if isnothing(vars) || length(vars)==0 + return concat(consts) end + + # preserve order of inputs + es = map((e) -> isa(e, Integer) ? bvconst(e, bitcount(e)) : e, es_mixed) + lengths = getproperty.(es, :length) - length = sum(lengths) - ReturnType = nextsize(length) + l = sum(lengths) + ReturnType = nextsize(l) values = getproperty.(es, :value) - value = any(isnothing.(values)) ? nothing : concat(values, lengths, ReturnType) + value = any(isnothing.(values)) ? nothing : __concat(values, lengths, ReturnType) name = __get_hash_name(:concat, collect(getproperty.(es, :name))) - return BitVectorExpr{ReturnType}(:concat, collect(es), value, name, length) + return BitVectorExpr{ReturnType}(:concat, collect(es), value, name, l) end -function concat(vals::Array{T}, bitsizes::Array{Integer}, ReturnType::Type) where T <: Integer +# for constant values +function concat(vals::Array{T}) where T <: Integer + lengths = map(bitcount, vals) + return __concat(vals, lengths, nextsize(sum(lengths))) +end +function __concat(vals::Array{T}, bitsizes::Array{R}, ReturnType::Type) where T <: Integer where R <: Integer value = ReturnType(0) # this generates an unsigned int or BigInt of the appropriate size - acc = 0 + acc = sum(bitsizes) for (v, s) in zip(vals, bitsizes) + acc -= s value |= ReturnType(v) << acc - acc += s end return value end @@ -296,24 +308,34 @@ end # size must be the SMT-LIB bitvector length, for example if you have a bitvector of length 12 pass in 12 NOT 16 # this function returns c of the correct Unsigned type to interoperate with the bitvector.value # which is the smallest Unsigned type that fits the SMT-LIB bitvector length. -function __wrap_bitvector_const(c::Union{Unsigned, BigInt}, size::Int) +function bvconst(c::Integer, size::Int) + if c < 0 + error("Cannot combine negative integer constant $c with BitVector") + end + minsize = bitcount(c) # nextsize(size) returns the correct Unsigned type ReturnType = nextsize(size) if minsize > size error("BitVector of size $size cannot be combined with constant of size $minsize") elseif minsize == size - return BitVectorExpr{ReturnType}(:const, AbstractExpr[], c, "const_$(hexstr(c))", size) + return BitVectorExpr{ReturnType}(:const, AbstractExpr[], ReturnType(c), "const_0x$(hexstr(c, ReturnType))", size) else # it's smaller and we need to pad it - return BitVectorExpr{ReturnType}(:const, AbstractExpr[], ReturnType(c), "const_$(hexstr(c))", size) + return BitVectorExpr{ReturnType}(:const, AbstractExpr[], ReturnType(c), "const_0x$(hexstr(c, ReturnType))", size) end end +# Constants, to match Julia conventions, may be specified in binary, hex, or octal. +# Constants may be specified in base 10 as long as they are explicitly constructed to be of type Unsigned or BigInt. +# Examples: 0xDEADBEEF (UInt32), 0b0101 (UInt8), 0o7700 (UInt16), big"123456789012345678901234567890" (BigInt) +# Consts can be padded, so for example you can add 0x01 (UInt8) to (_ BitVec 16) +# Variables cannot be padded! For example, 0x0101 (Uint16) cannot be added to (_ BitVec 8). + __2ops = [:+, :-, :*, :/, :<, :<=, :>, :>=, :(==), :sle, :slt, :sge, :sgt, :nand, :nor, :<<, :>>, :>>>, :&, :|, :~, :srem, :urem, :smod] for op in __2ops - @eval $op(a::Union{Unsigned, BigInt}, b::AbstractBitVectorExpr) = $op(__wrap_bitvector_const(a, b.length), b) - @eval $op(a::AbstractBitVectorExpr, b::Union{Unsigned, BigInt}) = $op(a, __wrap_bitvector_const(b, a.length)) + @eval $op(a::Integer, b::AbstractBitVectorExpr) = $op(bvconst(a, b.length), b) + @eval $op(a::AbstractBitVectorExpr, b::Integer) = $op(a, bvconst(b, a.length)) end @@ -324,3 +346,48 @@ function __trim_bits!(e::AbstractBitVectorExpr) e.value = e.value & mask end +__bitvector_const_ops = Dict( + :bvudiv => div, + :bvshl => (<<), + :bvlshr => (>>>), + :bvashr => __signfix(>>), + :bvand => (&), + :bvor => (|), + :bvnot => ~, + :bvneg => -, + :bvadd => +, + :bvsub => -, + :bvmul => *, + :bvurem => rem, + :bvsrem => __signfix(rem), + :bvsmod => __signfix(mod), + :bvnor => (a,b) -> ~(a & b), + :bvnand => (a,b) -> ~(a & b), + :bvxnor => (vals) -> reduce(xnor, vals), + :bvult => <, + :bvule => <=, + :bvugt => >=, + :bvuge => >, + :bvslt => __signfix(<), + :bvsle => __signfix(<=), + :bvsgt => __signfix(>=), + :bvsge => __signfix(>), +) + +# We overload this function from sat.jl to specialize it +# This is for propagating the values back up in __assign! (called when a problem is sat and a satisfying assignment is found). + +function __propagate_value!(z::AbstractBitVectorExpr) + vs = getproperty.(z.children, :value) + + # special cases + if z.op == :concat + ls = getproperty.(z.children, :length) + z.value = __concat(vs, ls, nextsize(z.length)) + elseif z.op == :int2bv + z.value = nextsize(z.length)(z.children[1].value) + else + op = __bitvector_const_ops[z.op] + z.value = length(vs)>1 ? op(vs...) : op(vs[1]) + end +end \ No newline at end of file diff --git a/src/BooleanSatisfiability.jl b/src/BooleanSatisfiability.jl index 780d7d5..7d28914 100644 --- a/src/BooleanSatisfiability.jl +++ b/src/BooleanSatisfiability.jl @@ -35,6 +35,7 @@ export <<, >>, >>>, + &, |, ~, srem, smod, nor, @@ -43,7 +44,8 @@ export slt, sle, sgt, sge, concat, - bv2int, int2bv + bv2int, int2bv, + bvconst export smt, save diff --git a/src/sat.jl b/src/sat.jl index 521f246..be8fc1c 100644 --- a/src/sat.jl +++ b/src/sat.jl @@ -72,6 +72,17 @@ __julia_symbolic_ops = Dict( :geq => >=, :gt => >, ) +# This is the default function for propagating the values back up in __assign! (called when a problem is sat and a satisfying assignment is found). +# This function should be specialized as necessary. +function __propagate_value!(z::AbstractExpr) + op = z.op ∈ keys(__julia_symbolic_ops) ? __julia_symbolic_ops[z.op] : eval(z.op) + vs = getproperty.(z.children, :value) + if length(vs)>1 + z.value = op(vs...) + else + z.value = op(vs[1]) + end +end function __assign!(z::T, values::Dict) where T <: AbstractExpr if z.op == :identity @@ -84,16 +95,13 @@ function __assign!(z::T, values::Dict) where T <: AbstractExpr elseif z.op == :const ; # const already has .value set so do nothing else - map( (z) -> __assign!(z, values), z.children) - values = getproperty.(z.children, :value) - op = z.op ∈ keys(__julia_symbolic_ops) ? __julia_symbolic_ops[z.op] : eval(z.op) - try - z.value = op(values...) - catch + if any(ismissing.(map( (z) -> __assign!(z, values), z.children))) z.value = missing - @warn "Unable to propagate value to $(z.name)." + else + __propagate_value!(z) end end + return z.value end function __clear_assignment!(z::AbstractExpr) diff --git a/test/bitvector_tests.jl b/test/bitvector_tests.jl index a618b21..13b2bb7 100644 --- a/test/bitvector_tests.jl +++ b/test/bitvector_tests.jl @@ -20,7 +20,7 @@ CLEAR_VARNAMES!() @test (-d).op == :bvneg # combining ops ops = [+, -, *, div, urem, <<, >>, srem, smod, >>>, nor, nand, xnor] - names = [:bvadd, :bvsub, :bvmul, :bvudiv, :bvurem, :bvshl, :bvlshr, :bvsrem, :bvsmod, :bvashr, :bvnor, :bvnand, :bvxnor] + names = [:bvadd, :bvsub, :bvmul, :bvudiv, :bvurem, :bvshl, :bvashr, :bvsrem, :bvsmod, :bvlshr, :bvnor, :bvnand, :bvxnor] for (op, name) in zip(ops, names) @test isequal(op(a,b), BitVectorExpr{UInt16}(name, [a,b], nothing, BooleanSatisfiability.__get_hash_name(name, [a,b]), 16)) end @@ -34,11 +34,11 @@ CLEAR_VARNAMES!() @satvariable(e, BitVector, 16) ops = [+, *, and, or] names = [:bvadd, :bvmul, :bvand, :bvor] - ct = BooleanSatisfiability.__wrap_bitvector_const(0x00ff, 16) + ct = BooleanSatisfiability.bvconst(0x00ff, 16) for (op, name) in zip(ops, names) @test isequal(op(a,b,0x00ff,e), BitVectorExpr{UInt16}(name, [a,b,ct, e], nothing, BooleanSatisfiability.__get_hash_name(name, [a,b,ct,e]), 16)) end - @test isequal(xnor(a,b,0x00ff,e), BitVectorExpr{UInt16}(:bvxnor, [a,b,e,ct], nothing, BooleanSatisfiability.__get_hash_name(:bvxnor, [a,b,e,ct]), 16)) + @test isequal(xnor(a,b,0x00ff,e), BitVectorExpr{UInt16}(:bvxnor, [a,b,ct,e], nothing, BooleanSatisfiability.__get_hash_name(:bvxnor, [a,b,ct,e]), 16)) # logical ops ops = [<, <=, >, >=, ==, slt, sle, sgt, sge] @@ -62,6 +62,23 @@ CLEAR_VARNAMES!() @test isequal(int2bv(e, 32), BitVectorExpr{UInt32}(:int2bv, [e], nothing, BooleanSatisfiability.__get_hash_name(:int2bv, [e.name]), 32)) end +@testset "Interoperability with constants" begin + @satvariable(a, BitVector, 8) + @satvariable(b, BitVector, 8) + + @test isequal(a + 0xff, 255 + a) + @test isequal(b - 0x02, b - 2) + @test_throws ErrorException b + -1 + a + + a.value = 0xff + @test concat(bvconst(0x01, 8), bvconst(0x04, 4)).value == 0x014 + @test isequal(concat(a, 0x1).value, 0x1ff) # because 0x1 is read as one bit + @test isequal(concat(a, bvconst(0x01, 8)).value, 0xff01) + @test isequal(concat(a, bvconst(0x01, 6)).value, 0b11111111000001) + + @test isequal(0x1 == a, 0x01 == a) +end + @testset "Spot checks for SMT generation" begin @satvariable(a, BitVector, 8) @satvariable(b, BitVector, 8) From bcdb9a93576c8180c55f5c88801848786712f3af Mon Sep 17 00:00:00 2001 From: Emiko Soroka Date: Mon, 14 Aug 2023 17:30:19 -0700 Subject: [PATCH 29/36] FINISHED fixing value propagation. All tests pass. The only things left to write for BitVector are docstrings and examples. --- src/BitVectorExpr.jl | 4 ++++ src/sat.jl | 1 + src/smt_representation.jl | 12 ++++++++---- test/bitvector_tests.jl | 14 +++++++------- 4 files changed, 20 insertions(+), 11 deletions(-) diff --git a/src/BitVectorExpr.jl b/src/BitVectorExpr.jl index 6b6e555..4978de2 100644 --- a/src/BitVectorExpr.jl +++ b/src/BitVectorExpr.jl @@ -386,6 +386,10 @@ function __propagate_value!(z::AbstractBitVectorExpr) z.value = __concat(vs, ls, nextsize(z.length)) elseif z.op == :int2bv z.value = nextsize(z.length)(z.children[1].value) + elseif z.op == :extract + ReturnIntType = typeof(z).parameters[1] + v = z.children[1].value + z.value = v & ReturnIntType(reduce(|, map((i) -> 2^(i-1), z.range))) else op = __bitvector_const_ops[z.op] z.value = length(vs)>1 ? op(vs...) : op(vs[1]) diff --git a/src/sat.jl b/src/sat.jl index be8fc1c..f4c9ac0 100644 --- a/src/sat.jl +++ b/src/sat.jl @@ -71,6 +71,7 @@ __julia_symbolic_ops = Dict( :leq => <=, :geq => >=, :gt => >, + :bv2int => Int, ) # This is the default function for propagating the values back up in __assign! (called when a problem is sat and a satisfying assignment is found). # This function should be specialized as necessary. diff --git a/src/smt_representation.jl b/src/smt_representation.jl index 3b6ac0a..0b6dd47 100644 --- a/src/smt_representation.jl +++ b/src/smt_representation.jl @@ -41,12 +41,16 @@ __smt_generated_ops = Dict( ) # Finally, we provide facilities for correct encoding of consts -function __format_smt_const(exprtype::Type, c) +function __format_smt_const(exprtype::Type, c::AbstractExpr) # there's no such thing as a Bool const because all Bool consts are simplifiable if exprtype <: IntExpr || exprtype <: RealExpr - return string(c) # automatically does the right thing for Ints and Reals + return string(c.value) # automatically does the right thing for Ints and Reals elseif exprtype <: AbstractBitVectorExpr - return "#x$(hexstr(c))" + if c.length % 4 == 0 # can be a hex string + return "#x$(string(c.value, base=16))" + else + return "#b$(string(c.value, base=16))" + end else error("Unable to encode constant $c for expression of type $exprtype.") end @@ -95,7 +99,7 @@ declare(zs::Array{T}; line_ending='\n') where T <: AbstractExpr = reduce(*, decl # It would arise if someone wrote something like @satvariable(x, Bool); x = xb; @satvariable(x, Int) function __get_smt_name(z::AbstractExpr) if z.op == :const - return __format_smt_const(typeof(z), z.value) + return __format_smt_const(typeof(z), z) end global GLOBAL_VARNAMES appears_in = map( (t) -> z.name ∈ GLOBAL_VARNAMES[t], __EXPR_TYPES) diff --git a/test/bitvector_tests.jl b/test/bitvector_tests.jl index 13b2bb7..fa1e1c8 100644 --- a/test/bitvector_tests.jl +++ b/test/bitvector_tests.jl @@ -89,15 +89,15 @@ end @test smt((a + b) << 0x2, assert=false) == "(declare-const a (_ BitVec 8)) (declare-const b (_ BitVec 8)) (define-fun bvadd_e2cecf976dd1f170 () (_ BitVec 8) (bvadd a b)) -(define-fun bvshl_c0674f1acfd5874d () (_ BitVec 8) (bvshl bvadd_e2cecf976dd1f170 #x02))\n" +(define-fun bvshl_e76bba3dcff1a5b9 () (_ BitVec 8) (bvshl bvadd_e2cecf976dd1f170 #x2))\n" @test smt(0xff >= b) == "(declare-const b (_ BitVec 8)) -(define-fun bvuge_a5b290d10bcab80 () Bool (bvuge #xff b)) -(assert bvuge_a5b290d10bcab80)\n" +(define-fun bvuge_5f6f17cc7a31ab62 () Bool (bvuge #xff b)) +(assert bvuge_5f6f17cc7a31ab62)\n" @test smt(0xff == a) == "(declare-const a (_ BitVec 8)) -(define-fun eq_d6dd66c61541c411 () Bool (= #xff a)) -(assert eq_d6dd66c61541c411)\n" +(define-fun eq_e7731db51d241c94 () Bool (= #xff a)) +(assert eq_e7731db51d241c94)\n" end @@ -116,8 +116,8 @@ end @test smt(a[1:8] == 0xff) == "(declare-const a (_ BitVec 8)) (define-fun extract_fa232f94411b00cd () (_ BitVec 8) ((_ extract 7 0) a)) -(define-fun eq_b1e0ef160af6310 () Bool (= #xff extract_fa232f94411b00cd)) -(assert eq_b1e0ef160af6310)\n" +(define-fun eq_209f324f32b93226 () Bool (= #xff extract_fa232f94411b00cd)) +(assert eq_209f324f32b93226)\n" end @testset "BitVector result parsing" begin From 2b2425acf660892315d24371322f03ccba754e4f Mon Sep 17 00:00:00 2001 From: Emiko Soroka Date: Mon, 14 Aug 2023 18:33:12 -0700 Subject: [PATCH 30/36] fixed an ambiguity in which == is called. established the standard that in a file corresponding to a specific theory, methods should not commit type piracy on other theories which seems obvious but I guess it wasn't. Added 2 mini BitVector examples! --- examples/bv_mini.jl | 31 +++++++++++++++++++++++++++++++ src/BitVectorExpr.jl | 8 ++++++-- src/IntExpr.jl | 26 +++++++++++++------------- src/call_solver.jl | 4 ++-- src/smt_representation.jl | 4 ++-- test/bitvector_tests.jl | 8 ++++++-- 6 files changed, 60 insertions(+), 21 deletions(-) create mode 100644 examples/bv_mini.jl diff --git a/examples/bv_mini.jl b/examples/bv_mini.jl new file mode 100644 index 0000000..2c32585 --- /dev/null +++ b/examples/bv_mini.jl @@ -0,0 +1,31 @@ +push!(LOAD_PATH, "../src") +push!(LOAD_PATH, "./") +using BooleanSatisfiability + +# https://microsoft.github.io/z3guide/docs/theories/Bitvectors/ +# There is a fast way to check that fixed size numbers are powers of two. +# A bitvector x is a power of two or zero if and only if x & (x - 1) is zero, +# where & represents the bitwise and. We check this for 8 bits. +println("Example 1 (should be SAT)") +@satvariable(b, BitVector, 8) +is_power_of_two = b & (b - 0x01) == 0 + +# iff is_power_of_two holds, b must be one of 1, 2, 4, ... 128 +expr = iff(is_power_of_two, + any([b == 2^i for i=0:7])) +status = sat!(expr) +#println(smt(expr)) +println(status) # if status is SAT we proved it. + + +# Here is another mini example: a bitwise version of de Morgan's law. +# In this example we want to show there is NO possible value of x and y such that de Morgan's bitwise law doesn't hold. +println("Example 2 (should be UNSAT)") +@satvariable(x, BitVector, 64) +@satvariable(y, BitVector, 64) + +expr = not((~x & ~y) == ~(x | y)) +status = sat!(expr) +println(smt(expr)) + +println(status) # if status is UNSAT we proved it. diff --git a/src/BitVectorExpr.jl b/src/BitVectorExpr.jl index 4978de2..2ff71bc 100644 --- a/src/BitVectorExpr.jl +++ b/src/BitVectorExpr.jl @@ -1,6 +1,6 @@ import Base.getindex, Base.setproperty! import Base.+, Base.-, Base.*, Base.<<, Base.>>, Base.>>>, Base.div, Base.&, Base.|, Base.~ -import Base.>, Base.>=, Base.<, Base.<= +import Base.>, Base.>=, Base.<, Base.<=, Base.== # >>> is arithmetic shift right, corresponding to bvashr in SMT-LIB # >> is logical shift right, bvlshr in SMT-LIB # << is logical shift left, bvshl in SMT-LIB @@ -218,6 +218,8 @@ xnor(zs::Vararg{Union{T, Integer}}) where T <: AbstractBitVectorExpr = xnor(coll >(e1::AbstractBitVectorExpr, e2::AbstractBitVectorExpr) = __bvnop(>, :bvugt, BoolExpr, [e1, e2]) >=(e1::AbstractBitVectorExpr, e2::AbstractBitVectorExpr) = __bvnop(>=, :bvuge, BoolExpr, [e1, e2]) +(==)(e1::AbstractBitVectorExpr, e2::AbstractBitVectorExpr) = __bvnop((==), :eq, BoolExpr, [e1, e2]) + # Signed comparisons are supported by Z3 but not part of the SMT-LIB standard. slt(e1::AbstractBitVectorExpr, e2::AbstractBitVectorExpr) = __bvnop(__signfix(>), :bvslt, BoolExpr, [e1, e2]) sle(e1::AbstractBitVectorExpr, e2::AbstractBitVectorExpr) = __bvnop(__signfix(>=), :bvsle, BoolExpr, [e1, e2]) @@ -331,13 +333,15 @@ end # Variables cannot be padded! For example, 0x0101 (Uint16) cannot be added to (_ BitVec 8). -__2ops = [:+, :-, :*, :/, :<, :<=, :>, :>=, :(==), :sle, :slt, :sge, :sgt, :nand, :nor, :<<, :>>, :>>>, :&, :|, :~, :srem, :urem, :smod] +__2ops = [:+, :-, :*, :/, :<, :<=, :>, :>=, :sle, :slt, :sge, :sgt, :nand, :nor, :<<, :>>, :>>>, :&, :|, :~, :srem, :urem, :smod] for op in __2ops @eval $op(a::Integer, b::AbstractBitVectorExpr) = $op(bvconst(a, b.length), b) @eval $op(a::AbstractBitVectorExpr, b::Integer) = $op(a, bvconst(b, a.length)) end +(==)(e::AbstractBitVectorExpr, c::Integer) = e == bvconst(c, e.length) +(==)(c::Integer, e::AbstractBitVectorExpr) = bvconst(c, e.length) == e ##### CONSTANT VERSIONS (for value propagation) ##### diff --git a/src/IntExpr.jl b/src/IntExpr.jl index d382e4c..7f6e43b 100644 --- a/src/IntExpr.jl +++ b/src/IntExpr.jl @@ -181,25 +181,25 @@ a .== b **Note:** To test whether two `AbstractExpr`s are eqivalent (in the sense that all properties are equal, not in the shared-memory-location sense of `===`), use `isequal`. """ -function Base.:(==)(e1::AbstractExpr, e2::AbstractExpr) +function Base.:(==)(e1::NumericInteroperableExpr, e2::NumericInteroperableExpr) value = isnothing(e1.value) || isnothing(e2.value) ? nothing : e1.value == e2.value name = __get_hash_name(:eq, [e1, e2]) return BoolExpr(:eq, [e1, e2], value, name, __is_commutative=true) end # INTEROPERABILITY FOR COMPARISON OPERATIONS -Base.:>(e1::AbstractExpr, e2::NumericInteroperableConst) = e1 > __wrap_const(e2) -Base.:>(e1::NumericInteroperableConst, e2::AbstractExpr) = __wrap_const(e1) > e2 -Base.:>=(e1::AbstractExpr, e2::NumericInteroperableConst) = e1 >= __wrap_const(e2) -Base.:>=(e1::NumericInteroperableConst, e2::AbstractExpr) = __wrap_const(e1) >= e2 - -Base.:<(e1::AbstractExpr, e2::NumericInteroperableConst) = e1 < __wrap_const(e2) -Base.:<(e1::NumericInteroperableConst, e2::AbstractExpr) = __wrap_const(e1) < e2 -Base.:<=(e1::AbstractExpr, e2::NumericInteroperableConst) = e1 <= __wrap_const(e2) -Base.:<=(e1::NumericInteroperableConst, e2::AbstractExpr) = __wrap_const(e1) <= e2 - -Base.:(==)(e1::AbstractExpr, e2::NumericInteroperableConst) = e1 == __wrap_const(e2) -Base.:(==)(e1::NumericInteroperableConst, e2::AbstractExpr) = __wrap_const(e1) == e2 +Base.:>(e1::NumericInteroperableExpr, e2::NumericInteroperableConst) = e1 > __wrap_const(e2) +Base.:>(e1::NumericInteroperableConst, e2::NumericInteroperableExpr) = __wrap_const(e1) > e2 +Base.:>=(e1::NumericInteroperableExpr, e2::NumericInteroperableConst) = e1 >= __wrap_const(e2) +Base.:>=(e1::NumericInteroperableConst, e2::NumericInteroperableExpr) = __wrap_const(e1) >= e2 + +Base.:<(e1::NumericInteroperableExpr, e2::NumericInteroperableConst) = e1 < __wrap_const(e2) +Base.:<(e1::NumericInteroperableConst, e2::NumericInteroperableExpr) = __wrap_const(e1) < e2 +Base.:<=(e1::NumericInteroperableExpr, e2::NumericInteroperableConst) = e1 <= __wrap_const(e2) +Base.:<=(e1::NumericInteroperableConst, e2::NumericInteroperableExpr) = __wrap_const(e1) <= e2 + +Base.:(==)(e1::NumericInteroperableExpr, e2::NumericInteroperableConst) = e1 == __wrap_const(e2) +Base.:(==)(e1::NumericInteroperableConst, e2::NumericInteroperableExpr) = __wrap_const(e1) == e2 ##### UNARY OPERATIONS ##### diff --git a/src/call_solver.jl b/src/call_solver.jl index 25bdbc4..f9e0df0 100644 --- a/src/call_solver.jl +++ b/src/call_solver.jl @@ -94,7 +94,7 @@ function talk_to_solver(input::String, s::Solver) @error "Solver crashed on input! Please file a bug report." return :ERROR, Dict{String, Bool}(), proc end - + original_output = deepcopy(output) output = filter(isletter, output) if output == "unsat" # the problem was successfully given to Z3, but it is UNSAT return :UNSAT, Dict{String, Bool}(), proc @@ -107,7 +107,7 @@ function talk_to_solver(input::String, s::Solver) return :SAT, satisfying_assignment, proc else - @error "Solver error:$line_ending $(output)" + @error "Solver error:$line_ending $(original_output)" return :ERROR, Dict{String, Bool}(), proc end end diff --git a/src/smt_representation.jl b/src/smt_representation.jl index 0b6dd47..01836fd 100644 --- a/src/smt_representation.jl +++ b/src/smt_representation.jl @@ -47,9 +47,9 @@ function __format_smt_const(exprtype::Type, c::AbstractExpr) return string(c.value) # automatically does the right thing for Ints and Reals elseif exprtype <: AbstractBitVectorExpr if c.length % 4 == 0 # can be a hex string - return "#x$(string(c.value, base=16))" + return "#x$(string(c.value, base=16, pad=div(c.length,4)))" else - return "#b$(string(c.value, base=16))" + return "#b$(string(c.value, base=2, pad=c.length))" end else error("Unable to encode constant $c for expression of type $exprtype.") diff --git a/test/bitvector_tests.jl b/test/bitvector_tests.jl index fa1e1c8..631d0f5 100644 --- a/test/bitvector_tests.jl +++ b/test/bitvector_tests.jl @@ -80,6 +80,10 @@ end end @testset "Spot checks for SMT generation" begin + + @test BooleanSatisfiability.__format_smt_const(BitVectorExpr, bvconst(0x04, 6)) == "#b000100" + @test BooleanSatisfiability.__format_smt_const(BitVectorExpr, bvconst(255, 12)) == "#x0ff" + @satvariable(a, BitVector, 8) @satvariable(b, BitVector, 8) @@ -89,7 +93,7 @@ end @test smt((a + b) << 0x2, assert=false) == "(declare-const a (_ BitVec 8)) (declare-const b (_ BitVec 8)) (define-fun bvadd_e2cecf976dd1f170 () (_ BitVec 8) (bvadd a b)) -(define-fun bvshl_e76bba3dcff1a5b9 () (_ BitVec 8) (bvshl bvadd_e2cecf976dd1f170 #x2))\n" +(define-fun bvshl_e76bba3dcff1a5b9 () (_ BitVec 8) (bvshl bvadd_e2cecf976dd1f170 #x02))\n" @test smt(0xff >= b) == "(declare-const b (_ BitVec 8)) (define-fun bvuge_5f6f17cc7a31ab62 () Bool (bvuge #xff b)) @@ -116,7 +120,7 @@ end @test smt(a[1:8] == 0xff) == "(declare-const a (_ BitVec 8)) (define-fun extract_fa232f94411b00cd () (_ BitVec 8) ((_ extract 7 0) a)) -(define-fun eq_209f324f32b93226 () Bool (= #xff extract_fa232f94411b00cd)) +(define-fun eq_209f324f32b93226 () Bool (= extract_fa232f94411b00cd #xff)) (assert eq_209f324f32b93226)\n" end From 9d063c6c5a02ba186a2eaa7158f7ec704662c789 Mon Sep 17 00:00:00 2001 From: Emiko Soroka Date: Mon, 14 Aug 2023 18:55:11 -0700 Subject: [PATCH 31/36] Added an example from Dennis Yurichev's SAT/SMT By Example (need to write a markdown page for it) on predicting a tiny toy LCG. It works! Awesome. --- examples/bv_lcg.jl | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 examples/bv_lcg.jl diff --git a/examples/bv_lcg.jl b/examples/bv_lcg.jl new file mode 100644 index 0000000..c90c0de --- /dev/null +++ b/examples/bv_lcg.jl @@ -0,0 +1,37 @@ +# This example is from "SAT/SMT by Example" by Dennis Yurichev. It is example 3.10.1 Cracking LCG with Z3. +# LCG is a crummy kind of random number generator. We will show a small implementation of LCG is predictable. + +# TODO clean up this example + +# In this example we observe 10 states n1,...,n10 from the LCG. +# We want to predict n0, the number before n1, and n11, the number after n10. +@satvariable(states[1:10], BitVector, 32) +@satvariable(output_prev, BitVector, 32) +@satvariable(output_next, BitVector, 32) + +transitions = BoolExpr[states[i+1] == states[i] * 214013+2531011 for i=1:9] +remainders = BoolExpr[ + output_prev == urem(( states[1] >> 16 ) & 0x7FFF, 100), + urem(( states[2] >> 16) & 0x7FFF, 100) == 29, + urem(( states[3] >> 16) & 0x7FFF, 100) == 74, + urem(( states[4] >> 16) & 0x7FFF, 100) == 95, + urem(( states[5] >> 16) & 0x7FFF, 100) == 98, + urem(( states[6] >> 16) & 0x7FFF, 100) == 40, + urem(( states[7] >> 16) & 0x7FFF, 100) == 23, + urem(( states[8] >> 16) & 0x7FFF, 100) == 58, + urem(( states[9] >> 16) & 0x7FFF, 100) == 61, + output_next == urem(( states[10] >> 16) & 0x7FFF, 100), +] + +expr = and(all(transitions), all(remainders)) +status = sat!(expr, solver=CVC5()) +println("status = $status") + +for (i,state) in enumerate(states) + println("state $i = $(value(state))") +end +println("prev = $(value(output_prev))") +println("next = $(value(output_next))") + +# According to Mr. Yurichev's example, the previous output is 37 and the next output is 17! +# This matches on my machine using Z3 and CVC5. From 1b40b98ffd170214471fb220b52d5659d6550c05 Mon Sep 17 00:00:00 2001 From: Emiko Soroka Date: Tue, 15 Aug 2023 14:45:10 -0700 Subject: [PATCH 32/36] Added docstrings to BitVectorExpr and section in documentation. Last outstanding task is markdown examples. --- docs/src/faq.md | 4 +- docs/src/functions.md | 86 +++++++++++++--- src/BitVectorExpr.jl | 188 +++++++++++++++++++++++++++++++---- src/BooleanSatisfiability.jl | 1 + src/smt_macros.jl | 6 +- test/runtests.jl | 2 +- 6 files changed, 251 insertions(+), 36 deletions(-) diff --git a/docs/src/faq.md b/docs/src/faq.md index da2e1ab..1bc3807 100644 --- a/docs/src/faq.md +++ b/docs/src/faq.md @@ -58,7 +58,5 @@ The (long, ugly) name of the combined expression `a <= b` is generated by hashin **Q:** Why don't you just concatenate `a` and `b` and call it `LEQ_a_b`? -**A:** Because what if we have `a = Int(10,"a"); expr = sum(a)`? Are we going to say `expr.name = ADD_a_1_a_2_a_3_a_4_a_5_a_6_a_7_a_8_a_9_a_10`? If not, where do we draw the line? What if we called it `ADD_a_1__a_10`, but then we defined `expr2 = a[1] + a[3:8] + a[10]`? Then both `expr` and `expr1` would share the name `ADD_a_1__a_10` and all heck would break loose. - -If you think of a nicer way to name expressions, please open an issue! +**A:** Because what if we have `a = Int(10,"a"); expr = sum(a)`? Then `expr.name = ADD_a_1_a_2_a_3_a_4_a_5_a_6_a_7_a_8_a_9_a_10`. Or we could call it `ADD_a_1__a_10`, but what if then we defined `expr2 = a[1] + a[3:8] + a[10]`? It's easier to hash the names. diff --git a/docs/src/functions.md b/docs/src/functions.md index f11efa5..ce4fdbd 100644 --- a/docs/src/functions.md +++ b/docs/src/functions.md @@ -6,20 +6,14 @@ Depth = 3 Test link [link](#Logical-Operations) ## Defining variables -The preferred way to define a variable is +Use the `@satvariable` macro to define a variable. ```@docs @satvariable ``` -This alternate syntax is also available. -```@docs -Bool(name::String) -Int(name::String) -Real(name::String) -``` ## Logical operations -These are operations in the theory of propositional logic. For a formal definition of this theory, see Figure 3.2 in *The SMT-LIB Standard, Version 2.6*. +These are operations in the theory of propositional logic. For a formal definition of this theory, see Figure 3.2 in *The SMT-LIB Standard, Version 2.6* or the SMT-LIB [Core theory declaration](http://smtlib.cs.uiowa.edu/theories.shtml). ```@docs not(z::BoolExpr) and(z1::BoolExpr, z2::BoolExpr) @@ -49,12 +43,78 @@ Base.:/(a::RealExpr, b::RealExpr) ``` ### Comparison operators +These operators are available for `IntExpr`, `RealExpr`, and `BitVector` SMT variables. +```@docs +Base.:(==)(a::IntExpr, b::IntExpr) +``` +For BitVector variables, the comparison operators implement unsigned comparison as defined in the SMT-LIB standard [theory of BitVectors](http://smtlib.cs.uiowa.edu/theories.shtml). + +```@docs +Base.:<(a::IntExpr, b::IntExpr) +Base.:<=(a::IntExpr, b::IntExpr) +Base.:>(a::IntExpr, b::IntExpr) +Base.:>=(a::IntExpr, b::IntExpr) +``` + +## BitVector +```julia + @satvariable(a, BitVector, 16) + @satvariable(b, BitVector, 12) + + a + concat(bvconst(0x0, 4), b) +``` +The SMT-LIB standard BitVector is often used to represent operations on fixed-size integers. Thus, BitVectorExprs can interoperate with Julia's native Integer, Unsigned and BigInt types. + +### Bitwise operators +In addition to supporting the comparison operators above and arithmetic operators `+`, `-`, and `*`, the following BitVector-specific operators are available. +Note that unsigned integer division is available using `div`. +```@docs +Base.div(a::BitVectorExpr{UInt8}, b::BitVectorExpr{UInt8}) +``` + +The bitwise logical operator symbols `&`, `~` and `|` are provided for BitVector types instead of the Boolean logic symbols. This matches Julia's use of bitwise logical operators for Unsigned integer types. + +```@docs +Base.:~(a::BitVectorExpr{UInt8}) +Base.:|(a::BitVectorExpr{UInt8}, b::BitVectorExpr{UInt8}) +Base.:&(a::BitVectorExpr{UInt8}, b::BitVectorExpr{UInt8}) +Base.:<<(a::BitVectorExpr{UInt8}, b::BitVectorExpr{UInt8}) +Base.:>>>(a::BitVectorExpr{UInt8}, b::BitVectorExpr{UInt8}) +urem(a::BitVectorExpr{UInt8}, b::BitVectorExpr{UInt8}) +``` + +The following word-level operations are also available in the SMT-LIB standard. +```@docs +concat(a::BitVectorExpr{UInt8}, b::BitVectorExpr{UInt8}) +Base.getindex(a::BitVectorExpr{UInt8}, ind::UnitRange{Int64}) +bv2int(a::BitVectorExpr{UInt8}) +int2bv(a::IntExpr, s::Int) +``` + +### Utility functions for BitVectors +```@docs +bitcount(a::Integer) +nextsize(n::Integer) +bvconst(c::Integer, size::Int) +``` + +### Additional Z3 BitVector operators. +Z3 implements the following signed comparisons for BitVectors. Note that these are not part of the SMT-LIB standard and other solvers may not support them. +```@docs +Base.:>>(a::BitVectorExpr{UInt8}, b::BitVectorExpr{UInt8}) +srem(a::BitVectorExpr{UInt8}, b::BitVectorExpr{UInt8}) +smod(a::BitVectorExpr{UInt8}, b::BitVectorExpr{UInt8}) +nor(a::BitVectorExpr{UInt8}, b::BitVectorExpr{UInt8}) +nand(a::BitVectorExpr{UInt8}, b::BitVectorExpr{UInt8}) +xnor(a::BitVectorExpr{UInt8}, b::BitVectorExpr{UInt8}) +``` + +Signed comparisons are also Z3-specific. ```@docs -Base.:(==)(a::AbstractExpr, b::AbstractExpr) -Base.:<(a::AbstractExpr, b::AbstractExpr) -Base.:<=(a::AbstractExpr, b::AbstractExpr) -Base.:>(a::AbstractExpr, b::AbstractExpr) -Base.:>=(a::AbstractExpr, b::AbstractExpr) +slt(a::BitVectorExpr{UInt8}, b::BitVectorExpr{UInt8}) +sle(a::BitVectorExpr{UInt8}, b::BitVectorExpr{UInt8}) +sgt(a::BitVectorExpr{UInt8}, b::BitVectorExpr{UInt8}) +sge(a::BitVectorExpr{UInt8}, b::BitVectorExpr{UInt8}) ``` ## Generating the SMT representation of a problem diff --git a/src/BitVectorExpr.jl b/src/BitVectorExpr.jl index 2ff71bc..f1e3fe9 100644 --- a/src/BitVectorExpr.jl +++ b/src/BitVectorExpr.jl @@ -55,10 +55,14 @@ function BitVectorExpr(name::String, length::Int) end -# Note that we don't have to define == because it's defined for AbstractExpr. - # some utility functions -function nextsize(n::Integer) :: Type # works on BigInt and UInt +"""" + nextsize(n::Integer) + +Returns the smallest unsigned integer type that can store a number with n bits. +If n is larger than the largest available type (`UInt128`), returns type `BigInt`. +""" +function nextsize(n::Integer) # works on BigInt and UInt if sign(n) == -1 @error("Constants must be unsigned or positive BigInts!") end @@ -71,6 +75,11 @@ function nextsize(n::Integer) :: Type # works on BigInt and UInt end end +"""" + bitcount(a::Integer) + +Returns the minimum number of bits required to store the number `a`. +""" function bitcount(a::Integer) # works on BigInt and UInt if a == 0 return 1 @@ -123,9 +132,15 @@ end ##### Integer arithmetic ##### -+(e1::AbstractBitVectorExpr, e2::AbstractBitVectorExpr) = __bvnop(+, :bvadd, BitVectorExpr, [e1, e2], __is_commutative=true, __try_flatten=true) --(e1::AbstractBitVectorExpr, e2::AbstractBitVectorExpr) = __bvnop(-, :bvsub, BitVectorExpr, [e1, e2]) -*(e1::AbstractBitVectorExpr, e2::AbstractBitVectorExpr) = __bvnop(*, :bvmul, BitVectorExpr, [e1, e2],__is_commutative=true, __try_flatten=true) ++(e1::T, e2::T) where T <: AbstractBitVectorExpr = __bvnop(+, :bvadd, BitVectorExpr, [e1, e2], __is_commutative=true, __try_flatten=true) +-(e1::T, e2::T) where T <: AbstractBitVectorExpr = __bvnop(-, :bvsub, BitVectorExpr, [e1, e2]) +*(e1::T, e2::T) where T <: AbstractBitVectorExpr = __bvnop(*, :bvmul, BitVectorExpr, [e1, e2],__is_commutative=true, __try_flatten=true) + +""" + div(a::BitVectorExpr, b::BitVectorExpr) + +Unsigned integer division of two BitVectors. +""" div(e1::AbstractBitVectorExpr, e2::AbstractBitVectorExpr) = __bvnop(div, :bvudiv, BitVectorExpr, [e1, e2]) # unary minus, this is an arithmetic minus not a bit flip. @@ -145,13 +160,48 @@ div(e1::AbstractBitVectorExpr, e2::AbstractBitVectorExpr) = __bvnop(div, :bvudiv __signfix(f::Function) = (a, b) -> unsigned(f(signed(a), signed(b))) # these all have arity 2 -urem(e1::AbstractBitVectorExpr, e2::AbstractBitVectorExpr) = __bvnop(rem, :bvurem, BitVectorExpr, [e1, e2]) -<<(e1::AbstractBitVectorExpr, e2::AbstractBitVectorExpr) = __bvnop(<<, :bvshl, BitVectorExpr, [e1, e2]) # shift left ->>>(e1::AbstractBitVectorExpr, e2::AbstractBitVectorExpr) = __bvnop(>>>, :bvlshr, BitVectorExpr, [e1, e2]) # logical shift right +""" + urem(a::BitVectorExpr, b::BitVectorExpr) + +Unsigned remainder of BitVector a divided by BitVector b. +""" +urem(e1::T, e2::T) where T <: AbstractBitVectorExpr = __bvnop(rem, :bvurem, BitVectorExpr, [e1, e2]) + +""" + a << b + +Logical left shift a << b. +""" +<<(e1::T, e2::T) where T <: AbstractBitVectorExpr = __bvnop(<<, :bvshl, BitVectorExpr, [e1, e2]) # shift left + +""" + a >>> b + +Logical right shift a >>> b. +""" +>>>(e1::T, e2::T) where T <: AbstractBitVectorExpr = __bvnop(>>>, :bvlshr, BitVectorExpr, [e1, e2]) # logical shift right # Extra arithmetic operators supported by Z3 but not part of the SMT-LIB standard. -srem(e1::AbstractBitVectorExpr, e2::AbstractBitVectorExpr) = __bvnop(__signfix(rem), :bvsrem, BitVectorExpr, [e1, e2]) # unique to z3 -smod(e1::AbstractBitVectorExpr, e2::AbstractBitVectorExpr) = __bvnop(__signfix(mod), :bvsmod, BitVectorExpr, [e1, e2]) # unique to z3 + +""" + srem(a::BitVectorExpr, b::BitVectorExpr) + +Signed remainder of BitVector a divided by BitVector b. This operator is not part of the SMT-LIB standard BitVector theory: it is implemented by Z3. It may not be available when using other solvers. +""" +srem(e1::T, e2::T) where T <: AbstractBitVectorExpr = __bvnop(__signfix(rem), :bvsrem, BitVectorExpr, [e1, e2]) # unique to z3 + +""" + smod(a::BitVectorExpr, b::BitVectorExpr) + +Signed modulus of BitVector a divided by BitVector b. This operator is not part of the SMT-LIB standard BitVector theory: it is implemented by Z3. It may not be available when using other solvers. +""" +smod(e1::T, e2::T) where T <: AbstractBitVectorExpr = __bvnop(__signfix(mod), :bvsmod, BitVectorExpr, [e1, e2]) # unique to z3 + +""" + a >> b + +Arithmetic right shift a >> b. This operator is not part of the SMT-LIB standard BitVector theory: it is implemented by Z3. It may not be available when using other solvers. +""" >>(e1::AbstractBitVectorExpr, e2::AbstractBitVectorExpr) = __bvnop(__signfix(>>), :bvashr, BitVectorExpr, [e1, e2]) # arithmetic shift right - unique to Z3 @@ -178,17 +228,44 @@ end and(zs::Vararg{Union{T, Integer}}) where T <: AbstractBitVectorExpr = and(collect(zs)) # We need this declaration to enable the syntax and.([z1, z2,...,zn]) where z1, z2,...,zn are broadcast-compatible +""" + a | b + or(a, b, c...) + +Bitwise or. For n>2 variables, use the or(...) notation. +""" (|)(e1::AbstractBitVectorExpr, e2::AbstractBitVectorExpr) = or([e1, e2]) + +""" + a & b + and(a, b, c...) + +Bitwise and. For n>2 variables, use the and(...) notation. +""" (&)(e1::AbstractBitVectorExpr, e2::AbstractBitVectorExpr) = and([e1, e2]) # Extra logical operators supported by Z3 but not part of the SMT-LIB standard. +""" + nor(a, b) + a ⊽ b + +Bitwise nor. This operator is not part of the SMT-LIB standard BitVector theory: it is implemented by Z3. It may not be available when using other solvers. When using other solvers, write ~(a | b) isntead of nor(a,b). +""" nor(e1::AbstractBitVectorExpr, e2::AbstractBitVectorExpr) = __bvnop((a,b) -> ~(a | b), :bvnor, BitVectorExpr, [e1, e2], __is_commutative=true) ⊽(e1::AbstractBitVectorExpr, e2::AbstractBitVectorExpr) = nor(e1, e2) +""" + nand(a, b) + a ⊼ b + +Bitwise nand. This operator is not part of the SMT-LIB standard BitVector theory: it is implemented by Z3. It may not be available when using other solvers. When using other solvers, write ~(a & b) isntead of nand(a,b). +""" nand(e1::AbstractBitVectorExpr, e2::AbstractBitVectorExpr) = __bvnop((a,b) -> ~(a & b), :bvnand, BitVectorExpr, [e1, e2], __is_commutative=true) ⊼(e1::AbstractBitVectorExpr, e2::AbstractBitVectorExpr) = nand(e1, e2) -# TODO Probably all the "extra" operators should behave like this for constants + +# note that bvxnor is left-accumulating, so bvxnor(a, b, c) = bvxnor(bvxnor(a, b), c) +# bvnor and bvnand have arity 2 xnor(a::T,b::T) where T <: Integer = (a & b) | (~a & ~b) function xnor(es_mixed::Array{T}) where T @@ -203,33 +280,79 @@ function xnor(es_mixed::Array{T}) where T return expr end +""" + xnor(a, b) + xnor(a, b, c...) + +Bitwise xnor. When n>2 operands are provided, xnor is left-associative (that is, `xnor(a, b, c) = reduce(xnor, [a,b,c])`. This operator is not part of the SMT-LIB standard BitVector theory: it is implemented by Z3. It may not be available when using other solvers. When using other solvers, write (a & b) | (~a & ~b). +""" xnor(zs::Vararg{Union{T, Integer}}) where T <: AbstractBitVectorExpr = xnor(collect(zs)) # We need this declaration to enable the syntax and.([z1, z2,...,zn]) where z1, z2,...,zn are broadcast-compatible -# TODO operations with arity n -# note that bvxnor is left-accumulating, so bvxnor(a, b, c) = bvxnor(bvxnor(a, b), c) -# bvnor and bvnand have arity 2 +""" + ~a +Bitwise not. +""" ~(e::BitVectorExpr) = __bv1op(e, ~, :bvnot) ##### Bitwise predicates ##### -<(e1::AbstractBitVectorExpr, e2::AbstractBitVectorExpr) = __bvnop(>, :bvult, BoolExpr, [e1, e2]) -<=(e1::AbstractBitVectorExpr, e2::AbstractBitVectorExpr) = __bvnop(>=, :bvule, BoolExpr, [e1, e2]) +<(e1::T, e2::T) where T <: AbstractBitVectorExpr = __bvnop(>, :bvult, BoolExpr, [e1, e2]) +<=(e1::T, e2::T) where T <: AbstractBitVectorExpr = __bvnop(>=, :bvule, BoolExpr, [e1, e2]) >(e1::AbstractBitVectorExpr, e2::AbstractBitVectorExpr) = __bvnop(>, :bvugt, BoolExpr, [e1, e2]) >=(e1::AbstractBitVectorExpr, e2::AbstractBitVectorExpr) = __bvnop(>=, :bvuge, BoolExpr, [e1, e2]) (==)(e1::AbstractBitVectorExpr, e2::AbstractBitVectorExpr) = __bvnop((==), :eq, BoolExpr, [e1, e2]) # Signed comparisons are supported by Z3 but not part of the SMT-LIB standard. +"""" + slt(a::BitVectorExpr, b::BitVectorExpr) + +Signed less-than. This is not the same as a < b (unsigned BitVectorExpr comparison). This operator is not part of the SMT-LIB standard BitVector theory: it is implemented by Z3. It may not be available when using other solvers. +""" slt(e1::AbstractBitVectorExpr, e2::AbstractBitVectorExpr) = __bvnop(__signfix(>), :bvslt, BoolExpr, [e1, e2]) + +""" + sle(a::BitVectorExpr, b::BitVectorExpr) + +Signed less-than-or-equal. This is not the same as a <+ b (unsigned BitVectorExpr comparison). This operator is not part of the SMT-LIB standard BitVector theory: it is implemented by Z3. It may not be available when using other solvers. +""" sle(e1::AbstractBitVectorExpr, e2::AbstractBitVectorExpr) = __bvnop(__signfix(>=), :bvsle, BoolExpr, [e1, e2]) + +""" + sgt(a::BitVectorExpr, b::BitVectorExpr) + +Signed greater-than. This is not the same as a > b (unsigned BitVectorExpr comparison). This operator is not part of the SMT-LIB standard BitVector theory: it is implemented by Z3. It may not be available when using other solvers. +""" sgt(e1::AbstractBitVectorExpr, e2::AbstractBitVectorExpr) = __bvnop(__signfix(>), :bvsgt, BoolExpr, [e1, e2]) + +""" + sge(a::BitVectorExpr, b::BitVectorExpr) + +Signed greater-than-or-equal. This is not the same as a >= b (unsigned BitVectorExpr comparison). This operator is not part of the SMT-LIB standard BitVector theory: it is implemented by Z3. It may not be available when using other solvers. +""" sge(e1::AbstractBitVectorExpr, e2::AbstractBitVectorExpr) = __bvnop(__signfix(>=), :bvsge, BoolExpr, [e1, e2]) ##### Word-level operations ##### # concat and extract are the only SMT-LIB standard operations # z3 adds some more, note that concat can accept constants and has arity n >= 2 +""" + concat(a, b) + concat(a, bvconst(0xffff, 16), b, bvconst(0x01, 8), ...) + concat(bvconst(0x01, 8), bvconst(0x02, 12)...) + +Concatenate BitVectorExprs and constants of varying sizes. To guarantee a constant is the correct bit size, it should be wrapped using bvconst - otherwise its size will be inferred using `bitcount`. + +concat(a,b) returns a BitVector with size a.length + b.length. + +Arguments are concatenated such that the first argument to concat corresponds to the most significant bits of the resulting value. Thus: +```julia + expr = concat(bvconst(0x01, 8), bvconst(0x02, 8), bvconst(0x03, 4)) + println(expr.length) # 20 + println(expr.value) # 0x01023 +``` +""" function concat(es_mixed::Vararg{Any}) es_mixed = collect(es_mixed) vars, consts = __check_inputs_nary_op(es_mixed, const_type=Integer, expr_type=BitVectorExpr) @@ -276,6 +399,13 @@ end Base.getindex(e::AbstractBitVectorExpr, ind_1::Int64, ind_2::Int64) = getindex(e, UnitRange(ind_1, ind_2)) Base.getindex(e::AbstractBitVectorExpr, ind::Int64) = getindex(e, ind, ind) +""" + @satvariable(a, BitVector, 8) + a[4:8] # has length 5 + a[3] + +Slice or index into a BitVector, returning a new BitVector with the appropriate length. This corresponds to the SMT-LIB operation `extract`. +""" function Base.getindex(e::AbstractBitVectorExpr, ind::UnitRange{Int64}) if first(ind) > last(ind) || first(ind) < 1 || last(ind) > e.length error("Cannot extract sequence $ind from BitVector!") @@ -292,8 +422,21 @@ end ##### Translation to/from integer ##### # Be aware these have high overhead +""" + @satvariable(b, BitVector, 8) + a = bv2int(b) + +Wrap BitVectorExpr b, representing a conversion to IntExpr. The value of the integer expression will be limited by the size of the wrapped BitVector. This operation has high overhead and may impact solver performance. +""" bv2int(e::AbstractBitVectorExpr) = IntExpr(:bv2int, [e,], isnothing(e.value) ? nothing : Int(e.value), __get_hash_name(:bv2int, [e.name])) +""" + @satvariable(a, Int) + b = int2bv(a, 8) + +Wrap IntExpr a, representing a conversion to a BitVector of specified length. This operation has high overhead and may impact solver performance. + +""" function int2bv(e::IntExpr, size::Int) name = __get_hash_name(:int2bv, [e.name]) expr = BitVectorExpr{nextsize(size)}(:int2bv, [e], isnothing(e.value) ? nothing : unsigned(e.value), name, size) @@ -310,6 +453,17 @@ end # size must be the SMT-LIB bitvector length, for example if you have a bitvector of length 12 pass in 12 NOT 16 # this function returns c of the correct Unsigned type to interoperate with the bitvector.value # which is the smallest Unsigned type that fits the SMT-LIB bitvector length. +""" + bvconst(0x01, 32) + bvconst(2, 8) + +Wraps a nonnegative integer constant for interoperability with BitVectorExprs. While the correct size of a BitVector constant can usually be inferred (for example, if `a` is a BitVector of length 16, the constant in `a + 0x0f` can also be wrapped to length 16), in a few cases it cannot. + +Specifically, when concatenating BitVectorExprs and constants, one should wrap the constants in `bvconst` to ensure their size matches your expectations. + +`bvconst` will pad constants to the requested size, but will not truncate constants. For example, `bvconst(0xffff, 12)` yields an error because `0xffff`` requires 16 bits. + +""" function bvconst(c::Integer, size::Int) if c < 0 error("Cannot combine negative integer constant $c with BitVector") diff --git a/src/BooleanSatisfiability.jl b/src/BooleanSatisfiability.jl index 7d28914..a729609 100644 --- a/src/BooleanSatisfiability.jl +++ b/src/BooleanSatisfiability.jl @@ -5,6 +5,7 @@ export AbstractExpr, IntExpr, @satvariable, RealExpr, + AbstractBitVectorExpr, BitVectorExpr, isequal, hash, # required by isequal (?) diff --git a/src/smt_macros.jl b/src/smt_macros.jl index f3c2dae..9196d08 100644 --- a/src/smt_macros.jl +++ b/src/smt_macros.jl @@ -3,10 +3,12 @@ __valid_vartypes = [:Bool, :Int, :Real, :BitVector, :FloatingPoint, :String, :Ar """ @satvariable(z, Bool) @satvariable(a[1:n], Int) + @satvariable(b, BitVector 32) -Construct a SAT variable with name z, optional array dimensions, and specified type (`Bool`, `Int` or `Real`). +Construct a SAT variable with name z, optional array dimensions, and specified type (`Bool`, `Int`, `Real` or `BitVector`). +Note that some require an optional third parameter. -One and two-dimensional variables can be constructed with the following syntax. +One and two-dimensional arrays of variables can be constructed with the following syntax. The result will be a native Julia array. ```julia @satvariable(a[1:n], Int) # an Int vector of length n @satvariable(x[1:m, 1:n], Real) # an m x n Int matrix diff --git a/test/runtests.jl b/test/runtests.jl index 8eab829..b8ff95f 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -10,7 +10,7 @@ include("boolean_operation_tests.jl") # Constructiong Int and Real exprs include("int_real_tests.jl") -# Generating SMT expressions +# Generating SMT expressionsexit() include("smt_representation_tests.jl") # Calling Z3 and interpreting the result From b0222f97f2c523d1d45c827915e28595a83bf83d Mon Sep 17 00:00:00 2001 From: Emiko Soroka Date: Tue, 15 Aug 2023 16:55:26 -0700 Subject: [PATCH 33/36] Finished documenting and cleaning up BitVector example, that means all BitVector docs are DONE. --- docs/make.jl | 3 ++- docs/src/example_bv_lcg.md | 48 ++++++++++++++++++++++++++++++++++++++ docs/src/tutorial.md | 16 +++++++++++++ examples/bv_lcg.jl | 15 +++++++++--- 4 files changed, 78 insertions(+), 4 deletions(-) create mode 100644 docs/src/example_bv_lcg.md diff --git a/docs/make.jl b/docs/make.jl index a721475..0efa0b9 100644 --- a/docs/make.jl +++ b/docs/make.jl @@ -20,7 +20,8 @@ pages = [ "faq.md", "Examples" => [ "example_scheduling.md", - "example_job_shop.md" + "example_job_shop.md", + "example_bv_lcg.md", ], "Library" => [ "functions.md" diff --git a/docs/src/example_bv_lcg.md b/docs/src/example_bv_lcg.md new file mode 100644 index 0000000..6de7616 --- /dev/null +++ b/docs/src/example_bv_lcg.md @@ -0,0 +1,48 @@ +# Predicting the output of a tiny LCG +This example is "3.10.1 Cracking LCG with Z3" from *[SAT/SMT by Example](https://sat-smt.codes/SAT_SMT_by_example.pdf)* by Dennis Yurichev. + +A linear congruential generator (LCG) is an algorithm for generating pseudo-random numbers in which a series of transformations is used to move from one number to the next. LCGs are easy to implement using low-level bit operations, making them popular for resource-constrained embedded applications. However, they are unsuitable for many applications because their output is predictable. + +*SAT/SMT by Example*, example 3.10.1 shows how to predict the future output of an LCG by encoding its transformations. The original example starts with a small C program that prints the output of `rand() % 100` 10 times, producing 10 2 digit random numbers. It turns out C's rand() has this LCG implementation: + +1. `state = state * 214013 + 2531011` +2. `state = (state >> 16) & 0x7FFF` +3. `return state` + +Suppose we observe 10 states `n1,...,n10 = [37, 29, 74, 95, 98, 40, 23, 58, 61, 17]` from the LCG. We want to predict `n0`, the number before `n1`, and `n11`, the number after `n10`. (These are the numbers from *SAT/SMT by Example*.) + +```@example +using BooleanSatisfiability + +@satvariable(states[1:10], BitVector, 32) +@satvariable(output_prev, BitVector, 32) +@satvariable(output_next, BitVector, 32) +``` +```@example +transitions = BoolExpr[states[i+1] == states[i] * 214013+2531011 for i=1:9] +remainders = BoolExpr[ + output_prev == urem(( states[1] >> 16 ) & 0x7FFF, 100), + urem(( states[2] >> 16) & 0x7FFF, 100) == 29, + urem(( states[3] >> 16) & 0x7FFF, 100) == 74, + urem(( states[4] >> 16) & 0x7FFF, 100) == 95, + urem(( states[5] >> 16) & 0x7FFF, 100) == 98, + urem(( states[6] >> 16) & 0x7FFF, 100) == 40, + urem(( states[7] >> 16) & 0x7FFF, 100) == 23, + urem(( states[8] >> 16) & 0x7FFF, 100) == 58, + urem(( states[9] >> 16) & 0x7FFF, 100) == 61, + output_next == urem(( states[10] >> 16) & 0x7FFF, 100), +] +``` +```@example +expr = and(all(transitions), all(remainders)) +status = sat!(expr, solver=CVC5()) +println("status = $status") + +for (i,state) in enumerate(states) + println("state $i = $(value(state))") +end + +# According to SAT/SMT By Example the previous output is 37 and the next output is 17. +println("prev = $(value(output_prev))") +println("next = $(value(output_next))") +``` diff --git a/docs/src/tutorial.md b/docs/src/tutorial.md index a29312d..ea943e9 100644 --- a/docs/src/tutorial.md +++ b/docs/src/tutorial.md @@ -14,6 +14,7 @@ One famous transformation is De Morgan's law: `a ∧ b = ¬(¬a ∨ ¬b)`. To sh conjecture = iff(a ∧ b, ¬(¬a ∨ ¬b)) status = sat!(¬conjecture, Z3()) # status will be either :SAT or :UNSAT ``` + ## A common logical mistake Suppose you have Boolean variables `p`, `q` and `r`. A common mistake made by students in discrete math classes is to think that if `p` implies `q` and `q` implies `r` (`(p ⟹ q) ∧ (q ⟹ r)`) then `p` must imply `r` (`p ⟹ r`). Are these statements equivalent? We can use a SAT solver to check. @@ -48,4 +49,19 @@ println("Result: $(value(a))") println("Check: $(sum(value(a) .* c))") ``` +## Proving properties of fixed-size integer arithmetic +This example is from Microsoft's [Z3 tutorial](https://microsoft.github.io/z3guide/docs/theories/Bitvectors/). +A bitvector `x` is a power of two (or zero) if and only if `x & (x - 1)` is zero, where & is bitwise and. We prove this property for an 8-bit vector. + +```@example +println("Example 1 (should be SAT)") +@satvariable(b, BitVector, 8) +is_power_of_two = b & (b - 0x01) == 0 +# iff is_power_of_two holds, b must be one of 1, 2, 4, ... 128 +expr = iff(is_power_of_two, + any([b == 2^i for i=0:7])) +status = sat!(expr) +#println(smt(expr)) +println(status) # if status is SAT we proved it. +``` diff --git a/examples/bv_lcg.jl b/examples/bv_lcg.jl index c90c0de..fe3e0e3 100644 --- a/examples/bv_lcg.jl +++ b/examples/bv_lcg.jl @@ -1,10 +1,19 @@ # This example is from "SAT/SMT by Example" by Dennis Yurichev. It is example 3.10.1 Cracking LCG with Z3. -# LCG is a crummy kind of random number generator. We will show a small implementation of LCG is predictable. +# A linear congruential generator (LCG) is an algorithm for generating pseudo-random numbers. A series of transformations is used to move from one number to the next +# LCGs are simple to implement using low-level bit operations. In SAT/SMT by example, +# Mr. Yurichev dumps the assmbly code for a small loop that prints `rand() % 100` (in C) 10 times. +# He finds the following LCG code: -# TODO clean up this example +# 1. `tmp := state * 214013 + 2531011` +# 2. `state = tmp` +# 3. `(state >> 16) & 0x7FFF` +# 4. `return state` -# In this example we observe 10 states n1,...,n10 from the LCG. +# Now suppose we observe 10 states n1,...,n10 = [37, 29, 74, 95, 98, 40, 23, 58, 61, 17] from the LCG. # We want to predict n0, the number before n1, and n11, the number after n10. +# The following code does exactly that. +using BooleanSatisfiability + @satvariable(states[1:10], BitVector, 32) @satvariable(output_prev, BitVector, 32) @satvariable(output_next, BitVector, 32) From 73ddfcc61c504364b3000cf1ed0f49c677a889c7 Mon Sep 17 00:00:00 2001 From: Emiko Soroka Date: Tue, 15 Aug 2023 18:12:16 -0700 Subject: [PATCH 34/36] README update. --- README.md | 34 +++++++++++++++++++--------------- 1 file changed, 19 insertions(+), 15 deletions(-) diff --git a/README.md b/README.md index 21d7fe4..e74e0db 100644 --- a/README.md +++ b/README.md @@ -2,31 +2,35 @@ [![build status](https://github.com/elsoroka/BooleanSatisfiability.jl/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/elsoroka/BooleanSatisfiability.jl/actions/workflows/CI.yml?query=branch%3Amain) [![docs](https://github.com/elsoroka/BooleanSatisfiability.jl/actions/workflows/docs.yml/badge.svg)](https://elsoroka.github.io/BooleanSatisfiability.jl/) [![codecov](https://codecov.io/gh/elsoroka/BooleanSatisfiability.jl/branch/main/graph/badge.svg?token=84BIREQL46)](https://codecov.io/gh/elsoroka/BooleanSatisfiability.jl) -BooleanSatisfiability.jl is a package for representing Boolean satisfiability (SAT) and selected other satisfiability modulo theories (SMT) problems in Julia. This package provides a simple front-end interface to common SMT solvers, including full support for vector-valued and matrix-valued expressions. +BooleanSatisfiability.jl is a package for representing satisfiability modulo theories (SMT) problems in Julia. This package provides a simple front-end interface to common SMT solvers, including full support for vector-valued and matrix-valued expressions. Currently, the theories of propositional logic, Integers, Reals and fixed-size BitVectors are supported. We will eventually add support for all [SMT-LIB standard theories](http://smtlib.cs.uiowa.edu/theories.shtml). -* Easily specify single-valued or vector-valued Boolean SAT, integer or real-valued SMT problems using Julia's built-in broadcasting capabilities. -* Generate files in [SMT2](http://www.smtlib.org/) format. -* BooleanSatisfiability.jl calls [Z3](https://www.microsoft.com/en-us/research/publication/z3-an-efficient-smt-solver/) as the back-end solver and interprets the result. +What you can do with this package: +* Easily specify single-valued or vector-valued SMT expressions using Julia's built-in broadcasting capabilities. +* Generate files in the [SMT-LIB](http://www.smtlib.org/) specification language. +* Interact with any solver that follows the SMT-LIB standard. -## Example - -Solving the single-valued problem **(x ∧ y) ∨ (¬x ∧ y)** -``` -x = Bool("x") -y = Bool("y") -expr = (x ∧ y) ∨ (¬x ∧ y) -status = sat!(expr) -println("x = $(value(x)), y = $(value(y))”) -``` +## Examples Solving the vector-valued problem **(x1 ∧ y1) ∨ (¬x1 ∧ y1) ∧ ... ∧ (xn ∧ yn) ∨ (¬xn ∧ yn)** ``` x = Bool(n, "x") y = Bool(n, "y") expr = (x .∧ y) .∨ (¬x .∧ y) -status = sat!(expr) +status = sat!(expr, solver=Z3()) println("x = $(value(x)), y = $(value(y))”) ``` +Proving a bitwise version of de Morgan's law. +In this example we want to show there is NO possible value of x and y such that de Morgan's bitwise law doesn't hold. +``` +@satvariable(x, BitVector, 64) +@satvariable(y, BitVector, 64) + +expr = not((~x & ~y) == ~(x | y)) + +status = sat!(expr, solver=Z3()) +println(status) # if status is UNSAT we proved it. +``` + ## Development status Working on a first release! Follow for updates. From fc7c89b50678cad191a60c70c6dd9108799f9739 Mon Sep 17 00:00:00 2001 From: Emiko Soroka Date: Tue, 15 Aug 2023 23:26:05 -0700 Subject: [PATCH 35/36] fixed one issue that caused the test to fail on Julia 1.9 --- examples/bv_mini.jl | 3 +-- src/BitVectorExpr.jl | 2 +- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/examples/bv_mini.jl b/examples/bv_mini.jl index 2c32585..35d79a5 100644 --- a/examples/bv_mini.jl +++ b/examples/bv_mini.jl @@ -25,7 +25,6 @@ println("Example 2 (should be UNSAT)") @satvariable(y, BitVector, 64) expr = not((~x & ~y) == ~(x | y)) -status = sat!(expr) -println(smt(expr)) +status = sat!(expr) println(status) # if status is UNSAT we proved it. diff --git a/src/BitVectorExpr.jl b/src/BitVectorExpr.jl index f1e3fe9..6f06165 100644 --- a/src/BitVectorExpr.jl +++ b/src/BitVectorExpr.jl @@ -1,5 +1,5 @@ import Base.getindex, Base.setproperty! -import Base.+, Base.-, Base.*, Base.<<, Base.>>, Base.>>>, Base.div, Base.&, Base.|, Base.~ +import Base.+, Base.-, Base.*, Base.<<, Base.>>, Base.>>>, Base.div, Base.&, Base.|, Base.~, Base.nor, Base.nand import Base.>, Base.>=, Base.<, Base.<=, Base.== # >>> is arithmetic shift right, corresponding to bvashr in SMT-LIB # >> is logical shift right, bvlshr in SMT-LIB From adc3c5ba0df7b0b0fd8f79b57ffff1d066ac3596 Mon Sep 17 00:00:00 2001 From: Emiko Soroka Date: Wed, 16 Aug 2023 00:26:51 -0700 Subject: [PATCH 36/36] Improved code coverage and final changes to README. --- README.md | 5 ++-- src/BitVectorExpr.jl | 8 +++--- src/BooleanOperations.jl | 42 ++++++-------------------------- src/BooleanSatisfiability.jl | 2 +- src/IntExpr.jl | 4 +-- src/smt_representation.jl | 2 +- src/utilities.jl | 2 +- test/bitvector_tests.jl | 25 ++++++++++--------- test/boolean_operation_tests.jl | 31 +++++++++++++---------- test/int_parse_tests.jl | 8 +++--- test/int_real_tests.jl | 9 ++++--- test/runtests.jl | 1 + test/smt_representation_tests.jl | 27 +++++++------------- test/solver_interface_tests.jl | 3 +++ 14 files changed, 75 insertions(+), 94 deletions(-) diff --git a/README.md b/README.md index e74e0db..e3b8876 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,8 @@ What you can do with this package: ## Examples -Solving the vector-valued problem **(x1 ∧ y1) ∨ (¬x1 ∧ y1) ∧ ... ∧ (xn ∧ yn) ∨ (¬xn ∧ yn)** +### Solving the vector-valued problem +(x1 ∧ y1) ∨ (¬x1 ∧ y1) ∧ ... ∧ (xn ∧ yn) ∨ (¬xn ∧ yn) ``` x = Bool(n, "x") y = Bool(n, "y") @@ -20,7 +21,7 @@ status = sat!(expr, solver=Z3()) println("x = $(value(x)), y = $(value(y))”) ``` -Proving a bitwise version of de Morgan's law. +### Proving a bitwise version of de Morgan's law. In this example we want to show there is NO possible value of x and y such that de Morgan's bitwise law doesn't hold. ``` @satvariable(x, BitVector, 64) diff --git a/src/BitVectorExpr.jl b/src/BitVectorExpr.jl index 6f06165..72a22d0 100644 --- a/src/BitVectorExpr.jl +++ b/src/BitVectorExpr.jl @@ -125,7 +125,7 @@ function __bv1op(e::AbstractBitVectorExpr, op::Function, opname::Symbol, l=nothi mask = typemax(valtype) >> (8*sizeof(valtype) - e.length) value = valtype(op(e.value) & mask) end - name = __get_hash_name(opname, [e.name,]) + name = __get_hash_name(opname, [e,]) return BitVectorExpr{nextsize(e.length)}(opname, [e,], value, name, l) end @@ -371,7 +371,7 @@ function concat(es_mixed::Vararg{Any}) values = getproperty.(es, :value) value = any(isnothing.(values)) ? nothing : __concat(values, lengths, ReturnType) - name = __get_hash_name(:concat, collect(getproperty.(es, :name))) + name = __get_hash_name(:concat, es) return BitVectorExpr{ReturnType}(:concat, collect(es), value, name, l) end @@ -428,7 +428,7 @@ end Wrap BitVectorExpr b, representing a conversion to IntExpr. The value of the integer expression will be limited by the size of the wrapped BitVector. This operation has high overhead and may impact solver performance. """ -bv2int(e::AbstractBitVectorExpr) = IntExpr(:bv2int, [e,], isnothing(e.value) ? nothing : Int(e.value), __get_hash_name(:bv2int, [e.name])) +bv2int(e::AbstractBitVectorExpr) = IntExpr(:bv2int, [e,], isnothing(e.value) ? nothing : Int(e.value), __get_hash_name(:bv2int, [e])) """ @satvariable(a, Int) @@ -438,7 +438,7 @@ Wrap IntExpr a, representing a conversion to a BitVector of specified length. Th """ function int2bv(e::IntExpr, size::Int) - name = __get_hash_name(:int2bv, [e.name]) + name = __get_hash_name(:int2bv, [e]) expr = BitVectorExpr{nextsize(size)}(:int2bv, [e], isnothing(e.value) ? nothing : unsigned(e.value), name, size) return expr end diff --git a/src/BooleanOperations.jl b/src/BooleanOperations.jl index b3f6ecc..53b4000 100644 --- a/src/BooleanOperations.jl +++ b/src/BooleanOperations.jl @@ -5,48 +5,22 @@ include("utilities.jl") ##### NAMING COMBINED BOOLEXPRS ##### -"Given an array of named BoolExprs with indices, returns the name stem with no indices. -Example: array with names z_1_1,...,z_m_n returns string z" -function __get_name_stem(zs::Array{T}) where T <: AbstractExpr - if length(size(zs)) == 1 - return zs[1].name[1:end-2] # since the name here will be name_1 - elseif length(size(zs)) == 2 - return zs[1].name[1:end-4] - else - error("Array of size $(size(zs)) not supported.") - end -end - "Given an array of named BoolExprs, returns a combined name for use when naming exprs that have multiple children. Example: array with names z_1_1,...,z_m_n returns string z_1_1...z_m_n if m*n>max_items. If m*n <= max_items, all names are listed." -function __get_combined_name(zs::Array{T}; max_items=3) where T <: AbstractExpr - names = sort(vec(getproperty.(zs, :name))) - if length(names) > max_items - return "$(names[1])_to_$(names[end])" +function __get_combined_name(zs::Array{T}; is_commutative=false) where T <: AbstractExpr + if is_commutative + names = sort(vec(getproperty.(zs, :name))) else - return join(names, "__") + names = vec(getproperty.(zs, :name)) end + return join(names, "__") end -function __get_hash_name(op::Symbol, zs::Array{T}) where T <: AbstractExpr - combined_name = __get_combined_name(zs, max_items=Inf) +function __get_hash_name(op::Symbol, zs::Array{T}; is_commutative=false) where T <: AbstractExpr + combined_name = __get_combined_name(zs, is_commutative=is_commutative)# TODO should sort when op is commutative return "$(op)_$(string(hash(combined_name), base=16))" end -# new version - switch to this -function __get_combined_name(names::Array{String}; max_items=3) - names = sort(vec(names)) - if length(names) > max_items - return "$(names[1])_to_$(names[end])" - else - return join(names, "__") - end -end - -function __get_hash_name(op::Symbol, names::Array{String}) - combined_name = __get_combined_name(names, max_items=Inf) - return "$(op)_$(string(hash(combined_name), base=16))" -end # combine children for Boolean n-ary ops function __bool_nary_op(zs::Array{T}, op::Symbol, ReturnType::Type, __is_commutative=false, __try_flatten=false) where T <: BoolExpr @@ -56,7 +30,7 @@ function __bool_nary_op(zs::Array{T}, op::Symbol, ReturnType::Type, __is_commuta children, name = __combine(zs, op, __is_commutative, __try_flatten) if __is_commutative && length(children)>1 # clear duplicates children = unique(children) - name = __get_hash_name(op, children) + name = __get_hash_name(op, children, is_commutative=__is_commutative) end # TODO here we should compute the value return ReturnType(op, children, nothing, name, __is_commutative=__is_commutative) diff --git a/src/BooleanSatisfiability.jl b/src/BooleanSatisfiability.jl index a729609..dcb023c 100644 --- a/src/BooleanSatisfiability.jl +++ b/src/BooleanSatisfiability.jl @@ -89,7 +89,7 @@ __EXPR_TYPES = [BoolExpr, RealExpr, IntExpr, BitVectorExpr] # Track the user-declared BoolExpr names so the user doesn't make duplicates. # This will NOT contain hash names. If the user declares x = Bool("x"); y = Bool("y"); xy = and(x,y) -# GLOBAL_VARNAMES will contain "x" and "y", but not __get_hash_name(:AND, [x,y]). +# GLOBAL_VARNAMES will contain "x" and "y", but not __get_hash_name(:AND, [x,y], is_commutative=true). global GLOBAL_VARNAMES = Dict(t => String[] for t in __EXPR_TYPES) # When false, no warnings will be issued global WARN_DUPLICATE_NAMES = false diff --git a/src/IntExpr.jl b/src/IntExpr.jl index 7f6e43b..eb04941 100644 --- a/src/IntExpr.jl +++ b/src/IntExpr.jl @@ -183,7 +183,7 @@ a .== b """ function Base.:(==)(e1::NumericInteroperableExpr, e2::NumericInteroperableExpr) value = isnothing(e1.value) || isnothing(e2.value) ? nothing : e1.value == e2.value - name = __get_hash_name(:eq, [e1, e2]) + name = __get_hash_name(:eq, [e1, e2], is_commutative=true) return BoolExpr(:eq, [e1, e2], value, name, __is_commutative=true) end @@ -262,7 +262,7 @@ function __numeric_n_ary_op(es_mixed::Array, op::Symbol; __is_commutative=false, # TO clean up, we should merge the CONST exprs if __is_commutative __merge_const!(children) - name = __get_hash_name(op, children) + name = __get_hash_name(op, children, is_commutative=__is_commutative) end # TODO should call a function indexed by op value = any(isnothing.(getproperty.(es, :value))) ? nothing : sum(getproperty.(es, :value)) diff --git a/src/smt_representation.jl b/src/smt_representation.jl index 01836fd..5c88d7e 100644 --- a/src/smt_representation.jl +++ b/src/smt_representation.jl @@ -127,7 +127,7 @@ function __define_n_op!(z::T, cache::Dict{UInt64, String}, depth::Int; assert=tr #if length(children) == 1 # return assert && depth == 0 ? "(assert ($(children[1].name)))$line_ending" : "" #else - fname = __get_hash_name(z.op, children) + fname = __get_hash_name(z.op, children, is_commutative=z.__is_commutative) # if the expr is a :const it will have a value (e.g. 2 or 1.5), otherwise use its name # This yields a list like String["z_1", "z_2", "1"]. varnames = __get_smt_name.(children) diff --git a/src/utilities.jl b/src/utilities.jl index ebb5f36..68246f5 100644 --- a/src/utilities.jl +++ b/src/utilities.jl @@ -49,7 +49,7 @@ function __combine(zs::Array{T}, op::Symbol, __is_commutative=false, __try_flatt if __is_commutative children = sort(children, by=(c) -> c.name) end - name = __get_hash_name(op, children) + name = __get_hash_name(op, children, is_commutative=__is_commutative) return children, name end diff --git a/test/bitvector_tests.jl b/test/bitvector_tests.jl index 631d0f5..59c01f9 100644 --- a/test/bitvector_tests.jl +++ b/test/bitvector_tests.jl @@ -15,6 +15,9 @@ CLEAR_VARNAMES!() @satvariable(b, BitVector, 16) @satvariable(c, BitVector, 12) @satvariable(d, BitVector, 4) + # can make vectors + @satvariable(bv[1:2], BitVector, 4) + @satvariable(cv[1:2, 1:2], BitVector, 4) # unary minus @test (-d).op == :bvneg @@ -26,8 +29,8 @@ CLEAR_VARNAMES!() end # three special cases! the native Julia bitwise ops have weird forms (&)(a,b) because they are short circuitable - @test isequal(a & b, BitVectorExpr{UInt16}(:bvand, [a,b], nothing, BooleanSatisfiability.__get_hash_name(:bvand, [a,b]), 16)) - @test isequal(a | b, BitVectorExpr{UInt16}(:bvor, [a,b], nothing, BooleanSatisfiability.__get_hash_name(:bvor, [a,b]), 16)) + @test isequal(a & b, BitVectorExpr{UInt16}(:bvand, [a,b], nothing, BooleanSatisfiability.__get_hash_name(:bvand, [a,b], is_commutative=true), 16)) + @test isequal(a | b, BitVectorExpr{UInt16}(:bvor, [a,b], nothing, BooleanSatisfiability.__get_hash_name(:bvor, [a,b], is_commutative=true), 16)) @test isequal(~a, BitVectorExpr{UInt16}(:bvnot, [a], nothing, BooleanSatisfiability.__get_hash_name(:bvnot, [a]), 16)) # n-ary ops @@ -57,9 +60,9 @@ CLEAR_VARNAMES!() @test_throws ErrorException a[15:30] # bv2int and int2bv - @test isequal(bv2int(a), IntExpr(:bv2int, [a], nothing, BooleanSatisfiability.__get_hash_name(:bv2int, [a.name]))) + @test isequal(bv2int(a), IntExpr(:bv2int, [a], nothing, BooleanSatisfiability.__get_hash_name(:bv2int, [a]))) @satvariable(e, Int) - @test isequal(int2bv(e, 32), BitVectorExpr{UInt32}(:int2bv, [e], nothing, BooleanSatisfiability.__get_hash_name(:int2bv, [e.name]), 32)) + @test isequal(int2bv(e, 32), BitVectorExpr{UInt32}(:int2bv, [e], nothing, BooleanSatisfiability.__get_hash_name(:int2bv, [e]), 32)) end @testset "Interoperability with constants" begin @@ -89,19 +92,19 @@ end @test smt(concat(a, b, a), assert=false) == "(declare-const a (_ BitVec 8)) (declare-const b (_ BitVec 8)) -(define-fun concat_aaa580f0c8a73d2a () (_ BitVec 24) (concat a b a))\n" +(define-fun concat_17d687cb15cd0d00 () (_ BitVec 24) (concat a b a))\n" @test smt((a + b) << 0x2, assert=false) == "(declare-const a (_ BitVec 8)) (declare-const b (_ BitVec 8)) (define-fun bvadd_e2cecf976dd1f170 () (_ BitVec 8) (bvadd a b)) (define-fun bvshl_e76bba3dcff1a5b9 () (_ BitVec 8) (bvshl bvadd_e2cecf976dd1f170 #x02))\n" @test smt(0xff >= b) == "(declare-const b (_ BitVec 8)) -(define-fun bvuge_5f6f17cc7a31ab62 () Bool (bvuge #xff b)) -(assert bvuge_5f6f17cc7a31ab62)\n" +(define-fun bvuge_7d54a0b390b2b8bc () Bool (bvuge #xff b)) +(assert bvuge_7d54a0b390b2b8bc)\n" @test smt(0xff == a) == "(declare-const a (_ BitVec 8)) -(define-fun eq_e7731db51d241c94 () Bool (= #xff a)) -(assert eq_e7731db51d241c94)\n" +(define-fun eq_51725a0a6dd23455 () Bool (= #xff a)) +(assert eq_51725a0a6dd23455)\n" end @@ -120,8 +123,8 @@ end @test smt(a[1:8] == 0xff) == "(declare-const a (_ BitVec 8)) (define-fun extract_fa232f94411b00cd () (_ BitVec 8) ((_ extract 7 0) a)) -(define-fun eq_209f324f32b93226 () Bool (= extract_fa232f94411b00cd #xff)) -(assert eq_209f324f32b93226)\n" +(define-fun eq_43f451e68918e86b () Bool (= extract_fa232f94411b00cd #xff)) +(assert eq_43f451e68918e86b)\n" end @testset "BitVector result parsing" begin diff --git a/test/boolean_operation_tests.jl b/test/boolean_operation_tests.jl index d74dcf6..c69a97b 100644 --- a/test/boolean_operation_tests.jl +++ b/test/boolean_operation_tests.jl @@ -4,7 +4,8 @@ using Test @testset "Construct variables" begin # Write your tests here. @satvariable(z1, Bool) - @test isa(z1,BoolExpr) + @test size(z1) == 1 + @test_throws UndefVarError @satvariable(x, faketype) @satvariable(z32[1:3, 1:2], Bool) @test isa(z32,Array{BoolExpr}) @@ -32,6 +33,10 @@ using Test # Nested wrong sizes also aren't broadcastable @test_throws DimensionMismatch (z1.∨z23) .∨ z32 + + # printing works + @satvariable(z, Bool) + @test string(not(z)) == "not_25ec308d1df79cdc\n | z\n" end @testset "Print variables" begin @@ -55,22 +60,22 @@ end # Can construct with 2 exprs @test BooleanSatisfiability.__is_permutation((z1 .∧ z32)[1].children, [z1[1], z32[1]] ) - @test (z1 .∧ z32)[1].name == BooleanSatisfiability.__get_hash_name(:and, [z1[1], z32[1]]) + @test (z1 .∧ z32)[1].name == BooleanSatisfiability.__get_hash_name(:and, [z1[1], z32[1]], is_commutative=true) @test BooleanSatisfiability.__is_permutation((z1 .∨ z32)[2,1].children, [z1[1], z32[2,1]] ) - @test (z1 .∨ z32)[1].name == BooleanSatisfiability.__get_hash_name(:or, [z1[1], z32[1]]) + @test (z1 .∨ z32)[1].name == BooleanSatisfiability.__get_hash_name(:or, [z1[1], z32[1]], is_commutative=true) # Can construct with N>2 exprs or_N = or.(z1, z12, z32) and_N = and.(z1, z12, z32) @test BooleanSatisfiability.__is_permutation(or_N[3,2].children, [z1[1], z12[1,2], z32[3,2]] ) - @test and_N[1].name == BooleanSatisfiability.__get_hash_name(:and, and_N[1].children) + @test and_N[1].name == BooleanSatisfiability.__get_hash_name(:and, and_N[1].children, is_commutative=true) @test BooleanSatisfiability.__is_permutation(or_N[1].children, [z1[1], z12[1], z32[1]] ) - @test or_N[1].name == BooleanSatisfiability.__get_hash_name(:or, and_N[1].children) + @test or_N[1].name == BooleanSatisfiability.__get_hash_name(:or, and_N[1].children, is_commutative=true) # Can construct negation - @test isequal((¬z32)[1].children, [z32[1]]) + @test isequal((not(z32))[1].children, [z32[1]]) # Can construct Implies @test isequal((z1 .⟹ z1)[1].children, [z1[1], z1[1]]) @@ -81,8 +86,8 @@ end @test isequal(all(z1 .∧ z12), and(z1 .∧ z12)) # mismatched all() and any() - @test isequal(any(z1 .∧ z12), BoolExpr(:or, [z1[1] ∧ z12[1,1], z1[1] ∧ z12[1,2]], nothing, BooleanSatisfiability.__get_hash_name(:or, z1.∧ z12), __is_commutative=true)) - @test isequal(and(z12 .∨ z1), BoolExpr(:and, [z1[1] ∨ z12[1,1], z1[1] ∨ z12[1,2]], nothing, BooleanSatisfiability.__get_hash_name(:and, z1.∨ z12), __is_commutative=true)) + @test isequal(any(z1 .∧ z12), BoolExpr(:or, [z1[1] ∧ z12[1,2], z1[1] ∧ z12[1,1]], nothing, BooleanSatisfiability.__get_hash_name(:or, z1.∧ z12, is_commutative=true))) + @test isequal(and(z12 .∨ z1), BoolExpr(:and, [z1[1] ∨ z12[1,2], z1[1] ∨ z12[1,1]], nothing, BooleanSatisfiability.__get_hash_name(:and, z1.∨ z12, is_commutative=true))) end @testset "Additional operations" begin @@ -123,20 +128,20 @@ end # Can operate on mixed literals and BoolExprs @test isequal(and(true, z), z) - @test and(z, false) == false - @test or(true, z) == true + @test z ∧ false == false + @test true ∨ z == true @test isequal(or(z, false, false), z) @test isequal(implies(z, false), ¬z) #or(¬z, false) == ¬z - @test isequal(implies(true, z), z) + @test isequal(true ⟹ z, z) end @testset "Operations with 1D literals and nxm exprs" begin @satvariable(z[1:2, 1:3], Bool) # Can operate on mixed literals and BoolExprs - @test isequal(and.(true, z), z) + @test isequal(true .∧ z, z) @test and.(z, false) == [false false false; false false false] - @test or.(true, z) == [true true true; true true true] + @test z .∨ true == [true true true; true true true] @test isequal(or.(z, false, false), z) @test isequal(implies.(z, false), ¬z) #or(¬z, false) == ¬z @test isequal(implies.(true, z), z) diff --git a/test/int_parse_tests.jl b/test/int_parse_tests.jl index 699913e..2789669 100644 --- a/test/int_parse_tests.jl +++ b/test/int_parse_tests.jl @@ -16,9 +16,9 @@ result = "(declare-const b Int) (define-fun add_f0a93f0b97da1ab2 () Int (+ 1 b)) (define-fun geq_e1bd460e008a4d8b () Bool (>= add_f0a93f0b97da1ab2 b)) (define-fun add_99dce5c325207b7 () Int (+ 2 a b)) -(define-fun leq_8df5432ee845c9e8 () Bool (<= add_99dce5c325207b7 a)) -(define-fun and_8014e2e143374eea () Bool (and geq_e1bd460e008a4d8b leq_8df5432ee845c9e8)) -(assert and_8014e2e143374eea)\n" +(define-fun leq_a64c028ce18b2942 () Bool (<= add_99dce5c325207b7 a)) +(define-fun and_79376630b5dc2f7c () Bool (and geq_e1bd460e008a4d8b leq_a64c028ce18b2942)) +(assert and_79376630b5dc2f7c)\n" @test smt(expr) == result status = sat!(expr) @@ -64,7 +64,7 @@ end @satvariable(a, Int) b = a @satvariable(a, Real) - hashname = BooleanSatisfiability.__get_hash_name(:add, [b, a]) + hashname = BooleanSatisfiability.__get_hash_name(:add, [b, a], is_commutative=true) @test smt(b+a, assert=false) == "(declare-const a Int) (declare-const a Real) (define-fun $hashname () Real (+ (as a Int) (as a Real))) diff --git a/test/int_real_tests.jl b/test/int_real_tests.jl index ee51ada..34ebfc8 100644 --- a/test/int_real_tests.jl +++ b/test/int_real_tests.jl @@ -52,16 +52,19 @@ end # Operations with mixed constants and type promotion # Adding Int and Bool types results in an IntExpr children = [a, IntExpr(:const, AbstractExpr[], 2, "const_2")] - @test isequal(sum([a, 1, true]), IntExpr(:add, children, nothing, BooleanSatisfiability.__get_hash_name(:add, children))) + @test isequal(sum([a, 1, true]), IntExpr(:add, children, nothing, BooleanSatisfiability.__get_hash_name(:add, children, is_commutative=true))) # Type promotion to RealExpr works when we add a float-valued literal children = [a, RealExpr(:const, AbstractExpr[], 3., "const_3.0")] - @test isequal(sum([1.0, a, true, 1]), RealExpr(:add, children, nothing, BooleanSatisfiability.__get_hash_name(:add, children))) + @test isequal(sum([1.0, a, true, 1]), RealExpr(:add, children, nothing, BooleanSatisfiability.__get_hash_name(:add, children, is_commutative=true))) # Type promotion to RealExpr works when we add a real-valued expr children = [a, b[1], IntExpr(:const, AbstractExpr[], 2, "const_2.0")] - @test isequal(sum([a, 1.0, 1, false, b[1]]), RealExpr(:add, children, nothing, BooleanSatisfiability.__get_hash_name(:add, children))) + @test isequal(sum([a, 1.0, 1, false, b[1]]), RealExpr(:add, children, nothing, BooleanSatisfiability.__get_hash_name(:add, children, is_commutative=true))) # Sum works automatically @test isequal(1 + a + b[1] + true, sum([1, a, b[1], true])) + + @test all(isequal.((a - 3).children, [a, IntExpr(:const, AbstractExpr[], 3, "const_3")])) + @test all(isequal.((ar/3.0).children, [ar, RealExpr(:const, AbstractExpr[], 3., "const_3.0")])) end \ No newline at end of file diff --git a/test/runtests.jl b/test/runtests.jl index b8ff95f..3ad570c 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -3,6 +3,7 @@ push!(LOAD_PATH, "./") using BooleanSatisfiability using Test, Logging SET_DUPLICATE_NAME_WARNING!(false) +CLEAR_VARNAMES!() # Constructing Boolean expressions include("boolean_operation_tests.jl") diff --git a/test/smt_representation_tests.jl b/test/smt_representation_tests.jl index bc1328b..3fc3ce4 100644 --- a/test/smt_representation_tests.jl +++ b/test/smt_representation_tests.jl @@ -15,31 +15,22 @@ using Test # idea from https://microsoft.github.io/z3guide/docs/logic/propositional-logic # broadcast expression correctly generated - hashname = BooleanSatisfiability.__get_hash_name(:and, [z1, z2[1]]) + hashname = BooleanSatisfiability.__get_hash_name(:and, [z1, z2[1]], is_commutative=true) @test smt(z1 .∧ z2) == smt(z1, assert=false)*smt(z2, assert=false)*"(define-fun $hashname () Bool (and z1 z2_1))\n(assert $hashname)\n" # indexing creates a 1d expression - hashname = BooleanSatisfiability.__get_hash_name(:and, [z1, z12[1,2]]) + hashname = BooleanSatisfiability.__get_hash_name(:and, [z1, z12[1,2]], is_commutative=true) @test smt(z1 ∧ z12[1,2]) == smt(z1, assert=false)*smt(z12[1,2], assert=false)*"(define-fun $hashname () Bool (and z1 z12_1_2))\n(assert $hashname)\n" - hashname = BooleanSatisfiability.__get_hash_name(:and, z12) + hashname = BooleanSatisfiability.__get_hash_name(:and, z12, is_commutative=true) @test smt(z12[1,1] ∧ z12[1,2]) == smt(z12[1,1], assert=false)*smt(z12[1,2], assert=false)*"(define-fun $hashname () Bool (and z12_1_1 z12_1_2))\n(assert $hashname)\n" # all() and any() work - hashname = BooleanSatisfiability.__get_hash_name(:or, [z1 z12]) + hashname = BooleanSatisfiability.__get_hash_name(:or, [z1 z12], is_commutative=true) @test smt(any(z1 .∨ z12)) == smt(z1, assert=false)*smt(z12, assert=false)*"(define-fun $hashname () Bool (or z1 z12_1_1 z12_1_2))\n(assert $hashname)\n" - hashname = BooleanSatisfiability.__get_hash_name(:and, [z1 z12]) + hashname = BooleanSatisfiability.__get_hash_name(:and, [z1 z12], is_commutative=true) @test smt(all(z1 .∧ z12)) == smt(z1, assert=false)*smt(z12, assert=false)*"(define-fun $hashname () Bool (and z1 z12_1_1 z12_1_2))\n(assert $hashname)\n" - # cross all() and any() terms - # TESTS DO NOT WORK - # inner = z1.∨ z12 - #hashname = BooleanSatisfiability.__get_hash_name(:AND, inner) - #@test smt(all(inner)) == smt(inner)*"(define-fun $hashname () Bool (and $(inner#[1].name) $(inner![2].name)))\n(assert $hashname)\n" - - # inner = z1.∧ z12 - #hashname = BooleanSatisfiability.__get_hash_name(:OR, inner) - #@test smt(any(inner)) == smt(inner)*"(define-fun $hashname () Bool (or $(inner#[1].name) $(inner[2].name)))\n(assert $hashname)\n" end @testset "Generate additional exprs" begin @@ -55,7 +46,7 @@ end @test smt(z1 ⟺ z12[1,2], line_ending="\r\n") == smt(z1, assert=false, line_ending="\r\n")*smt(z12[1,2], assert=false, line_ending="\r\n")*"(define-fun $hashname () Bool (= z1 z12_1_2))\r\n(assert $hashname)\r\n" # xor - hashname = BooleanSatisfiability.__get_hash_name(:xor, z12) + hashname = BooleanSatisfiability.__get_hash_name(:xor, z12, is_commutative=true) @test smt(xor(z12[1,1], z12[1,2])) == smt(z12[1,1], assert=false)*smt(z12[1,2], assert=false)*"(define-fun $hashname () Bool (xor z12_1_1 z12_1_2))\n(assert $hashname)\n" # if-then-else @@ -70,10 +61,10 @@ end @satvariable(x, Bool) @satvariable(y, Bool) - xyname = BooleanSatisfiability.__get_hash_name(:and, [x,y]) + xyname = BooleanSatisfiability.__get_hash_name(:and, [x,y], is_commutative=true) xy = and(x,y) yx = and(y,x) - topname = BooleanSatisfiability.__get_hash_name(:or, [xy]) + topname = BooleanSatisfiability.__get_hash_name(:or, [xy], is_commutative=true) @test smt(or(xy, yx)) == smt(x, assert=false)*smt(y, assert=false)* "(define-fun $xyname () Bool (and x y)) (define-fun $topname () Bool (or $xyname)) @@ -82,7 +73,7 @@ end # Generate a nested expr with not (1-ary op) without duplicating statements xname = BooleanSatisfiability.__get_hash_name(:not, [x]) nx = ¬x - xyname = BooleanSatisfiability.__get_hash_name(:and, [nx]) + xyname = BooleanSatisfiability.__get_hash_name(:and, [nx], is_commutative=true) @test smt(and(¬x, ¬x)) == smt(x, assert=false)* "(define-fun $xname () Bool (not x)) (define-fun $xyname () Bool (and $xname)) diff --git a/test/solver_interface_tests.jl b/test/solver_interface_tests.jl index e0e9176..96ba842 100644 --- a/test/solver_interface_tests.jl +++ b/test/solver_interface_tests.jl @@ -94,6 +94,9 @@ end @testset "Solving a SAT problem" begin + # can initialize cvc5 + s = CVC5() + @satvariable(x[1:3], Bool) @satvariable(y[1:2], Bool) @satvariable(z, Bool)