text:
include("../common.jl")

# Offset to add to the version number
version_offset = v"0.1.0"
# Minimum Julia version supported: this is important to decide which versions of
# the dependencies to use, in particular the JLL stdlibs.
min_julia_version = v"1.3"
# Fix to minor PROJ version; also update PROJ_LIBS
# needed for Windows because of https://github.com/OSGeo/PROJ/blob/949171a6e/cmake/ProjVersion.cmake#L40-L46
# to avoid this problem https://github.com/JuliaGeo/GDAL.jl/pull/102
# Note that this currently fixes it to the exact JLL version that is used,
# this is issue https://github.com/JuliaPackaging/BinaryBuilderBase.jl/issues/89.
# Ideally we could by default allow any version X??.Y?? here, i.e. the PROJ minor version.
proj_jll_version = "700.201.100"

# Build the tarballs, and possibly a `build.jl` as well.
build_tarballs(ARGS, configure(version_offset, min_julia_version, proj_jll_version)...;
    julia_compat="~1.0, ~1.1, ~1.2, ~1.3, ~1.4, ~1.5",
    preferred_gcc_version=v"6")

max_stars_repo_name: plut/Yggdrasil

max_issues_repo_name: plut/Yggdrasil

max_forks_repo_name: plut/Yggdrasil


text:
## TODO

##            code eval output
## .           o   o    o
## nocode      x   o    o
## noeval      o   x    x       (verbatim)
## noout       o   o    x
## Idea is we can mark our code fences as above and suppress the code, output or evaluation

## override HTML esc of strings
Markdown.htmlinline(io::IO, md::AbstractString) = write(io, md)

## Main function to take a jmd file and turn into an HTML
function markdownToHTML(fname::AbstractString; TITLE="", kwargs...)

    dirnm, basenm = dirname(fname), basename(fname)
    newnm = replace(fname, r"[.].*" => ".html")
    out = mdToHTML(fname; TITLE=TITLE, kwargs...)

    io = open(newnm, "w")
    write(io, out)
    close(io)
end

"""

Convert a markdown file into an HTML page.

Processes `Question` types, graphical output of `Winston`, `Gadfly`,
and `PyPlot`. For the latter, one should call `gcf()` as the last
expressions in a cell block.

Markdown idiosyncracies:
* there is no `_underscore_` or `__double underscore__`
* for sections, best not to skip 2 or more lines, as they can get wrapped in `<p></p>` tags and not show
* Can use LaTeX markup

"""
function mdToHTML(fname::AbstractString; TITLE="", kwargs...)
    m = make_module()
    safeeval(m, Meta.parse("using LaTeXStrings, Plots; plotly()"))
    safeeval(m, Meta.parse("macro q_str(x)  \"`\$x`\" end"))
    buf = IOBuffer()
    added_gadfly_preamble = false

    process_block("using WeavePynb, LaTeXStrings", m)
    out = Markdown.parse_file(fname, flavor=Markdown.julia)

    for i in 1:length(out.content)
        println("$i: ", out.content[i])
        if isa(out.content[i], Markdown.Code)
            ## Code Blocks are evaluated and their last value is added to the output
            ## this is different from IJulia, but similar.
            ## There are issues with Gadfly graphics (need the script...)
            ## and PyPlot, where we need an invocation to manage the figures

            txt = out.content[i].code
            lang = out.content[i].language

            print("$i: ")
            println(txt)

            ## we need to set
            ## nocode, noeval, noout
            langs = map(lstrip, split(lang, ","))

            docode, doeval, doout, docompact = true, true, true, false
            if "nocode" in langs
                docode = false
            end
            if "verbatim" in langs || "noeval" in langs
                doeval, doout = false, false
            end
            if "noout" in langs
                doout = false
            end
            if "nocompact" in langs
                docompact = false
            end

            ## language is used to pass in arguments
            result = nothing
            if doeval
                result = process_block(txt, m)
            end

            result !== nothing && @show result

            !docode && (txt = "")

            if isa(result, Outputonly)
                txt = ""
                result = result.x
            end

            ## special cases
            ## hsould use dispatch here, but we don't....
            if result == nothing
                "Do not show output, just input"
                txt = replace(txt, r"\nnothing$" => "") ## trim off trailing "nothing"
                docode && length(txt) > 0 && println(buf, """
$txt
""")
            elseif isa(result, Invisible)
                "Do not show output or input"
                nothing
            elseif isa(result, HTMLoutput)
                "Do not execute input, show as is"
                txt = ""
                doout && show(buf, "text/plain", result)
            elseif isa(result, Verbatim)
                "Do not execute input, show as is"
                doout && show(buf, "text/plain", result)
            elseif isa(result, Bootstrap)
                "Show with Bootstrap formatting"
                doout && show(buf, "text/html", result)
            elseif isa(result, Question)
                "Show a question"
                doout && show(buf, "text/html", result)
            elseif isa(result, ImageFile)
                "show an image stored in a file, but embed"
                txt = ""
                doout && println(buf, gif_to_data(result.f, result.caption))
            elseif isa(result, Plots.Plot)
                docode && length(txt) > 0 && println(buf, """
$txt
""")

                # if isa(result, Plots.Plot{Plots.GadflyBackend})
                #      if !added_gadfly_preamble
                #        ## XXX print out JavaScript
                #       added_gadfly_preamble = true
                #      end
                #     doout && show(buf, "text/html", result.o)
                # else
                if isa(result, Plots.Plot{Plots.PlotlyBackend})
                    Plots.prepare_output(result);
                    doout && write(buf,  Plots.html_body(result))
                else
                    #                    img = stringmime("image/png", result.o)
                    imgfile = tempname() * ".png"
                    png(result, imgfile)
                    img = base64encode(read(imgfile, String))
                    doout && println(buf, """""")
                end
            elseif string(typeof(result)) == "FramedPlot"
                length(txt) > 0 && println(buf, """
$txt
""")
                img = stringmime("image/png", result)
                doout && println(buf, """""")
            elseif  string(typeof(result)) == "Plot"
                docode && length(txt) > 0 && println(buf, """
$txt
""")
                # if !added_gadfly_preamble
                #     const snapsvgjs = Pkg.dir("Compose", "data", "snap.svg-min.js")
                #     ## XXX print out JavaScript
                #     added_gadfly_preamble = true
                # end
                doout && show(buf, "text/html", result)
            elseif string(typeof(result)) == "Figure"
                "Must do gcf() for last line"
                if length(txt) > 0
                    txt1 = join(split(txt, "\n")[1:(end-1)], "\n") ## trim last line which is gcf()
                    docode && println(buf, """
$txt1
""")
                end
                img = stringmime("image/png", result)
                println(buf, """""")
            else
                mtype =  bestmime(result)
                length(txt) > 0 && println(buf, """
$txt
""")
                try
                    tmpbuf = IOBuffer()
                    println(txt)
                    println((mtype, typeof(result)))#, sprint(io -> show(io, mtype, result))))
                    if doout
                        if string(mtype) == "text/plain"
                            println(tmpbuf, """
""")
                            show(IOContext(tmpbuf,:compact=> docompact), mtype, result)
                            println(tmpbuf, """
""")
                        else
                            @show "latex", result
                            println(tmpbuf, """
""")
                            show(IOContext(tmpbuf,:compact=> docompact), mtype, result)
                            println(tmpbuf, """
""")
                        end
                        txt = String(take!(tmpbuf))
                        @show txt
                        println(buf, txt)
                    end

                catch e
                    ## no output
                end
            end

        else
           if isa(out.content[i], Markdown.LaTeX)
               Markdown.latex(buf, out.content[i])
           else
             ## we drill down
               Markdown.html(buf,  out.content[i])
           end
        end

    end

    body = String(take!(buf)) #takebuf_string(buf)

    ## return string
    D = Dict()
    D[:Title] = TITLE
    D[:style] = ""
    D[:body] = body
    for (k,v) in kwargs
        D[k] = v
    end
    Mustache.render(html_tpl, D)
end

"""
  Helper function to allow the md file to be a Mustache template.
  Expects a file `fname.jl` which defines a module `fname`.

  XXX Needs work XXX
"""
function mmd_to_html(fname::AbstractString; kwargs...)
    mmd_to_md(fname)

    bname = basename(fname)
    bname = replace(bname, r"\.mmd$" => "")
    markdownToHTML("$bname.md"; kwargs...)
end
export mmd_to_html

"""
Template for an HTML page with embedded questions.

Takes the following  arguments in template for Mustache

:style -- optional additional style values
:BRAND_HREF -- for upper left corner of nav bar
:BRAND_NAME
:body -- filled in

Uses Bootstrap styling and MathJaX for LaTeX markup.

"""
html_tpl = mt"""

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

<link
  href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css"
  rel="stylesheet">

      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
        Toggle navigation

      </button>
         {{#:BRAND_HREF}}{{:BRAND_NAME}}{{/:BRAND_HREF}}

           Jump to...

{{{:body}}}

"""

#const snapsvgjs = Pkg.dir("Compose", "data", "snap.svg-min.js")

ext: jl


text:
using Dojo
global REG = 1.0e-6

vis= Visualizer()
open(vis)
include("env.jl")
include("initialize.jl")
# mech = get_rexhopper(timestep=0.01, gravity=-2.81, model="rexhopper2",
mech = get_rexhopper(timestep=0.01, gravity= -0.99 * 9.81, model="rexhopper_no_wheel",
    floating=true, contact_foot=true, limits=true, spring=0.0, damper=0.5, contact_type=:linear)

q0 = [1,0.5,0,0]
q0 = Quaternion(q0 ./ norm(q0)..., true)
initialize!(mech, :rexhopper, body_position=[0,0,0.4], body_orientation=[0.5,0.8,0.0])
z0 = get_maximal_state(mech)

storage = simulate!(mech, 0.40, record=true, abort_upon_failure=false,
    opts=SolverOptions(rtol=1e-4, btol=1e-4, undercut=5.0, verbose=true))
visualize(mech, storage, vis=vis, show_contact=true, build=true)

# build_robot(mech, vis=vis, show_contact=true, color=RGBA(0.2, 0.2, 0.2, 1.0))
visualize(mech, generate_storage(mech, [z0]), show_contact=true, vis=vis, build=false)

function ctrl!(m,k)
    set_input!(m, 0*sin(4k*m.timestep) * m.timestep * [szeros(6); sones(10)])
    return nothing
end

verbose=false
VERBOSE_MEHROTRA = false
# mech_failing = deepcopy(mech)
storage = simulate!(mech, 0.41, ctrl!, record=true, abort_upon_failure=true,
    opts=SolverOptions(rtol=1e-4, btol=1e-4, undercut=5.0, verbose=true))
visualize(mech, storage, vis=vis, show_contact=true, build=false)

mech.system.dimrow
mech.system.dimcol

mech.system.matrix_entries[1,8]
mech.bodies[1]
mech.system.matrix_entries[1,1]
mech.system.matrix_entries[2,2]
mech.system.matrix_entries[3,3]
mech.system.matrix_entries[4,4]
mech.system.matrix_entries[5,5]
mech.system.matrix_entries[6,6]
mech.system.matrix_entries[7,7]
mech.system.matrix_entries[7,8]
mech.system.matrix_entries[8,8]
mech.system.matrix_entries[9,9]
mech.system.matrix_entries[10,10]
mech.system.matrix_entries[11,11]
mech.system.matrix_entries[12,12]
mech.system.matrix_entries[13,13]
mech.system.matrix_entries[14,14]
mech.system.matrix_entries[15,15]

mech.joints[3].rotational.joint_limits
joint = mech.joints[3]

Diagonal(sones(3))

body = mech.bodies[1]
body.state.D[1:3,1:3] += rand(3,3)
# jldsave(joinpath(@__DIR__, "mech_failing.jld"), mech=mech_failing)
mech_failing = jldopen(joinpath(@__DIR__, "mech_failing.jld"))["mech"]
storage = simulate!(mech_failing, 0.01, record=true, abort_upon_failure=true,
    opts=SolverOptions(rtol=1e-4, btol=1e-4, undercut=5.0, verbose=true))

convert_frames_to_video_and_gif("rexhopper_new_failure")

mech.bodies[1].state.D

function control!(mechanism, k; u=0.1)
    for (i, joint) in enumerate(mechanism.joints)
        nu = Dojo.control_dimension(joint, ignore_floating_base=false)
        su = mechanism.timestep * u * sones(nu)
        Dojo.set_input!(joint, su)
    end
    return
end

# mechanism
mech = get_mechanism(:pendulum)
initialize!(mech, :pendulum)

mech.bodies[1].state.ϕsol[2] = 0.5*srand(3)
mech.bodies[1].impulses[2] = 0.5*sones(1)
mech.bodies[1].impulses_dual[2] = 0.1*sones(1)
# simulate
# storage = simulate!(mech, 0.1, control!,
    # record=true, opts=SolverOptions(rtol=1e-4, btol=1e-4, verbose=true))

# Set data
Nb = length(mech.bodies)
data = Dojo.get_data0(mech)
Dojo.set_data0!(mech, data)
sol = Dojo.get_solution0(mech)
attjac = Dojo.attitude_jacobian(data, Nb)

# IFT
set_entries!(mech)
solmat = Dojo.full_matrix(mech.system)
# finite diff
fd_solmat = finitediff_sol_matrix(mech, data, sol, δ=1.0e-5, verbose=true)
norm(fd_solmat + solmat, Inf) < 1e-4

solmat
fd_solmat
solmat + fd_solmat
plot(Gray.(1e8*abs.(solmat+fd_solmat)))

plot(Gray.(solmat))
plot(Gray.(fd_solmat))

plot(Gray.(abs.(solmat)))
plot(Gray.(abs.(fd_solmat)))

mech = get_quadruped(timestep=0.01, gravity= -9.81, contact_feet=true, contact_body=true,
    limits=true, spring=0.0, damper=0.2)

initialize!(mech, :quadruped, tran=[0,0,0.2], rot=[0.003,0.0003,0.])
z0 = get_maximal_state(mech)

visualize(mech, generate_storage(mech, [z0]), show_contact=true, vis=vis, build=true)

storage = simulate!(mech, 0.40, record=true, abort_upon_failure=false,
    opts=SolverOptions(rtol=1e-4, btol=1e-4, undercut=5.0, verbose=true))
visualize(mech, storage, vis=vis, show_contact=true, build=true)

sol0 = get_solution(mech)
data0 = get_data(mech)

scn(residual_violation(mech), digits=0)
residual_violation(mech)

set_entries!(mech)
fv0 = full_vector(mech.system)
fM0 = full_matrix(mech.system)
Δv0 = fM0 \ fv0

ldu_factorization!(mech.system)    # factorize system, modifies the matrix in place
ldu_backsubstitution!(mech.system) # solve system, modifies the vector in place
Δv1 = full_vector(mech.system)

mech.system.vector_entries
res = norm(fv0, Inf)
Δ0 = norm(Δv0, Inf)

using Plots
plot(Gray.(fM0))

findmax(fv0)
fM0[:,111]
plot(Gray.(1e1abs.(reshape(Δv0, (6,47)))))
plot(Gray.(1e1abs.(reshape(Δv1, (6,47)))))
plot(Gray.(1e10abs.(reshape(Δv0 - Δv1, (6,47)))))
norm(Δv0 - Δv1, Inf)

plot(Gray.(1e1abs.(reshape(fv0, (6,47)))))
plot(Gray.(1e1abs.(reshape(fM0[:,111], (6,47)))))

fv0[111]
fM0[111,111]
Δv0[111]

dc0 = mech.system.dimcol
[sum(dc0[1:i-1])+1:sum(dc0[1:i]) for i in 1:length(dc0)][14]

getfield.(mech.bodies, :id)


text:
# This file is a part of Julia. License is MIT: https://julialang.org/license

const uv_thread_t = UInt # TODO: this is usually correct (or tolerated by the API), but not guaranteed

function uv_thread_getaffinity()
    masksize = ccall(:uv_cpumask_size, Cint, ())
    self = ccall(:uv_thread_self, uv_thread_t, ())
    ref = Ref(self)
    cpumask = zeros(Bool, masksize)
    err = ccall(
        :uv_thread_getaffinity,
        Cint,
        (Ref{uv_thread_t}, Ptr{Bool}, Cssize_t),
        ref,
        cpumask,
        masksize,
    )
    Base.uv_error("getaffinity", err)
    n = something(findlast(cpumask)) # we must have at least one active core
    resize!(cpumask, n)
    return cpumask
end

function print_process_affinity()
    join(stdout, findall(uv_thread_getaffinity()), ",")
    println()
end

if Base.Filesystem.samefile(PROGRAM_FILE, @__FILE__)
    print_process_affinity()
end

max_stars_repo_name: JuliaLabs/julia

max_issues_repo_name: JuliaLabs/julia

max_forks_repo_name: JuliaLabs/julia


text:
int_rules_4_7_9 = @theory begin

    #= ::Subsection::Closed:: =#
    #= 4.7.9*Active*trig*functions =#
    @apply_utils Antiderivative(((~(e') + ~(f') * ~x) ^ ~(m') * sin(~(c') + ~(d') * ~x) ^ ~(n')) / (~a + ~(b') * sin(~(c') + ~(d') * ~x)), ~x) => (1 / ~b) * Antiderivative((~e + ~f * ~x) ^ ~m * sin(~c + ~d * ~x) ^ (~n - 1), ~x) - (~a / ~b) * Antiderivative(((~e + ~f * ~x) ^ ~m * sin(~c + ~d * ~x) ^ (~n - 1)) / (~a + ~b * sin(~c + ~d * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f], ~x) && (IGtQ(~m, 0) && IGtQ(~n, 0))
    @apply_utils Antiderivative(((~(e') + ~(f') * ~x) ^ ~(m') * cos(~(c') + ~(d') * ~x) ^ ~(n')) / (~a + ~(b') * cos(~(c') + ~(d') * ~x)), ~x) => (1 / ~b) * Antiderivative((~e + ~f * ~x) ^ ~m * cos(~c + ~d * ~x) ^ (~n - 1), ~x) - (~a / ~b) * Antiderivative(((~e + ~f * ~x) ^ ~m * cos(~c + ~d * ~x) ^ (~n - 1)) / (~a + ~b * cos(~c + ~d * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f], ~x) && (IGtQ(~m, 0) && IGtQ(~n, 0))
    @apply_utils Antiderivative(((~(e') + ~(f') * ~x) ^ ~(m') * cos(~(c') + ~(d') * ~x)) / (~a + ~(b') * sin(~(c') + ~(d') * ~x)), ~x) => (-im * (~e + ~f * ~x) ^ (~m + 1)) / (~b * ~f * (~m + 1)) + 2 * Antiderivative(((~e + ~f * ~x) ^ ~m * ℯ ^ (im * (~c + ~d * ~x))) / (~a - im * ~b * ℯ ^ (im * (~c + ~d * ~x))), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f], ~x) && (IGtQ(~m, 0) && EqQ((~a) ^ 2 - (~b) ^ 2, 0))
    @apply_utils Antiderivative(((~(e') + ~(f') * ~x) ^ ~(m') * sin(~(c') + ~(d') * ~x)) / (~a + ~(b') * cos(~(c') + ~(d') * ~x)), ~x) => (im * (~e + ~f * ~x) ^ (~m + 1)) / (~b * ~f * (~m + 1)) - 2 * im * Antiderivative(((~e + ~f * ~x) ^ ~m * ℯ ^ (im * (~c + ~d * ~x))) / (~a + ~b * ℯ ^ (im * (~c + ~d * ~x))), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f], ~x) && (IGtQ(~m, 0) && EqQ((~a) ^ 2 - (~b) ^ 2, 0))
    @apply_utils Antiderivative(((~(e') + ~(f') * ~x) ^ ~(m') * cos(~(c') + ~(d') * ~x)) / (~a + ~(b') * sin(~(c') + ~(d') * ~x)), ~x) => (-im * (~e + ~f * ~x) ^ (~m + 1)) / (~b * ~f * (~m + 1)) + Antiderivative(((~e + ~f * ~x) ^ ~m * ℯ ^ (im * (~c + ~d * ~x))) / ((~a - Rt((~a) ^ 2 - (~b) ^ 2, 2)) - im * ~b * ℯ ^ (im * (~c + ~d * ~x))), ~x) + Antiderivative(((~e + ~f * ~x) ^ ~m * ℯ ^ (im * (~c + ~d * ~x))) / ((~a + Rt((~a) ^ 2 - (~b) ^ 2, 2)) - im * ~b * ℯ ^ (im * (~c + ~d * ~x))), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f], ~x) && (IGtQ(~m, 0) && PosQ((~a) ^ 2 - (~b) ^ 2))
    @apply_utils Antiderivative(((~(e') + ~(f') * ~x) ^ ~(m') * sin(~(c') + ~(d') * ~x)) / (~a + ~(b') * cos(~(c') + ~(d') * ~x)), ~x) => ((im * (~e + ~f * ~x) ^ (~m + 1)) / (~b * ~f * (~m + 1)) - im * Antiderivative(((~e + ~f * ~x) ^ ~m * ℯ ^ (im * (~c + ~d * ~x))) / ((~a - Rt((~a) ^ 2 - (~b) ^ 2, 2)) + ~b * ℯ ^ (im * (~c + ~d * ~x))), ~x)) - im * Antiderivative(((~e + ~f * ~x) ^ ~m * ℯ ^ (im * (~c + ~d * ~x))) / (~a + Rt((~a) ^ 2 - (~b) ^ 2, 2) + ~b * ℯ ^ (im * (~c + ~d * ~x))), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f], ~x) && (IGtQ(~m, 0) && PosQ((~a) ^ 2 - (~b) ^ 2))
    @apply_utils Antiderivative(((~(e') + ~(f') * ~x) ^ ~(m') * cos(~(c') + ~(d') * ~x)) / (~a + ~(b') * sin(~(c') + ~(d') * ~x)), ~x) => (-im * (~e + ~f * ~x) ^ (~m + 1)) / (~b * ~f * (~m + 1)) + im * Antiderivative(((~e + ~f * ~x) ^ ~m * ℯ ^ (im * (~c + ~d * ~x))) / ((im * ~a - Rt(-((~a) ^ 2) + (~b) ^ 2, 2)) + ~b * ℯ ^ (im * (~c + ~d * ~x))), ~x) + im * Antiderivative(((~e + ~f * ~x) ^ ~m * ℯ ^ (im * (~c + ~d * ~x))) / (im * ~a + Rt(-((~a) ^ 2) + (~b) ^ 2, 2) + ~b * ℯ ^ (im * (~c + ~d * ~x))), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f], ~x) && (IGtQ(~m, 0) && NegQ((~a) ^ 2 - (~b) ^ 2))
    @apply_utils Antiderivative(((~(e') + ~(f') * ~x) ^ ~(m') * sin(~(c') + ~(d') * ~x)) / (~a + ~(b') * cos(~(c') + ~(d') * ~x)), ~x) => (im * (~e + ~f * ~x) ^ (~m + 1)) / (~b * ~f * (~m + 1)) + Antiderivative(((~e + ~f * ~x) ^ ~m * ℯ ^ (im * (~c + ~d * ~x))) / ((im * ~a - Rt(-((~a) ^ 2) + (~b) ^ 2, 2)) + im * ~b * ℯ ^ (im * (~c + ~d * ~x))), ~x) + Antiderivative(((~e + ~f * ~x) ^ ~m * ℯ ^ (im * (~c + ~d * ~x))) / (im * ~a + Rt(-((~a) ^ 2) + (~b) ^ 2, 2) + im * ~b * ℯ ^ (im * (~c + ~d * ~x))), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f], ~x) && (IGtQ(~m, 0) && NegQ((~a) ^ 2 - (~b) ^ 2))
    @apply_utils Antiderivative(((~(e') + ~(f') * ~x) ^ ~(m') * cos(~(c') + ~(d') * ~x) ^ ~n) / (~a + ~(b') * sin(~(c') + ~(d') * ~x)), ~x) => (1 / ~a) * Antiderivative((~e + ~f * ~x) ^ ~m * cos(~c + ~d * ~x) ^ (~n - 2), ~x) - (1 / ~b) * Antiderivative((~e + ~f * ~x) ^ ~m * cos(~c + ~d * ~x) ^ (~n - 2) * sin(~c + ~d * ~x), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~m], ~x) && (IGtQ(~n, 1) && EqQ((~a) ^ 2 - (~b) ^ 2, 0))
    @apply_utils Antiderivative(((~(e') + ~(f') * ~x) ^ ~(m') * sin(~(c') + ~(d') * ~x) ^ ~n) / (~a + ~(b') * cos(~(c') + ~(d') * ~x)), ~x) => (1 / ~a) * Antiderivative((~e + ~f * ~x) ^ ~m * sin(~c + ~d * ~x) ^ (~n - 2), ~x) - (1 / ~b) * Antiderivative((~e + ~f * ~x) ^ ~m * sin(~c + ~d * ~x) ^ (~n - 2) * cos(~c + ~d * ~x), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~m], ~x) && (IGtQ(~n, 1) && EqQ((~a) ^ 2 - (~b) ^ 2, 0))
    @apply_utils Antiderivative(((~(e') + ~(f') * ~x) ^ ~(m') * cos(~(c') + ~(d') * ~x) ^ ~n) / (~a + ~(b') * sin(~(c') + ~(d') * ~x)), ~x) => ((~a / (~b) ^ 2) * Antiderivative((~e + ~f * ~x) ^ ~m * cos(~c + ~d * ~x) ^ (~n - 2), ~x) - (1 / ~b) * Antiderivative((~e + ~f * ~x) ^ ~m * cos(~c + ~d * ~x) ^ (~n - 2) * sin(~c + ~d * ~x), ~x)) - (((~a) ^ 2 - (~b) ^ 2) / (~b) ^ 2) * Antiderivative(((~e + ~f * ~x) ^ ~m * cos(~c + ~d * ~x) ^ (~n - 2)) / (~a + ~b * sin(~c + ~d * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f], ~x) && (IGtQ(~n, 1) && (NeQ((~a) ^ 2 - (~b) ^ 2, 0) && IGtQ(~m, 0)))
    @apply_utils Antiderivative(((~(e') + ~(f') * ~x) ^ ~(m') * sin(~(c') + ~(d') * ~x) ^ ~n) / (~a + ~(b') * cos(~(c') + ~(d') * ~x)), ~x) => ((~a / (~b) ^ 2) * Antiderivative((~e + ~f * ~x) ^ ~m * sin(~c + ~d * ~x) ^ (~n - 2), ~x) - (1 / ~b) * Antiderivative((~e + ~f * ~x) ^ ~m * sin(~c + ~d * ~x) ^ (~n - 2) * cos(~c + ~d * ~x), ~x)) - (((~a) ^ 2 - (~b) ^ 2) / (~b) ^ 2) * Antiderivative(((~e + ~f * ~x) ^ ~m * sin(~c + ~d * ~x) ^ (~n - 2)) / (~a + ~b * cos(~c + ~d * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f], ~x) && (IGtQ(~n, 1) && (NeQ((~a) ^ 2 - (~b) ^ 2, 0) && IGtQ(~m, 0)))
    @apply_utils Antiderivative(((~(e') + ~(f') * ~x) ^ ~(m') * tan(~(c') + ~(d') * ~x) ^ ~(n')) / (~a + ~(b') * sin(~(c') + ~(d') * ~x)), ~x) => (1 / ~b) * Antiderivative((~e + ~f * ~x) ^ ~m * sec(~c + ~d * ~x) * tan(~c + ~d * ~x) ^ (~n - 1), ~x) - (~a / ~b) * Antiderivative(((~e + ~f * ~x) ^ ~m * sec(~c + ~d * ~x) * tan(~c + ~d * ~x) ^ (~n - 1)) / (~a + ~b * sin(~c + ~d * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f], ~x) && (IGtQ(~m, 0) && IGtQ(~n, 0))
    @apply_utils Antiderivative(((~(e') + ~(f') * ~x) ^ ~(m') * cot(~(c') + ~(d') * ~x) ^ ~(n')) / (~a + ~(b') * cos(~(c') + ~(d') * ~x)), ~x) => (1 / ~b) * Antiderivative((~e + ~f * ~x) ^ ~m * csc(~c + ~d * ~x) * cot(~c + ~d * ~x) ^ (~n - 1), ~x) - (~a / ~b) * Antiderivative(((~e + ~f * ~x) ^ ~m * csc(~c + ~d * ~x) * cot(~c + ~d * ~x) ^ (~n - 1)) / (~a + ~b * cos(~c + ~d * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f], ~x) && (IGtQ(~m, 0) && IGtQ(~n, 0))
    @apply_utils Antiderivative(((~(e') + ~(f') * ~x) ^ ~(m') * cot(~(c') + ~(d') * ~x) ^ ~(n')) / (~a + ~(b') * sin(~(c') + ~(d') * ~x)), ~x) => (1 / ~a) * Antiderivative((~e + ~f * ~x) ^ ~m * cot(~c + ~d * ~x) ^ ~n, ~x) - (~b / ~a) * Antiderivative(((~e + ~f * ~x) ^ ~m * cos(~c + ~d * ~x) * cot(~c + ~d * ~x) ^ (~n - 1)) / (~a + ~b * sin(~c + ~d * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f], ~x) && (IGtQ(~m, 0) && IGtQ(~n, 0))
    @apply_utils Antiderivative(((~(e') + ~(f') * ~x) ^ ~(m') * tan(~(c') + ~(d') * ~x) ^ ~(n')) / (~a + ~(b') * cos(~(c') + ~(d') * ~x)), ~x) => (1 / ~a) * Antiderivative((~e + ~f * ~x) ^ ~m * tan(~c + ~d * ~x) ^ ~n, ~x) - (~b / ~a) * Antiderivative(((~e + ~f * ~x) ^ ~m * sin(~c + ~d * ~x) * tan(~c + ~d * ~x) ^ (~n - 1)) / (~a + ~b * cos(~c + ~d * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f], ~x) && (IGtQ(~m, 0) && IGtQ(~n, 0))
    @apply_utils Antiderivative(((~(e') + ~(f') * ~x) ^ ~(m') * sec(~(c') + ~(d') * ~x) ^ ~(n')) / (~a + ~(b') * sin(~(c') + ~(d') * ~x)), ~x) => (1 / ~a) * Antiderivative((~e + ~f * ~x) ^ ~m * sec(~c + ~d * ~x) ^ (~n + 2), ~x) - (1 / ~b) * Antiderivative((~e + ~f * ~x) ^ ~m * sec(~c + ~d * ~x) ^ (~n + 1) * tan(~c + ~d * ~x), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~n], ~x) && (IGtQ(~m, 0) && EqQ((~a) ^ 2 - (~b) ^ 2, 0))
    @apply_utils Antiderivative(((~(e') + ~(f') * ~x) ^ ~(m') * csc(~(c') + ~(d') * ~x) ^ ~(n')) / (~a + ~(b') * cos(~(c') + ~(d') * ~x)), ~x) => (1 / ~a) * Antiderivative((~e + ~f * ~x) ^ ~m * csc(~c + ~d * ~x) ^ (~n + 2), ~x) - (1 / ~b) * Antiderivative((~e + ~f * ~x) ^ ~m * csc(~c + ~d * ~x) ^ (~n + 1) * cot(~c + ~d * ~x), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~n], ~x) && (IGtQ(~m, 0) && EqQ((~a) ^ 2 - (~b) ^ 2, 0))
    @apply_utils Antiderivative(((~(e') + ~(f') * ~x) ^ ~(m') * sec(~(c') + ~(d') * ~x) ^ ~(n')) / (~a + ~(b') * sin(~(c') + ~(d') * ~x)), ~x) => (-((~b) ^ 2) / ((~a) ^ 2 - (~b) ^ 2)) * Antiderivative(((~e + ~f * ~x) ^ ~m * sec(~c + ~d * ~x) ^ (~n - 2)) / (~a + ~b * sin(~c + ~d * ~x)), ~x) + (1 / ((~a) ^ 2 - (~b) ^ 2)) * Antiderivative((~e + ~f * ~x) ^ ~m * sec(~c + ~d * ~x) ^ ~n * (~a - ~b * sin(~c + ~d * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f], ~x) && (IGtQ(~m, 0) && (NeQ((~a) ^ 2 - (~b) ^ 2, 0) && IGtQ(~n, 0)))
    @apply_utils Antiderivative(((~(e') + ~(f') * ~x) ^ ~(m') * csc(~(c') + ~(d') * ~x) ^ ~(n')) / (~a + ~(b') * cos(~(c') + ~(d') * ~x)), ~x) => (-((~b) ^ 2) / ((~a) ^ 2 - (~b) ^ 2)) * Antiderivative(((~e + ~f * ~x) ^ ~m * csc(~c + ~d * ~x) ^ (~n - 2)) / (~a + ~b * cos(~c + ~d * ~x)), ~x) + (1 / ((~a) ^ 2 - (~b) ^ 2)) * Antiderivative((~e + ~f * ~x) ^ ~m * csc(~c + ~d * ~x) ^ ~n * (~a - ~b * cos(~c + ~d * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f], ~x) && (IGtQ(~m, 0) && (NeQ((~a) ^ 2 - (~b) ^ 2, 0) && IGtQ(~n, 0)))
    @apply_utils Antiderivative(((~(e') + ~(f') * ~x) ^ ~(m') * csc(~(c') + ~(d') * ~x) ^ ~(n')) / (~a + ~(b') * sin(~(c') + ~(d') * ~x)), ~x) => (1 / ~a) * Antiderivative((~e + ~f * ~x) ^ ~m * csc(~c + ~d * ~x) ^ ~n, ~x) - (~b / ~a) * Antiderivative(((~e + ~f * ~x) ^ ~m * csc(~c + ~d * ~x) ^ (~n - 1)) / (~a + ~b * sin(~c + ~d * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f], ~x) && (IGtQ(~m, 0) && IGtQ(~n, 0))
    @apply_utils Antiderivative(((~(e') + ~(f') * ~x) ^ ~(m') * sec(~(c') + ~(d') * ~x) ^ ~(n')) / (~a + ~(b') * cos(~(c') + ~(d') * ~x)), ~x) => (1 / ~a) * Antiderivative((~e + ~f * ~x) ^ ~m * sec(~c + ~d * ~x) ^ ~n, ~x) - (~b / ~a) * Antiderivative(((~e + ~f * ~x) ^ ~m * sec(~c + ~d * ~x) ^ (~n - 1)) / (~a + ~b * cos(~c + ~d * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f], ~x) && (IGtQ(~m, 0) && IGtQ(~n, 0))
    @apply_utils Antiderivative(((~(e') + ~(f') * ~x) ^ ~(m') * (~F)(~(c') + ~(d') * ~x) ^ ~(n')) / (~a + ~(b') * sin(~(c') + ~(d') * ~x)), ~x) => Unintegrable(((~e + ~f * ~x) ^ ~m * (~F)(~c + ~d * ~x) ^ ~n) / (~a + ~b * sin(~c + ~d * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~m, ~n], ~x) && TrigQ(~F)
    @apply_utils Antiderivative(((~(e') + ~(f') * ~x) ^ ~(m') * (~F)(~(c') + ~(d') * ~x) ^ ~(n')) / (~a + ~(b') * cos(~(c') + ~(d') * ~x)), ~x) => Unintegrable(((~e + ~f * ~x) ^ ~m * (~F)(~c + ~d * ~x) ^ ~n) / (~a + ~b * cos(~c + ~d * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~m, ~n], ~x) && TrigQ(~F)
    @apply_utils Antiderivative(((~(e') + ~(f') * ~x) ^ ~(m') * cos(~(c') + ~(d') * ~x) ^ ~(p') * sin(~(c') + ~(d') * ~x) ^ ~(n')) / (~a + ~(b') * sin(~(c') + ~(d') * ~x)), ~x) => (1 / ~b) * Antiderivative((~e + ~f * ~x) ^ ~m * cos(~c + ~d * ~x) ^ ~p * sin(~c + ~d * ~x) ^ (~n - 1), ~x) - (~a / ~b) * Antiderivative(((~e + ~f * ~x) ^ ~m * cos(~c + ~d * ~x) ^ ~p * sin(~c + ~d * ~x) ^ (~n - 1)) / (~a + ~b * sin(~c + ~d * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f], ~x) && (IGtQ(~m, 0) && (IGtQ(~n, 0) && IGtQ(~p, 0)))
    @apply_utils Antiderivative(((~(e') + ~(f') * ~x) ^ ~(m') * sin(~(c') + ~(d') * ~x) ^ ~(p') * cos(~(c') + ~(d') * ~x) ^ ~(n')) / (~a + ~(b') * cos(~(c') + ~(d') * ~x)), ~x) => (1 / ~b) * Antiderivative((~e + ~f * ~x) ^ ~m * sin(~c + ~d * ~x) ^ ~p * cos(~c + ~d * ~x) ^ (~n - 1), ~x) - (~a / ~b) * Antiderivative(((~e + ~f * ~x) ^ ~m * sin(~c + ~d * ~x) ^ ~p * cos(~c + ~d * ~x) ^ (~n - 1)) / (~a + ~b * cos(~c + ~d * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f], ~x) && (IGtQ(~m, 0) && (IGtQ(~n, 0) && IGtQ(~p, 0)))
    @apply_utils Antiderivative(((~(e') + ~(f') * ~x) ^ ~(m') * cos(~(c') + ~(d') * ~x) ^ ~(p') * tan(~(c') + ~(d') * ~x) ^ ~(n')) / (~a + ~(b') * sin(~(c') + ~(d') * ~x)), ~x) => (1 / ~b) * Antiderivative((~e + ~f * ~x) ^ ~m * cos(~c + ~d * ~x) ^ (~p - 1) * tan(~c + ~d * ~x) ^ (~n - 1), ~x) - (~a / ~b) * Antiderivative(((~e + ~f * ~x) ^ ~m * cos(~c + ~d * ~x) ^ (~p - 1) * tan(~c + ~d * ~x) ^ (~n - 1)) / (~a + ~b * sin(~c + ~d * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f], ~x) && (IGtQ(~m, 0) && (IGtQ(~n, 0) && IGtQ(~p, 0)))
    @apply_utils Antiderivative(((~(e') + ~(f') * ~x) ^ ~(m') * sin(~(c') + ~(d') * ~x) ^ ~(p') * cot(~(c') + ~(d') * ~x) ^ ~(n')) / (~a + ~(b') * cos(~(c') + ~(d') * ~x)), ~x) => (1 / ~b) * Antiderivative((~e + ~f * ~x) ^ ~m * sin(~c + ~d * ~x) ^ (~p - 1) * cot(~c + ~d * ~x) ^ (~n - 1), ~x) - (~a / ~b) * Antiderivative(((~e + ~f * ~x) ^ ~m * sin(~c + ~d * ~x) ^ (~p - 1) * cot(~c + ~d * ~x) ^ (~n - 1)) / (~a + ~b * cos(~c + ~d * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f], ~x) && (IGtQ(~m, 0) && (IGtQ(~n, 0) && IGtQ(~p, 0)))
    @apply_utils Antiderivative(((~(e') + ~(f') * ~x) ^ ~(m') * cos(~(c') + ~(d') * ~x) ^ ~(p') * cot(~(c') + ~(d') * ~x) ^ ~(n')) / (~a + ~(b') * sin(~(c') + ~(d') * ~x)), ~x) => (1 / ~a) * Antiderivative((~e + ~f * ~x) ^ ~m * cos(~c + ~d * ~x) ^ ~p * cot(~c + ~d * ~x) ^ ~n, ~x) - (~b / ~a) * Antiderivative(((~e + ~f * ~x) ^ ~m * cos(~c + ~d * ~x) ^ (~p + 1) * cot(~c + ~d * ~x) ^ (~n - 1)) / (~a + ~b * sin(~c + ~d * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f], ~x) && (IGtQ(~m, 0) && (IGtQ(~n, 0) && IGtQ(~p, 0)))
    @apply_utils Antiderivative(((~(e') + ~(f') * ~x) ^ ~(m') * sin(~(c') + ~(d') * ~x) ^ ~(p') * tan(~(c') + ~(d') * ~x) ^ ~(n')) / (~a + ~(b') * cos(~(c') + ~(d') * ~x)), ~x) => (1 / ~a) * Antiderivative((~e + ~f * ~x) ^ ~m * sin(~c + ~d * ~x) ^ ~p * tan(~c + ~d * ~x) ^ ~n, ~x) - (~b / ~a) * Antiderivative(((~e + ~f * ~x) ^ ~m * sin(~c + ~d * ~x) ^ (~p + 1) * tan(~c + ~d * ~x) ^ (~n - 1)) / (~a + ~b * cos(~c + ~d * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f], ~x) && (IGtQ(~m, 0) && (IGtQ(~n, 0) && IGtQ(~p, 0)))
    @apply_utils Antiderivative(((~(e') + ~(f') * ~x) ^ ~(m') * cos(~(c') + ~(d') * ~x) ^ ~(p') * csc(~(c') + ~(d') * ~x) ^ ~(n')) / (~a + ~(b') * sin(~(c') + ~(d') * ~x)), ~x) => (1 / ~a) * Antiderivative((~e + ~f * ~x) ^ ~m * cos(~c + ~d * ~x) ^ ~p * csc(~c + ~d * ~x) ^ ~n, ~x) - (~b / ~a) * Antiderivative(((~e + ~f * ~x) ^ ~m * cos(~c + ~d * ~x) ^ ~p * csc(~c + ~d * ~x) ^ (~n - 1)) / (~a + ~b * sin(~c + ~d * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f], ~x) && (IGtQ(~m, 0) && (IGtQ(~n, 0) && IGtQ(~p, 0)))
    @apply_utils Antiderivative(((~(e') + ~(f') * ~x) ^ ~(m') * sin(~(c') + ~(d') * ~x) ^ ~(p') * sec(~(c') + ~(d') * ~x) ^ ~(n')) / (~a + ~(b') * cos(~(c') + ~(d') * ~x)), ~x) => (1 / ~a) * Antiderivative((~e + ~f * ~x) ^ ~m * sin(~c + ~d * ~x) ^ ~p * sec(~c + ~d * ~x) ^ ~n, ~x) - (~b / ~a) * Antiderivative(((~e + ~f * ~x) ^ ~m * sin(~c + ~d * ~x) ^ ~p * sec(~c + ~d * ~x) ^ (~n - 1)) / (~a + ~b * cos(~c + ~d * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f], ~x) && (IGtQ(~m, 0) && (IGtQ(~n, 0) && IGtQ(~p, 0)))
    @apply_utils Antiderivative(((~(e') + ~(f') * ~x) ^ ~(m') * cos(~(c') + ~(d') * ~x) ^ ~(p') * (~F)(~(c') + ~(d') * ~x) ^ ~(n')) / (~a + ~(b') * sin(~(c') + ~(d') * ~x)), ~x) => Unintegrable(((~e + ~f * ~x) ^ ~m * cos(~c + ~d * ~x) ^ ~p * (~F)(~c + ~d * ~x) ^ ~n) / (~a + ~b * sin(~c + ~d * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~m, ~n, ~p], ~x) && TrigQ(~F)
    @apply_utils Antiderivative(((~(e') + ~(f') * ~x) ^ ~(m') * sin(~(c') + ~(d') * ~x) ^ ~(p') * (~F)(~(c') + ~(d') * ~x) ^ ~(n')) / (~a + ~(b') * cos(~(c') + ~(d') * ~x)), ~x) => Unintegrable(((~e + ~f * ~x) ^ ~m * sin(~c + ~d * ~x) ^ ~p * (~F)(~c + ~d * ~x) ^ ~n) / (~a + ~b * cos(~c + ~d * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~m, ~n], ~x) && TrigQ(~F)
    @apply_utils Antiderivative(((~(e') + ~(f') * ~x) ^ ~(m') * (~F)(~(c') + ~(d') * ~x) ^ ~(n')) / (~a + ~(b') * sec(~(c') + ~(d') * ~x)), ~x) => Antiderivative(((~e + ~f * ~x) ^ ~m * cos(~c + ~d * ~x) * (~F)(~c + ~d * ~x) ^ ~n) / (~b + ~a * cos(~c + ~d * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f], ~x) && (TrigQ(~F) && IntegersQ(~m, ~n))
    @apply_utils Antiderivative(((~(e') + ~(f') * ~x) ^ ~(m') * (~F)(~(c') + ~(d') * ~x) ^ ~(n')) / (~a + ~(b') * csc(~(c') + ~(d') * ~x)), ~x) => Antiderivative(((~e + ~f * ~x) ^ ~m * sin(~c + ~d * ~x) * (~F)(~c + ~d * ~x) ^ ~n) / (~b + ~a * sin(~c + ~d * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f], ~x) && (TrigQ(~F) && IntegersQ(~m, ~n))
    @apply_utils Antiderivative(((~(e') + ~(f') * ~x) ^ ~(m') * (~F)(~(c') + ~(d') * ~x) ^ ~(n') * (~G)(~(c') + ~(d') * ~x) ^ ~(p')) / (~a + ~(b') * sec(~(c') + ~(d') * ~x)), ~x) => Antiderivative(((~e + ~f * ~x) ^ ~m * cos(~c + ~d * ~x) * (~F)(~c + ~d * ~x) ^ ~n * (~G)(~c + ~d * ~x) ^ ~p) / (~b + ~a * cos(~c + ~d * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f], ~x) && (TrigQ(~F) && (TrigQ(~G) && IntegersQ(~m, ~n, ~p)))
    @apply_utils Antiderivative(((~(e') + ~(f') * ~x) ^ ~(m') * (~F)(~(c') + ~(d') * ~x) ^ ~(n') * (~G)(~(c') + ~(d') * ~x) ^ ~(p')) / (~a + ~(b') * csc(~(c') + ~(d') * ~x)), ~x) => Antiderivative(((~e + ~f * ~x) ^ ~m * sin(~c + ~d * ~x) * (~F)(~c + ~d * ~x) ^ ~n * (~G)(~c + ~d * ~x) ^ ~p) / (~b + ~a * sin(~c + ~d * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f], ~x) && (TrigQ(~F) && (TrigQ(~G) && IntegersQ(~m, ~n, ~p)))
    @apply_utils Antiderivative(sin(~(a') + ~(b') * ~x) ^ ~(p') * sin(~(c') + ~(d') * ~x) ^ ~(q'), ~x) => (1 / 2 ^ (~p + ~q)) * Antiderivative(ExpandIntegrand((im / ℯ ^ (im * (~c + ~d * ~x)) - im * ℯ ^ (im * (~c + ~d * ~x))) ^ ~q, (im / ℯ ^ (im * (~a + ~b * ~x)) - im * ℯ ^ (im * (~a + ~b * ~x))) ^ ~p, ~x), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~q], ~x) && (IGtQ(~p, 0) && Not(IntegerQ(~q)))
    @apply_utils Antiderivative(cos(~(a') + ~(b') * ~x) ^ ~(p') * cos(~(c') + ~(d') * ~x) ^ ~(q'), ~x) => (1 / 2 ^ (~p + ~q)) * Antiderivative(ExpandIntegrand((ℯ ^ (-im * (~c + ~d * ~x)) + ℯ ^ (im * (~c + ~d * ~x))) ^ ~q, (ℯ ^ (-im * (~a + ~b * ~x)) + ℯ ^ (im * (~a + ~b * ~x))) ^ ~p, ~x), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~q], ~x) && (IGtQ(~p, 0) && Not(IntegerQ(~q)))
    @apply_utils Antiderivative(sin(~(a') + ~(b') * ~x) ^ ~(p') * cos(~(c') + ~(d') * ~x) ^ ~(q'), ~x) => (1 / 2 ^ (~p + ~q)) * Antiderivative(ExpandIntegrand((ℯ ^ (-im * (~c + ~d * ~x)) + ℯ ^ (im * (~c + ~d * ~x))) ^ ~q, (im / ℯ ^ (im * (~a + ~b * ~x)) - im * ℯ ^ (im * (~a + ~b * ~x))) ^ ~p, ~x), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~q], ~x) && (IGtQ(~p, 0) && Not(IntegerQ(~q)))
    @apply_utils Antiderivative(cos(~(a') + ~(b') * ~x) ^ ~(p') * sin(~(c') + ~(d') * ~x) ^ ~(q'), ~x) => (1 / 2 ^ (~p + ~q)) * Antiderivative(ExpandIntegrand((im / ℯ ^ (im * (~c + ~d * ~x)) - im * ℯ ^ (im * (~c + ~d * ~x))) ^ ~q, (ℯ ^ (-im * (~a + ~b * ~x)) + ℯ ^ (im * (~a + ~b * ~x))) ^ ~p, ~x), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~q], ~x) && (IGtQ(~p, 0) && Not(IntegerQ(~q)))
    @apply_utils Antiderivative(sin(~(a') + ~(b') * ~x) * tan(~(c') + ~(d') * ~x), ~x) => Antiderivative(((ℯ ^ (-im * (~a + ~b * ~x)) / 2 - ℯ ^ (im * (~a + ~b * ~x)) / 2) - ℯ ^ (-im * (~a + ~b * ~x)) / (1 + ℯ ^ (2 * im * (~c + ~d * ~x)))) + ℯ ^ (im * (~a + ~b * ~x)) / (1 + ℯ ^ (2 * im * (~c + ~d * ~x))), ~x) <-- FreeQ([~a, ~b, ~c, ~d], ~x) && NeQ((~b) ^ 2 - (~d) ^ 2, 0)
    @apply_utils Antiderivative(cos(~(a') + ~(b') * ~x) * cot(~(c') + ~(d') * ~x), ~x) => Antiderivative((((im * ℯ ^ (-im * (~a + ~b * ~x))) / 2 + (im * ℯ ^ (im * (~a + ~b * ~x))) / 2) - (im * ℯ ^ (-im * (~a + ~b * ~x))) / (1 - ℯ ^ (2 * im * (~c + ~d * ~x)))) - (im * ℯ ^ (im * (~a + ~b * ~x))) / (1 - ℯ ^ (2 * im * (~c + ~d * ~x))), ~x) <-- FreeQ([~a, ~b, ~c, ~d], ~x) && NeQ((~b) ^ 2 - (~d) ^ 2, 0)
    @apply_utils Antiderivative(sin(~(a') + ~(b') * ~x) * cot(~(c') + ~(d') * ~x), ~x) => Antiderivative((-(ℯ ^ (-im * (~a + ~b * ~x))) / 2 + ℯ ^ (im * (~a + ~b * ~x)) / 2 + ℯ ^ (-im * (~a + ~b * ~x)) / (1 - ℯ ^ (2 * im * (~c + ~d * ~x)))) - ℯ ^ (im * (~a + ~b * ~x)) / (1 - ℯ ^ (2 * im * (~c + ~d * ~x))), ~x) <-- FreeQ([~a, ~b, ~c, ~d], ~x) && NeQ((~b) ^ 2 - (~d) ^ 2, 0)
    @apply_utils Antiderivative(cos(~(a') + ~(b') * ~x) * tan(~(c') + ~(d') * ~x), ~x) => Antiderivative(((-im * ℯ ^ (-im * (~a + ~b * ~x))) / 2 - (im * ℯ ^ (im * (~a + ~b * ~x))) / 2) + (im * ℯ ^ (-im * (~a + ~b * ~x))) / (1 + ℯ ^ (2 * im * (~c + ~d * ~x))) + (im * ℯ ^ (im * (~a + ~b * ~x))) / (1 + ℯ ^ (2 * im * (~c + ~d * ~x))), ~x) <-- FreeQ([~a, ~b, ~c, ~d], ~x) && NeQ((~b) ^ 2 - (~d) ^ 2, 0)
    @apply_utils Antiderivative(sin(~(a') / (~(c') + ~(d') * ~x)) ^ ~(n'), ~x) => (-1 / ~d) * Subst(Antiderivative(sin(~a * ~x) ^ ~n / (~x) ^ 2, ~x), ~x, 1 / (~c + ~d * ~x)) <-- FreeQ([~a, ~c, ~d], ~x) && IGtQ(~n, 0)
    @apply_utils Antiderivative(cos(~(a') / (~(c') + ~(d') * ~x)) ^ ~(n'), ~x) => (-1 / ~d) * Subst(Antiderivative(cos(~a * ~x) ^ ~n / (~x) ^ 2, ~x), ~x, 1 / (~c + ~d * ~x)) <-- FreeQ([~a, ~c, ~d], ~x) && IGtQ(~n, 0)
    @apply_utils Antiderivative(sin((~(e') * (~(a') + ~(b') * ~x)) / (~(c') + ~(d') * ~x)) ^ ~(n'), ~x) => (-1 / ~d) * Subst(Antiderivative(sin((~b * ~e) / ~d - (~e * (~b * ~c - ~a * ~d) * ~x) / ~d) ^ ~n / (~x) ^ 2, ~x), ~x, 1 / (~c + ~d * ~x)) <-- FreeQ([~a, ~b, ~c, ~d], ~x) && (IGtQ(~n, 0) && NeQ(~b * ~c - ~a * ~d, 0))
    @apply_utils Antiderivative(cos((~(e') * (~(a') + ~(b') * ~x)) / (~(c') + ~(d') * ~x)) ^ ~(n'), ~x) => (-1 / ~d) * Subst(Antiderivative(cos((~b * ~e) / ~d - (~e * (~b * ~c - ~a * ~d) * ~x) / ~d) ^ ~n / (~x) ^ 2, ~x), ~x, 1 / (~c + ~d * ~x)) <-- FreeQ([~a, ~b, ~c, ~d], ~x) && (IGtQ(~n, 0) && NeQ(~b * ~c - ~a * ~d, 0))
    @apply_utils Antiderivative(sin(~u) ^ ~(n'), ~x) => Module([lst = QuotientOfLinearsParts(~u, ~x)], Antiderivative(sin((lst(1) + lst(2) * ~x) / (lst(3) + lst(4) * ~x)) ^ ~n, ~x)) <-- IGtQ(~n, 0) && QuotientOfLinearsQ(~u, ~x)
    @apply_utils Antiderivative(cos(~u) ^ ~(n'), ~x) => Module([lst = QuotientOfLinearsParts(~u, ~x)], Antiderivative(cos((lst(1) + lst(2) * ~x) / (lst(3) + lst(4) * ~x)) ^ ~n, ~x)) <-- IGtQ(~n, 0) && QuotientOfLinearsQ(~u, ~x)
    @apply_utils Antiderivative(~(u') * sin(~v) ^ ~(p') * sin(~w) ^ ~(q'), ~x) => Antiderivative(~u * sin(~v) ^ (~p + ~q), ~x) <-- EqQ(~w, ~v)
    @apply_utils Antiderivative(~(u') * cos(~v) ^ ~(p') * cos(~w) ^ ~(q'), ~x) => Antiderivative(~u * cos(~v) ^ (~p + ~q), ~x) <-- EqQ(~w, ~v)
    @apply_utils Antiderivative(sin(~v) ^ ~(p') * sin(~w) ^ ~(q'), ~x) => Antiderivative(ExpandTrigReduce(sin(~v) ^ ~p * sin(~w) ^ ~q, ~x), ~x) <-- (PolynomialQ(~v, ~x) && PolynomialQ(~w, ~x) || BinomialQ([~v, ~w], ~x) && IndependentQ(Cancel(~v / ~w), ~x)) && (IGtQ(~p, 0) && IGtQ(~q, 0))
    @apply_utils Antiderivative(cos(~v) ^ ~(p') * cos(~w) ^ ~(q'), ~x) => Antiderivative(ExpandTrigReduce(cos(~v) ^ ~p * cos(~w) ^ ~q, ~x), ~x) <-- (PolynomialQ(~v, ~x) && PolynomialQ(~w, ~x) || BinomialQ([~v, ~w], ~x) && IndependentQ(Cancel(~v / ~w), ~x)) && (IGtQ(~p, 0) && IGtQ(~q, 0))
    @apply_utils Antiderivative((~x) ^ ~(m') * sin(~v) ^ ~(p') * sin(~w) ^ ~(q'), ~x) => Antiderivative(ExpandTrigReduce((~x) ^ ~m, sin(~v) ^ ~p * sin(~w) ^ ~q, ~x), ~x) <-- IGtQ(~m, 0) && (IGtQ(~p, 0) && (IGtQ(~q, 0) && (PolynomialQ(~v, ~x) && PolynomialQ(~w, ~x) || BinomialQ([~v, ~w], ~x) && IndependentQ(Cancel(~v / ~w), ~x))))
    @apply_utils Antiderivative((~x) ^ ~(m') * cos(~v) ^ ~(p') * cos(~w) ^ ~(q'), ~x) => Antiderivative(ExpandTrigReduce((~x) ^ ~m, cos(~v) ^ ~p * cos(~w) ^ ~q, ~x), ~x) <-- IGtQ(~m, 0) && (IGtQ(~p, 0) && (IGtQ(~q, 0) && (PolynomialQ(~v, ~x) && PolynomialQ(~w, ~x) || BinomialQ([~v, ~w], ~x) && IndependentQ(Cancel(~v / ~w), ~x))))
    @apply_utils Antiderivative(~(u') * sin(~v) ^ ~(p') * cos(~w) ^ ~(p'), ~x) => (1 / 2 ^ ~p) * Antiderivative(~u * sin(2 * ~v) ^ ~p, ~x) <-- EqQ(~w, ~v) && IntegerQ(~p)
    @apply_utils Antiderivative(sin(~v) ^ ~(p') * cos(~w) ^ ~(q'), ~x) => Antiderivative(ExpandTrigReduce(sin(~v) ^ ~p * cos(~w) ^ ~q, ~x), ~x) <-- IGtQ(~p, 0) && (IGtQ(~q, 0) && (PolynomialQ(~v, ~x) && PolynomialQ(~w, ~x) || BinomialQ([~v, ~w], ~x) && IndependentQ(Cancel(~v / ~w), ~x)))
    @apply_utils Antiderivative((~x) ^ ~(m') * sin(~v) ^ ~(p') * cos(~w) ^ ~(q'), ~x) => Antiderivative(ExpandTrigReduce((~x) ^ ~m, sin(~v) ^ ~p * cos(~w) ^ ~q, ~x), ~x) <-- IGtQ(~m, 0) && (IGtQ(~p, 0) && (IGtQ(~q, 0) && (PolynomialQ(~v, ~x) && PolynomialQ(~w, ~x) || BinomialQ([~v, ~w], ~x) && IndependentQ(Cancel(~v / ~w), ~x))))
    @apply_utils Antiderivative(sin(~v) * tan(~w) ^ ~(n'), ~x) => -(Antiderivative(cos(~v) * tan(~w) ^ (~n - 1), ~x)) + cos(~v - ~w) * Antiderivative(sec(~w) * tan(~w) ^ (~n - 1), ~x) <-- GtQ(~n, 0) && (FreeQ(~v - ~w, ~x) && NeQ(~w, ~v))
    @apply_utils Antiderivative(cos(~v) * cot(~w) ^ ~(n'), ~x) => -(Antiderivative(sin(~v) * cot(~w) ^ (~n - 1), ~x)) + cos(~v - ~w) * Antiderivative(csc(~w) * cot(~w) ^ (~n - 1), ~x) <-- GtQ(~n, 0) && (FreeQ(~v - ~w, ~x) && NeQ(~w, ~v))
    @apply_utils Antiderivative(sin(~v) * cot(~w) ^ ~(n'), ~x) => Antiderivative(cos(~v) * cot(~w) ^ (~n - 1), ~x) + sin(~v - ~w) * Antiderivative(csc(~w) * cot(~w) ^ (~n - 1), ~x) <-- GtQ(~n, 0) && (FreeQ(~v - ~w, ~x) && NeQ(~w, ~v))
    @apply_utils Antiderivative(cos(~v) * tan(~w) ^ ~(n'), ~x) => Antiderivative(sin(~v) * tan(~w) ^ (~n - 1), ~x) - sin(~v - ~w) * Antiderivative(sec(~w) * tan(~w) ^ (~n - 1), ~x) <-- GtQ(~n, 0) && (FreeQ(~v - ~w, ~x) && NeQ(~w, ~v))
    @apply_utils Antiderivative(sin(~v) * sec(~w) ^ ~(n'), ~x) => cos(~v - ~w) * Antiderivative(tan(~w) * sec(~w) ^ (~n - 1), ~x) + sin(~v - ~w) * Antiderivative(sec(~w) ^ (~n - 1), ~x) <-- GtQ(~n, 0) && (FreeQ(~v - ~w, ~x) && NeQ(~w, ~v))
    @apply_utils Antiderivative(cos(~v) * csc(~w) ^ ~(n'), ~x) => cos(~v - ~w) * Antiderivative(cot(~w) * csc(~w) ^ (~n - 1), ~x) - sin(~v - ~w) * Antiderivative(csc(~w) ^ (~n - 1), ~x) <-- GtQ(~n, 0) && (FreeQ(~v - ~w, ~x) && NeQ(~w, ~v))
    @apply_utils Antiderivative(sin(~v) * csc(~w) ^ ~(n'), ~x) => sin(~v - ~w) * Antiderivative(cot(~w) * csc(~w) ^ (~n - 1), ~x) + cos(~v - ~w) * Antiderivative(csc(~w) ^ (~n - 1), ~x) <-- GtQ(~n, 0) && (FreeQ(~v - ~w, ~x) && NeQ(~w, ~v))
    @apply_utils Antiderivative(cos(~v) * sec(~w) ^ ~(n'), ~x) => -(sin(~v - ~w)) * Antiderivative(tan(~w) * sec(~w) ^ (~n - 1), ~x) + cos(~v - ~w) * Antiderivative(sec(~w) ^ (~n - 1), ~x) <-- GtQ(~n, 0) && (FreeQ(~v - ~w, ~x) && NeQ(~w, ~v))
    @apply_utils Antiderivative((~(e') + ~(f') * ~x) ^ ~(m') * (~a + ~(b') * sin(~(c') + ~(d') * ~x) * cos(~(c') + ~(d') * ~x)) ^ ~(n'), ~x) => Antiderivative((~e + ~f * ~x) ^ ~m * (~a + (~b * sin(2 * ~c + 2 * ~d * ~x)) / 2) ^ ~n, ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~m, ~n], ~x)
    @apply_utils Antiderivative((~x) ^ ~(m') * (~a + ~(b') * sin(~(c') + ~(d') * ~x) ^ 2) ^ ~n, ~x) => (1 / 2 ^ ~n) * Antiderivative((~x) ^ ~m * ((2 * ~a + ~b) - ~b * cos(2 * ~c + 2 * ~d * ~x)) ^ ~n, ~x) <-- FreeQ([~a, ~b, ~c, ~d], ~x) && (NeQ(~a + ~b, 0) && (IGtQ(~m, 0) && (ILtQ(~n, 0) && (EqQ(~n, -1) || EqQ(~m, 1) && EqQ(~n, -2)))))
    @apply_utils Antiderivative((~x) ^ ~(m') * (~a + ~(b') * cos(~(c') + ~(d') * ~x) ^ 2) ^ ~n, ~x) => (1 / 2 ^ ~n) * Antiderivative((~x) ^ ~m * (2 * ~a + ~b + ~b * cos(2 * ~c + 2 * ~d * ~x)) ^ ~n, ~x) <-- FreeQ([~a, ~b, ~c, ~d], ~x) && (NeQ(~a + ~b, 0) && (IGtQ(~m, 0) && (ILtQ(~n, 0) && (EqQ(~n, -1) || EqQ(~m, 1) && EqQ(~n, -2)))))
    @apply_utils Antiderivative((~(f') + ~(g') * ~x) ^ ~(m') / (~(a') + ~(b') * cos(~(d') + ~(e') * ~x) ^ 2 + ~(c') * sin(~(d') + ~(e') * ~x) ^ 2), ~x) => 2 * Antiderivative((~f + ~g * ~x) ^ ~m / (2 * ~a + ~b + ~c + (~b - ~c) * cos(2 * ~d + 2 * ~e * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~g], ~x) && (IGtQ(~m, 0) && (NeQ(~a + ~b, 0) && NeQ(~a + ~c, 0)))
    @apply_utils Antiderivative(((~(f') + ~(g') * ~x) ^ ~(m') * sec(~(d') + ~(e') * ~x) ^ 2) / (~b + ~(c') * tan(~(d') + ~(e') * ~x) ^ 2), ~x) => 2 * Antiderivative((~f + ~g * ~x) ^ ~m / (~b + ~c + (~b - ~c) * cos(2 * ~d + 2 * ~e * ~x)), ~x) <-- FreeQ([~b, ~c, ~d, ~e, ~f, ~g], ~x) && IGtQ(~m, 0)
    @apply_utils Antiderivative(((~(f') + ~(g') * ~x) ^ ~(m') * sec(~(d') + ~(e') * ~x) ^ 2) / (~(b') + ~(a') * sec(~(d') + ~(e') * ~x) ^ 2 + ~(c') * tan(~(d') + ~(e') * ~x) ^ 2), ~x) => 2 * Antiderivative((~f + ~g * ~x) ^ ~m / (2 * ~a + ~b + ~c + (~b - ~c) * cos(2 * ~d + 2 * ~e * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~g], ~x) && (IGtQ(~m, 0) && (NeQ(~a + ~b, 0) && NeQ(~a + ~c, 0)))
    @apply_utils Antiderivative(((~(f') + ~(g') * ~x) ^ ~(m') * csc(~(d') + ~(e') * ~x) ^ 2) / (~c + ~(b') * cot(~(d') + ~(e') * ~x) ^ 2), ~x) => 2 * Antiderivative((~f + ~g * ~x) ^ ~m / (~b + ~c + (~b - ~c) * cos(2 * ~d + 2 * ~e * ~x)), ~x) <-- FreeQ([~b, ~c, ~d, ~e, ~f, ~g], ~x) && IGtQ(~m, 0)
    @apply_utils Antiderivative(((~(f') + ~(g') * ~x) ^ ~(m') * csc(~(d') + ~(e') * ~x) ^ 2) / (~(c') + ~(b') * cot(~(d') + ~(e') * ~x) ^ 2 + ~(a') * csc(~(d') + ~(e') * ~x) ^ 2), ~x) => 2 * Antiderivative((~f + ~g * ~x) ^ ~m / (2 * ~a + ~b + ~c + (~b - ~c) * cos(2 * ~d + 2 * ~e * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~g], ~x) && (IGtQ(~m, 0) && (NeQ(~a + ~b, 0) && NeQ(~a + ~c, 0)))
    @apply_utils Antiderivative(((~(e') + ~(f') * ~x) * (~A + ~(B') * sin(~(c') + ~(d') * ~x))) / (~a + ~(b') * sin(~(c') + ~(d') * ~x)) ^ 2, ~x) => (-(~B) * (~e + ~f * ~x) * cos(~c + ~d * ~x)) / (~a * ~d * (~a + ~b * sin(~c + ~d * ~x))) + ((~B * ~f) / (~a * ~d)) * Antiderivative(cos(~c + ~d * ~x) / (~a + ~b * sin(~c + ~d * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~A, ~B], ~x) && EqQ(~a * ~A - ~b * ~B, 0)
    @apply_utils Antiderivative(((~(e') + ~(f') * ~x) * (~A + ~(B') * cos(~(c') + ~(d') * ~x))) / (~a + ~(b') * cos(~(c') + ~(d') * ~x)) ^ 2, ~x) => (~B * (~e + ~f * ~x) * sin(~c + ~d * ~x)) / (~a * ~d * (~a + ~b * cos(~c + ~d * ~x))) - ((~B * ~f) / (~a * ~d)) * Antiderivative(sin(~c + ~d * ~x) / (~a + ~b * cos(~c + ~d * ~x)), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~A, ~B], ~x) && EqQ(~a * ~A - ~b * ~B, 0)
    @apply_utils Antiderivative((~x) ^ 2 / (~(c') * sin(~(a') * ~x) + ~(d') * ~x * cos(~(a') * ~x)) ^ 2, ~x) => ~x / (~a * ~d * sin(~a * ~x) * (~c * sin(~a * ~x) + ~d * ~x * cos(~a * ~x))) + (1 / (~d) ^ 2) * Antiderivative(1 / sin(~a * ~x) ^ 2, ~x) <-- FreeQ([~a, ~c, ~d], ~x) && EqQ(~a * ~c + ~d, 0)
    @apply_utils Antiderivative((~x) ^ 2 / (~(c') * cos(~(a') * ~x) + ~(d') * ~x * sin(~(a') * ~x)) ^ 2, ~x) => -(~x) / (~a * ~d * cos(~a * ~x) * (~c * cos(~a * ~x) + ~d * ~x * sin(~a * ~x))) + (1 / (~d) ^ 2) * Antiderivative(1 / cos(~a * ~x) ^ 2, ~x) <-- FreeQ([~a, ~c, ~d], ~x) && EqQ(~a * ~c - ~d, 0)
    @apply_utils Antiderivative(sin(~(a') * ~x) ^ 2 / (~(c') * sin(~(a') * ~x) + ~(d') * ~x * cos(~(a') * ~x)) ^ 2, ~x) => 1 / ((~d) ^ 2 * ~x) + sin(~a * ~x) / (~a * ~d * ~x * (~d * ~x * cos(~a * ~x) + ~c * sin(~a * ~x))) <-- FreeQ([~a, ~c, ~d], ~x) && EqQ(~a * ~c + ~d, 0)
    @apply_utils Antiderivative(cos(~(a') * ~x) ^ 2 / (~(c') * cos(~(a') * ~x) + ~(d') * ~x * sin(~(a') * ~x)) ^ 2, ~x) => 1 / ((~d) ^ 2 * ~x) - cos(~a * ~x) / (~a * ~d * ~x * (~d * ~x * sin(~a * ~x) + ~c * cos(~a * ~x))) <-- FreeQ([~a, ~c, ~d], ~x) && EqQ(~a * ~c - ~d, 0)
    @apply_utils Antiderivative(((~(b') * ~x) ^ ~m * sin(~(a') * ~x) ^ ~n) / (~(c') * sin(~(a') * ~x) + ~(d') * ~x * cos(~(a') * ~x)) ^ 2, ~x) => (~b * (~b * ~x) ^ (~m - 1) * sin(~a * ~x) ^ (~n - 1)) / (~a * ~d * (~c * sin(~a * ~x) + ~d * ~x * cos(~a * ~x))) - (((~b) ^ 2 * (~n - 1)) / (~d) ^ 2) * Antiderivative((~b * ~x) ^ (~m - 2) * sin(~a * ~x) ^ (~n - 2), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~m, ~n], ~x) && (EqQ(~a * ~c + ~d, 0) && EqQ(~m, 2 - ~n))
    @apply_utils Antiderivative(((~(b') * ~x) ^ ~m * cos(~(a') * ~x) ^ ~n) / (~(c') * cos(~(a') * ~x) + ~(d') * ~x * sin(~(a') * ~x)) ^ 2, ~x) => (-(~b) * (~b * ~x) ^ (~m - 1) * cos(~a * ~x) ^ (~n - 1)) / (~a * ~d * (~c * cos(~a * ~x) + ~d * ~x * sin(~a * ~x))) - (((~b) ^ 2 * (~n - 1)) / (~d) ^ 2) * Antiderivative((~b * ~x) ^ (~m - 2) * cos(~a * ~x) ^ (~n - 2), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~m, ~n], ~x) && (EqQ(~a * ~c - ~d, 0) && EqQ(~m, 2 - ~n))
    @apply_utils Antiderivative(((~(b') * ~x) ^ ~(m') * csc(~(a') * ~x) ^ ~(n')) / (~(c') * sin(~(a') * ~x) + ~(d') * ~x * cos(~(a') * ~x)) ^ 2, ~x) => (~b * (~b * ~x) ^ (~m - 1) * csc(~a * ~x) ^ (~n + 1)) / (~a * ~d * (~c * sin(~a * ~x) + ~d * ~x * cos(~a * ~x))) + (((~b) ^ 2 * (~n + 1)) / (~d) ^ 2) * Antiderivative((~b * ~x) ^ (~m - 2) * csc(~a * ~x) ^ (~n + 2), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~m, ~n], ~x) && (EqQ(~a * ~c + ~d, 0) && EqQ(~m, ~n + 2))
    @apply_utils Antiderivative(((~(b') * ~x) ^ ~(m') * sec(~(a') * ~x) ^ ~(n')) / (~(c') * cos(~(a') * ~x) + ~(d') * ~x * sin(~(a') * ~x)) ^ 2, ~x) => (-(~b) * (~b * ~x) ^ (~m - 1) * sec(~a * ~x) ^ (~n + 1)) / (~a * ~d * (~c * cos(~a * ~x) + ~d * ~x * sin(~a * ~x))) + (((~b) ^ 2 * (~n + 1)) / (~d) ^ 2) * Antiderivative((~b * ~x) ^ (~m - 2) * sec(~a * ~x) ^ (~n + 2), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~m, ~n], ~x) && (EqQ(~a * ~c - ~d, 0) && EqQ(~m, ~n + 2))
    @apply_utils Antiderivative((~(g') + ~(h') * ~x) ^ ~(p') * (~a + ~(b') * sin(~(e') + ~(f') * ~x)) ^ ~(m') * (~c + ~(d') * sin(~(e') + ~(f') * ~x)) ^ ~(n'), ~x) => (~a) ^ ~m * (~c) ^ ~m * Antiderivative((~g + ~h * ~x) ^ ~p * cos(~e + ~f * ~x) ^ (2 * ~m) * (~c + ~d * sin(~e + ~f * ~x)) ^ (~n - ~m), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~g, ~h], ~x) && (EqQ(~b * ~c + ~a * ~d, 0) && (EqQ((~a) ^ 2 - (~b) ^ 2, 0) && (IntegerQ(~m) && IGtQ(~n - ~m, 0))))
    @apply_utils Antiderivative((~(g') + ~(h') * ~x) ^ ~(p') * (~a + ~(b') * cos(~(e') + ~(f') * ~x)) ^ ~(m') * (~c + ~(d') * cos(~(e') + ~(f') * ~x)) ^ ~(n'), ~x) => (~a) ^ ~m * (~c) ^ ~m * Antiderivative((~g + ~h * ~x) ^ ~p * sin(~e + ~f * ~x) ^ (2 * ~m) * (~c + ~d * cos(~e + ~f * ~x)) ^ (~n - ~m), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~g, ~h], ~x) && (EqQ(~b * ~c + ~a * ~d, 0) && (EqQ((~a) ^ 2 - (~b) ^ 2, 0) && (IntegerQ(~m) && IGtQ(~n - ~m, 0))))
    @apply_utils Antiderivative((~(g') + ~(h') * ~x) ^ ~(p') * (~a + ~(b') * sin(~(e') + ~(f') * ~x)) ^ ~m * (~c + ~(d') * sin(~(e') + ~(f') * ~x)) ^ ~n, ~x) => (((~a) ^ IntPart(~m) * (~c) ^ IntPart(~m) * (~a + ~b * sin(~e + ~f * ~x)) ^ FracPart(~m) * (~c + ~d * sin(~e + ~f * ~x)) ^ FracPart(~m)) / cos(~e + ~f * ~x) ^ (2 * FracPart(~m))) * Antiderivative((~g + ~h * ~x) ^ ~p * cos(~e + ~f * ~x) ^ (2 * ~m) * (~c + ~d * sin(~e + ~f * ~x)) ^ (~n - ~m), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~g, ~h], ~x) && (EqQ(~b * ~c + ~a * ~d, 0) && (EqQ((~a) ^ 2 - (~b) ^ 2, 0) && (IntegerQ(~p) && (IntegerQ(2 * ~m) && IGeQ(~n - ~m, 0)))))
    @apply_utils Antiderivative((~(g') + ~(h') * ~x) ^ ~(p') * (~a + ~(b') * cos(~(e') + ~(f') * ~x)) ^ ~m * (~c + ~(d') * cos(~(e') + ~(f') * ~x)) ^ ~n, ~x) => (((~a) ^ IntPart(~m) * (~c) ^ IntPart(~m) * (~a + ~b * cos(~e + ~f * ~x)) ^ FracPart(~m) * (~c + ~d * cos(~e + ~f * ~x)) ^ FracPart(~m)) / sin(~e + ~f * ~x) ^ (2 * FracPart(~m))) * Antiderivative((~g + ~h * ~x) ^ ~p * sin(~e + ~f * ~x) ^ (2 * ~m) * (~c + ~d * cos(~e + ~f * ~x)) ^ (~n - ~m), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~f, ~g, ~h], ~x) && (EqQ(~b * ~c + ~a * ~d, 0) && (EqQ((~a) ^ 2 - (~b) ^ 2, 0) && (IntegerQ(~p) && (IntegerQ(2 * ~m) && IGeQ(~n - ~m, 0)))))
    @apply_utils Antiderivative(sec(~v) ^ ~(m') * (~a + ~(b') * tan(~v)) ^ ~(n'), ~x) => Antiderivative((~a * cos(~v) + ~b * sin(~v)) ^ ~n, ~x) <-- FreeQ([~a, ~b], ~x) && (IntegerQ((~m - 1) / 2) && EqQ(~m + ~n, 0))
    @apply_utils Antiderivative(csc(~v) ^ ~(m') * (~a + ~(b') * cot(~v)) ^ ~(n'), ~x) => Antiderivative((~b * cos(~v) + ~a * sin(~v)) ^ ~n, ~x) <-- FreeQ([~a, ~b], ~x) && (IntegerQ((~m - 1) / 2) && EqQ(~m + ~n, 0))
    @apply_utils Antiderivative(~(u') * sin(~(a') + ~(b') * ~x) ^ ~(m') * sin(~(c') + ~(d') * ~x) ^ ~(n'), ~x) => Antiderivative(ExpandTrigReduce(~u, sin(~a + ~b * ~x) ^ ~m * sin(~c + ~d * ~x) ^ ~n, ~x), ~x) <-- FreeQ([~a, ~b, ~c, ~d], ~x) && (IGtQ(~m, 0) && IGtQ(~n, 0))
    @apply_utils Antiderivative(~(u') * cos(~(a') + ~(b') * ~x) ^ ~(m') * cos(~(c') + ~(d') * ~x) ^ ~(n'), ~x) => Antiderivative(ExpandTrigReduce(~u, cos(~a + ~b * ~x) ^ ~m * cos(~c + ~d * ~x) ^ ~n, ~x), ~x) <-- FreeQ([~a, ~b, ~c, ~d], ~x) && (IGtQ(~m, 0) && IGtQ(~n, 0))
    @apply_utils Antiderivative(sec(~(a') + ~(b') * ~x) * sec(~c + ~(d') * ~x), ~x) => -(csc((~b * ~c - ~a * ~d) / ~d)) * Antiderivative(tan(~a + ~b * ~x), ~x) + csc((~b * ~c - ~a * ~d) / ~b) * Antiderivative(tan(~c + ~d * ~x), ~x) <-- FreeQ([~a, ~b, ~c, ~d], ~x) && (EqQ((~b) ^ 2 - (~d) ^ 2, 0) && NeQ(~b * ~c - ~a * ~d, 0))
    @apply_utils Antiderivative(csc(~(a') + ~(b') * ~x) * csc(~c + ~(d') * ~x), ~x) => csc((~b * ~c - ~a * ~d) / ~b) * Antiderivative(cot(~a + ~b * ~x), ~x) - csc((~b * ~c - ~a * ~d) / ~d) * Antiderivative(cot(~c + ~d * ~x), ~x) <-- FreeQ([~a, ~b, ~c, ~d], ~x) && (EqQ((~b) ^ 2 - (~d) ^ 2, 0) && NeQ(~b * ~c - ~a * ~d, 0))
    @apply_utils Antiderivative(tan(~(a') + ~(b') * ~x) * tan(~c + ~(d') * ~x), ~x) => (-(~b) * ~x) / ~d + (~b / ~d) * cos((~b * ~c - ~a * ~d) / ~d) * Antiderivative(sec(~a + ~b * ~x) * sec(~c + ~d * ~x), ~x) <-- FreeQ([~a, ~b, ~c, ~d], ~x) && (EqQ((~b) ^ 2 - (~d) ^ 2, 0) && NeQ(~b * ~c - ~a * ~d, 0))
    @apply_utils Antiderivative(cot(~(a') + ~(b') * ~x) * cot(~c + ~(d') * ~x), ~x) => (-(~b) * ~x) / ~d + cos((~b * ~c - ~a * ~d) / ~d) * Antiderivative(csc(~a + ~b * ~x) * csc(~c + ~d * ~x), ~x) <-- FreeQ([~a, ~b, ~c, ~d], ~x) && (EqQ((~b) ^ 2 - (~d) ^ 2, 0) && NeQ(~b * ~c - ~a * ~d, 0))
    @apply_utils Antiderivative(~(u') * (~(a') * cos(~v) + ~(b') * sin(~v)) ^ ~(n'), ~x) => Antiderivative(~u * (~a * ℯ ^ ((-(~a) / ~b) * ~v)) ^ ~n, ~x) <-- FreeQ([~a, ~b, ~n], ~x) && EqQ((~a) ^ 2 + (~b) ^ 2, 0)
    @apply_utils Antiderivative(sin(~(d') * (~(a') + ~(b') * log(~(c') * (~x) ^ ~(n'))) ^ 2), ~x) => (im / 2) * Antiderivative(ℯ ^ (-im * ~d * (~a + ~b * log(~c * (~x) ^ ~n)) ^ 2), ~x) - (im / 2) * Antiderivative(ℯ ^ (im * ~d * (~a + ~b * log(~c * (~x) ^ ~n)) ^ 2), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~n], ~x)
    @apply_utils Antiderivative(cos(~(d') * (~(a') + ~(b') * log(~(c') * (~x) ^ ~(n'))) ^ 2), ~x) => (1 / 2) * Antiderivative(ℯ ^ (-im * ~d * (~a + ~b * log(~c * (~x) ^ ~n)) ^ 2), ~x) + (1 / 2) * Antiderivative(ℯ ^ (im * ~d * (~a + ~b * log(~c * (~x) ^ ~n)) ^ 2), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~n], ~x)
    @apply_utils Antiderivative((~(e') * ~x) ^ ~(m') * sin(~(d') * (~(a') + ~(b') * log(~(c') * (~x) ^ ~(n'))) ^ 2), ~x) => (im / 2) * Antiderivative((~e * ~x) ^ ~m * ℯ ^ (-im * ~d * (~a + ~b * log(~c * (~x) ^ ~n)) ^ 2), ~x) - (im / 2) * Antiderivative((~e * ~x) ^ ~m * ℯ ^ (im * ~d * (~a + ~b * log(~c * (~x) ^ ~n)) ^ 2), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~m, ~n], ~x)
    @apply_utils Antiderivative((~(e') * ~x) ^ ~(m') * cos(~(d') * (~(a') + ~(b') * log(~(c') * (~x) ^ ~(n'))) ^ 2), ~x) => (1 / 2) * Antiderivative((~e * ~x) ^ ~m * ℯ ^ (-im * ~d * (~a + ~b * log(~c * (~x) ^ ~n)) ^ 2), ~x) + (1 / 2) * Antiderivative((~e * ~x) ^ ~m * ℯ ^ (im * ~d * (~a + ~b * log(~c * (~x) ^ ~n)) ^ 2), ~x) <-- FreeQ([~a, ~b, ~c, ~d, ~e, ~m, ~n], ~x)
end

max_stars_repo_path: src/rules/4 Trig functions/4.7 Miscellaneous/4.7.9 Active trig functions.jl


text:
"""
    FlexibilityAnalysis

A Julia package that implements a computational framework for quantifying and analyzing system flexibility.

The basic functionality emulates typical JuMP models to facilitate general computation of the flexibility
index problem. Thus, basic functionality uses [`FlexibilityModel`](@ref), [`@randomvariable`](@ref),
[`@recoursevariable`](@ref), `@variable`, `@constraint`, [`setuncertaintyset`](@ref), and `solve`.

**Methods/Macros**
- [`FlexibilityModel`](@ref)
- [`@randomvariable`](@ref)
- [`@recoursevariable`](@ref)
- [`getflexibilitydata`](@ref)
- [`setcovariance`](@ref)
- [`getcovariance`](@ref)
- [`getmean`](@ref)
- [`setmean`](@ref)
- [`setuncertaintyset`](@ref)
- [`ismeanfeasible`](@ref)
- [`findcenteredmean`](@ref)
- [`getflexibilityindex`](@ref)
- [`getsolutiontime`](@ref)
- [`getconfidencelevel`](@ref)
- [`getactiveconstraints`](@ref)
- [`rankinequalities`](@ref)
- [`findstochasticflexibility`](@ref)
"""
module FlexibilityAnalysis

    using Distributions
    using JuMP
    using LinearAlgebra
    using Random
    using Ipopt, Clp # Default solver

    # Define functions/macros to be readily accesible to the user
    export FlexibilityModel, @randomvariable, @recoursevariable, getflexibilitydata, setcovariance, getcovariance,
           getactiveconstraints, setuncertaintyset, getflexibilityindex, findcenteredmean, ismeanfeasible,
           getconfidencelevel, findstochasticflexibility, rankinequalities, getmean, setmean, getsolutiontime

    # Import all of the datatypes, methods, macros, and definitions
    include("datatypes.jl")
    include("model.jl")
    include("solve.jl")
    include("variables.jl")
    include("constraints.jl")
    include("macros.jl")
    include("uncertaintyset.jl")
    include("mean.jl")
    include("functions.jl")
    include("operators.jl")

end


text:
# csci_textread.jl
#
#	Load a Campbell Scientific TOA5 file
#
# Jeremy Rüffer
# Thünen Institut
# Institut für Agrarklimaschutz
# Junior Research Group NITROSPHERE
# Julia 1.6.0
# Created: 04.11.2013
# Last Edit: 28.07.2021

"""# csci_textread

Load a TOA5 data file generated by Campbell Scientific dataloggers

---

### Examples

`t, d = csci_textread(\"K:\\\\Data\\\\AirTemp.dat\")` Load the data from a file into \"t\", a DateTime array, and \"d\", a floating point array.

`t, d, logger_Str, columns_Str, units_Str, type_Str = csci_textload(\"K:\\\\Data\\\\AirTemp.dat\",headerout = true)` # Output the header lines in addition to the data

---

`t, d = csci_textread(F::String;headerlines::Int=4,headeroutput::Bool=false,verbose::Bool=true,strlist::Array{String,1}=String[],intlist::Array{String,1}=String[],timelist::Array{String,1}=String[])`\n
* **data**::DataFrame = Loaded data, including a fully parsed time column
* **F**::String = File of file to load
* **headerlines**::Int (optional) = Number of header lines, 4 is default
* **headeroutput**::Bool (optional) = Add four header lines to output, FALSE is default
* **verbose**::Bool (optional) = Display information about what is happening when set to TRUE, TRUE is default
* **strlist**::Vector{String} (optional) = List of column names that should be strings, [] is default
* **intlist**::Vector{String} (optional) = List of column names that should be integers, [] is default
* **timelist**::Vector{String} (optional) = List of column names that should be DateTime values, [] is default
* **select**::Vector{Symbol} (optional) = List of column names to be loaded, names not included will not be loaded. [] is default
"""
function csci_textread(F::String;headerlines::Int=4,headeroutput::Bool=false,verbose::Bool=true,strlist::Vector{String}=String[],intlist::Vector{String}=String[],timelist::Vector{String}=String[],select::Vector{Symbol}=Symbol[])
	# F = file name and location
	# kwargs = KeyWord Arguments
	#	hout::Bool = Include four additional header lines in outputs
	#	headerlines::Int = Number of header lines

	## SELECT Check
	if !isempty(select) && :Timestamp ∉ select
		select = [:Timestamp;select] # Timestamp must be included
	end

	headerlines += 1
	df = Dates.DateFormat("yyyy-mm-dd HH:MM:SS.ss") # Date format

	## Update Conversion Lists
	strlist = ["OSVersion";"ProgName";"CompileResults";"CardStatus";"IPInfo";"pppDialResponse";"DataTableName\\(\\d\\)";"PortConfig\\(\\d\\)";"IPAddressEth";"IPMaskEth";"IPGateway";"pppIPAddr";"pppUsername";"pppPassword";"pppDial";"Messages";strlist]
	intlist = ["RECORD";"TCPPort";intlist]
	timelist = ["TIMESTAMP";"StartTime";"LastSystemScan";timelist]

	## Load Header Data
	fid = open(F,"r")
	loggerStr = readline(fid)
	colsStr = readline(fid)
	unitsStr = readline(fid)
	processingStr = readline(fid)
	close(fid)

	logger = readdlm(IOBuffer(loggerStr),',')
	cols_temp = readdlm(IOBuffer(colsStr),',')
	units = readdlm(IOBuffer(unitsStr),',')
	processing_temp = readdlm(IOBuffer(processingStr),',')

	cols = Array{String}(undef,length(cols_temp))
	processing = Array{String}(undef,length(cols_temp))
	for i=1:length(cols)
		cols[i] = cols_temp[i]
		processing[i] = processing_temp[i]
	end

	## Prepare Type List
	types = Any[Float64 for i=1:length(processing)]
	for i=1:1:length(types)
		for j=1:1:length(strlist)
			if occursin(Regex(strlist[j]),cols[i])
				types[i] = Union{Missing,String}
			end
		end
	end
	for i=1:1:length(types)
		for j=1:1:length(intlist)
			if occursin(Regex(intlist[j]),cols[i])
				types[i] = Int
			end
		end
	end
	t_index = Int[]
	for i=1:1:length(types)
		for j=1:1:length(timelist)
			if occursin(Regex(timelist[j]),cols[i])
				types[i] = DateTime
				t_index = [t_index;i]
			end
		end
	end

	cols[1] = "Timestamp"
	cols[2] = "Record"

	## Load Data
	if isempty(select)
		D = CSV.read(F,DataFrame;types = types,header=cols,delim = ',',datarow = headerlines,dateformat = df)
	else
		D = CSV.read(F,DataFrame;types = types,header=cols,delim = ',',datarow = headerlines,dateformat = df,select = select)
	end

	if headeroutput
		return D,loggerStr,colsStr,unitsStr,processingStr
	else
		return D
	end
end # csci_textread(F::String;headerlines=4,headeroutput=false,verbose=true,strlist=[],intlist=[],timelist=[])


text:
@testset "SimpleEdgeIter" begin
    ga = @inferred(SimpleGraph(10,20; seed=1))
    gb = @inferred(SimpleGraph(10,20; seed=1))
    @test sprint(show,edges(ga)) == "SimpleEdgeIter 20"
    @test sprint(show, start(edges(ga))) == "SimpleEdgeIterState [1, 1, false]"

    @test length(collect(edges(Graph(0,0)))) == 0

    @test @inferred(edges(ga)) == edges(gb)
    @test @inferred(edges(ga)) == collect(Edge, edges(gb))
    @test collect(Edge, edges(gb)) == edges(ga)
    @test Set{Edge}(collect(Edge, edges(gb))) == edges(ga)
    @test @inferred(edges(ga)) == Set{Edge}(collect(Edge, edges(gb)))

    @test @inferred(eltype(edges(ga))) == eltype(typeof(edges(ga))) == SimpleEdge

    ga = @inferred(SimpleDiGraph(10,20; seed=1))
    gb = @inferred(SimpleDiGraph(10,20; seed=1))
    @test @inferred(edges(ga)) == edges(gb)
    @test @inferred(edges(ga)) == collect(SimpleEdge, edges(gb))
    @test collect(SimpleEdge, edges(gb)) == edges(ga)
    @test Set{Edge}(collect(SimpleEdge, edges(gb))) == edges(ga)
    @test @inferred(edges(ga)) == Set{SimpleEdge}(collect(SimpleEdge, edges(gb)))

    ga = SimpleGraph(10)
    add_edge!(ga, 3, 2)
    add_edge!(ga, 3, 10)
    add_edge!(ga, 5, 10)
    add_edge!(ga, 10, 3)

    eit = edges(ga)
    es = @inferred(start(eit))

    @test es.s == 2
    @test es.di == 1

    @test [e for e in eit] == [Edge(2, 3), Edge(3, 10), Edge(5,10)]

    ga = SimpleDiGraph(10)
    add_edge!(ga, 3, 2)
    add_edge!(ga, 3, 10)
    add_edge!(ga, 5, 10)
    add_edge!(ga, 10, 3)

    eit = @inferred(edges(ga))
    es = @inferred(start(eit))

    @test es.s == 3
    @test es.di == 1

    @test [e for e in eit] == [
      SimpleEdge(3, 2), SimpleEdge(3, 10),
      SimpleEdge(5,10), SimpleEdge(10,3)
    ]
end

max_stars_repo_name: AsileBcd/JohnsonCycles

max_issues_repo_name: AsileBcd/JohnsonCycles

max_forks_repo_name: AsileBcd/JohnsonCycles


text:
include("problems.jl")
include("temps.jl")

function main()
    tic()

    res = 32
    nbits = 4

    change_f3_size(res)
    change_deceptiveN_size(res, nbits)

    size           = res * nbits
    formula        = 0
    #=s_i            = map( x -> x == 1, rand(0:1, size))=#
    s_i            = (rand(Float64, 10) .* 10.0) .- 5.0
    maxIter        = 1 * 10^8
    t_0            = 20.0
    t_n            = 0.0
    iter           = 0
    temp           = hyperbolic_cos
    acceptf        = accept_default
    x              = []
    y              = []
    ytemp          = []
    progressInt    = 1 * 10^5
    progress       = true
    scale          = 1.0

    best           = 300
    bb             = s_i

    while iter < maxIter
        T     = temp(t_0, t_n, iter, maxIter)
        iter += 1
        s_new = neighbour(s_i)
        t     = energy(s_i  , formula)
        t_new = energy(s_new, formula)
        p     = rand()
        Δc    = t_new - t

        if iter == 0
            best = t
        end

        if t_new < best
            best = t_new
            bb = s_new
        end

        if progress && ( iter % progressInt == 0 )
            @printf("%10.2f %10.2f %10.2f %10.2f %10.2f %10.2f\n", 100.0*iter/maxIter, t, T, Δc, acceptf(Δc, T, t_0), best)
        end

        if Δc < 0.0
            s_i = s_new
        elseif acceptf(Δc * scale, T, t_0) > p
            s_i = s_new
        end
    end

    println(bb)
    println(best)

    #=return (toq(), solvedIter, solved, x, y)=#
end

main()


text:
using Images, MXNet

### LOADING THE MODEL

const MODEL_NAME = "weights/mobilenet-v2/mobilenet_v2"
const MODEL_CLASS_NAMES = "weights/mobilenet-v2/synset.txt"

nnet = mx.load_checkpoint(MODEL_NAME, 0, mx.FeedForward);
synset = readlines(MODEL_CLASS_NAMES);

img = imresize(load("sample-images/bird-3183441_640.jpg"), (224, 224));
img = permutedims(Float16.(channelview(img)), (3, 2, 1));

img[:, :, :] *= 256.0;
img[:, :, :] -= 128.;
img[:, :, :] /= 128.;

img = reshape(img, 224, 224, 3, 1);

mx_data = mx.zeros((224, 224, 3, 1));
mx_data[1:1] = img;
data_provider = mx.ArrayDataProvider(:data => mx_data);

### PREDICTING

@time pred = mx.predict(nnet, data_provider);
mxval, mxindx = findmax(pred[:, 1]);
println(mxval, " ", mxindx, " ", synset[mxindx])


text:
function main(r::Robot)
    for i ∈ (North, South, West, East)
        go_to_border_come_back_and_return_distance!(r, i; markers = true, go_around_barriers = true)
    end
    putmarker!(r)
end

max_stars_repo_name: Savko-fokin/mirea-progs

max_issues_repo_name: Savko-fokin/mirea-progs

max_forks_repo_name: Savko-fokin/mirea-progs


text:
### A Pluto.jl notebook ###
# v0.12.20

using Markdown
using InteractiveUtils

# ╔═╡ cf890c59-4b23-4cf9-8620-8259911a8b76
begin
	using Pkg
	Pkg.activate(mktempdir())
	Pkg.Registry.update()
	Pkg.add("Yao")
	Pkg.add("YaoPlots")
	Pkg.add("StatsBase")
	Pkg.add("Plots")
	Pkg.add("BitBasis")
end

# ╔═╡ 3636e5d4-0276-11eb-2346-b77b042e1240
using Yao, YaoPlots

# ╔═╡ d1930710-4466-11eb-3528-8bdcf0543578
begin
	using StatsBase: Histogram, fit
	using Plots: bar, scatter!, gr; gr()
	using BitBasis
	function plotmeasure(x::Array{BitStr{n,Int},1}) where n
		hist = fit(Histogram, Int.(x), 0:2^n)
		x = 0
		if(n<=3)
			s=8
		elseif(n>3 && n<=6)
			s=5
		elseif(n>6 && n<=10)
			s=3.2
		elseif(n>10 && n<=15)
			s=2
		elseif(n>15)
			s=1
		end
		bar(hist.edges[1] .- 0.5, hist.weights, legend=:none, size=(600*(2^n)/s,400), ylims=(0:maximum(hist.weights)), xlims=(0:2^n), grid=:false, ticks=false, border=:none, color=:lightblue, lc=:lightblue)
		scatter!(0:2^n-1, ones(2^n,1), markersize=0,
         series_annotations="|" .* string.(hist.edges[1]; base=2, pad=n) .* "⟩")
		scatter!(0:2^n-1, zeros(2^n,1) .+ maximum(hist.weights), markersize=0,
         series_annotations=string.(hist.weights))
	end
end

# ╔═╡ 1aba2418-0273-11eb-2fb6-a12d0afc33c6
md"# Applications
We'll discuss a few applications of qubits and quantum circuits. Namely the Bell States, Superdense Coding and Quantum Teleportation."

# ╔═╡ 84abe9cc-0273-11eb-0e38-c3a2b42c0848
md"## Bell States
The states,

`` \frac{|00〉 + |11〉}{\sqrt2},  \frac{|01〉 + |10〉}{\sqrt2} ``

`` \frac{|00〉 - |11〉}{\sqrt2} `` and `` \frac{|01〉 - |10〉}{\sqrt2} ``

are known as the bell states. They are made by the bell circuit. The bell circuit looks like this."

# ╔═╡ 24727e9e-0276-11eb-344c-25a2ba5f138c
begin
	bellcircuit = chain(2, put(1=>H), control(1, 2=>X))
	plot(bellcircuit)
end

# ╔═╡ 6a117428-0276-11eb-156f-cf8597070a34
md"As you can see, the circuit takes in two qubits as input, and operates on them to give the bell states."

# ╔═╡ 932449a0-0277-11eb-0805-c533ef1ceebb
md"#### Feeding qubits to a circuit in Yao
There are many ways to create qubits to feed to quantum circuits in Yao."

# ╔═╡ 1a64822e-0278-11eb-1ed7-8f7f03623cee
q1 = ArrayReg(bit"00") #creating the system of two qubits with state |00>.

# ╔═╡ 6af54232-027d-11eb-087e-3b2516a14eb8
state(q1) #state of a qubit in vector form

# ╔═╡ 97a2930a-0278-11eb-1e5b-c1dc5b203022
md" **Note:** _**Normalizing** basically means making the summation of squares of probability amplitudes, equal to 1._"

# ╔═╡ 1e60af8c-0279-11eb-21fd-77cbe8640448
md"Other ways of doing it are"

# ╔═╡ 23f8e17c-0287-11eb-34ab-25db7b60da63
ArrayReg(bit"00") + ArrayReg(bit"11") |> normalize! #Equivalent to (1/√2)*(|00>+|11>)

# ╔═╡ 3951f92c-0279-11eb-1097-0b9935025360
zero_state(2) #2 qubits, both with the state |0> and |0>

# ╔═╡ 033aa410-0279-11eb-3742-c7b3084f847b
md" There! We have a system of two qubits! Let's try feeding the qubits to the Bell circuit we made!"

# ╔═╡ 4a6f0f16-027b-11eb-0d9e-77a3d5c6f1ee
a = (q1 |> bellcircuit) #Passing the qubit q1 through the bell circuit

# ╔═╡ f6d9ad26-0285-11eb-115c-db22262790db
state(a)

# ╔═╡ 7f471eb2-0286-11eb-3fa4-45952f77d4eb
md"### Reverse Bell Circuit
A circuit which reverses the effects of the bell circuit on a qubit. It's represented in a circuit as follows"

# ╔═╡ a6ab9b2e-0286-11eb-382e-07d449a188c6
begin
	reversebellcircuit = chain(2, control(1,2=>X), put(1=>H))
	plot(reversebellcircuit)
end

# ╔═╡ cfa3d672-0286-11eb-3ce5-47a7afe1d336
md"You can input the output state you got from the bell circuit, into the reverse bell circuit, and you'll get back your original state. Why not give it a try?"

# ╔═╡ 43241144-031c-11eb-01f4-d91cefa66359
md"Let's pass the qubits we got by passing two qubits in the Bell circuit, into the Reverse Bell Circuit."

# ╔═╡ 0f1b1ea0-031d-11eb-326c-65cd5aa41630
let
		res = (a |> reversebellcircuit)
		state(res)
end

# ╔═╡ f7b24140-0320-11eb-010d-db85da69ed7c
md"What do you think is the effect of single qubit gates on a qubit, which is entangled with another qubit? Lets check it out!"

# ╔═╡ 30a26136-0321-11eb-3375-af7b708a196d
begin
	singlequbitcircuit = chain(2, put(1=>X))
	plot(singlequbitcircuit)
end

# ╔═╡ 57be66c2-0326-11eb-0090-39e6b4f26b19
begin
	bellstate = ArrayReg(bit"00") + ArrayReg(bit"11") |> normalize!
	re = bellstate |> singlequbitcircuit
	state(re)
end

# ╔═╡ 68a743ea-0322-11eb-0039-d9a5ab8ad3f9
md"Can you notice how the circuit behaves as if its operating on one qubit? If the input is |{0}[1]〉 + |{1}[1]〉, it behaves like the bits in the curly braces are the state of one qubit, while the bits in sqare brackets are the state of the other qubit, and it operates on them accordingly?"

# ╔═╡ 4d4432a2-031d-11eb-28f1-f39a26b8b789
md"### Super-dense Coding and Quantum Teleportation"

# ╔═╡ 8012368e-031d-11eb-1aa6-f53e9ca5f88f
md"Suppose we have two entangled qubits in a bell state, represented by
`` \frac{|00〉 + |11〉}{\sqrt2} .`` Alice and Bob are two friends. Alice gets one qubit and Bob gets the other one. Both of them travel far apart with their qubits, and not measuring their qubits so as to preserve the entangled state. The above information is the premise for both:
1. Super-dense coding
2. Quantum Teleportation"

# ╔═╡ 669e0b32-031e-11eb-231f-956bf10c9850
md"##### 1. Super-dense coding
Alice wants to send Bob two classical bits of information. That means, one of the four states `` 00, 01, 10 `` and `` 11 ``. How does she do this?
Lets say she achieves this by passing her qubits through one of the following gates, corresponding to the information she wants to send.

1. If she wants to send Bob `` 00 ``, then she'll send her qubit to Bob, as it is
2. If she wants to send Bob `` 01 ``, then she'll send her qubit to Bob, after passing it through X gate.
3. If she wants to send Bob `` 10 ``, then she'll send her qubit to Bob, after passing it through Z gate.
4. If she wants to send Bob `` 11 ``, then she'll send her qubit to Bob, after passing it through Y gate.

Bob will then run both the qubits through the reverse bell circuit and measure them and he'll get what Alice wanted to send him."

# ╔═╡ 65c3b24c-0324-11eb-11bb-8dfba3e35770
md"Measuring qubits in Yao can be done by using the measure function.

Assume you've the a qubit or a system of qubits in q, and you want to measure it, the syntax is,

	q |> r->measure(r, nshots=number_of_runs)
We can't determine the probability amplitudes of a qubit. But, we can run the measurement many times, and count the frequency of each bit combination it gives.

If you don't get that, just know the syntax and keep nshots=1024.

Now, lets try measuring the result of the previous assignment!"

# ╔═╡ 0e2e6f62-0325-11eb-1637-116783c77ea8
measuredqubits = re |> r->measure(r, nshots=1024)

# ╔═╡ d623229e-04b3-11eb-37e4-65be46f8a1c2
md"Sometimes the measurement gives `` |01〉 `` and sometimes `` |10〉 ``. The probability of getting a `` |01〉 `` is same as getting the probability of `` |10〉 ``, which is `` (1/\sqrt2)^2 `` that is `` 0.5 `` ."

# ╔═╡ 42eda908-04b4-11eb-1d71-2b2df3ab0b82
md"Wanna see how we can test that? The below function plots the probability as histograms. You don't need to know its inner workings to use it."

# ╔═╡ 89e76d2e-04b4-11eb-0704-17b457103932
plotmeasure(measuredqubits)

# ╔═╡ b544dd14-446a-11eb-19c1-914694722f0e
md"The probability of the measurement giving `` |01〉 `` is $ $(sum(measuredqubits .== bit\"01\")/10.24)% $ and the number of times the measurement result is `` |10〉 `` is $ $(sum(measuredqubits .== bit\"10\")/10.24)\%. $"

# ╔═╡ ef6e1276-03d8-11eb-08b6-1fc082d158f6
md"Implementing the superdense coding."

# ╔═╡ 124eca24-03d9-11eb-3bca-c188b5d09404
begin
	Alice_and_Bobs_entangled_qubits = ArrayReg(bit"00") + ArrayReg(bit"11") |> normalize!
	input = ["00" "01" "10" "11"][rand(1:4)] #Assuming Alice wants to send one of these inputs to Bob.
end

# ╔═╡ 3e4d90dc-03df-11eb-371e-130d4339b472
state(Alice_and_Bobs_entangled_qubits)

# ╔═╡ ae574c4c-03da-11eb-2eb0-b1d06f9d61de
begin
	if(input == "00")
		Alices_circuit = chain(2)
	elseif(input == "01")
		Alices_circuit = chain(2, put(1=>X))
	elseif(input == "10")
		Alices_circuit = chain(2, put(1=>Z))
	elseif(input == "11")
		Alices_circuit = chain(2, put(1=>Y))
	end
	plot(Alices_circuit)
end

# ╔═╡ adf60706-03db-11eb-2206-c7f5ac69ab41
Bobs_part = ((Alice_and_Bobs_entangled_qubits |> Alices_circuit) |> reversebellcircuit) |> r->measure(r, nshots=1024)
#The content in the first round bracket, outputs qubits, which are then fed to reversebellcircuit we saw before, which is then fed to the measure function.

# ╔═╡ 8570a5d0-03b7-11eb-0f75-09aad5a4b811
md"##### 2. Quantum Teleportation
Alice now has one more qubit, in the state `` a|0〉 + b|1〉.`` She wants to send her qubit to Bob, by changing the state of Bob's entangled qubit to Alice's extra qubit.

Confusing? Let's try naming the qubits. Alice and Bob have the qubits A and B respectively, which are entangled in the bell state. Alice has another qubit C.

Alice wants to send her qubit to Bob by changing the state of B, to that of C. She wants the state of the qubit B to be `` a|0〉 + b|1〉. `` Alice doesn't know the values of a and b. Also, Bob can't make a measurement in any case as doing so will destroy B's state.

How does Alice do it? Well, she first passes both her qubits through the Reverse Bell circuit. She then measures both of her qubits. She gets one of the following outputs: `` |00〉, |01〉, |10〉 or |11〉, `` each with probability 1/4. Alice sends these two classical bits to Bob, via any classical means, example, she texts him or calls and tells him. Bob knows that corresponding to her message, there are 4 options, and he takes action accordingly for each.
1. He gets the message, `` |00〉, `` from Alice and knows that his qubit\(qubit B\) changed its state to that of qubit C.
2. He gets the message, `` |01〉, `` and knows that his qubit changed its state to `` a|1〉 + b|0〉, `` and he passes his qubit through X gate to change its state to that of qubit C.
3. He gets the message, `` |10〉, `` and knows that his qubit changed its state to `` a|0〉 - b|1〉, `` and he passes his qubit through Z gate to change its state to that of qubit C.
4. He gets the message, `` |11〉, `` and knows that his qubit changed its state to `` a|1〉 - b|0〉, `` and he passes his qubit through Y gate to change its state to that of qubit C."

# ╔═╡ 37d4357e-03be-11eb-3e1f-dda5a699af33
begin
	Alices_and_Bobs_entangled_qubits = ArrayReg(bit"00") + ArrayReg(bit"11") |> normalize!
	Alicequbit = rand_state(1) #This function creates a qubit with a random state.
	state(Alicequbit)
end

# ╔═╡ 6ca5a9cc-03be-11eb-2afa-295c81c21e35
state(Alices_and_Bobs_entangled_qubits)

# ╔═╡ af31a570-03be-11eb-1af1-03950ee1c51f
begin
	teleportationcircuit = chain(3, control(1,2=>X), put(1=>H))
	plot(teleportationcircuit)
end

# ╔═╡ 6498549a-03bf-11eb-0348-a9072154b85e
begin
	feeding = join(Alices_and_Bobs_entangled_qubits, Alicequbit) |> teleportationcircuit
	state(feeding)
end

# ╔═╡ 14abac76-03c1-11eb-0634-afc86a739215
md"The ``` join(qubit1, qubit2.....,qubitn) ``` function is used to join multiple qubits. Remember, the circuit takes the qubits as inputs, in reverse order."

# ╔═╡ b2e2fea0-03e4-11eb-1a20-157447a12ce5
Alices_measuredqubits = measure!(RemoveMeasured(), feeding, 1:2)

# ╔═╡ 5331ad20-03e5-11eb-1244-1b494c4afa02
if(Alices_measuredqubits == bit"00")
	Bobs_qubit = feeding
elseif(Alices_measuredqubits == bit"01")
	Bobs_qubit = feeding |> chain(1, put(1=>Z))
elseif(Alices_measuredqubits == bit"10")
	Bobs_qubit = feeding |> chain(1, put(1=>X))
else
	Bobs_qubit = feeding |> chain(1, put(1=>Y))
end

# ╔═╡ 8e222eee-03e2-11eb-3419-edfe12b7c61a
md"The ` RemoveMeasured() ` parameter in ` measure!() `, first measures the qubits, then removes the measured qubits from the system of qubits."

# ╔═╡ 49604160-03c4-11eb-2480-ff7abbe90508
state(Bobs_qubit)

# ╔═╡ bec22f54-03e7-11eb-34fd-0fce9ea7da8f
md"Is Alice's qubit same as Bob's qubit now?
You can see that for yourself!"

# ╔═╡ 14a7320c-03e8-11eb-0909-1354fd574659
[state(Alicequbit) state(Bobs_qubit)]

# ╔═╡ 340a69fe-068c-11eb-3b37-ed2694843113
md"Left side : State of Alice's qubit. Right side : State of Bob's qubit. Almost equivalent!"

# ╔═╡ Cell order:
# ╠═cf890c59-4b23-4cf9-8620-8259911a8b76
# ╠═3636e5d4-0276-11eb-2346-b77b042e1240
# ╟─1aba2418-0273-11eb-2fb6-a12d0afc33c6
# ╟─84abe9cc-0273-11eb-0e38-c3a2b42c0848
# ╠═24727e9e-0276-11eb-344c-25a2ba5f138c
# ╟─6a117428-0276-11eb-156f-cf8597070a34
# ╟─932449a0-0277-11eb-0805-c533ef1ceebb
# ╠═1a64822e-0278-11eb-1ed7-8f7f03623cee
# ╠═6af54232-027d-11eb-087e-3b2516a14eb8
# ╟─97a2930a-0278-11eb-1e5b-c1dc5b203022
# ╟─1e60af8c-0279-11eb-21fd-77cbe8640448
# ╠═23f8e17c-0287-11eb-34ab-25db7b60da63
# ╠═3951f92c-0279-11eb-1097-0b9935025360
# ╟─033aa410-0279-11eb-3742-c7b3084f847b
# ╠═4a6f0f16-027b-11eb-0d9e-77a3d5c6f1ee
# ╠═f6d9ad26-0285-11eb-115c-db22262790db
# ╟─7f471eb2-0286-11eb-3fa4-45952f77d4eb
# ╠═a6ab9b2e-0286-11eb-382e-07d449a188c6
# ╟─cfa3d672-0286-11eb-3ce5-47a7afe1d336
# ╟─43241144-031c-11eb-01f4-d91cefa66359
# ╠═0f1b1ea0-031d-11eb-326c-65cd5aa41630
# ╟─f7b24140-0320-11eb-010d-db85da69ed7c
# ╠═30a26136-0321-11eb-3375-af7b708a196d
# ╠═57be66c2-0326-11eb-0090-39e6b4f26b19
# ╟─68a743ea-0322-11eb-0039-d9a5ab8ad3f9
# ╟─4d4432a2-031d-11eb-28f1-f39a26b8b789
# ╟─8012368e-031d-11eb-1aa6-f53e9ca5f88f
# ╟─669e0b32-031e-11eb-231f-956bf10c9850
# ╟─65c3b24c-0324-11eb-11bb-8dfba3e35770
# ╠═0e2e6f62-0325-11eb-1637-116783c77ea8
# ╟─d623229e-04b3-11eb-37e4-65be46f8a1c2
# ╟─42eda908-04b4-11eb-1d71-2b2df3ab0b82
# ╠═d1930710-4466-11eb-3528-8bdcf0543578
# ╠═89e76d2e-04b4-11eb-0704-17b457103932
# ╟─b544dd14-446a-11eb-19c1-914694722f0e
# ╟─ef6e1276-03d8-11eb-08b6-1fc082d158f6
# ╠═124eca24-03d9-11eb-3bca-c188b5d09404
# ╠═3e4d90dc-03df-11eb-371e-130d4339b472
# ╠═ae574c4c-03da-11eb-2eb0-b1d06f9d61de
# ╠═adf60706-03db-11eb-2206-c7f5ac69ab41
# ╟─8570a5d0-03b7-11eb-0f75-09aad5a4b811
# ╠═37d4357e-03be-11eb-3e1f-dda5a699af33
# ╠═6ca5a9cc-03be-11eb-2afa-295c81c21e35
# ╠═af31a570-03be-11eb-1af1-03950ee1c51f
# ╠═6498549a-03bf-11eb-0348-a9072154b85e
# ╟─14abac76-03c1-11eb-0634-afc86a739215
# ╠═b2e2fea0-03e4-11eb-1a20-157447a12ce5
# ╠═5331ad20-03e5-11eb-1244-1b494c4afa02
# ╟─8e222eee-03e2-11eb-3419-edfe12b7c61a
# ╠═49604160-03c4-11eb-2480-ff7abbe90508
# ╟─bec22f54-03e7-11eb-34fd-0fce9ea7da8f
# ╠═14a7320c-03e8-11eb-0909-1354fd574659
# ╟─340a69fe-068c-11eb-3b37-ed2694843113


text:
using Oceananigans

# Definition of the "Bickley jet": a sech(y)^2 jet with sinusoidal tracer
Ψ(y) = - tanh(y)
U(y) = sech(y)^2

# A sinusoidal tracer
C(y, L) = sin(2π * y / L)

# Slightly off-center vortical perturbations
ψ̃(x, y, ℓ, k) = exp(-(y + ℓ/10)^2 / 2ℓ^2) * cos(k * x) * cos(k * y)

# Vortical velocity fields (ũ, ṽ) = (-∂_y, +∂_x) ψ̃
ũ(x, y, ℓ, k) = + ψ̃(x, y, ℓ, k) * (k * tan(k * y) + y / ℓ^2)
ṽ(x, y, ℓ, k) = - ψ̃(x, y, ℓ, k) * k * tan(k * x)

"""
    u, v: Large-scale jet + vortical perturbations
       c: Sinusoid
"""
function set_bickley_jet!(model;
                          ϵ = 0.1, # perturbation magnitude
                          ℓ = 0.5, # gaussian width
                          k = 0.5) # sinusoidal wavenumber

    # total initial conditions
    uᵢ(x, y, z) = U(y) + ϵ * ũ(x, y, ℓ, k)
    vᵢ(x, y, z) = ϵ * ṽ(x, y, ℓ, k)
    cᵢ(x, y, z) = C(y, model.grid.Ly)

    # Note that u, v are only horizontally-divergence-free as resolution -> ∞.
    set!(model, u=uᵢ, v=vᵢ, c=cᵢ)

    return nothing
end

bickley_grid(; Nh, arch=CPU(), halo=(3, 3, 3)) = RectilinearGrid(arch; size=(Nh, Nh, 1), halo,
                                                                 x = (-2π, 2π), y=(-2π, 2π), z=(0, 1),
                                                                 topology = (Periodic, Periodic, Bounded))


text:
include("random_particles.jl")
include("moments.jl")


text:
# SEIR-like model for Corona outbreak 2019/20
#
# based on Wang et al. Evolving epidemiology and impact of non-pharmaceutical
# interventions on the outbreak of coronavirus disease 2019 in Wuhan, China.
# MedRxive (2020) doi.org/10.1101/2020.03.03.2003059

module C

using Dates, PyPlot, DifferentialEquations, Polynomials

include("read_data.jl")

function rhs(du,u,p,t)
  S,E,I,A,H,R = u
  b,alpha,n,De,Dq,Di,Dh,r = p
  N = S+E+I+A+H+R
  du[1] = dS = -b*S*(I+alpha*A)/N + n - n*S/(N-I-H)   # susceptible
  du[2] = dE = b*S*(I+alpha*A)/N - E/De - n*E/(N-I-H) # latent
  du[3] = dI = r*E/De - I/Dq - I/Di                   # reported infectious
  du[4] = dA = (1-r)*E/De - A/Di - n*A/(N-I-H)        # unreported infectious
  du[5] = dH = I/Dq - H/Dh                            # hospitalized
  du[6] = dR = (I+A)/Di + H/Dh - n*R/(N-I-H)          # recovered
end

function nlys(scenario)
  tmax = 100.0  # all time units in days

  # The Wang et al. study changes parameters withing 4 periods
  # period 1: Jan 1-10   # before Chunyun (Chinese New Year)
  # period 2: Jan 11-22  # Chunyun period massive population movement
                         # hospitals starting to be crowded
  # period 3: Jan 23 - Feb 1 # implementation of social distancing
  # period 4: Feb 2-18   # improvement in medical resources

  b =  1.75  # transmission rate [1.75, 1.75, 0.58, 0.15]
  alpha = 1  # transmission rate ratio of unacertained ov acertained cases
  r =  0.19  # acertainment rate [0.19, 0.19, 0.22, 0.17]
  De =  5.2  # latent period
  Di =  2.3  # infectious period
  Dq =  10   # time from onset of illness to hospitalization [10, 7, 5, 2]
  Dh =  30   # hospitalization period
  n  = 0     # daily inbound and outbound size [500000, 800000, 0 , 0]

  if scenario == :wuhan
      N  = 10 * 1e6  # population size Wuhan
      E0 = 346
      I0 = 80
      A0 = 80
      H0 = 27
  elseif scenario == :de
      N  = 82 * 1e6  # population size Germany
      E0 = 500   # this is just put in by hand to make a smooth start
      I0 = 16
      A0 = 16    # intially equal number of reported and unreported
      H0 = 0     # assume initially there are no hospitalized

      r = 0.22 # slightly increase the acertainment rate
      #Di =  4.2  # infectious period
  elseif scenario == :it
      N  = 60 * 1e6  # population size Italy
      E0 = 1000
      I0 = 20
      A0 = 200
      H0 = 0
      b = 2.0 # to fit the data
      #r = 0.32 # or we increase the acertainment rate a lot
  elseif scenario == :us
      N = 327 * 1e6  # population size US
      E0 = 346
      I0 = 80
      A0 = 80
      H0 = 27
  elseif scenario == :OL   # try the model on a city-scale
      N  = 170000.0 # population size of Oldenburg (my city in Germany)
      E0 = 50
      I0 = 5
      A0 = 5
      H0 = 0
      #b = 2.0 # to fit the data in the first 10 days in Germany,
      r = 0.32 # or we increase the acertainment rate a lot
  end
  R0 = 0
  S0 = N - E0 - I0 - A0 - H0 - R0

  u0 = [S0;E0;I0;A0;H0;R0]
  tspan = (0.0,tmax)
  p = (b,alpha,n,De,Dq,Di,Dh,r)
  prob = ODEProblem(rhs,u0,tspan,p)
  sol = solve(prob)
  t = 0:0.1:tmax  # use interpolation of results
  res = sol(t)
  S = res[1,:]
  E = res[2,:]
  I = res[3,:]
  A = res[4,:]
  H = res[5,:]
  R = res[6,:]

  # effective reproductive number  (formula from Wang et al)
  R0 = Di .* b ./ (A .+ I) .* (alpha .* A .+ Dq .* I ./ (Di .+ Dq))

  t_de,I_de,R_de,D_de = covid_ts("Germany", Date(2020,2,24))
  t_it,I_it,R_it,D_it = covid_ts("Italy",   Date(2020,2,21))

  ## Plots ****************************************************

  if scenario == :OL  # this scenario calculates the epidemic course for a small city
      figure("ts_OL")
      clf()
      subplot(3,1,1)
      plot(t,I)
      plot(t,I .+ A, "r")
      ylabel("infected")
      xlim(0,50)
      subplot(3,1,2)
      plot(t, log10.(I))
      plot(t, log10.(I .+ A),"r")
      ylabel("log10(infected)")
      xlim(0,50)
      subplot(3,1,3)
      plot(t,R)
      ylabel("recovered")
      xlabel("time (days)")
  end

  if scenario == :de    # simulate scenario for Germany
      figure("ts_ge")
      clf()

      subplot(3,2,1)  # show the whole outbreak
      #plot(t_it .+ 6 ,I_it,"g*")  # time delay Italy cases
      plot(t_de,I_de,"r*")        # German cases
      plot(t,I)                   # model for acertained infected
      plot(t,A .+ I .+ H, "g")    # model of real (including non-acerted) infected
      xlim(0,60)
      ylabel("infected")

      subplot(3,2,2)   # show only the first weeks
      #plot(t_it .+ 6 ,I_it,"g*")  # time delay Italy cases
      plot(t_de,I_de,"r*")
      plot(t,I)
      xlim(0,30)
      ylim(0,10000)
      ylabel("infected, inital period")

      subplot(3,2,3)  # whole outbreak on a half-logarithmic scale
      #plot(t_it .+ 6,log10.(I_it),"g*")
      plot(t_de,log10.(I_de),"r*")
      plot(t, log10.(I))
      plot(t, log10.(A), "g")
      ylabel("log10(infected)")
      xlim(0,60)

      subplot(3,2,4)  # first weeks on a half-logarithmic scale
      #plot(t_it .+ 6,log10.(I_it),"g*")
      plot(t_de,log10.(I_de),"r*")
      plot(t, log10.(I))
      xlabel("time (days)")
      ylabel("log10(infected)")
      xlim(0,30)
      ylim(0,4.5)

      subplot(3,2,5)  # other model stages
      plot(t,E)
      plot(t,R)
      plot(t_de,R_de,"r*")
      plot(t,H)
      plot(t,S)
      ylabel("Other states")
      xlim(0,60)
      xlabel("time (days)")

      subplot(3,2,6)  # other model stages
      plot(t,E)
      plot(t,R,"r")
      plot(t_de,R_de,"r*")
      plot(t,H)
      #plot(t,S)
      ylabel("Other states")
      xlim(0,30)
      ylim(0,100)
      xlabel("time (days)")

      #subplot(3,2,6)
      #plot(t,R0)  # basic reproductive number according to the formula of Wang et al.
      #xlim(0,60)
      #ylabel("R0")
      #xlabel("time (days)")

      #savefig("outbreak_Germany.png")

  end

  if scenario == :it   # analysis for Italy (it seems the is a slight reduction
                       # in growth rates after first week)
      figure("ts_it")
      clf()

      subplot(2,2,1)
      #plot(1:14,I_Italy,"b*")
      plot(t_it,I_it,"r*")
      plot(t,I)
      plot(t,A, "g")
      xlim(0,80)
      #ylim(0,2000)
      #plot(t,Rt)
      ylabel("infected")
      #xlim(0,10)

      subplot(2,2,2)
      #plot(1:14,I_Italy,"b*")
      plot(t_it,I_it,"r*")
      plot(t,I)
      xlim(0,20)
      ylim(0,15000)
      ylabel("infected, inital period")
      subplot(2,2,3)
      #plot(1:14,log10.(I_Italy),"b*")
      plot(t_it,log10.(I_it),"r*")
      plot(t, log10.(I))
      plot(t, log10.(A), "g")
      xlabel("time (days)")
      ylabel("log10(infected)")
      #xlim(0,50)

      subplot(2,2,4)
      plot(t,E)
      plot(t,R)
      plot(t,H)
      plot(t,S)
      xlim(0,80)
  end

end

#scenario = :wuhan # Wuhan
#scenario = :de    # Germany
#scenario = :it    # Italy
#scenario = :us    # US
#scenario = :OL    # Oldenburg (my city in Germany)
nlys(:de)

end   # module

max_stars_repo_name: AlexRyabov/covid

max_issues_repo_name: AlexRyabov/covid

max_forks_repo_name: AlexRyabov/covid


text:
# Computes classical Stein discrepancy based on the g and gradg coefficients
# for univariate target distributions:
#
#     max_{g} sum_i gobjcoeff(i) * g(x(i)) + gradgobjcoeff(i) * g'(x(i)))
#     subject to, for all z, y
#     |g(z)| <= c_{1} I[alpha < z < beta], |g'(z)| <= c_{2},
#     |g(z) - g(y)| <= c_{2} |z-y|,
#     |g'(z) - g'(y)| <= c_3 |z-y|,
#     |g(z) - g(y) - g'(y)(z - y)| <= (c_3/2) |z-y|^2,
#     |g(z) - g(y) - g'(z)(z - y)| <= (c_3/2) |z-y|^2
#    where (alpha,beta) is the support of target distribution.
#
# Despite this being an infinite dimensional feasible set, there
# is a set of finite dimensional constraints that can exactly
# recover the optimal solution g, g' on the points x_i.
#
# Args:
#  sample - SteinDiscrete object representing a sample
#  gobjcoefficients - a vector of coefficients for the objective for g
#  gradgobjcoefficients - a vector of coefficients for the objective for gprime
#  solver - optimization program solver supported by JuMP that can solve
#   a quadratically constrained quadratic program (QCQP)
#  operator - the operator being used for the objective
function affine_classical_discrepancy(sample::SteinDiscrete,
                                      gobjcoefficients::Array{Float64,1},
                                      gradgobjcoefficients::Array{Float64,1},
                                      solver::AbstractMathProgSolver,
                                      operator::AbstractString;
                                      c1::Float64=1.0,
                                      c2::Float64=1.0,
                                      c3::Float64=1.0,
                                      supportlowerbounds=[-Inf],
                                      supportupperbounds=[Inf])

    # get primary objects
    points = sample.support
    weights = vec(sample.weights)
    n = length(weights)
    ## reset the support bounds if needed
    if isa(supportlowerbounds, Number)
        supportlowerbounds = [supportlowerbounds]
    end
    if isa(supportupperbounds, Number)
        supportupperbounds = [supportupperbounds]
    end
    ## Find spanner edges (consecutive pairs)
    println("[Computing spanner edges]")
    edgetime = @elapsed edges = getspanneredges(points)
    println("\tusing $(size(edges,1)) of $(binomial(n,2)) edges")

    elapsed = @elapsed begin
        # start setting up the model
        m = Model(solver=solver)
        # Define variables and specify single variable bounds
        @variable(m, -c1 <= g[1:n] <= c1)
        @variable(m, -c2 <= gprime[1:n] <= c2)
        # Introduce classical Stein program slack variables
        @variable(m, -Inf <= tb[1:(n-1)] <= Inf)
        @variable(m, -Inf <= tu[1:(n-1)] <= Inf)
        # set objective
        gobj = g[1:n]'gobjcoefficients
        gprimeobj = gprime[1:n]'gradgobjcoefficients
        @objective(m, Max, gobj + gprimeobj)
        # add gprime constraints
        xdistances = points[2:n, 1] - points[1:(n-1), 1]
        for i=1:(n-1)
            @constraint(m, gprime[i] - gprime[i+1] <= c3*xdistances[i])
            @constraint(m, gprime[i] - gprime[i+1] >= -c3*xdistances[i])
        end
        # Introduce constraints tb >= Lb and tu >= Lu:
        # tb_i >= c3/2 * (x_{i+1} - x_i) - (g'(x_i) + g'(x_{i+1}))/2 - c2
        # tu_i >= c3/2 * (x_{i+1} - x_i) + (g'(x_i) + g'(x_{i+1}))/2 - c2
        slackoffsets = (c3/2) * xdistances - c2
        for i=1:(n-1)
            @constraint(m, tb[i] + 0.5 * gprime[i] + 0.5 * gprime[i+1] >= slackoffsets[i])
            @constraint(m, tu[i] - 0.5 * gprime[i] - 0.5 * gprime[i+1] >= slackoffsets[i])
        end
        # Introduce quadratic buffer constraints:
        # |g(x_i)| <= c_1 - (1/(2c_3)) g'(x_i)^2
        for i=1:n
            qexp = QuadExpr([gprime[i]], [gprime[i]], [1/(2*c3)], [g[i]]'[1.0])
            @constraint(m, qexp <= c1)
            qexp = QuadExpr([gprime[i]], [gprime[i]], [1/(2*c3)], [g[i]]'[-1.0])
            @constraint(m, qexp <= c1)
        end
        # Add sharp constraints linking g and g':
        # g(x_{i+1}) - g(x_i) + (g'(x_{i+1}) - g'(x_i))^2/(4c3) - (x_{i+1} - x_i)*(g'(x_i) + g'(x_{i+1}))/2 + (1/c3)(L_u)^2_+ <= (c3/4)(x_{i+1} - x_i)^2
        # g(x_i) - g(x_{i+1}) + (g'(x_{i+1}) - g'(x_i))^2/(4c3) + (x_{i+1} - x_i)*(g'(x_i) + g'(x_{i+1}))/2 + (1/c3)(L_b)^2_+ <= (c3/4)(x_{i+1} - x_i)^2
        scaledsquaredxdistances = (xdistances.^2) .* (c3/4)
        for i=1:(n-1)
            rexp = [g[i:(i+1)]; gprime[i:(i+1)]]'[1.0, -1.0,  xdistances[i]/2, xdistances[i]/2]
            qbexp = QuadExpr(
                [gprime[[i, i, i+1]]; tb[i]],
                [gprime[[i, i+1, i+1]]; tb[i]],
                [1.0, -2.0, 1.0, 4.0] ./ (4*c3),
                rexp
            )
            quexp = QuadExpr(
                [gprime[[i, i, i+1]]; tu[i]],
                [gprime[[i, i+1, i+1]]; tu[i]],
                [1.0, -2.0, 1.0, 4.0] ./ (4*c3),
                -1 * rexp
            )

            @constraint(m, qbexp <= scaledsquaredxdistances[i])
            @constraint(m, quexp <= scaledsquaredxdistances[i])
         end

        # get boundary of support
        alpha = supportlowerbounds[1]
        beta = supportupperbounds[1]
        # add support slack constraints if necessary
        if isfinite(alpha)
            xdistance = points[1,1] - alpha
            # |g(x_1)| <= c2 (x_1 - alpha)
            @constraint(m, g[1] <= c2*xdistance)
            @constraint(m, g[1] >= -c2*xdistance)
            # g(x_1) <= g'(x_1)*(x_1 - alpha) + (c3/2)*(x_1-alpha)^2 - 1/(2c3) max{g'(x_1) + c3(x_1 - alpha) - c2, 0}^2,
            # g(x_1) >= g'(x_1)*(x_1 - alpha) - (c3/2)*(x_1-alpha)^2 + 1/(2c3) max{-g'(x_1) + c3(x_1 - alpha) - c2, 0}^2
            @variable(m, -Inf <= alphab <= Inf)
            @variable(m, -Inf <= alphau <= Inf)
            @constraint(m, alphab - gprime[1] >= c3 * xdistance - c2)
            @constraint(m, alphau + gprime[1] >= c3 * xdistance - c2)
            rexp = [g[1], gprime[1]]'[1.0, -xdistance]
            qbexp = QuadExpr([alphab], [alphab], [1/(2*c3)], rexp)
            quexp = QuadExpr([alphau], [alphau], [1/(2*c3)], -1 * rexp)
            @constraint(m, qbexp <= (c3/2) * xdistance^2)
            @constraint(m, quexp <= (c3/2) * xdistance^2)
        end
        if isfinite(beta)
            xdistance = beta - points[end,1]
            # |g(x_n)| <= c2 (beta - x_n)
            @constraint(m, g[n] <= c2*xdistance)
            @constraint(m, g[n] >= -c2*xdistance)
            # -g(x_n) <= g'(x_n)*(beta-x_n) + (c3/2)*(beta-x_n)^2 - 1/(2c3) max{g'(x_n) + c3(beta-x_n) - c2, 0}^2
            # -g(x_n) >= g'(x_n)*(beta-x_n) - (c3/2)*(beta-x_n)^2 + 1/(2c3) max{-g'(x_n) + c3(beta-x_n) - c2, 0}^2
            @variable(m, -Inf <= betab <= Inf)
            @variable(m, -Inf <= betau <= Inf)
            @constraint(m, betab + gprime[n] >= c3 * xdistance - c2)
            @constraint(m, betau - gprime[n] >= c3 * xdistance - c2)
            rexp = [g[n], gprime[n]]'[1.0, xdistance]
            qbexp = QuadExpr([betab], [betab], [1/(2*c3)], rexp)
            quexp = QuadExpr([betau], [betau], [1/(2*c3)], -1 * rexp)
            @constraint(m, qbexp <= (c3/2) * xdistance^2)
            @constraint(m, quexp <= (c3/2) * xdistance^2)
    end
    # Solve the optimization program
    @time optimize!(m)
    print(termination_status(m))
    end
    solvetime = elapsed
    # Package the results
    objval = [getobjectivevalue(m)]
    gopt = getvalue(g)[1:n]
    gprimeopt = getvalue(gprime)[1:n]
    operatorgopt = (gopt .* gobjcoefficients) + (gprimeopt .* gradgobjcoefficients)

    AffineDiscrepancyResult(
        points,
        weights,
        edges,
        objval,
        gopt,
        gprimeopt,
        operatorgopt,
        edgetime,
        solvetime,
        operator
    )
end


text:
# ------------------------------------------------------------------
# Licensed under the ISC License. See LICENCE in the project root.
# ------------------------------------------------------------------

"""
    SequentialTimelessProcess

A a sesquence of `first` and `second` timeless processes.
"""
struct SequentialTimelessProcess{P1,P2} <: TimelessProcess
  first::P1
  second::P2
end

function evolve!(land::Matrix, proc::SequentialTimelessProcess)
  evolve!(land, proc.first)
  evolve!(land, proc.second)
end

GeoStatsBase.:→(first::TimelessProcess, second::TimelessProcess) =
  SequentialTimelessProcess(first, second)