text:
#ENV["MOSEKLM_LICENSE_FILE"]="/home/ryancw/mosek/mosek.lic" #needed on cluster
using JuMP, LinearAlgebra, Suppressor, StatsBase, CSV, DataFrames, Compat, Test, Random
include("exact_approaches.jl")
include("alt_min.jl")
include("convexpenalties.jl")

results_template = DataFrame(n=Int[], r=Int[], p=Real[], gamma=Real[], err_GD=Real[], rnk_GD=Int[], solve_GD=Real[], err_AM=Real[], rnk_AM=Int[], solve_AM=Real[], err_EX=Real[],
rnk_EX=Int[], solve_EX=Real[], nc_EX=Int[], gap_EX=Real[], err_OA=Real[], rnk_OA=Int[], solve_OA=Real[], nc_OA=Int[], gap_OA=Real[], cuts_OA=Int[],
err_OA_inout=Real[], rnk_OA_inout=Int[], solve_OA_inout=Real[], nc_OA_inout=Int[], gap_OA_inout=Real[], cuts_OA_inout=Int[])

results_exact=similar(results_template, 0)

# note: you will need to manually vary n, r, gamma to obtain all the output you want.
for ARG in ARGS #1-4
    for iter in 1:1
        #Random.seed!(1234)
        p=[0.05, 0.1, 0.15, 0.2][parse(Int, ARG)]
        n=10
        r=1
        gamma=100/p
        M_L=randn(n, r)
        M_L=round.(1000*M_L)./1000
        M_R=randn(n, r)
        M_R=round.(1000*M_R)./1000
        M=M_L*M_R'

        @show maximum(M)
        numEntriesSampled=Int(round(p*n^2))
        coords=[repeat(1:n, inner=size(1:n,1)) repeat(1:n, outer=size(1:n,1))];
        entries=sample(1:n^2, Int(numEntriesSampled), replace=false)

        theIndices=zeros(n,n)
        for t=1:Int(numEntriesSampled)
            theIndices[coords[entries[t],1], coords[entries[t],2]]=1.0
        end

        k=r

        t_GD=@elapsed X_GD,LB, UB, Y_relax=getMatrixFrobeniusNorm_greedy(coords, entries, M, n, numEntriesSampled, k, gamma, true)

        @show "SDP lower bound is: " LB
        u,sigma,v,=svd(X_GD)
        rnk_GD=sum(sigma.>1e-2);
        err_GD = norm(X_GD.-M)/norm(M);

        t_AM=@elapsed X_AM,=alternatingminimization_matrixcompletion(coords, entries, M, n, numEntriesSampled, k, gamma, 50, X_GD)

        # Test solution on overall data.
        u,sigma,v,=svd(X_AM)
        @show rnk_AM=sum(sigma.>1e-2);
        @show err_AM = norm(X_AM.-M)/norm(M);

        u_0=u[:,1:k]
        v_0=(Diagonal(sigma[1:k])*v[:,1:k]')'

        # # # Apply the cutting-plane method (with the in-out nethod)
        t_OA=@elapsed X_OA, nc_OA, cuts_OA, gap_OA=getMatrixFrobeniusNorm_cuttingplanes_exact_inout(coords, entries, M, n, numEntriesSampled, k, gamma, Y_relax, X_AM, true, true, false)
        # # Test solution on overall data.
        u,v,=svd(X_OA)
        @show rnk_OA=sum(v.>1e-2);
        @show err_OA=norm(X_OA.-M)/norm(M);

        # Apply the cutting-plane method (with the in-out nethod)
        t_OA_inout=@elapsed X_OA, nc_OA_inout, cuts_OA_inout, gap_OA_inout=getMatrixFrobeniusNorm_cuttingplanesmultitree_exact_inout(coords, entries, M, n, numEntriesSampled, k, gamma, Y_relax, X_AM, true)
        # Test solution on overall data.
        u,v,=svd(X_OA)
        @show rnk_OA_inout=sum(v.>1e-2);
        @show err_OA_inout = norm(X_OA.-M)/norm(M);

        t_EX=@elapsed X_EX, nc_EX, gap_EX=getMatrixFrobeniusNorm_exact(coords, entries, M, n, numEntriesSampled, k, gamma, false, u_0, v_0)

        # Test solution on overall data.
        u,v,=svd(X_EX)
        @show rnk_EX=sum(v.>1e-2);
        @show err_EX = norm(X_EX.-M)/norm(M);

        push!(results_exact, [n, r, p, gamma, err_GD, rnk_GD, t_GD, err_AM, rnk_AM, t_AM, err_EX, rnk_EX, t_EX, nc_EX, gap_EX, err_OA, rnk_OA, t_OA, nc_OA, gap_OA, cuts_OA, err_OA_inout, rnk_OA_inout, t_OA_inout, nc_OA_inout, gap_OA_inout, cuts_OA_inout])

        end
    end

CSV.write("benchmark_gurobi_vs_cuts_grbnolazy.csv", results_exact, append=true)

max_stars_repo_name: ryancorywright/MixedProjectionSoftware

max_issues_repo_name: ryancorywright/MixedProjectionSoftware

max_forks_repo_name: ryancorywright/MixedProjectionSoftware


text:
# %% transfer entropy
using DrWatson
@quickactivate "NonlinearDynamicsTextbook"
include(srcdir("style.jl"))
using DynamicalSystems, PyPlot

using TransferEntropy, Random

function ulam(dx, x, p, t)
    f(x) = 2 - x^2;
    ε = p[1];
    N = length(x)
    for i in 1:N
        dx[i] = f(ε*x[mod1(i-1, N)] + (1-ε)*x[i])
    end
end
ds = DiscreteDynamicalSystem(ulam, rand(100), [0.04])

genmeth(r) = VisitationFrequency(RectangularBinning(r))
methods = genmeth.((0.01, 0.1, 0.4))
εs = 0.0:0.01:1.0
tes = [zeros(length(εs), 2) for j in 1:length(methods)]

for (i, ε) in enumerate(εs), (j, meth) in enumerate(methods)
    set_parameter!(ds, 1, ε)
    A = trajectory(ds, 10000; Ttr = 10000)
    x1 = A[:, 1]; x2 = A[:, 2]
    tes[j][i, 1] = transferentropy(x1, x2, meth)
    tes[j][i, 2] = transferentropy(x2, x1, meth)
end

fig = figure(figsize = (6figx/10, figx/3))
rs = (0.01, 0.1, 0.4)

for j in 1:length(methods)
    plot(εs, tes[j][:, 1], color = "C$(j-1)", label = "\$r=$(rs[j])\$")
    plot(εs, tes[j][:, 2], color = "C$(j-1)", ls = "dashed")
end
xlabel("coupling strength \$\\epsilon\$")
ylabel("transfer entropy")
legend(loc = "center", handlelength = 1)
tight_layout(pad=0.3)
wsave(plotsdir("7", "transfer"), fig)

ext: jl

max_stars_repo_name: JuliaDynamics/NonlinearDynamicsTextbook

max_issues_repo_name: JuliaDynamics/NonlinearDynamicsTextbook

max_forks_repo_name: JuliaDynamics/NonlinearDynamicsTextbook


text:
##### deal with particles moved out of the domain
@inline function particle_boundary_condition(x, xl, xr, ::Periodic)
    x > xr && return xl + (x  - xr)
    x < xl && return xr - (xl - x)
    return x
end
@inline function particle_boundary_condition(x, xl, xr, ::Bounded)
    x > xr && return xr - (x - xr) * 1.0
    x < xl && return xl + (xl - x) * 1.0
    return x
end

@kernel function particle_boundaries_kernel!(plank, ac, g::AbstractGrid{TX, TY, TZ}) where {TX, TY, TZ}
    i = @index(Global)
    @inbounds plank.x[i] = particle_boundary_condition(plank.x[i], 0, g.Nx, TX()) * ac[i]
    @inbounds plank.y[i] = particle_boundary_condition(plank.y[i], 0, g.Ny, TY()) * ac[i]
    @inbounds plank.z[i] = particle_boundary_condition(plank.z[i], 0, g.Nz, TZ()) * ac[i]
end
function particle_boundaries!(plank, ac, g::AbstractGrid, arch::Architecture)
    kernel! = particle_boundaries_kernel!(device(arch), 256, (size(ac,1)))
    event = kernel!(plank, ac, g)
    wait(device(arch), event)
    return nothing
end

##### calculate uvw velocities at (x, y, z)
@kernel function vel_interpolate_kernel!(uₜ, vₜ, wₜ, x, y, z, ac, u, v, w, g::AbstractGrid)
    i = @index(Global)
    @inbounds uₜ[i] = u_itpl(u, x[i], y[i], z[i], ac[i], g) * ac[i]
    @inbounds vₜ[i] = v_itpl(v, x[i], y[i], z[i], ac[i], g) * ac[i]
    @inbounds wₜ[i] = w_itpl(w, x[i], y[i], z[i], ac[i], g) * ac[i]
end

function vel_interpolate!(uₜ, vₜ, wₜ, x, y, z, ac, u, v, w, g::AbstractGrid, arch::Architecture)
    kernel! = vel_interpolate_kernel!(device(arch), 256, (size(ac,1)))
    event = kernel!(uₜ, vₜ, wₜ, x, y, z, ac, u, v, w, g)
    wait(device(arch), event)
    return nothing
end

##### calculate intermediate coordinates
@kernel function calc_coord_kernel!(velos, plank, u, v, w, ac, ΔT, weight::Float64)
    i = @index(Global)
    @inbounds velos.x[i] = plank.x[i] + weight * u[i] * ΔT * ac[i]
    @inbounds velos.y[i] = plank.y[i] + weight * v[i] * ΔT * ac[i]
    @inbounds velos.z[i] = plank.z[i] - weight * w[i] * ΔT * ac[i] # index increases when w is negtive
end
function calc_coord!(velos, plank, u, v, w, ac, ΔT, weight::Float64, arch::Architecture)
    kernel! = calc_coord_kernel!(device(arch), 256, (size(ac,1)))
    event = kernel!(velos, plank, u, v, w, ac, ΔT, weight)
    wait(device(arch), event)
    return nothing
end

##### calculate final velocities by RK4
@kernel function calc_rk4_kernel!(velos)
    i = @index(Global)
    velos.u1[i] = (velos.u1[i] + 2*velos.u2[i] + 2*velos.u3[i] + velos.u4[i])/6
    velos.v1[i] = (velos.v1[i] + 2*velos.v2[i] + 2*velos.v3[i] + velos.v4[i])/6
    velos.w1[i] = (velos.w1[i] + 2*velos.w2[i] + 2*velos.w3[i] + velos.w4[i])/6
end
function calc_vel_rk4!(velos, arch::Architecture)
    kernel! = calc_rk4_kernel!(device(arch), 256, (size(velos.u1,1)))
    event = kernel!(velos)
    wait(device(arch), event)
    return nothing
end

##### calculate final velocities by AB2
@kernel function calc_ab2_kernel!(velos, χ)
    i = @index(Global)
    velos.u1[i] = (1.5 + χ) * velos.u1[i] - (0.5 + χ) * velos.u2[i]
    velos.v1[i] = (1.5 + χ) * velos.v1[i] - (0.5 + χ) * velos.v2[i]
    velos.w1[i] = (1.5 + χ) * velos.w1[i] - (0.5 + χ) * velos.w2[i]
end
function calc_vel_ab2!(velos, χ, arch::Architecture)
    kernel! = calc_ab2_kernel!(device(arch), 256, (size(velos.u1,1)))
    event = kernel!(velos, χ)
    wait(device(arch), event)
    return nothing
end


text:
push!(LOAD_PATH,"../src/")
using Documenter, JsonDB

makedocs(;
		 modules=[JsonDB],
		 format = Documenter.HTML(
		    canonical = "https://glitzflitz.github.io/JsonDB.jl/stable/",
		 ),

		 sitename="JsonDB.jl",
		 authors="Amey Narkhede",
		 )

deploydocs(
    repo = "github.com/glitzflitz/JsonDB.jl.git",
	target="build",
)


text:
using NPZ, Compat

@static if VERSION >= v"0.7.0-DEV.2575"
    using Test
else
    using Base.Test
end

Debug = false

tmp = mktempdir()
if Debug
    println("temporary directory: $tmp")
end

TestArrays = Any[
    true,
    false,
    Int8(-42),
    Int16(-42),
    Int32(-42),
    Int64(-42),
    UInt8(42),
    UInt16(42),
    UInt32(42),
    UInt64(42),
    Float16(3.1415),
    Float32(3.1415),
    Float64(3.1415),
    Complex{Float32}(1, 7),
    Complex{Float64}(1, 7),
    Bool[0, 1, 0, 1, 1, 0],
    Int8[-42, 0, 1, 2, 3, 4],
    Int16[-42, 0, 1, 2, 3, 4],
    Int32[-42, 0, 1, 2, 3, 4],
    Int64[-42, 0, 1, 2, 3, 4],
    UInt8[0, 1, 2, 3, 4],
    UInt16[0, 1, 2, 3, 4],
    UInt32[0, 1, 2, 3, 4],
    UInt64[0, 1, 2, 3, 4],
    Float64[-42, 0, 1, 2, 3.14, 4],
    Float32[-42, 0, 1, 2, 3.14, 4],
    Float16[-42, 0, 1, 2, 3.14, 4],
    Complex{Float32}[1+2im, 3, 4+5im, 6im, 7+8im],
    Complex{Float64}[1+2im, 3, 4+5im, 6im, 7+8im],
    [i-j for i in 1:3, j in 1:5],
    [i-j+k for i in 1:3, j in 1:4, k in 1:5],
]

# Write a NPZ file with all the test arrays and numbers,
# and read it back in.
old = Dict{String, Any}()
for (i, x) in enumerate(TestArrays)
    old["testvar_" * string(i)] = x
end
filename = "$tmp/big.npz"
npzwrite(filename, old)
new = npzread(filename)
for (k, v) in old
    @test v == new[k]
end
@test old == new

# Write and then read NPY files for each array
for x in TestArrays
    let filename = "$tmp/test.npy"
        npzwrite(filename, x)
        y = npzread(filename)
        @test typeof(x) == typeof(y)
        @test size(x) == size(y)
        @test x == y
    end
end

if !Debug
    run(`rm -rf $tmp`)
end


text:
#!/usr/bin/env julia

using EzXML

doc = readhtml(ARGS[1])
# Select <a/> links that contain a non-blank text node.
links = findall("//a[@href and normalize-space(text()) != '']", doc)
width = ndigits(length(links))
for (i, link) in enumerate(links)
    println(lpad(i, width), ": ", strip(nodecontent(link)), " -- ", link["href"])
end


text:
#### Extract subset
# -------------------------------------------------------------------------------------------------
#
# Subsetting, meaning extracting some portion of the 3D domain
#
# -------------------------------------------------------------------------------------------------
function extract_subset_dim1_3d(ncol, nlay, ngpt, array_in, colS, colE, array_out)#
    #    bind (C, name="extract_subset_dim1_3d")
    #    integer,                             intent(in ) :: ncol, nlay, ngpt
    #    real(FT), dimension(ncol,nlay,ngpt), intent(in ) :: array_in
    #    integer,                             intent(in ) :: colS, colE
    #    real(FT), dimension(colE-colS+1,
    #                             nlay,ngpt), intent(out) :: array_out

    #    integer :: icol, ilay, igpt
    for igpt in 1:ngpt
        for ilay in 1:nlay
            for icol in colS:colE
                array_out[icol - colS + 1, ilay, igpt] = array_in[icol, ilay, igpt]
            end
        end
    end

end
# ---------------------------------
function extract_subset_dim2_4d(nmom, ncol, nlay, ngpt, array_in, colS, colE, array_out)#
    #    bind (C, name="extract_subset_dim2_4d")
    #    integer,                                  intent(in ) :: nmom, ncol, nlay, ngpt
    #    real(FT), dimension(nmom,ncol,nlay,ngpt), intent(in ) :: array_in
    #    integer,                                  intent(in ) :: colS, colE
    #    real(FT), dimension(nmom,colE-colS+1,
    #                                  nlay,ngpt), intent(out) :: array_out

    #    integer :: icol, ilay, igpt, imom

    for igpt in 1:ngpt
        for ilay in 1:nlay
            for icol in colS:colE
                for imom in 1:nmom
                    array_out[imom, icol - colS + 1, ilay, igpt] = array_in[imom, icol, ilay, igpt]
                end
            end
        end
    end

end

#
# Extract the absorption optical thickness which requires mulitplying by 1 - ssa
#
#    integer,                             intent(in ) :: ncol, nlay, ngpt
#    real(FT), dimension(ncol,nlay,ngpt), intent(in ) :: tau_in, ssa_in
#    integer,                             intent(in ) :: colS, colE
#    real(FT), dimension(colE-colS+1,
#                             nlay,ngpt), intent(out) :: tau_out
#    integer :: icol, ilay, igpt
function extract_subset_absorption_tau(ncol, nlay, ngpt, tau_in, ssa_in, colS, colE, tau_out)
    FT = eltype(tau_in)

    for igpt in 1:ngpt
        for ilay in 1:nlay
            for icol in colS:colE
                tau_out[icol - colS + 1, ilay, igpt] = tau_in[icol, ilay, igpt] * (FT(1) - ssa_in[icol, ilay, igpt])
            end
        end
    end
end

# Extract a subset of n columns starting with column 'start'
function get_subset_range(this::GasConcs, start::I, n::I, subset::GasConcs) where {I}
    # class(GasConcs),      intent(in   ) :: this
    # integer,                  intent(in   ) :: start, n
    # class(GasConcs),      intent(inout) :: subset
    @assert !(n <= 0)
    @assert !(start < 1)
    @assert !(this.ncol ≠ nothing && start > this.ncol || start + n - 1 > this.ncol)

    this.nlay = 0
    this.ncol = 0
    # reset!(subset)
    # These two arrays should be the same length
    subset.gas_name = Array(undef, size(this.gas_name))
    subset.concs = Array(undef, size(this.concs))
    subset.nlay = this.nlay
    subset.ncol = this.ncol ≠ nothing ? n : 0
    subset.gas_name[:] .= this.gas_name[:]

    for i in 1:size(this.gas_name)
        #
        # Preserve scalar/1D/2D representation in subset,
        #   but need to ensure at least extent 1 in col dimension (ncol = 0 means no gas exploits this dimension)
        #
        allocate(
            subset.concs[i].conc(
                min(max(subset.ncol, 1), size(this.concs[i].conc, 1)),
                min(subset.nlay, size(this.concs[i].conc, 2)),
            ),
        )
        if size(this.concs[i].conc, 1) > 1      # Concentration stored as 2D
            subset.concs[i].conc[:, :] .= this.concs[i].conc[start:(start + n - 1), :]
        else
            subset.concs[i].conc[:, :] .= this.concs[i].conc[:, :]
        end
    end

end

max_stars_repo_name: climate-machine/JRRTMGP

max_issues_repo_name: climate-machine/JRRTMGP

max_forks_repo_name: climate-machine/JRRTMGP


text:
using Test

@testset "GardenOptim.jl" begin
    include("classification.jl")
    include("mcmc.jl")
end

max_stars_repo_name: dlozeve/GardenOptim

max_issues_repo_name: dlozeve/GardenOptim

max_forks_repo_name: dlozeve/GardenOptim


text:
loadcrabs(filename) = parse.(Int, split(readchomp(filename), ','))

if basename(pwd()) == "aoc"
    cd("2021/7")
end
examplecrabs = loadcrabs("example.txt")
inputcrabs = loadcrabs("input.txt")

using Statistics
part1(crabs) = sum(abs.(crabs .- median(crabs)))
part1(inputcrabs) # 331067

triangle(n) = n * (n + 1) ÷ 2
offset(a, b) = triangle(abs(a - b))

function part2(crabs)
    minimum(sum(offset(x, n) for x in crabs) for n in range(extrema(crabs)...))
end

max_stars_repo_name: stellartux/advent-of-code

max_issues_repo_name: stellartux/advent-of-code

max_forks_repo_name: stellartux/advent-of-code


text:
function num_var(model::PointFootQuadruped)
    nq = model.nq
    nc = model.nc
    nb = 2

    nq + nc + nc + nc + nc * nb + nc + nc * nb
end

function indices_z(model::PointFootQuadruped)
    nq = model.nq
    nc = model.nc
    nb = 2
    q = collect(1:nq)
    γ = collect(nq .+ (1:nc))
    sγ = collect(nq + nc .+ (1:nc))
    ψ = collect(nq + nc + nc .+ (1:nc))
    b = collect(nq + nc + nc + nc .+ (1:(nc * nb)))
    sψ = collect(nq + nc + nc + nc + nc * nb .+ (1:nc))
    sb = collect(nq + nc + nc + nc + nc * nb + nc .+ (1:(nc * nb)))
    IndicesZ(q, γ, sγ, ψ, b, sψ, sb)
end

function indices_optimization(model::PointFootQuadruped)
    nq = model.nq
    nc = model.nc
    nb = 2
    nz = num_var(model)

    IndicesOptimization(
        nz,
        nz,
        [collect(nq .+ (1:nc)), collect(nq + nc .+ (1:nc))],
        [collect(nq .+ (1:nc)), collect(nq + nc .+ (1:nc))],
        [
            [collect([nq + 2nc + 1, (nq + 2nc + nc + 0 .+ (1:2))...]), collect([nq + 2nc + nc + nc * nb + 1, (nq + 2nc + nc + nc * nb + nc + 0 .+ (1:2))...])],
            [collect([nq + 2nc + 2, (nq + 2nc + nc + 2 .+ (1:2))...]), collect([nq + 2nc + nc + nc * nb + 2, (nq + 2nc + nc + nc * nb + nc + 2 .+ (1:2))...])],
            [collect([nq + 2nc + 3, (nq + 2nc + nc + 4 .+ (1:2))...]), collect([nq + 2nc + nc + nc * nb + 3, (nq + 2nc + nc + nc * nb + nc + 4 .+ (1:2))...])],
            [collect([nq + 2nc + 4, (nq + 2nc + nc + 6 .+ (1:2))...]), collect([nq + 2nc + nc + nc * nb + 4, (nq + 2nc + nc + nc * nb + nc + 6 .+ (1:2))...])],
            # [collect([nq + 2nc + 5, (nq + 2nc + nc + 8 .+ (1:2))...]), collect([nq + 2nc + nc + nc * nb + 5, (nq + 2nc + nc + nc * nb + nc + 8 .+ (1:2))...])],
        ],
        [
            [collect([nq + 2nc + 1, (nq + 2nc + nc + 0 .+ (1:2))...]), collect([nq + 2nc + nc + nc * nb + 1, (nq + 2nc + nc + nc * nb + nc + 0 .+ (1:2))...])],
            [collect([nq + 2nc + 2, (nq + 2nc + nc + 2 .+ (1:2))...]), collect([nq + 2nc + nc + nc * nb + 2, (nq + 2nc + nc + nc * nb + nc + 2 .+ (1:2))...])],
            [collect([nq + 2nc + 3, (nq + 2nc + nc + 4 .+ (1:2))...]), collect([nq + 2nc + nc + nc * nb + 3, (nq + 2nc + nc + nc * nb + nc + 4 .+ (1:2))...])],
            [collect([nq + 2nc + 4, (nq + 2nc + nc + 6 .+ (1:2))...]), collect([nq + 2nc + nc + nc * nb + 4, (nq + 2nc + nc + nc * nb + nc + 6 .+ (1:2))...])],
            # [collect([nq + 2nc + 5, (nq + 2nc + nc + 8 .+ (1:2))...]), collect([nq + 2nc + nc + nc * nb + 5, (nq + 2nc + nc + nc * nb + nc + 8 .+ (1:2))...])],
        ],
        collect(1:(nq + nc + nc * nb + nc)),
        collect(nq + nc + nc * nb + nc .+ (1:nc)),
        collect(nq + nc + nc * nb + nc + nc .+ (1:(nc * 3))),
        [collect(nq + nc + nc * nb + nc + nc + (i - 1) * 3 .+ (1:3)) for i = 1:nc],
        collect(nq + nc + nc * nb + nc .+ (1:(nc + nc * 3))))
end

Trajectory(model::PointFootQuadruped, T) = Trajectory(model, T, nc=model.nc, nb=(2 * model.nc))
GradientTrajectory(model::PointFootQuadruped, T) = GradientTrajectory(model, T, nc=model.nc, nb=(2 * model.nc))

function residual(model::PointFootQuadruped, mass_matrix, dynamics_bias, kinematics, kinematics_jacobians, z, θ, μ)

    # dimensions
    nq = model.nq
    nu = model.nu
    nw = model.nw
    nc = model.nc
    nb = 2
    nf = length(friction_coefficients(model))

    # unpack data
    q0 = θ[1:nq]
    q1 = θ[nq .+ (1:nq)]
    u1 = θ[2nq .+ (1:nu)]
    w1 = θ[2nq + nu .+ (1:nw)]
    friction = θ[2nq + nu + nw .+ (1:nf)]
    h = θ[2nq + nu + nw + nf .+ (1:1)]

    # unpack variables
    q2 = z[1:nq]
    γ1 = z[nq .+ (1:nc)]
    sγ1 = z[nq + nc .+ (1:nc)]
    ψ1 = z[nq + nc + nc .+ (1:nc)]
    b1 = z[nq + nc + nc + nc .+ (1:(nc * nb))]
    sψ1 = z[nq + nc + nc + nc + (nc * nb) .+ (1:nc)]
    sb1 = z[nq + nc + nc + nc + (nc * nb) + nc .+ (1:(nc * nb))]

    # rotation matrix at surface
    rotation = [I(3) for i = 1:nc] #TODO non-flat surfaces

    # tangential velocity
    v1 = (q2 - q1) / h[1]
    vT = [(rotation[i] * kinematics_jacobians[i](q2) * v1)[1:2] for i = 1:nc]

    # contact forces
    J = contact_jacobian(model, q1)
    λ1 = transpose(J) * vcat([transpose(rotation[i]) * [b1[(i - 1) * nb .+ (1:nb)]; γ1[i]] for i = 1:nc]...)

    # residual
    [
    dynamics(model, mass_matrix, dynamics_bias, h, q0, q1, u1, w1, λ1, q2);
    signed_distance(model, q2) - sγ1;
    vcat([vT[i] - sb1[(i - 1) * nb .+ (1:nb)] for i = 1:nc]...);
    vcat([friction[i] * γ1[i] - ψ1[i] for i = 1:nc]...);
    γ1 .* sγ1 .- μ[1];
    vcat([cone_product([ψ1[i]; b1[(i - 1) * nb .+ (1:nb)]], [sψ1[i]; sb1[(i - 1) * nb .+ (1:nb)]]) - [μ[1]; 0.0; 0.0] for i = 1:nc]...);
    ]
end

function codegen_dynamics(model::PointFootQuadruped)
    mm = q -> mass_matrix(model, q)
    db = (q, q̇) -> dynamics_bias(model, q, q̇)
    return mm, db
end

function dynamics(model::PointFootQuadruped, mass_matrix, dynamics_bias, h, q0, q1, u1, w1, λ1, q2)
    # evalutate at midpoint
    qm1 = 0.5 * (q0 + q1)
    vm1 = (q1 - q0) / h[1]
    qm2 = 0.5 * (q1 + q2)
    vm2 = (q2 - q1) / h[1]

    D1L1, D2L1 = lagrangian_derivatives(mass_matrix, dynamics_bias, qm1, vm1)
    D1L2, D2L2 = lagrangian_derivatives(mass_matrix, dynamics_bias, qm2, vm2)

    d = 0.5 * h[1] * D1L1 + D2L1 + 0.5 * h[1] * D1L2 - D2L2 # variational integrator (midpoint)
    d .+= transpose(input_jacobian(model, qm2)) * u1             # control inputs
    d .+= λ1                                                # contact impulses

    # d[(floating_base_dim(model) + 1):end] .-= model.friction_joint .* [vm2[(floating_base_dim(model) + 1):end] - [vm2[1:3]] # joint friction
    d[1:3] .-= model.friction_joint .* (vm2[1:3] - vm2[7:9]) # joint friction
    d[1:3] .-= model.friction_joint .* (vm2[1:3] - vm2[10:12]) # joint friction
    d[1:3] .-= model.friction_joint .* (vm2[1:3] - vm2[13:15]) # joint friction
    d[1:3] .-= model.friction_joint .* (vm2[1:3] - vm2[16:18]) # joint friction

    d[7:9]   .-= model.friction_joint .* (vm2[7:9] - vm2[1:3]) # joint friction
    d[10:12] .-= model.friction_joint .* (vm2[10:12] - vm2[1:3]) # joint friction
    d[13:15] .-= model.friction_joint .* (vm2[13:15] - vm2[1:3]) # joint friction
    d[16:18] .-= model.friction_joint .* (vm2[16:18] - vm2[1:3]) # joint friction
    return d
end


text:
""" multiple strings replacement, for multiple on Julia version """
function replace_multi(text, pairs...)::String
    VERSION ≥ v"1.7" && return replace(text, pairs...)
    VERSION < v"1.7" && begin
        for pair in pairs
            text = replace(text, pair)
        end
    end
    return text
end

# ---------------------------------------------------------------------------- #
#                                     REGEX                                    #
# ---------------------------------------------------------------------------- #
# ---------------------------------- markup ---------------------------------- #

"""
This regex uses lookahead and lookbehind to exclude [[
at the beginning of a tag, with this:
    (?<!\\{)\\[(?!\\{)
"""
OPEN_TAG_REGEX = r"(?<!\{)\{(?!\{)[a-zA-Z _0-9. ,()#\n]*\}"
CLOSE_TAG_REGEX = r"\{\/[a-zA-Z _0-9. ,()#\n]+[^/\{]\}"
GENERIC_CLOSER_REGEX = r"(?<!\{)\{(?!\{)\/\}"

"""
    remove_markup(input_text::AbstractString)::AbstractString

Remove all markup tags from a string of text.
"""
remove_markup(input_text)::String = replace_multi(
    input_text,
    OPEN_TAG_REGEX => "",
    GENERIC_CLOSER_REGEX => "",
    CLOSE_TAG_REGEX => "",
)

"""
    has_markup(text::String)

Returns `true` if `text` includes a `MarkupTag`
"""
has_markup(text)::Bool = occursin(OPEN_TAG_REGEX, text)

# ----------------------------------- ansi ----------------------------------- #
const ANSI_REGEXE = r"\e\[[0-9;]*m"

"""
    remove_ansi(input_text::AbstractString)::AbstractString

Remove all ANSI tags from a string of text
"""
remove_ansi(input_text)::String = replace(input_text, ANSI_REGEXE => "")

"""
    has_ansi(text::String)

Returns `true` if `text` includes a `MarkupTag`
"""
has_ansi(text)::Bool = occursin(ANSI_REGEXE, text)

"""
    get_last_ANSI_code(text)::String

Get the last ANSI code in a sting, returns "" if no ANSI code found.
"""
function get_last_ANSI_code(text)::String
    has_ansi(text) || return ""

    # get the last matching regex
    rmatch = collect((eachmatch(ANSI_REGEXE, text)))[end]
    return rmatch.match
end

"""
    get_ANSI_codes(text)::String

Returns a string with all ANSI codes in the input.
"""
function get_ANSI_codes(text)::String
    has_ansi(text) || return ""
    matches = collect((eachmatch(ANSI_REGEXE, text)))
    return *(map(m -> m.match, matches)...)
end

"""
    replace_ansi(input_text)

Replace ANSI tags with ¦.

The number of '¦' matches the length of the ANSI tags.
Used when we want to hide ANSI tags but keep the string length intact.
"""
function replace_ansi(input_text)
    while occursin(rx, input_text)
        mtch = match(ANSI_REGEXE, input_text)
        input_text = replace_text(
            input_text,
            mtch.offset - 1,
            mtch.offset + length(mtch.match) - 1,
            '¦',
        )
    end
    return input_text
end

ANSI_CLEANUP_REGEXES = [
    r"\e\[[0-9][0-9]m\e\[39m" => "",
    r"\e\[[0-9][0-9]m\e\[49m" => "",
    r"\e\[[0-9]m\e\[2[0-9]m" => "",
    r"\e\[22m\e\[22m" => "",
]

cleanup_ansi(text) = replace_multi(text, ANSI_CLEANUP_REGEXES...)

# --------------------------- clean text / text len -------------------------- #
"""
    cleantext(str::AbstractString)

Remove all style information from a string.
"""
cleantext(str)::String = (remove_ansi ∘ remove_markup)(str)

"""
    textlen(x::AbstractString)

Get length of text after all style information is removed.
"""
textlen(x::String)::Int = (textwidth ∘ remove_markup ∘ remove_ansi)(x)
textlen(x::SubString)::Int = (textwidth ∘ remove_markup ∘ remove_ansi)(x)

# --------------------------------- brackets --------------------------------- #
const brackets_regexes = [r"(?<!\{)\{(?!\{)", r"(?<!\})\}(?!\})"]

"""
    remove_ansi(str)::String

Replace each cirly bracket with a double copy of itself
"""
escape_brackets(text)::String =
    replace_multi(text, brackets_regexes[1] => "{{", brackets_regexes[2] => "}}")

const remove_brackets_regexes = [r"\{\{", r"\}\}"]

"""
    unescape_brackets(text)::String

Replece every double squared parenthesis with a single copy of itself
"""
unescape_brackets(text)::String = replace_multi(
    text,
    remove_brackets_regexes[1] => "{",
    remove_brackets_regexes[2] => "}",
)

unescape_brackets_with_space(text)::String = replace_multi(
    text,
    remove_brackets_regexes[1] => " {",
    remove_brackets_regexes[2] => "} ",
)

# ---------------------------------------------------------------------------- #
#                                      I/O                                     #
# ---------------------------------------------------------------------------- #
"""
    read_file_lines(path::String, start::Int, stop::Int)

Read a file and select only lines in range `start` -> `stop`.

Returns a vector of tuples with the line number and line content.
"""
function read_file_lines(path::AbstractString, start::Int, stop::Int)
    !isfile(path) && return nothing

    start = start < 1 ? 1 : start
    stop = stop ≥ countlines(path) ? countlines(path) : stop
    lines = readlines(path; keep = true)
    return collect(enumerate(lines))[start:stop]
end

# ---------------------------------------------------------------------------- #
#                                     MISC                                     #
# ---------------------------------------------------------------------------- #
"""
    tview(text, start::Int, stop::Int)

Get a view object with appropriate indices
"""
tview(text, start::Int, stop::Int) = view(text, thisind(text, start):thisind(text, stop))
tview(text, start::Int, stop::Int, simple::Symbol) = view(text, start:stop)

"""
    replace_text(text::AbstractString, start::Int, stop::Int, replace::AbstractString)

Replace a section of a `text` between `start` and `stop` with `replace`.
"""
function replace_text(text, start::Int, stop::Int, replace::String)::String
    if start == 0
        return replace * text[(stop + 1):end]
    end

    start = isvalid(text, start) ? start : max(prevind(text, start), 1)
    return if start == 1
        text[1] * replace * text[(stop + 1):end]
    elseif stop == ncodeunits(text)
        text[1:start] * replace
    else
        text[1:start] * replace * text[(stop + 1):end]
    end
end

"""
    replace_text(text::AbstractString, start::Int, stop::Int, char::Char='_')

Replace a section of a `text`  between `start` and `stop` with another string composed of repeats of a given character `char`.
"""
function replace_text(text, start::Int, stop::Int, char::Char = '_')::String
    replacement = char^(stop - start)
    return replace_text(text, start, stop, replacement)
end

"""
    ltrim_str(str, width)

Cut a chunk of width `width` form the left of a string
"""
function ltrim_str(str, width)
    edge = nextind(str, 0, width)
    return if edge ≥ ncodeunits(str)
        str
    else
        str[1:edge]
    end
end

"""
    rtrim_str(str, width)

Cut a chunk of width `width` form the right of a string
"""
function rtrim_str(str, width)
    edge = nextind(str, 0, width)
    return str[edge:end]
end

"""
    nospaces(text::AbstractString)

Remove all spaces from a string.
"""
nospaces(text::AbstractString) = replace(text, " " => "")

"""
    remove_brackets(text::AbstractString)

Remove all () brackets from a string.
"""
remove_brackets(text)::String = replace_multi(text, "(" => "", ")" => "")

"""
    unspace_commas(text::AbstractString)

Remove spaces after commas.
"""
unspace_commas(text)::String = replace_multi(text, ", " => ",", ". " => ".")

"""
Split a string into a vector of Chars.
"""
chars(text::AbstractString)::Vector{Char} = collect(text)

"""
    join_lines(lines)

Merge a vector of strings in a single string.
"""
join_lines(lines::Vector{String})::String = join(lines, "\n")
join_lines(lines::Vector)::String = join(lines, "\n")
join_lines(lines...) = join(lines, "\n")

"""
    split_lines(text::AbstractString)

Split a string into its composing lines.
"""
split_lines(text::String)::Vector{String} = split(text, "\n")
split_lines(text::SubString)::Vector{String} = String.(split(text, "\n"))

"""
    split_lines(renderable)

Split a renderable's text.
"""
function split_lines(renderable)
    string(typeof(renderable)) == "Segment" && return split_lines(renderable.text)
    return [s.text for s in renderable.segments]
end

"""
    do_by_line(fn::Function, text::String)

Apply `fn` to each line in the `text`.

The function `fn` should accept a single `::String` argument.
"""
function do_by_line(fn::Function, text)::String
    out = ""
    for (last, line) in loop_last(split_lines(text))
        out *= fn(line) * (last ? "" : "\n")
    end
    return out
end

do_by_line(fn::Function, text::Vector)::String = join_lines(fn.(text))

# ------------------------------- reshape text ------------------------------- #
"""
    fillin(text::String)::String

Ensure that each line in a multi-line text has the same width.
"""
function fillin(text)::String
    lines = split_lines(text)
    length(lines) == 1 && return text

    w = max(map(textlen, lines)...)
    return join_lines(map((ln) -> ln * " "^(w - textlen(ln)), lines))
end

"""
    truncate(text::AbstractString, width::Int)

Shorten a string of text to a target width
"""
function truncate(text::AbstractString, width::Int; trailing_dots = "...")
    # occursin('\n', text) &&  do_by_line(ln -> truncate(ln, width; trailing_dots=trailing_dots), text)
    width < 0 && return text
    textlen(text) ≤ width && return text

    trunc = reshape_text(text, width - 3)
    return split_lines(trunc)[1] * trailing_dots
end


text:
# Wrappers for Tensor type are defined by
# the math operation defined in tensorflow
# and the KB function in keras.
#
# Refs:
# - https://www.tensorflow.org/api_docs/python/framework/core_graph_data_structures#Tensor.__add__
#
# NOTE: Unfortunately, this needs to be largely written by hand as we don't have a perfect
# mapping of function names and we aren't performing inspection on the python KB code.
#
# TODO: Check that PyObject is an appropriate Tensor.
using Compat.Statistics

struct Tensor
    o::PyObject
end

# PyObject(tensor::Tensor) = tensor.o
# Base.convert(::Type{Tensor}, obj::PyObject) = Tensor(obj)
Base.abs(x::Tensor) = Tensor(Keras._backend[:abs](x.o))

Base.:-(x::Tensor) = Tensor(x.o[:__neg__]())
Base.:~(x::Tensor) = Tensor(x.o[:__invert__]())
Base.:&(a::Tensor, b::Tensor) = Tensor(a.o[:__and__](b.o))
Base.:|(a::Tensor, b::Tensor) = Tensor(a.o[:__or__](b.o))

Base.broadcast(::typeof(mod), a::Tensor, b::Tensor) = Tensor(a.o[:__mod__](b.o))
Base.broadcast(::typeof(==), a::Tensor, b::Tensor) = Tensor(Keras._backend[:equal](a.o, b.o))
Base.broadcast(::typeof(!=), a::Tensor, b::Tensor) = Tensor(Keras._backend[:not_equal](a.o, b.o))
Base.broadcast(::typeof(>), a::Tensor, b::Tensor) = Tensor(Keras._backend[:greater](a.o, b.o))
Base.broadcast(::typeof(<), a::Tensor, b::Tensor) = Tensor(Keras._backend[:less](a.o, b.o))
Base.broadcast(::typeof(>=), a::Tensor, b::Tensor) = Tensor(Keras._backend[:greater_equal](a.o, b.o))
Base.broadcast(::typeof(<=), a::Tensor, b::Tensor) = Tensor(Keras._backend[:less_equal](a.o, b.o))
Base.broadcast(::typeof(^), a::Tensor, b::Tensor) = Tensor(a.o[:__pow__](b.o))
Base.broadcast(::typeof(+), a::Tensor, b::Tensor) = Tensor(a.o[:__add__](b.o))
Base.broadcast(::typeof(-), a::Tensor, b::Tensor) = Tensor(a.o[:__sub__](b.o))
Base.broadcast(::typeof(*), a::Tensor, b::Tensor) = Tensor(a.o[:__mul__](b.o))
Base.broadcast(::typeof(/), a::Tensor, b::Tensor) = Tensor(a.o[:__div__](b.o))

# The dot product in Keras is just a matrix multiply in julia
Base.:*(a::Tensor, b::Tensor) = Tensor(Keras._backend[:dot](a.o, b.o))

Base.transpose(x::Tensor) = Tensor(Keras._backend[:transpose](x.o))
Base.maximum(x::Tensor, dims=nothing) = Tensor(Keras._backend[:max](x.o, axis=dims))
Base.minimum(x::Tensor, dims=nothing) = Tensor(Keras._backend[:min](x.o, axis=dims))
Base.sum(x::Tensor, dims=nothing) = Tensor(Keras._backend[:sum](x.o, axis=dims))
Base.prod(x::Tensor, dims=nothing) = Tensor(Keras._backend[:prod](x.o, axis=dims))
Statistics.var(x::Tensor, dims=nothing) = Tensor(Keras._backend[:var](x.o, axis=dims))
Statistics.std(x::Tensor, dims=nothing) = Tensor(Keras._backend[:std](x.o, axis=dims))
Statistics.mean(x::Tensor, dims=nothing) = Tensor(Keras._backend[:mean](x.o, axis=dims))
Base.any(x::Tensor, dims=nothing) = Tensor(Keras._backend[:any](x.o, axis=dims))
Base.all(x::Tensor, dims=nothing) = Tensor(Keras._backend[:all](x.o, axis=dims))
Base.broadcast(::typeof(sqrt), x::Tensor) = Tensor(Keras._backend[:sqrt](x.o))
Base.broadcast(::typeof(exp), x::Tensor) = Tensor(Keras._backend[:exp](x.o))
Base.broadcast(::typeof(log), x::Tensor) = Tensor(Keras._backend[:log](x.o))
Base.broadcast(::typeof(round), x::Tensor) = Tensor(Keras._backend[:round](x.o))
Base.broadcast(::typeof(sin), x::Tensor) = Tensor(Keras._backend[:sin](x.o))
Base.broadcast(::typeof(cos), x::Tensor) = Tensor(Keras._backend[:cos](x.o))

eval(x::Tensor) = Keras._backend[:eval](x.o)

clip(x::Tensor, min_val, max_val) = Tensor(Keras._backend[:clip](x.o, min_val, max_val))
square(x::Tensor) = Tensor(Keras._backend[:square](x.o))
variable(x::Any, name=nothing) = Tensor(Keras._backend[:variable](x, name=name))
rand_uni(args...; kwargs...) = Keras._backend[:random_uniform_variable](args...; kwargs...)
rand_norm(args...; kwargs...) = Keras._backend[:random_normal_variable](args...; kwargs...)
cast(x::Tensor, dtype) =  Keras._backend[:cast](x.o, dtype)

# Utility methods for pairwise operations to support backwards compatibility
Base.mod(a::Tensor, b::Tensor) = mod.(a, b)
Base.:+(a::Tensor, b::Tensor) = broadcast(+, a, b)
Base.:-(a::Tensor, b::Tensor) = broadcast(-, a, b)
Base.exp(x::Tensor) = broadcast(exp, x)
Base.sqrt(x::Tensor) = broadcast(sqrt, x)
Base.log(x::Tensor) = broadcast(log, x)
Base.round(x::Tensor) = broadcast(round, x)
Base.sin(x::Tensor) = broadcast(sin, x)
Base.cos(x::Tensor) = broadcast(cos, x)

# This is not a complete wrapping of the keras backend.
export Tensor, square, clip, variable, rand_uni, rand_norm


text:
let
    n = 50
    p = 3
    t = (1:n)/n
    Ut,Vt = egrss.generators(t,p);

    @test ( size(Ut) == (p,n) )
    @test ( size(Vt) == (p,n) )

    K = Symmetric(tril(Ut'*Vt) + triu(Vt'*Ut,1))
    cholesky(K)
end

max_stars_repo_name: martinandersen/EGRSS

max_issues_repo_name: martinandersen/EGRSS

max_forks_repo_name: martinandersen/EGRSS


text:
# getindex on patterns

#### Globs

function Base.getindex(t::FileTree, g::GlobMatch)
    sub = _glob_filter(t, name(t), g.pattern...)
    if sub === nothing
        error("$g did not match in tree")
    end
    setparent(sub)
end

_occursin(p::AbstractString, x) = p == x
_occursin(p, x) = occursin(p, x)

_glob_filter(t::Node, ps...) = _glob_map(identity, x->nothing, t, ps...)

_glob_map(yes, no, t::File) = yes(t)

_glob_map(yes, no, t::FileTree) = yes(t)

function _glob_map(yes, no, t::FileTree, p, ps...)
    if _occursin(p, name(t))
        # This path (maybe a FileTree) matches. And is the end of the pattern.
        if (isempty(ps) || (ps[1] isa AbstractString && isempty(ps[1])))
            return yes(t)
        end

        # Full path hasn't been matched, continue into the children.
        cs = filter(!isnothing, map(c->_glob_map(yes, no, c, ps...), children(t)))
        if isempty(cs)
            return no(t)
        else
            return FileTree(t, children=cs)
        end
    else
        return no(t)
    end
end

_glob_map(yes, no, t::File, p) = _occursin(p, name(t)) ? yes(t) : no(t)
_glob_map(yes, no, t::File, p...) = no(t)

#### Regexes

"""
    getindex(t::FileTree, regex::Regex)
    t[regex]

Returns a filtered trees where paths match the `regex` regular expression.
Surround the regular expression in `^` and `\$` (to match the entire string).
"""

function Base.getindex(x::Union{FileTree, File}, regex::Regex)
    t = _regex_map(identity, x->nothing, x, regex)
    isnothing(t) ?  empty(x) : setparent(t)
end

function _regex_map(yes, no, t::FileTree, regex::Regex, toplevel=true)
    if !toplevel && !isnothing(match(regex, canonical_path(Path(t))))
        return yes(t)
    end

    cs = map(children(t)) do x
        if toplevel
            x = setparent(x, nothing)
        end
        _regex_map(yes, no, x, regex, false)
    end

    cs = filter(!isnothing, cs)

    if isempty(cs)
        return no(t)
    else
        return FileTree(t; children=cs) |> setparent
    end
end

function _regex_map(yes, no, t::File, regex::Regex, toplevel=false)
    !isnothing(match(regex, canonical_path(Path(t)))) ? yes(t) : no(t)
end

"""
    mapsubtrees(f, t::FileTree, pattern::Union{GlobMatch, Regex})

For every node that matches the pattern provided, apply the function `f`.

If `f` returns either a `File` or `FileTree`, this new node will replace the matched node.

If `f` returns `nothing`, the matched node will be deleted

If `f` returns any other value, the value will be used as the value of the node
and the node itself will be emptied of children.

This will allow use of mapsubtrees for complex use cases.

Suppose you would like to combine the values of a subdirectory with the
function `hcat` and in turn those values using `vcat`, you can use
`mapsubtrees` to accomplish this:

Here is a demo:

```julia
t = maketree("dir"=>([string(j)=>[(name=string(i), value=(i,j)]
                        for i=1:2] for j=1:3]

t1 = mapsubtrees("*") do subtree
    reducevalues(vcat, subtree)
end
```

```julia
reducevalues(hcat, t1)
```
"""
function mapsubtrees(f, t::FileTree, g::GlobMatch, combine=_merge_error)
    _glob_map(m->apply_to_match(f, m), identity, t, name(t), g.pattern...) |> setparent |> xs->normdots(xs, combine=combine)
end

function mapsubtrees(f, t::FileTree, r::Regex, combine=_merge_error)
    _regex_map(m->apply_to_match(f, m), identity, t, r) |> setparent |> xs->normdots(xs, combine=combine)
end

function apply_to_match(f, match)
    x = f(match)
    !(x isa Union{FileTree, File}) ?
        setvalue(empty(match), x) : x
end


text:
# function turbine_velocities(windfarm::AbstractWindFarmModel,
#     windresource::AbstractWindResourceModel,
#     windshearmodel::AbstractWindShearModel,
#     wakedeficitmodel::AbstractWakeDeficitModel,
#     wakedeflectionmodel::AbstractWakeDeflectionModel,
#     wakecombinationmodel::AbstractWakeCombinationModel)

#     @test ff.point_velocity(loc, windfarm, windfarmstate, windresource, wakedeficitmodel, wakedeflectionmodel, wakecombinationmodel, windshearmodel, 0) == expected_velocity

# end

# function flow_field(windfarm::AbstractWindFarmModel,
#     windresource::AbstractWindResourceModel,
#     windshearmodel::AbstractWindShearModel,
#     wakedeficitmodel::AbstractWakeDeficitModel,
#     wakedeflectionmodel::AbstractWakeDeflectionModel,
#     wakecombinationmodel::AbstractWakeCombinationModel)

#     @test ff.point_velocity(loc, windfarm, windfarmstate, windresource, wakedeficitmodel, wakedeflectionmodel, wakecombinationmodel, windshearmodel, 0) == expected_velocity

# end


text:
module TargetPlot
import Base.MathConstants as cons
import Plots as plt
plt.pyplot()

function f(x, y)
    return -20.0 * exp(-0.2 * sqrt(0.5 * (x^2 + y^2))) -
  exp(0.5 * (cos(2.0 * pi * x) + cos(2.0 * pi * y))) +  cons.e + 20.0
  #  ((1.0 - y) * sin(x))^2 + (y * (2.0 - x))^2
end

const plot = function ()
    x = -5.0:0.1:5.0
    y = -5.0:0.1:5.0
    # plt.heatmap(x, y, f)
    plt.plot(x, y, f, st=:wireframe)
    plt.png("my-plots/wireframe.png")
end

end

max_stars_repo_name: applied-math-coding/heuristic

max_issues_repo_name: applied-math-coding/heuristic

max_forks_repo_name: applied-math-coding/heuristic


text:
int_rules_4_5_1_2 = @theory begin

    #= ::Subsection::Closed:: =#
    #= 4.5.1.2*(d*sec)^n*(a+b*sec)^m =#
    @apply_utils Antiderivative((~a + ~(b') * csc(~(e') + ~(f') * ~x)) * (~(d') * csc(~(e') + ~(f') * ~x)) ^ ~(n'), ~x) => ~a * Antiderivative((~d * csc(~e + ~f * ~x)) ^ ~n, ~x) + (~b / ~d) * Antiderivative((~d * csc(~e + ~f * ~x)) ^ (~n + 1), ~x) <-- FreeQ([~a, ~b, ~d, ~e, ~f, ~n], ~x)
    @apply_utils Antiderivative((~a + ~(b') * csc(~(e') + ~(f') * ~x)) ^ 2 * (~(d') * csc(~(e') + ~(f') * ~x)) ^ ~(n'), ~x) => ((2 * ~a * ~b) / ~d) * Antiderivative((~d * csc(~e + ~f * ~x)) ^ (~n + 1), ~x) + Antiderivative((~d * csc(~e + ~f * ~x)) ^ ~n * ((~a) ^ 2 + (~b) ^ 2 * csc(~e + ~f * ~x) ^ 2), ~x) <-- FreeQ([~a, ~b, ~d, ~e, ~f, ~n], ~x)
    @apply_utils Antiderivative(csc(~(e') + ~(f') * ~x) ^ 2 / (~a + ~(b') * csc(~(e') + ~(f') * ~x)), ~x) => (1 / ~b) * Antiderivative(csc(~e + ~f * ~x), ~x) - (~a / ~b) * Antiderivative(csc(~e + ~f * ~x) / (~a + ~b * csc(~e + ~f * ~x)), ~x) <-- FreeQ([~a, ~b, ~e, ~f], ~x)
    @apply_utils Antiderivative(csc(~(e') + ~(f') * ~x) ^ 3 / (~a + ~(b') * csc(~(e') + ~(f') * ~x)), ~x) => -(cot(~e + ~f * ~x)) / (~b * ~f) - (~a / ~b) * Antiderivative(csc(~e + ~f * ~x) ^ 2 / (~a + ~b * csc(~e + ~f * ~x)), ~x) <-- FreeQ([~a, ~b, ~e, ~f], ~x)
    @apply_utils Antiderivative((~a + ~(b') * csc(~(e') + ~(f') * ~x)) ^ ~m * (~(d') * csc(~(e') + ~(f') * ~x)) ^ ~(n'), ~x) => Antiderivative(ExpandTrig((~a + ~b * csc(~e + ~f * ~x)) ^ ~m * (~d * csc(~e + ~f * ~x)) ^ ~n, ~x), ~x) <-- FreeQ([~a, ~b, ~d, ~e, ~f, ~m, ~n], ~x) && (EqQ((~a) ^ 2 - (~b) ^ 2, 0) && (IGtQ(~m, 0) && RationalQ(~n)))
    @apply_utils Antiderivative(csc(~(e') + ~(f') * ~x) * sqrt(~a + ~(b') * csc(~(e') + ~(f') * ~x)), ~x) => (-2 * ~b * cot(~e + ~f * ~x)) / (~f * sqrt(~a + ~b * csc(~e + ~f * ~x))) <-- FreeQ([~a, ~b, ~e, ~f], ~x) && EqQ((~a) ^ 2 - (~b) ^ 2, 0)
    @apply_utils Antiderivative(csc(~(e') + ~(f') * ~x) * (~a + ~(b') * csc(~(e') + ~(f') * ~x)) ^ ~m, ~x) => (-(~b) * cot(~e + ~f * ~x) * (~a + ~b * csc(~e + ~f * ~x)) ^ (~m - 1)) / (~f * ~m) + ((~a * (2 * ~m - 1)) / ~m) * Antiderivative(csc(~e + ~f * ~x) * (~a + ~b * csc(~e + ~f * ~x)) ^ (~m - 1), ~x) <-- FreeQ([~a, ~b, ~e, ~f], ~x) && (EqQ((~a) ^ 2 - (~b) ^ 2, 0) && (GtQ(~m, 1 / 2) && IntegerQ(2 * ~m)))
    @apply_utils Antiderivative(csc(~(e') + ~(f') * ~x) / (~a + ~(b') * csc(~(e') + ~(f') * ~x)), ~x) => -(cot(~e + ~f * ~x)) / (~f * (~b + ~a * csc(~e + ~f * ~x))) <-- FreeQ([~a, ~b, ~e, ~f], ~x) && EqQ((~a) ^ 2 - (~b) ^ 2, 0)
    @apply_utils Antiderivative(csc(~(e') + ~(f') * ~x) / sqrt(~a + ~(b') * csc(~(e') + ~(f') * ~x)), ~x) => (-2 / ~f) * Subst(Antiderivative(1 / (2 * ~a + (~x) ^ 2), ~x), ~x, (~b * cot(~e + ~f * ~x)) / sqrt(~a + ~b * csc(~e + ~f * ~x))) <-- FreeQ([~a, ~b, ~e, ~f], ~x) && EqQ((~a) ^ 2 - (~b) ^ 2, 0)
    @apply_utils Antiderivative(csc(~(e') + ~(f') * ~x) * (~a + ~(b') * csc(~(e') + ~(f') * ~x)) ^ ~m, ~x) => (~b * cot(~e + ~f * ~x) * (~a + ~b * csc(~e + ~f * ~x)) ^ ~m) / (~a * ~f * (2 * ~m + 1)) + ((~m + 1) / (~a * (2 * ~m + 1))) * Antiderivative(csc(~e + ~f * ~x) * (~a + ~b * csc(~e + ~f * ~x)) ^ (~m + 1), ~x) <-- FreeQ([~a, ~b, ~e, ~f], ~x) && (EqQ((~a) ^ 2 - (~b) ^ 2, 0) && (LtQ(~m, -1 / 2) && IntegerQ(2 * ~m)))
    @apply_utils Antiderivative(csc(~(e') + ~(f') * ~x) ^ 2 * (~a + ~(b') * csc(~(e') + ~(f') * ~x)) ^ ~m, ~x) => (-(cot(~e + ~f * ~x)) * (~a + ~b * csc(~e + ~f * ~x)) ^ ~m) / (~f * (2 * ~m + 1)) + (~m / (~b * (2 * ~m + 1))) * Antiderivative(csc(~e + ~f * ~x) * (~a + ~b * csc(~e + ~f * ~x)) ^ (~m + 1), ~x) <-- FreeQ([~a, ~b, ~e, ~f], ~x) && (EqQ((~a) ^ 2 - (~b) ^ 2, 0) && LtQ(~m, -1 / 2))
    @apply_utils Antiderivative(csc(~(e') + ~(f') * ~x) ^ 2 * (~a + ~(b') * csc(~(e') + ~(f') * ~x)) ^ ~m, ~x) => (-(cot(~e + ~f * ~x)) * (~a + ~b * csc(~e + ~f * ~x)) ^ ~m) / (~f * (~m + 1)) + ((~a * ~m) / (~b * (~m + 1))) * Antiderivative(csc(~e + ~f * ~x) * (~a + ~b * csc(~e + ~f * ~x)) ^ ~m, ~x) <-- FreeQ([~a, ~b, ~e, ~f, ~m], ~x) && (EqQ((~a) ^ 2 - (~b) ^ 2, 0) && Not(LtQ(~m, -1 / 2)))
    @apply_utils Antiderivative(csc(~(e') + ~(f') * ~x) ^ 3 * (~a + ~(b') * csc(~(e') + ~(f') * ~x)) ^ ~m, ~x) => (~b * cot(~e + ~f * ~x) * (~a + ~b * csc(~e + ~f * ~x)) ^ ~m) / (~a * ~f * (2 * ~m + 1)) - (1 / ((~a) ^ 2 * (2 * ~m + 1))) * Antiderivative(csc(~e + ~f * ~x) * (~a + ~b * csc(~e + ~f * ~x)) ^ (~m + 1) * (~a * ~m - ~b * (2 * ~m + 1) * csc(~e + ~f * ~x)), ~x) <-- FreeQ([~a, ~b, ~e, ~f], ~x) && (EqQ((~a) ^ 2 - (~b) ^ 2, 0) && LtQ(~m, -1 / 2))
    @apply_utils Antiderivative(csc(~(e') + ~(f') * ~x) ^ 3 * (~a + ~(b') * csc(~(e') + ~(f') * ~x)) ^ ~m, ~x) => (-(cot(~e + ~f * ~x)) * (~a + ~b * csc(~e + ~f * ~x)) ^ (~m + 1)) / (~b * ~f * (~m + 2)) + (1 / (~b * (~m + 2))) * Antiderivative(csc(~e + ~f * ~x) * (~a + ~b * csc(~e + ~f * ~x)) ^ ~m * (~b * (~m + 1) - ~a * csc(~e + ~f * ~x)), ~x) <-- FreeQ([~a, ~b, ~e, ~f, ~m], ~x) && (EqQ((~a) ^ 2 - (~b) ^ 2, 0) && Not(LtQ(~m, -1 / 2)))
    @apply_utils Antiderivative(sqrt(~a + ~(b') * csc(~(e') + ~(f') * ~x)) * sqrt(~(d') * csc(~(e') + ~(f') * ~x)), ~x) => ((-2 * ~a) / (~b * ~f)) * sqrt((~a * ~d) / ~b) * Subst(Antiderivative(1 / sqrt(1 + (~x) ^ 2 / ~a), ~x), ~x, (~b * cot(~e + ~f * ~x)) / sqrt(~a + ~b * csc(~e + ~f * ~x))) <-- FreeQ([~a, ~b, ~d, ~e, ~f], ~x) && (EqQ((~a) ^ 2 - (~b) ^ 2, 0) && GtQ((~a * ~d) / ~b, 0))
    @apply_utils Antiderivative(sqrt(~a + ~(b') * csc(~(e') + ~(f') * ~x)) * sqrt(~(d') * csc(~(e') + ~(f') * ~x)), ~x) => ((-2 * ~b * ~d) / ~f) * Subst(Antiderivative(1 / (~b - ~d * (~x) ^ 2), ~x), ~x, (~b * cot(~e + ~f * ~x)) / (sqrt(~a + ~b * csc(~e + ~f * ~x)) * sqrt(~d * csc(~e + ~f * ~x)))) <-- FreeQ([~a, ~b, ~d, ~e, ~f], ~x) && (EqQ((~a) ^ 2 - (~b) ^ 2, 0) && Not(GtQ((~a * ~d) / ~b, 0)))
    @apply_utils Antiderivative(sqrt(~a + ~(b') * csc(~(e') + ~(f') * ~x)) * (~(d') * csc(~(e') + ~(f') * ~x)) ^ ~n, ~x) => (-2 * ~b * ~d * cot(~e + ~f * ~x) * (~d * csc(~e + ~f * ~x)) ^ (~n - 1)) / (~f * (2 * ~n - 1) * sqrt(~a + ~b * csc(~e + ~f * ~x))) + ((2 * ~a * ~d * (~n - 1)) / (~b * (2 * ~n - 1))) * Antiderivative(sqrt(~a + ~b * csc(~e + ~f * ~x)) * (~d * csc(~e + ~f * ~x)) ^ (~n - 1), ~x) <-- FreeQ([~a, ~b, ~d, ~e, ~f], ~x) && (EqQ((~a) ^ 2 - (~b) ^ 2, 0) && (GtQ(~n, 1) && IntegerQ(2 * ~n)))
    @apply_utils Antiderivative(sqrt(~a + ~(b') * csc(~(e') + ~(f') * ~x)) / sqrt(~(d') * csc(~(e') + ~(f') * ~x)), ~x) => (-2 * ~a * cot(~e + ~f * ~x)) / (~f * sqrt(~a + ~b * csc(~e + ~f * ~x)) * sqrt(~d * csc(~e + ~f * ~x))) <-- FreeQ([~a, ~b, ~d, ~e, ~f], ~x) && EqQ((~a) ^ 2 - (~b) ^ 2, 0)
    @apply_utils Antiderivative(sqrt(~a + ~(b') * csc(~(e') + ~(f') * ~x)) * (~(d') * csc(~(e') + ~(f') * ~x)) ^ ~n, ~x) => (~a * cot(~e + ~f * ~x) * (~d * csc(~e + ~f * ~x)) ^ ~n) / (~f * ~n * sqrt(~a + ~b * csc(~e + ~f * ~x))) + ((~a * (2 * ~n + 1)) / (2 * ~b * ~d * ~n)) * Antiderivative(sqrt(~a + ~b * csc(~e + ~f * ~x)) * (~d * csc(~e + ~f * ~x)) ^ (~n + 1), ~x) <-- FreeQ([~a, ~b, ~d, ~e, ~f], ~x) && (EqQ((~a) ^ 2 - (~b) ^ 2, 0) && (LtQ(~n, -1 / 2) && IntegerQ(2 * ~n)))
    @apply_utils Antiderivative(sqrt(~a + ~(b') * csc(~(e') + ~(f') * ~x)) * (~(d') * csc(~(e') + ~(f') * ~x)) ^ ~n, ~x) => (((~a) ^ 2 * ~d * cot(~e + ~f * ~x)) / (~f * sqrt(~a + ~b * csc(~e + ~f * ~x)) * sqrt(~a - ~b * csc(~e + ~f * ~x)))) * Subst(Antiderivative((~d * ~x) ^ (~n - 1) / sqrt(~a - ~b * ~x), ~x), ~x, csc(~e + ~f * ~x)) <-- FreeQ([~a, ~b, ~d, ~e, ~f, ~n], ~x) && EqQ((~a) ^ 2 - (~b) ^ 2, 0)
    @apply_utils Antiderivative(sqrt(~(d') * csc(~(e') + ~(f') * ~x)) / sqrt(~a + ~(b') * csc(~(e') + ~(f') * ~x)), ~x) => ((-(sqrt(2)) * sqrt(~a)) / (~b * ~f)) * Subst(Antiderivative(1 / sqrt(1 + (~x) ^ 2), ~x), ~x, (~b * cot(~e + ~f * ~x)) / (~a + ~b * csc(~e + ~f * ~x))) <-- FreeQ([~a, ~b, ~d, ~e, ~f], ~x) && (EqQ((~a) ^ 2 - (~b) ^ 2, 0) && (EqQ(~d - ~a / ~b, 0) && GtQ(~a, 0)))
    @apply_utils Antiderivative(sqrt(~(d') * csc(~(e') + ~(f') * ~x)) / sqrt(~a + ~(b') * csc(~(e') + ~(f') * ~x)), ~x) => ((-2 * ~b * ~d) / (~a * ~f)) * Subst(Antiderivative(1 / (2 * ~b - ~d * (~x) ^ 2), ~x), ~x, (~b * cot(~e + ~f * ~x)) / (sqrt(~a + ~b * csc(~e + ~f * ~x)) * sqrt(~d * csc(~e + ~f * ~x)))) <-- FreeQ([~a, ~b, ~d, ~e, ~f], ~x) && EqQ((~a) ^ 2 - (~b) ^ 2, 0)
    @apply_utils Antiderivative((~a + ~(b') * csc(~(e') + ~(f') * ~x)) ^ ~m * (~(d') * csc(~(e') + ~(f') * ~x)) ^ ~n, ~x) => (-(~a) * cot(~e + ~f * ~x) * (~a + ~b * csc(~e + ~f * ~x)) ^ (~m - 1) * (~d * csc(~e + ~f * ~x)) ^ ~n) / (~f * ~m) + ((~b * (2 * ~m - 1)) / (~d * ~m)) * Antiderivative((~a + ~b * csc(~e + ~f * ~x)) ^ (~m - 1) * (~d * csc(~e + ~f * ~x)) ^ (~n + 1), ~x) <-- FreeQ([~a, ~b, ~d, ~e, ~f, ~m, ~n], ~x) && (EqQ((~a) ^ 2 - (~b) ^ 2, 0) && (EqQ(~m + ~n, 0) && (GtQ(~m, 1 / 2) && IntegerQ(2 * ~m))))
    @apply_utils Antiderivative((~a + ~(b') * csc(~(e') + ~(f') * ~x)) ^ ~m * (~(d') * csc(~(e') + ~(f') * ~x)) ^ ~n, ~x) => (~b * ~d * cot(~e + ~f * ~x) * (~a + ~b * csc(~e + ~f * ~x)) ^ ~m * (~d * csc(~e + ~f * ~x)) ^ (~n - 1)) / (~a * ~f * (2 * ~m + 1)) + ((~d * (~m + 1)) / (~b * (2 * ~m + 1))) * Antiderivative((~a + ~b * csc(~e + ~f * ~x)) ^ (~m + 1) * (~d * csc(~e + ~f * ~x)) ^ (~n - 1), ~x) <-- FreeQ([~a, ~b, ~d, ~e, ~f, ~m, ~n], ~x) && (EqQ((~a) ^ 2 - (~b) ^ 2, 0) && (EqQ(~m + ~n, 0) && (LtQ(~m, -1 / 2) && IntegerQ(2 * ~m))))
    @apply_utils Antiderivative((~a + ~(b') * csc(~(e') + ~(f') * ~x)) ^ ~m * (~(d') * csc(~(e') + ~(f') * ~x)) ^ ~n, ~x) => (-(cot(~e + ~f * ~x)) * (~a + ~b * csc(~e + ~f * ~x)) ^ ~m * (~d * csc(~e + ~f * ~x)) ^ ~n) / (~f * (2 * ~m + 1)) + (~m / (~a * (2 * ~m + 1))) * Antiderivative((~a + ~b * csc(~e + ~f * ~x)) ^ (~m + 1) * (~d * csc(~e + ~f * ~x)) ^ ~n, ~x) <-- FreeQ([~a, ~b, ~d, ~e, ~f], ~x) && (EqQ((~a) ^ 2 - (~b) ^ 2, 0) && (EqQ(~m + ~n + 1, 0) && LtQ(~m, -1 / 2)))
    @apply_utils Antiderivative((~a + ~(b') * csc(~(e') + ~(f') * ~x)) ^ ~m * (~(d') * csc(~(e') + ~(f') * ~x)) ^ ~n, ~x) => (-(cot(~e + ~f * ~x)) * (~a + ~b * csc(~e + ~f * ~x)) ^ ~m * (~d * csc(~e + ~f * ~x)) ^ ~n) / (~f * (~m + 1)) + ((~a * ~m) / (~b * ~d * (~m + 1))) * Antiderivative((~a + ~b * csc(~e + ~f * ~x)) ^ ~m * (~d * csc(~e + ~f * ~x)) ^ (~n + 1), ~x) <-- FreeQ([~a, ~b, ~d, ~e, ~f, ~m, ~n], ~x) && (EqQ((~a) ^ 2 - (~b) ^ 2, 0) && (EqQ(~m + ~n + 1, 0) && Not(LtQ(~m, -1 / 2))))
    @apply_utils Antiderivative((~a + ~(b') * csc(~(e') + ~(f') * ~x)) ^ ~m * (~(d') * csc(~(e') + ~(f') * ~x)) ^ ~n, ~x) => ((~b) ^ 2 * cot(~e + ~f * ~x) * (~a + ~b * csc(~e + ~f * ~x)) ^ (~m - 2) * (~d * csc(~e + ~f * ~x)) ^ ~n) / (~f * ~n) - (~a / (~d * ~n)) * Antiderivative((~a + ~b * csc(~e + ~f * ~x)) ^ (~m - 2) * (~d * csc(~e + ~f * ~x)) ^ (~n + 1) * (~b * ((~m - 2 * ~n) - 2) - ~a * ((~m + 2 * ~n) - 1) * csc(~e + ~f * ~x)), ~x) <-- FreeQ([~a, ~b, ~d, ~e, ~f], ~x) && (EqQ((~a) ^ 2 - (~b) ^ 2, 0) && (GtQ(~m, 1) && ((LtQ(~n, -1) || EqQ(~m, 3 / 2) && EqQ(~n, -1 / 2)) && IntegerQ(2 * ~m))))
    @apply_utils Antiderivative((~a + ~(b') * csc(~(e') + ~(f') * ~x)) ^ ~m * (~(d') * csc(~(e') + ~(f') * ~x)) ^ ~n, ~x) => (-((~b) ^ 2) * cot(~e + ~f * ~x) * (~a + ~b * csc(~e + ~f * ~x)) ^ (~m - 2) * (~d * csc(~e + ~f * ~x)) ^ ~n) / (~f * ((~m + ~n) - 1)) + (~b / ((~m + ~n) - 1)) * Antiderivative((~a + ~b * csc(~e + ~f * ~x)) ^ (~m - 2) * (~d * csc(~e + ~f * ~x)) ^ ~n * (~b * ((~m + 2 * ~n) - 1) + ~a * ((3 * ~m + 2 * ~n) - 4) * csc(~e + ~f * ~x)), ~x) <-- FreeQ([~a, ~b, ~d, ~e, ~f, ~n], ~x) && (EqQ((~a) ^ 2 - (~b) ^ 2, 0) && (GtQ(~m, 1) && (NeQ((~m + ~n) - 1, 0) && IntegerQ(2 * ~m))))
    @apply_utils Antiderivative((~a + ~(b') * csc(~(e') + ~(f') * ~x)) ^ ~m * (~(d') * csc(~(e') + ~(f') * ~x)) ^ ~n, ~x) => (~b * ~d * cot(~e + ~f * ~x) * (~a + ~b * csc(~e + ~f * ~x)) ^ ~m * (~d * csc(~e + ~f * ~x)) ^ (~n - 1)) / (~a * ~f * (2 * ~m + 1)) - (~d / (~a * ~b * (2 * ~m + 1))) * Antiderivative((~a + ~b * csc(~e + ~f * ~x)) ^ (~m + 1) * (~d * csc(~e + ~f * ~x)) ^ (~n - 1) * (~a * (~n - 1) - ~b * (~m + ~n) * csc(~e + ~f * ~x)), ~x) <-- FreeQ([~a, ~b, ~d, ~e, ~f], ~x) && (EqQ((~a) ^ 2 - (~b) ^ 2, 0) && (LtQ(~m, -1) && (LtQ(1, ~n, 2) && (IntegersQ(2 * ~m, 2 * ~n) || IntegerQ(~m)))))
    @apply_utils Antiderivative((~a + ~(b') * csc(~(e') + ~(f') * ~x)) ^ ~m * (~(d') * csc(~(e') + ~(f') * ~x)) ^ ~n, ~x) => (-((~d) ^ 2) * cot(~e + ~f * ~x) * (~a + ~b * csc(~e + ~f * ~x)) ^ ~m * (~d * csc(~e + ~f * ~x)) ^ (~n - 2)) / (~f * (2 * ~m + 1)) + ((~d) ^ 2 / (~a * ~b * (2 * ~m + 1))) * Antiderivative((~a + ~b * csc(~e + ~f * ~x)) ^ (~m + 1) * (~d * csc(~e + ~f * ~x)) ^ (~n - 2) * (~b * (~n - 2) + ~a * ((~m - ~n) + 2) * csc(~e + ~f * ~x)), ~x) <-- FreeQ([~a, ~b, ~d, ~e, ~f], ~x) && (EqQ((~a) ^ 2 - (~b) ^ 2, 0) && (LtQ(~m, -1) && (GtQ(~n, 2) && (IntegersQ(2 * ~m, 2 * ~n) || IntegerQ(~m)))))
    @apply_utils Antiderivative((~a + ~(b') * csc(~(e') + ~(f') * ~x)) ^ ~m * (~(d') * csc(~(e') + ~(f') * ~x)) ^ ~n, ~x) => (-(cot(~e + ~f * ~x)) * (~a + ~b * csc(~e + ~f * ~x)) ^ ~m * (~d * csc(~e + ~f * ~x)) ^ ~n) / (~f * (2 * ~m + 1)) + (1 / ((~a) ^ 2 * (2 * ~m + 1))) * Antiderivative((~a + ~b * csc(~e + ~f * ~x)) ^ (~m + 1) * (~d * csc(~e + ~f * ~x)) ^ ~n * (~a * (2 * ~m + ~n + 1) - ~b * (~m + ~n + 1) * csc(~e + ~f * ~x)), ~x) <-- FreeQ([~a, ~b, ~d, ~e, ~f, ~n], ~x) && (EqQ((~a) ^ 2 - (~b) ^ 2, 0) && (LtQ(~m, -1) && (IntegersQ(2 * ~m, 2 * ~n) || IntegerQ(~m))))
    @apply_utils Antiderivative((~(d') * csc(~(e') + ~(f') * ~x)) ^ ~n / (~a + ~(b') * csc(~(e') + ~(f') * ~x)), ~x) => ((~d) ^ 2 * cot(~e + ~f * ~x) * (~d * csc(~e + ~f * ~x)) ^ (~n - 2)) / (~f * (~a + ~b * csc(~e + ~f * ~x))) - ((~d) ^ 2 / (~a * ~b)) * Antiderivative((~d * csc(~e + ~f * ~x)) ^ (~n - 2) * (~b * (~n - 2) - ~a * (~n - 1) * csc(~e + ~f * ~x)), ~x) <-- FreeQ([~a, ~b, ~d, ~e, ~f], ~x) && (EqQ((~a) ^ 2 - (~b) ^ 2, 0) && GtQ(~n, 1))
    @apply_utils Antiderivative((~(d') * csc(~(e') + ~(f') * ~x)) ^ ~n / (~a + ~(b') * csc(~(e') + ~(f') * ~x)), ~x) => (cot(~e + ~f * ~x) * (~d * csc(~e + ~f * ~x)) ^ ~n) / (~f * (~a + ~b * csc(~e + ~f * ~x))) - (1 / (~a) ^ 2) * Antiderivative((~d * csc(~e + ~f * ~x)) ^ ~n * (~a * (~n - 1) - ~b * ~n * csc(~e + ~f * ~x)), ~x) <-- FreeQ([~a, ~b, ~d, ~e, ~f], ~x) && (EqQ((~a) ^ 2 - (~b) ^ 2, 0) && LtQ(~n, 0))
    @apply_utils Antiderivative((~(d') * csc(~(e') + ~(f') * ~x)) ^ ~n / (~a + ~(b') * csc(~(e') + ~(f') * ~x)), ~x) => (-(~b) * ~d * cot(~e + ~f * ~x) * (~d * csc(~e + ~f * ~x)) ^ (~n - 1)) / (~a * ~f * (~a + ~b * csc(~e + ~f * ~x))) + ((~d * (~n - 1)) / (~a * ~b)) * Antiderivative((~d * csc(~e + ~f * ~x)) ^ (~n - 1) * (~a - ~b * csc(~e + ~f * ~x)), ~x) <-- FreeQ([~a, ~b, ~d, ~e, ~f, ~n], ~x) && EqQ((~a) ^ 2 - (~b) ^ 2, 0)
    @apply_utils Antiderivative((~(d') * csc(~(e') + ~(f') * ~x)) ^ (3 / 2) / sqrt(~a + ~(b') * csc(~(e') + ~(f') * ~x)), ~x) => (~d / ~b) * Antiderivative(sqrt(~a + ~b * csc(~e + ~f * ~x)) * sqrt(~d * csc(~e + ~f * ~x)), ~x) - ((~a * ~d) / ~b) * Antiderivative(sqrt(~d * csc(~e + ~f * ~x)) / sqrt(~a + ~b * csc(~e + ~f * ~x)), ~x) <-- FreeQ([~a, ~b, ~d, ~e, ~f], ~x) && EqQ((~a) ^ 2 - (~b) ^ 2, 0)
    @apply_utils Antiderivative((~(d') * csc(~(e') + ~(f') * ~x)) ^ ~n / sqrt(~a + ~(b') * csc(~(e') + ~(f') * ~x)), ~x) => (-2 * (~d) ^ 2 * cot(~e + ~f * ~x) * (~d * csc(~e + ~f * ~x)) ^ (~n - 2)) / (~f * (2 * ~n - 3) * sqrt(~a + ~b * csc(~e + ~f * ~x))) + ((~d) ^ 2 / (~b * (2 * ~n - 3))) * Antiderivative(((~d * csc(~e + ~f * ~x)) ^ (~n - 2) * (2 * ~b * (~n - 2) - ~a * csc(~e + ~f * ~x))) / sqrt(~a + ~b * csc(~e + ~f * ~x)), ~x) <-- FreeQ([~a, ~b, ~d, ~e, ~f], ~x) && (EqQ((~a) ^ 2 - (~b) ^ 2, 0) && (GtQ(~n, 2) && IntegerQ(2 * ~n)))
    @apply_utils Antiderivative((~(d') * csc(~(e') + ~(f') * ~x)) ^ ~n / sqrt(~a + ~(b') * csc(~(e') + ~(f') * ~x)), ~x) => (cot(~e + ~f * ~x) * (~d * csc(~e + ~f * ~x)) ^ ~n) / (~f * ~n * sqrt(~a + ~b * csc(~e + ~f * ~x))) + (1 / (2 * ~b * ~d * ~n)) * Antiderivative(((~d * csc(~e + ~f * ~x)) ^ (~n + 1) * (~a + ~b * (2 * ~n + 1) * csc(~e + ~f * ~x))) / sqrt(~a + ~b * csc(~e + ~f * ~x)), ~x) <-- FreeQ([~a, ~b, ~d, ~e, ~f], ~x) && (EqQ((~a) ^ 2 - (~b) ^ 2, 0) && (LtQ(~n, 0) && IntegerQ(2 * ~n)))
    @apply_utils Antiderivative((~a + ~(b') * csc(~(e') + ~(f') * ~x)) ^ ~m * (~(d') * csc(~(e') + ~(f') * ~x)) ^ ~n, ~x) => (-((~d) ^ 2) * cot(~e + ~f * ~x) * (~a + ~b * csc(~e + ~f * ~x)) ^ ~m * (~d * csc(~e + ~f * ~x)) ^ (~n - 2)) / (~f * ((~m + ~n) - 1)) + ((~d) ^ 2 / (~b * ((~m + ~n) - 1))) * Antiderivative((~a + ~b * csc(~e + ~f * ~x)) ^ ~m * (~d * csc(~e + ~f * ~x)) ^ (~n - 2) * (~b * (~n - 2) + ~a * ~m * csc(~e + ~f * ~x)), ~x) <-- FreeQ([~a, ~b, ~d, ~e, ~f, ~m], ~x) && (EqQ((~a) ^ 2 - (~b) ^ 2, 0) && (GtQ(~n, 2) && (NeQ((~m + ~n) - 1, 0) && IntegerQ(~n))))
    @apply_utils Antiderivative((~a + ~(b') * csc(~(e') + ~(f') * ~x)) ^ ~m * (~(d') * csc(~(e') + ~(f') * ~x)) ^ ~n, ~x) => ((-(((~a * ~d) / ~b) ^ ~n) * cot(~e + ~f * ~x)) / ((~a) ^ (~n - 2) * ~f * sqrt(~a + ~b * csc(~e + ~f * ~x)) * sqrt(~a - ~b * csc(~e + ~f * ~x)))) * Subst(Antiderivative(((~a - ~x) ^ (~n - 1) * (2 * ~a - ~x) ^ (~m - 1 / 2)) / sqrt(~x), ~x), ~x, ~a - ~b * csc(~e + ~f * ~x)) <-- FreeQ([~a, ~b, ~d, ~e, ~f, ~m, ~n], ~x) && (EqQ((~a) ^ 2 - (~b) ^ 2, 0) && (Not(IntegerQ(~m)) && (GtQ(~a, 0) && (Not(IntegerQ(~n)) && GtQ((~a * ~d) / ~b, 0)))))
    @apply_utils Antiderivative((~a + ~(b') * csc(~(e') + ~(f') * ~x)) ^ ~m * (~(d') * csc(~(e') + ~(f') * ~x)) ^ ~n, ~x) => ((-(((-(~a) * ~d) / ~b) ^ ~n) * cot(~e + ~f * ~x)) / ((~a) ^ (~n - 1) * ~f * sqrt(~a + ~b * csc(~e + ~f * ~x)) * sqrt(~a - ~b * csc(~e + ~f * ~x)))) * Subst(Antiderivative(((~x) ^ (~m - 1 / 2) * (~a - ~x) ^ (~n - 1)) / sqrt(2 * ~a - ~x), ~x), ~x, ~a + ~b * csc(~e + ~f * ~x)) <-- FreeQ([~a, ~b, ~d, ~e, ~f, ~m, ~n], ~x) && (EqQ((~a) ^ 2 - (~b) ^ 2, 0) && (Not(IntegerQ(~m)) && (GtQ(~a, 0) && (Not(IntegerQ(~n)) && LtQ((~a * ~d) / ~b, 0)))))
    @apply_utils Antiderivative((~a + ~(b') * csc(~(e') + ~(f') * ~x)) ^ ~m * (~(d') * csc(~(e') + ~(f') * ~x)) ^ ~(n'), ~x) => (((~a) ^ 2 * ~d * cot(~e + ~f * ~x)) / (~f * sqrt(~a + ~b * csc(~e + ~f * ~x)) * sqrt(~a - ~b * csc(~e + ~f * ~x)))) * Subst(Antiderivative(((~d * ~x) ^ (~n - 1) * (~a + ~b * ~x) ^ (~m - 1 / 2)) / sqrt(~a - ~b * ~x), ~x), ~x, csc(~e + ~f * ~x)) <-- FreeQ([~a, ~b, ~d, ~e, ~f, ~m, ~n], ~x) && (EqQ((~a) ^ 2 - (~b) ^ 2, 0) && (Not(IntegerQ(~m)) && GtQ(~a, 0)))
    @apply_utils Antiderivative((~a + ~(b') * csc(~(e') + ~(f') * ~x)) ^ ~m * (~(d') * csc(~(e') + ~(f') * ~x)) ^ ~(n'), ~x) => (((~a) ^ IntPart(~m) * (~a + ~b * csc(~e + ~f * ~x)) ^ FracPart(~m)) / (1 + (~b / ~a) * csc(~e + ~f * ~x)) ^ FracPart(~m)) * Antiderivative((1 + (~b / ~a) * csc(~e + ~f * ~x)) ^ ~m * (~d * csc(~e + ~f * ~x)) ^ ~n, ~x) <-- FreeQ([~a, ~b, ~d, ~e, ~f, ~m, ~n], ~x) && (EqQ((~a) ^ 2 - (~b) ^ 2, 0) && (Not(IntegerQ(~m)) && Not(GtQ(~a, 0))))
    @apply_utils Antiderivative(csc(~(e') + ~(f') * ~x) * sqrt(~a + ~(b') * csc(~(e') + ~(f') * ~x)), ~x) => (~a - ~b) * Antiderivative(csc(~e + ~f * ~x) / sqrt(~a + ~b * csc(~e + ~f * ~x)), ~x) + ~b * Antiderivative((csc(~e + ~f * ~x) * (1 + csc(~e + ~f * ~x))) / sqrt(~a + ~b * csc(~e + ~f * ~x)), ~x) <-- FreeQ([~a, ~b, ~e, ~f], ~x) && NeQ((~a) ^ 2 - (~b) ^ 2, 0)
    @apply_utils Antiderivative(csc(~(e') + ~(f') * ~x) * (~a + ~(b') * csc(~(e') + ~(f') * ~x)) ^ ~m, ~x) => (-(~b) * cot(~e + ~f * ~x) * (~a + ~b * csc(~e + ~f * ~x)) ^ (~m - 1)) / (~f * ~m) + (1 / ~m) * Antiderivative(csc(~e + ~f * ~x) * (~a + ~b * csc(~e + ~f * ~x)) ^ (~m - 2) * ((~b) ^ 2 * (~m - 1) + (~a) ^ 2 * ~m + ~a * ~b * (2 * ~m - 1) * csc(~e + ~f * ~x)), ~x) <-- FreeQ([~a, ~b, ~e, ~f], ~x) && (NeQ((~a) ^ 2 - (~b) ^ 2, 0) && (GtQ(~m, 1) && IntegerQ(2 * ~m)))
    #= Antiderivative(csc((~e')+(~f')*(~x))/((~a)+(~b')*csc((~e')+(~f')*(~x))),~x) :=  -2/f*Subst(Antiderivative(1/(a+b-(a-b)*x^2),x),x,cot(e+f*x)/(1+csc(e+f*x))) <--  FreeQ([a,b,e,f],x) && NeQ(a^2-b^2,0) =#
    @apply_utils Antiderivative(csc(~(e') + ~(f') * ~x) / (~a + ~(b') * csc(~(e') + ~(f') * ~x)), ~x) => (1 / ~b) * Antiderivative(1 / (1 + (~a / ~b) * sin(~e + ~f * ~x)), ~x) <-- FreeQ([~a, ~b, ~e, ~f], ~x) && NeQ((~a) ^ 2 - (~b) ^ 2, 0)
    @apply_utils Antiderivative(csc(~(e') + ~(f') * ~x) / sqrt(~a + ~(b') * csc(~(e') + ~(f') * ~x)), ~x) => ((-2 * Rt(~a + ~b, 2)) / (~b * ~f * cot(~e + ~f * ~x))) * sqrt((~b * (1 - csc(~e + ~f * ~x))) / (~a + ~b)) * sqrt((-(~b) * (1 + csc(~e + ~f * ~x))) / (~a - ~b)) * Elliptic.F(asin(sqrt(~a + ~b * csc(~e + ~f * ~x)) / Rt(~a + ~b, 2)), (~a + ~b) / (~a - ~b)) <-- FreeQ([~a, ~b, ~e, ~f], ~x) && NeQ((~a) ^ 2 - (~b) ^ 2, 0)
    @apply_utils Antiderivative(csc(~(e') + ~(f') * ~x) * (~a + ~(b') * csc(~(e') + ~(f') * ~x)) ^ ~m, ~x) => (-(~b) * cot(~e + ~f * ~x) * (~a + ~b * csc(~e + ~f * ~x)) ^ (~m + 1)) / (~f * (~m + 1) * ((~a) ^ 2 - (~b) ^ 2)) + (1 / ((~m + 1) * ((~a) ^ 2 - (~b) ^ 2))) * Antiderivative(csc(~e + ~f * ~x) * (~a + ~b * csc(~e + ~f * ~x)) ^ (~m + 1) * (~a * (~m + 1) - ~b * (~m + 2) * csc(~e + ~f * ~x)), ~x) <-- FreeQ([~a, ~b, ~e, ~f], ~x) && (NeQ((~a) ^ 2 - (~b) ^ 2, 0) && (LtQ(~m, -1) && IntegerQ(2 * ~m)))
    @apply_utils Antiderivative(csc(~(e') + ~(f') * ~x) * (~a + ~(b') * csc(~(e') + ~(f') * ~x)) ^ ~m, ~x) => (cot(~e + ~f * ~x) / (~f * sqrt(1 + csc(~e + ~f * ~x)) * sqrt(1 - csc(~e + ~f * ~x)))) * Subst(Antiderivative((~a + ~b * ~x) ^ ~m / (sqrt(1 + ~x) * sqrt(1 - ~x)), ~x), ~x, csc(~e + ~f * ~x)) <-- FreeQ([~a, ~b, ~e, ~f, ~m], ~x) && (NeQ((~a) ^ 2 - (~b) ^ 2, 0) && Not(IntegerQ(2 * ~m)))
    @apply_utils Antiderivative(csc(~(e') + ~(f') * ~x) ^ 2 * (~a + ~(b') * csc(~(e') + ~(f') * ~x)) ^ ~m, ~x) => (-(cot(~e + ~f * ~x)) * (~a + ~b * csc(~e + ~f * ~x)) ^ ~m) / (~f * (~m + 1)) + (~m / (~m + 1)) * Antiderivative(csc(~e + ~f * ~x) * (~a + ~b * csc(~e + ~f * ~x)) ^ (~m - 1) * (~b + ~a * csc(~e + ~f * ~x)), ~x) <-- FreeQ([~a, ~b, ~e, ~f], ~x) && (NeQ((~a) ^ 2 - (~b) ^ 2, 0) && GtQ(~m, 0))
    @apply_utils Antiderivative(csc(~(e') + ~(f') * ~x) ^ 2 * (~a + ~(b') * csc(~(e') + ~(f') * ~x)) ^ ~m, ~x) => (~a * cot(~e + ~f * ~x) * (~a + ~b * csc(~e + ~f * ~x)) ^ (~m + 1)) / (~f * (~m + 1) * ((~a) ^ 2 - (~b) ^ 2)) - (1 / ((~m + 1) * ((~a) ^ 2 - (~b) ^ 2))) * Antiderivative(csc(~e + ~f * ~x) * (~a + ~b * csc(~e + ~f * ~x)) ^ (~m + 1) * (~b * (~m + 1) - ~a * (~m + 2) * csc(~e + ~f * ~x)), ~x) <-- FreeQ([~a, ~b, ~e, ~f], ~x) && (NeQ((~a) ^ 2 - (~b) ^ 2, 0) && LtQ(~m, -1))
    @apply_utils Antiderivative(csc(~(e') + ~(f') * ~x) ^ 2 / sqrt(~a + ~(b') * csc(~(e') + ~(f') * ~x)), ~x) => -(Antiderivative(csc(~e + ~f * ~x) / sqrt(~a + ~b * csc(~e + ~f * ~x)), ~x)) + Antiderivative((csc(~e + ~f * ~x) * (1 + csc(~e + ~f * ~x))) / sqrt(~a + ~b * csc(~e + ~f * ~x)), ~x) <-- FreeQ([~a, ~b, ~e, ~f], ~x) && NeQ((~a) ^ 2 - (~b) ^ 2, 0)
    @apply_utils Antiderivative(csc(~(e') + ~(f') * ~x) ^ 2 * (~a + ~(b') * csc(~(e') + ~(f') * ~x)) ^ ~m, ~x) => (-(~a) / ~b) * Antiderivative(csc(~e + ~f * ~x) * (~a + ~b * csc(~e + ~f * ~x)) ^ ~m, ~x) + (1 / ~b) * Antiderivative(csc(~e + ~f * ~x) * (~a + ~b * csc(~e + ~f * ~x)) ^ (~m + 1), ~x) <-- FreeQ([~a, ~b, ~e, ~f, ~m], ~x) && NeQ((~a) ^ 2 - (~b) ^ 2, 0)
    @apply_utils Antiderivative(csc(~(e') + ~(f') * ~x) ^ 3 * (~a + ~(b') * csc(~(e') + ~(f') * ~x)) ^ ~m, ~x) => (-((~a) ^ 2) * cot(~e + ~f * ~x) * (~a + ~b * csc(~e + ~f * ~x)) ^ (~m + 1)) / (~b * ~f * (~m + 1) * ((~a) ^ 2 - (~b) ^ 2)) + (1 / (~b * (~m + 1) * ((~a) ^ 2 - (~b) ^ 2))) * Antiderivative(csc(~e + ~f * ~x) * (~a + ~b * csc(~e + ~f * ~x)) ^ (~m + 1) * Simp(~a * ~b * (~m + 1) - ((~a) ^ 2 + (~b) ^ 2 * (~m + 1)) * csc(~e + ~f * ~x), ~x), ~x) <-- FreeQ([~a, ~b, ~e, ~f], ~x) && (NeQ((~a) ^ 2 - (~b) ^ 2, 0) && LtQ(~m, -1))
    @apply_utils Antiderivative(csc(~(e') + ~(f') * ~x) ^ 3 * (~a + ~(b') * csc(~(e') + ~(f') * ~x)) ^ ~m, ~x) => (-(cot(~e + ~f * ~x)) * (~a + ~b * csc(~e + ~f * ~x)) ^ (~m + 1)) / (~b * ~f * (~m + 2)) + (1 / (~b * (~m + 2))) * Antiderivative(csc(~e + ~f * ~x) * (~a + ~b * csc(~e + ~f * ~x)) ^ ~m * (~b * (~m + 1) - ~a * csc(~e + ~f * ~x)), ~x) <-- FreeQ([~a, ~b, ~e, ~f, ~m], ~x) && (NeQ((~a) ^ 2 - (~b) ^ 2, 0) && Not(LtQ(~m, -1)))
    @apply_utils Antiderivative((~a + ~(b') * csc(~(e') + ~(f') * ~x)) ^ ~m * (~(d') * csc(~(e') + ~(f') * ~x)) ^ ~n, ~x) => ((~a) ^ 2 * cot(~e + ~f * ~x) * (~a + ~b * csc(~e + ~f * ~x)) ^ (~m - 2) * (~d * csc(~e + ~f * ~x)) ^ ~n) / (~f * ~n) - (1 / (~d * ~n)) * Antiderivative((~a + ~b * csc(~e + ~f * ~x)) ^ (~m - 3) * (~d * csc(~e + ~f * ~x)) ^ (~n + 1) * Simp(((~a) ^ 2 * ~b * ((~m - 2 * ~n) - 2) - ~a * (3 * (~b) ^ 2 * ~n + (~a) ^ 2 * (~n + 1)) * csc(~e + ~f * ~x)) - ~b * ((~b) ^ 2 * ~n + (~a) ^ 2 * ((~m + ~n) - 1)) * csc(~e + ~f * ~x) ^ 2, ~x), ~x) <-- FreeQ([~a, ~b, ~d, ~e, ~f], ~x) && (NeQ((~a) ^ 2 - (~b) ^ 2, 0) && (GtQ(~m, 2) && (IntegerQ(~m) && LtQ(~n, -1) || IntegersQ(~m + 1 / 2, 2 * ~n) && LeQ(~n, -1))))
    @apply_utils Antiderivative((~a + ~(b') * csc(~(e') + ~(f') * ~x)) ^ ~m * (~(d') * csc(~(e') + ~(f') * ~x)) ^ ~n, ~x) => (-((~b) ^ 2) * cot(~e + ~f * ~x) * (~a + ~b * csc(~e + ~f * ~x)) ^ (~m - 2) * (~d * csc(~e + ~f * ~x)) ^ ~n) / (~f * ((~m + ~n) - 1)) + (1 / (~d * ((~m + ~n) - 1))) * Antiderivative((~a + ~b * csc(~e + ~f * ~x)) ^ (~m - 3) * (~d * csc(~e + ~f * ~x)) ^ ~n * Simp((~a) ^ 3 * ~d * ((~m + ~n) - 1) + ~a * (~b) ^ 2 * ~d * ~n + ~b * ((~b) ^ 2 * ~d * ((~m + ~n) - 2) + 3 * (~a) ^ 2 * ~d * ((~m + ~n) - 1)) * csc(~e + ~f * ~x) + ~a * (~b) ^ 2 * ~d * ((3 * ~m + 2 * ~n) - 4) * csc(~e + ~f * ~x) ^ 2, ~x), ~x) <-- FreeQ([~a, ~b, ~d, ~e, ~f, ~n], ~x) && (NeQ((~a) ^ 2 - (~b) ^ 2, 0) && (GtQ(~m, 2) && ((IntegerQ(~m) || IntegersQ(2 * ~m, 2 * ~n)) && Not(IGtQ(~n, 2) && Not(IntegerQ(~m))))))
    @apply_utils Antiderivative((~a + ~(b') * csc(~(e') + ~(f') * ~x)) ^ ~m * (~(d') * csc(~(e') + ~(f') * ~x)) ^ ~n, ~x) => (-(~b) * ~d * cot(~e + ~f * ~x) * (~a + ~b * csc(~e + ~f * ~x)) ^ (~m + 1) * (~d * csc(~e + ~f * ~x)) ^ (~n - 1)) / (~f * (~m + 1) * ((~a) ^ 2 - (~b) ^ 2)) + (1 / ((~m + 1) * ((~a) ^ 2 - (~b) ^ 2))) * Antiderivative((~a + ~b * csc(~e + ~f * ~x)) ^ (~m + 1) * (~d * csc(~e + ~f * ~x)) ^ (~n - 1) * Simp((~b * ~d * (~n - 1) + ~a * ~d * (~m + 1) * csc(~e + ~f * ~x)) - ~b * ~d * (~m + ~n + 1) * csc(~e + ~f * ~x) ^ 2, ~x), ~x) <-- FreeQ([~a, ~b, ~d, ~e, ~f], ~x) && (NeQ((~a) ^ 2 - (~b) ^ 2, 0) && (LtQ(~m, -1) && (LtQ(0, ~n, 1) && IntegersQ(2 * ~m, 2 * ~n))))
    @apply_utils Antiderivative((~a + ~(b') * csc(~(e') + ~(f') * ~x)) ^ ~m * (~(d') * csc(~(e') + ~(f') * ~x)) ^ ~n, ~x) => (~a * (~d) ^ 2 * cot(~e + ~f * ~x) * (~a + ~b * csc(~e + ~f * ~x)) ^ (~m + 1) * (~d * csc(~e + ~f * ~x)) ^ (~n - 2)) / (~f * (~m + 1) * ((~a) ^ 2 - (~b) ^ 2)) - ((~d) ^ 2 / ((~m + 1) * ((~a) ^ 2 - (~b) ^ 2))) * Antiderivative((~a + ~b * csc(~e + ~f * ~x)) ^ (~m + 1) * (~d * csc(~e + ~f * ~x)) ^ (~n - 2) * ((~a * (~n - 2) + ~b * (~m + 1) * csc(~e + ~f * ~x)) - ~a * (~m + ~n) * csc(~e + ~f * ~x) ^ 2), ~x) <-- FreeQ([~a, ~b, ~d, ~e, ~f], ~x) && (NeQ((~a) ^ 2 - (~b) ^ 2, 0) && (LtQ(~m, -1) && (LtQ(1, ~n, 2) && IntegersQ(2 * ~m, 2 * ~n))))
    @apply_utils Antiderivative((~a + ~(b') * csc(~(e') + ~(f') * ~x)) ^ ~m * (~(d') * csc(~(e') + ~(f') * ~x)) ^ ~n, ~x) => (-((~a) ^ 2) * (~d) ^ 3 * cot(~e + ~f * ~x) * (~a + ~b * csc(~e + ~f * ~x)) ^ (~m + 1) * (~d * csc(~e + ~f * ~x)) ^ (~n - 3)) / (~b * ~f * (~m + 1) * ((~a) ^ 2 - (~b) ^ 2)) + ((~d) ^ 3 / (~b * (~m + 1) * ((~a) ^ 2 - (~b) ^ 2))) * Antiderivative((~a + ~b * csc(~e + ~f * ~x)) ^ (~m + 1) * (~d * csc(~e + ~f * ~x)) ^ (~n - 3) * Simp(((~a) ^ 2 * (~n - 3) + ~a * ~b * (~m + 1) * csc(~e + ~f * ~x)) - ((~a) ^ 2 * (~n - 2) + (~b) ^ 2 * (~m + 1)) * csc(~e + ~f * ~x) ^ 2, ~x), ~x) <-- FreeQ([~a, ~b, ~d, ~e, ~f], ~x) && (NeQ((~a) ^ 2 - (~b) ^ 2, 0) && (LtQ(~m, -1) && (IGtQ(~n, 3) || IntegersQ(~n + 1 / 2, 2 * ~m) && GtQ(~n, 2))))
    @apply_utils Antiderivative((~a + ~(b') * csc(~(e') + ~(f') * ~x)) ^ ~m * (~(d') * csc(~(e') + ~(f') * ~x)) ^ ~n, ~x) => (cot(~e + ~f * ~x) * (~a + ~b * csc(~e + ~f * ~x)) ^ (~m + 1) * (~d * csc(~e + ~f * ~x)) ^ ~n) / (~a * ~f * ~n) - (1 / (~a * ~d * ~n)) * Antiderivative((~a + ~b * csc(~e + ~f * ~x)) ^ ~m * (~d * csc(~e + ~f * ~x)) ^ (~n + 1) * Simp((~b * (~m + ~n + 1) - ~a * (~n + 1) * csc(~e + ~f * ~x)) - ~b * (~m + ~n + 2) * csc(~e + ~f * ~x) ^ 2, ~x), ~x) <-- FreeQ([~a, ~b, ~d, ~e, ~f], ~x) && (NeQ((~a) ^ 2 - (~b) ^ 2, 0) && (ILtQ(~m + 1 / 2, 0) && ILtQ(~n, 0)))
    @apply_utils Antiderivative((~a + ~(b') * csc(~(e') + ~(f') * ~x)) ^ ~m * (~(d') * csc(~(e') + ~(f') * ~x)) ^ ~n, ~x) => ((~b) ^ 2 * cot(~e + ~f * ~x) * (~a + ~b * csc(~e + ~f * ~x)) ^ (~m + 1) * (~d * csc(~e + ~f * ~x)) ^ ~n) / (~a * ~f * (~m + 1) * ((~a) ^ 2 - (~b) ^ 2)) + (1 / (~a * (~m + 1) * ((~a) ^ 2 - (~b) ^ 2))) * Antiderivative((~a + ~b * csc(~e + ~f * ~x)) ^ (~m + 1) * (~d * csc(~e + ~f * ~x)) ^ ~n * ((((~a) ^ 2 * (~m + 1) - (~b) ^ 2 * (~m + ~n + 1)) - ~a * ~b * (~m + 1) * csc(~e + ~f * ~x)) + (~b) ^ 2 * (~m + ~n + 2) * csc(~e + ~f * ~x) ^ 2), ~x) <-- FreeQ([~a, ~b, ~d, ~e, ~f, ~n], ~x) && (NeQ((~a) ^ 2 - (~b) ^ 2, 0) && (LtQ(~m, -1) && IntegersQ(2 * ~m, 2 * ~n)))
    @apply_utils Antiderivative(sqrt(~(d') * csc(~(e') + ~(f') * ~x)) / (~a + ~(b') * csc(~(e') + ~(f') * ~x)), ~x) => ((sqrt(~d * sin(~e + ~f * ~x)) * sqrt(~d * csc(~e + ~f * ~x))) / ~d) * Antiderivative(sqrt(~d * sin(~e + ~f * ~x)) / (~b + ~a * sin(~e + ~f * ~x)), ~x) <-- FreeQ([~a, ~b, ~d, ~e, ~f], ~x) && NeQ((~a) ^ 2 - (~b) ^ 2, 0)
    @apply_utils Antiderivative((~(d') * csc(~(e') + ~(f') * ~x)) ^ (3 / 2) / (~a + ~(b') * csc(~(e') + ~(f') * ~x)), ~x) => ~d * sqrt(~d * sin(~e + ~f * ~x)) * sqrt(~d * csc(~e + ~f * ~x)) * Antiderivative(1 / (sqrt(~d * sin(~e + ~f * ~x)) * (~b + ~a * sin(~e + ~f * ~x))), ~x) <-- FreeQ([~a, ~b, ~d, ~e, ~f], ~x) && NeQ((~a) ^ 2 - (~b) ^ 2, 0)
    @apply_utils Antiderivative((~(d') * csc(~(e') + ~(f') * ~x)) ^ (5 / 2) / (~a + ~(b') * csc(~(e') + ~(f') * ~x)), ~x) => (~d / ~b) * Antiderivative((~d * csc(~e + ~f * ~x)) ^ (3 / 2), ~x) - ((~a * ~d) / ~b) * Antiderivative((~d * csc(~e + ~f * ~x)) ^ (3 / 2) / (~a + ~b * csc(~e + ~f * ~x)), ~x) <-- FreeQ([~a, ~b, ~d, ~e, ~f], ~x) && NeQ((~a) ^ 2 - (~b) ^ 2, 0)
    @apply_utils Antiderivative((~(d') * csc(~(e') + ~(f') * ~x)) ^ ~n / (~a + ~(b') * csc(~(e') + ~(f') * ~x)), ~x) => (-((~d) ^ 3) * cot(~e + ~f * ~x) * (~d * csc(~e + ~f * ~x)) ^ (~n - 3)) / (~b * ~f * (~n - 2)) + ((~d) ^ 3 / (~b * (~n - 2))) * Antiderivative(((~d * csc(~e + ~f * ~x)) ^ (~n - 3) * Simp((~a * (~n - 3) + ~b * (~n - 3) * csc(~e + ~f * ~x)) - ~a * (~n - 2) * csc(~e + ~f * ~x) ^ 2, ~x)) / (~a + ~b * csc(~e + ~f * ~x)), ~x) <-- FreeQ([~a, ~b, ~d, ~e, ~f], ~x) && (NeQ((~a) ^ 2 - (~b) ^ 2, 0) && GtQ(~n, 3))
    @apply_utils Antiderivative(1 / (sqrt(~(d') * csc(~(e') + ~(f') * ~x)) * (~a + ~(b') * csc(~(e') + ~(f') * ~x))), ~x) => ((~b) ^ 2 / ((~a) ^ 2 * (~d) ^ 2)) * Antiderivative((~d * csc(~e + ~f * ~x)) ^ (3 / 2) / (~a + ~b * csc(~e + ~f * ~x)), ~x) + (1 / (~a) ^ 2) * Antiderivative((~a - ~b * csc(~e + ~f * ~x)) / sqrt(~d * csc(~e + ~f * ~x)), ~x) <-- FreeQ([~a, ~b, ~d, ~e, ~f], ~x) && NeQ((~a) ^ 2 - (~b) ^ 2, 0)
    @apply_utils Antiderivative((~(d') * csc(~(e') + ~(f') * ~x)) ^ ~n / (~a + ~(b') * csc(~(e') + ~(f') * ~x)), ~x) => (cot(~e + ~f * ~x) * (~d * csc(~e + ~f * ~x)) ^ ~n) / (~a * ~f * ~n) - (1 / (~a * ~d * ~n)) * Antiderivative(((~d * csc(~e + ~f * ~x)) ^ (~n + 1) / (~a + ~b * csc(~e + ~f * ~x))) * Simp((~b * ~n - ~a * (~n + 1) * csc(~e + ~f * ~x)) - ~b * (~n + 1) * csc(~e + ~f * ~x) ^ 2, ~x), ~x) <-- FreeQ([~a, ~b, ~d, ~e, ~f], ~x) && (NeQ((~a) ^ 2 - (~b) ^ 2, 0) && (LeQ(~n, -1) && IntegerQ(2 * ~n)))
    @apply_utils Antiderivative(sqrt(~a + ~(b') * csc(~(e') + ~(f') * ~x)) * sqrt(~(d') * csc(~(e') + ~(f') * ~x)), ~x) => ~a * Antiderivative(sqrt(~d * csc(~e + ~f * ~x)) / sqrt(~a + ~b * csc(~e + ~f * ~x)), ~x) + (~b / ~d) * Antiderivative((~d * csc(~e + ~f * ~x)) ^ (3 / 2) / sqrt(~a + ~b * csc(~e + ~f * ~x)), ~x) <-- FreeQ([~a, ~b, ~d, ~e, ~f], ~x) && NeQ((~a) ^ 2 - (~b) ^ 2, 0)
    @apply_utils Antiderivative(sqrt(~a + ~(b') * csc(~(e') + ~(f') * ~x)) * (~(d') * csc(~(e') + ~(f') * ~x)) ^ ~n, ~x) => (-2 * ~d * cos(~e + ~f * ~x) * sqrt(~a + ~b * csc(~e + ~f * ~x)) * (~d * csc(~e + ~f * ~x)) ^ (~n - 1)) / (~f * (2 * ~n - 1)) + ((~d) ^ 2 / (2 * ~n - 1)) * Antiderivative(((~d * csc(~e + ~f * ~x)) ^ (~n - 2) * Simp(2 * ~a * (~n - 2) + ~b * (2 * ~n - 3) * csc(~e + ~f * ~x) + ~a * csc(~e + ~f * ~x) ^ 2, ~x)) / sqrt(~a + ~b * csc(~e + ~f * ~x)), ~x) <-- FreeQ([~a, ~b, ~d, ~e, ~f], ~x) && (NeQ((~a) ^ 2 - (~b) ^ 2, 0) && (GtQ(~n, 1) && IntegerQ(2 * ~n)))
    @apply_utils Antiderivative(sqrt(~a + ~(b') * csc(~(e') + ~(f') * ~x)) / sqrt(~(d') * csc(~(e') + ~(f') * ~x)), ~x) => (sqrt(~a + ~b * csc(~e + ~f * ~x)) / (sqrt(~d * csc(~e + ~f * ~x)) * sqrt(~b + ~a * sin(~e + ~f * ~x)))) * Antiderivative(sqrt(~b + ~a * sin(~e + ~f * ~x)), ~x) <-- FreeQ([~a, ~b, ~d, ~e, ~f], ~x) && NeQ((~a) ^ 2 - (~b) ^ 2, 0)
    @apply_utils Antiderivative(sqrt(~a + ~(b') * csc(~(e') + ~(f') * ~x)) * (~(d') * csc(~(e') + ~(f') * ~x)) ^ ~n, ~x) => (cot(~e + ~f * ~x) * sqrt(~a + ~b * csc(~e + ~f * ~x)) * (~d * csc(~e + ~f * ~x)) ^ ~n) / (~f * ~n) - (1 / (2 * ~d * ~n)) * Antiderivative(((~d * csc(~e + ~f * ~x)) ^ (~n + 1) * Simp((~b - 2 * ~a * (~n + 1) * csc(~e + ~f * ~x)) - ~b * (2 * ~n + 3) * csc(~e + ~f * ~x) ^ 2, ~x)) / sqrt(~a + ~b * csc(~e + ~f * ~x)), ~x) <-- FreeQ([~a, ~b, ~d, ~e, ~f], ~x) && (NeQ((~a) ^ 2 - (~b) ^ 2, 0) && (LeQ(~n, -1) && IntegerQ(2 * ~n)))
    @apply_utils Antiderivative(sqrt(~(d') * csc(~(e') + ~(f') * ~x)) / sqrt(~a + ~(b') * csc(~(e') + ~(f') * ~x)), ~x) => ((sqrt(~d * csc(~e + ~f * ~x)) * sqrt(~b + ~a * sin(~e + ~f * ~x))) / sqrt(~a + ~b * csc(~e + ~f * ~x))) * Antiderivative(1 / sqrt(~b + ~a * sin(~e + ~f * ~x)), ~x) <-- FreeQ([~a, ~b, ~d, ~e, ~f], ~x) && NeQ((~a) ^ 2 - (~b) ^ 2, 0)
    @apply_utils Antiderivative((~(d') * csc(~(e') + ~(f') * ~x)) ^ (3 / 2) / sqrt(~a + ~(b') * csc(~(e') + ~(f') * ~x)), ~x) => ((~d * sqrt(~d * csc(~e + ~f * ~x)) * sqrt(~b + ~a * sin(~e + ~f * ~x))) / sqrt(~a + ~b * csc(~e + ~f * ~x))) * Antiderivative(1 / (sin(~e + ~f * ~x) * sqrt(~b + ~a * sin(~e + ~f * ~x))), ~x) <-- FreeQ([~a, ~b, ~d, ~e, ~f], ~x) && NeQ((~a) ^ 2 - (~b) ^ 2, 0)
    @apply_utils Antiderivative((~(d') * csc(~(e') + ~(f') * ~x)) ^ ~n / sqrt(~a + ~(b') * csc(~(e') + ~(f') * ~x)), ~x) => (-2 * (~d) ^ 2 * cos(~e + ~f * ~x) * (~d * csc(~e + ~f * ~x)) ^ (~n - 2) * sqrt(~a + ~b * csc(~e + ~f * ~x))) / (~b * ~f * (2 * ~n - 3)) + ((~d) ^ 3 / (~b * (2 * ~n - 3))) * Antiderivative(((~d * csc(~e + ~f * ~x)) ^ (~n - 3) / sqrt(~a + ~b * csc(~e + ~f * ~x))) * Simp((2 * ~a * (~n - 3) + ~b * (2 * ~n - 5) * csc(~e + ~f * ~x)) - 2 * ~a * (~n - 2) * csc(~e + ~f * ~x) ^ 2, ~x), ~x) <-- FreeQ([~a, ~b, ~d, ~e, ~f], ~x) && (NeQ((~a) ^ 2 - (~b) ^ 2, 0) && (GtQ(~n, 2) && IntegerQ(2 * ~n)))
    @apply_utils Antiderivative(1 / (csc(~(e') + ~(f') * ~x) * sqrt(~a + ~(b') * csc(~(e') + ~(f') * ~x))), ~x) => (-(cos(~e + ~f * ~x)) * sqrt(~a + ~b * csc(~e + ~f * ~x))) / (~a * ~f) - (~b / (2 * ~a)) * Antiderivative((1 + csc(~e + ~f * ~x) ^ 2) / sqrt(~a + ~b * csc(~e + ~f * ~x)), ~x) <-- FreeQ([~a, ~b, ~e, ~f], ~x) && NeQ((~a) ^ 2 - (~b) ^ 2, 0)
    @apply_utils Antiderivative(1 / (sqrt(~a + ~(b') * csc(~(e') + ~(f') * ~x)) * sqrt(~(d') * csc(~(e') + ~(f') * ~x))), ~x) => (1 / ~a) * Antiderivative(sqrt(~a + ~b * csc(~e + ~f * ~x)) / sqrt(~d * csc(~e + ~f * ~x)), ~x) - (~b / (~a * ~d)) * Antiderivative(sqrt(~d * csc(~e + ~f * ~x)) / sqrt(~a + ~b * csc(~e + ~f * ~x)), ~x) <-- FreeQ([~a, ~b, ~d, ~e, ~f], ~x) && NeQ((~a) ^ 2 - (~b) ^ 2, 0)
    @apply_utils Antiderivative((~(d') * csc(~(e') + ~(f') * ~x)) ^ ~n / sqrt(~a + ~(b') * csc(~(e') + ~(f') * ~x)), ~x) => (cos(~e + ~f * ~x) * (~d * csc(~e + ~f * ~x)) ^ (~n + 1) * sqrt(~a + ~b * csc(~e + ~f * ~x))) / (~a * ~d * ~f * ~n) + (1 / (2 * ~a * ~d * ~n)) * Antiderivative(((~d * csc(~e + ~f * ~x)) ^ (~n + 1) / sqrt(~a + ~b * csc(~e + ~f * ~x))) * Simp(-(~b) * (2 * ~n + 1) + 2 * ~a * (~n + 1) * csc(~e + ~f * ~x) + ~b * (2 * ~n + 3) * csc(~e + ~f * ~x) ^ 2, ~x), ~x) <-- FreeQ([~a, ~b, ~d, ~e, ~f], ~x) && (NeQ((~a) ^ 2 - (~b) ^ 2, 0) && (LtQ(~n, -1) && IntegerQ(2 * ~n)))
    @apply_utils Antiderivative((~a + ~(b') * csc(~(e') + ~(f') * ~x)) ^ (3 / 2) * (~(d') * csc(~(e') + ~(f') * ~x)) ^ ~n, ~x) => (~a * cot(~e + ~f * ~x) * sqrt(~a + ~b * csc(~e + ~f * ~x)) * (~d * csc(~e + ~f * ~x)) ^ ~n) / (~f * ~n) + (1 / (2 * ~d * ~n)) * Antiderivative(((~d * csc(~e + ~f * ~x)) ^ (~n + 1) / sqrt(~a + ~b * csc(~e + ~f * ~x))) * Simp(~a * ~b * (2 * ~n - 1) + 2 * ((~b) ^ 2 * ~n + (~a) ^ 2 * (~n + 1)) * csc(~e + ~f * ~x) + ~a * ~b * (2 * ~n + 3) * csc(~e + ~f * ~x) ^ 2, ~x), ~x) <-- FreeQ([~a, ~b, ~d, ~e, ~f], ~x) && (NeQ((~a) ^ 2 - (~b) ^ 2, 0) && (LeQ(~n, -1) && IntegersQ(2 * ~n)))
    @apply_utils Antiderivative((~a + ~(b') * csc(~(e') + ~(f') * ~x)) ^ ~m * (~(d') * csc(~(e') + ~(f') * ~x)) ^ ~n, ~x) => (-((~d) ^ 3) * cot(~e + ~f * ~x) * (~a + ~b * csc(~e + ~f * ~x)) ^ (~m + 1) * (~d * csc(~e + ~f * ~x)) ^ (~n - 3)) / (~b * ~f * ((~m + ~n) - 1)) + ((~d) ^ 3 / (~b * ((~m + ~n) - 1))) * Antiderivative((~a + ~b * csc(~e + ~f * ~x)) ^ ~m * (~d * csc(~e + ~f * ~x)) ^ (~n - 3) * Simp((~a * (~n - 3) + ~b * ((~m + ~n) - 2) * csc(~e + ~f * ~x)) - ~a * (~n - 2) * csc(~e + ~f * ~x) ^ 2, ~x), ~x) <-- FreeQ([~a, ~b, ~d, ~e, ~f, ~m], ~x) && (NeQ((~a) ^ 2 - (~b) ^ 2, 0) && (GtQ(~n, 3) && ((IntegerQ(~n) || IntegersQ(2 * ~m, 2 * ~n)) && Not(IGtQ(~m, 2)))))
    @apply_utils Antiderivative((~a + ~(b') * csc(~(e') + ~(f') * ~x)) ^ ~m * (~(d') * csc(~(e') + ~(f') * ~x)) ^ ~n, ~x) => (-(~b) * ~d * cot(~e + ~f * ~x) * (~a + ~b * csc(~e + ~f * ~x)) ^ (~m - 1) * (~d * csc(~e + ~f * ~x)) ^ (~n - 1)) / (~f * ((~m + ~n) - 1)) + (~d / ((~m + ~n) - 1)) * Antiderivative((~a + ~b * csc(~e + ~f * ~x)) ^ (~m - 2) * (~d * csc(~e + ~f * ~x)) ^ (~n - 1) * Simp(~a * ~b * (~n - 1) + ((~b) ^ 2 * ((~m + ~n) - 2) + (~a) ^ 2 * ((~m + ~n) - 1)) * csc(~e + ~f * ~x) + ~a * ~b * ((2 * ~m + ~n) - 2) * csc(~e + ~f * ~x) ^ 2, ~x), ~x) <-- FreeQ([~a, ~b, ~d, ~e, ~f], ~x) && (NeQ((~a) ^ 2 - (~b) ^ 2, 0) && (LtQ(0, ~m, 2) && (LtQ(0, ~n, 3) && (NeQ((~m + ~n) - 1, 0) && (IntegerQ(~m) || IntegersQ(2 * ~m, 2 * ~n))))))
    @apply_utils Antiderivative((~a + ~(b') * csc(~(e') + ~(f') * ~x)) ^ ~m * (~(d') * csc(~(e') + ~(f') * ~x)) ^ ~n, ~x) => (-((~d) ^ 2) * cot(~e + ~f * ~x) * (~a + ~b * csc(~e + ~f * ~x)) ^ ~m * (~d * csc(~e + ~f * ~x)) ^ (~n - 2)) / (~f * ((~m + ~n) - 1)) + ((~d) ^ 2 / (~b * ((~m + ~n) - 1))) * Antiderivative((~a + ~b * csc(~e + ~f * ~x)) ^ (~m - 1) * (~d * csc(~e + ~f * ~x)) ^ (~n - 2) * Simp(~a * ~b * (~n - 2) + (~b) ^ 2 * ((~m + ~n) - 2) * csc(~e + ~f * ~x) + ~a * ~b * ~m * csc(~e + ~f * ~x) ^ 2, ~x), ~x) <-- FreeQ([~a, ~b, ~d, ~e, ~f], ~x) && (NeQ((~a) ^ 2 - (~b) ^ 2, 0) && (LtQ(-1, ~m, 2) && (LtQ(1, ~n, 3) && (NeQ((~m + ~n) - 1, 0) && (IntegerQ(~n) || IntegersQ(2 * ~m, 2 * ~n))))))
    @apply_utils Antiderivative((~a + ~(b') * csc(~(e') + ~(f') * ~x)) ^ (3 / 2) / sqrt(~(d') * csc(~(e') + ~(f') * ~x)), ~x) => ~a * Antiderivative(sqrt(~a + ~b * csc(~e + ~f * ~x)) / sqrt(~d * csc(~e + ~f * ~x)), ~x) + (~b / ~d) * Antiderivative(sqrt(~a + ~b * csc(~e + ~f * ~x)) * sqrt(~d * csc(~e + ~f * ~x)), ~x) <-- FreeQ([~a, ~b, ~d, ~e, ~f], ~x) && NeQ((~a) ^ 2 - (~b) ^ 2, 0)
    @apply_utils Antiderivative((~(d') * csc(~(e') + ~(f') * ~x)) ^ ~(n') * (~a + ~(b') * csc(~(e') + ~(f') * ~x)) ^ ~(m'), ~x) => sin(~e + ~f * ~x) ^ ~n * (~d * csc(~e + ~f * ~x)) ^ ~n * Antiderivative((~b + ~a * sin(~e + ~f * ~x)) ^ ~m / sin(~e + ~f * ~x) ^ (~m + ~n), ~x) <-- FreeQ([~a, ~b, ~d, ~e, ~f, ~n], ~x) && (NeQ((~a) ^ 2 - (~b) ^ 2, 0) && IntegerQ(~m))
    @apply_utils Antiderivative((~a + ~(b') * csc(~(e') + ~(f') * ~x)) ^ ~(m') * (~(d') * csc(~(e') + ~(f') * ~x)) ^ ~(n'), ~x) => Unintegrable((~a + ~b * csc(~e + ~f * ~x)) ^ ~m * (~d * csc(~e + ~f * ~x)) ^ ~n, ~x) <-- FreeQ([~a, ~b, ~d, ~e, ~f, ~m, ~n], ~x)
    @apply_utils Antiderivative((~(d') * cos(~(e') + ~(f') * ~x)) ^ ~m * (~(a') + ~(b') * sec(~(e') + ~(f') * ~x)) ^ ~p, ~x) => (~d * cos(~e + ~f * ~x)) ^ FracPart(~m) * (sec(~e + ~f * ~x) / ~d) ^ FracPart(~m) * Antiderivative((sec(~e + ~f * ~x) / ~d) ^ -(~m) * (~a + ~b * sec(~e + ~f * ~x)) ^ ~p, ~x) <-- FreeQ([~a, ~b, ~d, ~e, ~f, ~m, ~p], ~x) && (Not(IntegerQ(~m)) && Not(IntegerQ(~p)))
end

max_stars_repo_path: src/rules/4 Trig functions/4.5 Secant/4.5.1.2 (d sec)^n (a+b sec)^m.jl


text:
# Generic Cholesky decomposition for fixed-size matrices, mostly unrolled

# Currently all sanity checks are disabled!
@generated function Base.chol(A::StaticMatrix)
    if size(A) === (1, 1)
        return :(_chol1(A))
    elseif size(A) === (2, 2)
        #ishermitian(A) || Base.LinAlg.non_hermitian_error("chol")
        return :(_chol2(A))
    elseif size(A) === (3, 3)
        #ishermitian(A) || Base.LinAlg.non_hermitian_error("chol")
        return :(_chol3(A))
    else
        return :(chol(Array(A)))
    end
end

@generated function _chol1(A::StaticMatrix)
    @assert size(A) == (1,1)
    T = promote_type(typeof(sqrt(one(eltype(A)))), Float32)
    newtype = similar_type(A,T)

    quote
        $(Expr(:meta, :inline))
        ($newtype)((sqrt(A[1]), ))
    end
end

@generated function _chol2(A::StaticMatrix)
    @assert size(A) == (2,2)
    T = promote_type(typeof(sqrt(one(eltype(A)))), Float32)
    newtype = similar_type(A,T)

    quote
        $(Expr(:meta, :inline))
        @inbounds a = sqrt(A[1])
        @inbounds b = A[3] / a
        @inbounds c = sqrt(A[4] - b'*b)
        ($newtype)((a, $(zero(T)), b, c))
    end
end

@generated function _chol3(A::StaticMatrix)
    @assert size(A) == (3,3)
    T = promote_type(typeof(sqrt(one(eltype(A)))), Float32)
    newtype = similar_type(A,T)

    quote
        $(Expr(:meta, :inline))
        @inbounds a11 = sqrt(A[1])
        @inbounds a12 = A[4] / a11
        @inbounds a22 = sqrt(A[5] - a12'*a12)
        @inbounds a13 = A[7] / a11
        @inbounds a23 = (A[8] - a12'*a13) / a22
        @inbounds a33 = sqrt(A[9] - a13'*a13 - a23'*a23)
        ($newtype)((a11, $(zero(T)), $(zero(T)), a12, a22, $(zero(T)), a13, a23, a33))
    end
end


text:
using Test
using CompilerPluginTools

struct TestInterpreter <: JuliaLikeInterpreter
    native_interpreter::NativeInterpreter
end

function CompilerPluginTools.optimize(interp::TestInterpreter, ir::IRCode)
    @test true
    return ir
end

code_ircode(sin, (Float64, ); interp=NativeInterpreter())
code_ircode_by_signature(Tuple{typeof(sin), Float64}; interp=TestInterpreter(NativeInterpreter()))


text:
"""
The InputChannelState.jl module defines the InputChannelState type and methods

------------------------------------------------------------------------------
COPYRIGHT/LICENSE. This file is part of the XYZ package. It is subject to
the license terms in the LICENSE file found in the top-level directory of
this distribution. No part of the XYZ package, including this file, may be
copied, modified, propagated, or distributed except according to the terms
contained in the LICENSE file.
------------------------------------------------------------------------------
"""
# --- Exports

# ------ Types

export InputChannelState

# --- Type definitions

"""
    mutable struct InputChannelState

State of input channel.
"""
mutable struct InputChannelState
    #=
      Fields
      ------
      * `is_listening`: flag indicating whether the channel is currently
                        listening
    =#
    is_listening::Bool
end

"""
    InputChannelState()

Construct an InputChannelState instance initialized with default values.
"""
function InputChannelState()
    # Initialize state
    is_listening = false

    # Return new InputChannelState
    InputChannelState(is_listening)
end


text:
using OptimalSpacecraftTrajectories
using Test

@testset "OptimalSpacecraftTrajectories.jl" begin
    # Write your tests here.
end


text:
using CommonFactorModelStats
using Distributions

function issymmetric_approx(x::Matrix{Float64}, tol::Float64=sqrt(eps()))::Bool
    size(x, 1) != size(x, 2) && error("Input is not square: $(size(x))")
    for i = 1:size(x, 1)
        for j = 1:size(x, 2)
            abs(x[i, j] - x[j, i]) > tol && error("Symmetry test failed at index ($(i), $(j)): $(x[i,j] - x[j,i])")
        end
    end
    return true
end

function sim_mvnormal(numobs::Int, muvec::Vector{<:Number}, stdvec::Vector{<:Number}, rhomat::Matrix{<:Number})::Matrix{Float64}
    numobs < 1 && error("Invalid numobs: $(numobs)")
    !(length(muvec) == length(stdvec) == size(rhomat, 1) == size(rhomat, 2)) && error("Length mismatch: $(length(muvec)), $(length(stdvec)), $(size(rhomat, 1)), $(size(rhomat, 2))")
    any(diag(rhomat) .!= 1) && error("rhomat diagonal not equal to one: $(diag(rhomat))")
    any(abs.(rhomat) .> 1) && error("rhomat contains elements greater than one (in absolute value): $(rhomat)")
    !issymmetric_approx(rhomat) && error("rhomat is not symmetric: $(rhomat)")
    covmat = [ rhomat[i,j] * stdvec[i] * stdvec[j] for i = 1:size(rhomat, 1), j = 1:size(rhomat, 2) ]
    !issymmetric_approx(covmat) && error("Logic fail: $(covmat)")
    mvdist = MvNormal(Float64.(muvec), Matrix{Float64}(Symmetric(Float64.(covmat))))
    x = rand(mvdist, numobs)
    return x'
end
function sim_common_factors(numobs::Int, numfac::Int)::Matrix{Float64}
    muvec = randn(numfac)
    stdvec = 2*rand(numfac)
    stdvec[stdvec .< 0.5] = 0.5
    rhomat = 2*rand(numfac, numfac) - 1
    rhomat = Matrix{Float64}(Symmetric(rhomat))
    for i = 1:numfac
        for j = 1:numfac
            i == j ? (rhomat[i,j] = 1.0) : (rhomat[i,j] = 0.2*rhomat[i,j])
        end
    end
    facmat = sim_mvnormal(numobs, muvec, stdvec, rhomat)
    return facmat
end
sim_factor_loadings(numfac::Int, numvar::Int, muscalar::Number)::Matrix{Float64} = muscalar + randn(numfac, numvar)
function sim_common_factor_model(numobs::Int, numfac::Int, numvar::Int, loadmu::Number, errorstd::Number)
    errorstd <= 0.0 && error("Invalid errorstd: $(errorstd)")
    emat = errorstd * randn(numobs, numvar)
    facmat = sim_common_factors(numobs, numfac)
    loadmat = sim_factor_loadings(numfac, numvar, loadmu)
    x = facmat * loadmat + emat
    return (x, facmat, loadmat, emat)
end
function sim_obs_factor(facmat::Matrix{Float64}, mu1::Number, std1::Number)
    paramvec = randn(size(facmat, 2))
    facobsexact = facmat * paramvec
    facobs = mu1 + facobsexact + std1*randn(size(facobsexact, 1), 1)
    return (facobsexact, facobs)
end

function test_num_factor(numtest::Int, numobs::Int, numvar::Int, loadmu::Number, errorstd::Number)
    for t = 1:numtest
        numfac = rand(1:8)
        (x, f, l, e) = sim_common_factor_model(numobs, numfac, numvar, loadmu, errorstd)
        nf = CommonFactorModelStats.numfactor(x, covmatmethod=:auto)
        println("($(t)) True num fac = $(numfac). Estimates = $(CommonFactorModelStats.numfactor(nf)). Average estimate = $(CommonFactorModelStats.avgnumfactor(nf))")
    end
end

function test_obs_factor(numtest::Int, numobs::Int, numvar::Int, loadmu::Number, errorstd::Number,
                        obsbias::Number, obsstd::Float64, covmethod::Symbol=:eq4, alpha::Float64=0.05)
    for t = 1:numtest
        #numfac = rand(1:8)
        numfac = 1
        (x, f, l, e) = sim_common_factor_model(numobs, numfac, numvar, loadmu, errorstd)
        (facexact, facobs) = sim_obs_factor(f, obsbias, obsstd)
        oft = CommonFactorModelStats.testobsfactor(x, facobs, numfac, xcent=false, covmethod=covmethod, alpha=alpha)
        println("($(t)) num fac = $(numfac). aj = $(oft.aj[1]), mj = $(oft.mj[1]), mjpval = $(oft.mjpval[1]), r2 = $(oft.r2[1])")
        println("-------------------------------------------")
    end
end

function test_obs_factor_bai_ng(numtest::Int, numobs::Int, numvar::Int, covmethod::Symbol, alpha::Float64)
    ajmat = Array{Float64}(numtest, 7)
    mjmat = Array{Float64}(numtest, 7)
    mjpvalmat = Array{Float64}(numtest, 7)
    mjrejmat = Array{Float64}(numtest, 7)
    r2mat = Array{Float64}(numtest, 7)
    deltamat = [1.0 1.0 0.0 ; 1.0 0.0 0.0 ; 1.0 1.0 0.2 ; 1.0 0.0 0.2 ; 1.0 1.0 2.0 ; 1.0 0.0 2.0 ; 0.0 0.0 1.0]
    for m = 1:numtest
        mod(m, 50) == 0 && println("Up to $(m)")
        f = randn(numobs, 2)
        l = randn(2, numvar)
        resid = randn(numobs, numvar)
        x = f*l + resid
        x = std_x_mat(x)
        for d = 1:7
            gtemp = f*deltamat[d, 1:2]
            g = gtemp + deltamat[d, 3] * randn(length(gtemp))
            g = reshape(g, length(g), 1)
            tof = CommonFactorModelStats.testobsfactor(x, g, 2, covmethod=covmethod, alpha=0.05)
            ajmat[m, d] = tof.aj[1]
            mjmat[m, d] = tof.mj[1]
            mjpvalmat[m, d] = tof.mjpval[1]
            tof.mjpval[1] < 0.05 ? (mjrejmat[m, d] = 1.0) : (mjrejmat[m, d] = 0.0)
            r2mat[m, d] = tof.r2[1]
        end
    end
    println("Test result with numtest=$(numtest), numobs=$(numobs), and numvar=$(numvar)")
    println("Avg aj = $(mean(ajmat, 1))")
    println("Avg mj rej = $(mean(mjrejmat, 1))")
    println("Avg r2 = $(mean(r2mat, 1))")
    println("----------------------------")
    nothing
end
std_x_vec(x::Vector{Float64})::Vector{Float64} = (1 / std(x)) * (x - mean(x))
std_x_mat(x::Matrix{Float64})::Matrix{Float64} = hcat([ std_x_vec(x[:, k]) for k = 1:size(x, 2) ]...)

# numobs = 200
# numfac = 3
# numvar = 100
# loadmu = 0
# errorstd = 2
# (x, f, l, e) = sim_common_factor_model(numobs, numfac, numvar, loadmu, errorstd)

# numtest = 10;
# numobs = 100;
# numvar = 200;
# loadmu = 0;
# errorstd = 2;
# test_num_factor(numtest, numobs, numvar, loadmu, errorstd)

# numtest = 4;
# numobs = 1000;
# numvar = 1000;
# loadmu = 0;
# errorstd = 1.0;
# obsbias = 0.0;
# obsstd = 0.05;
# #obsstd = 0.0;
# covmethod = :eq4;
# alpha = 0.05;
# test_obs_factor(numtest, numobs, numvar, loadmu, errorstd, obsbias, obsstd, covmethod, alpha)
#blah

numtest = 1000;
numobs = 50;
numvar = 50;
covmethod = :eq6;
alpha = 0.05;
test_obs_factor_bai_ng(numtest, numobs, numvar, covmethod, alpha);


text:
using NCTiles,NCDatasets,NetCDF,Dates,Printf

examplesdir = joinpath("data","ex3")
indir = joinpath(examplesdir,"data","cs510","diags_interp")
availdiagsfname = joinpath(examplesdir,"data","available_diagnostics.log")
savedir = joinpath(examplesdir,"data","cs510","interp_nctiles")

if ~ispath(savedir); mkpath(savedir); end
README = readlines(joinpath(examplesdir,"README"))

exdir = "../../../run/run_cs510/"
fnameprefix = "darwin_v0.2_cs510"
groups = ["Nutrients","Bulk_Ecosystem_Characteristcs","Phytoplankton_Functional_Types","Ocean_Color"]

rename = Dict(["TRAC05" => "PO4",
"TRAC06" => "SiO2",
"TRAC07" => "FeT",
"TRAC19" => "O2"])

unitsrename = Dict(["mmol C/" => "mmol N/m^3",
                    "mmol O/" => "mmol O/m^3",
                    "mmol P/" => "mmol P/m^3",
                    "mmol Si" => "mmol Si/m^3",
                    "mmol Fe" => "mmol Fe/m^3"])

# Hard coding dims for now
lon=-179.75:0.5:179.75; lat=-89.75:0.5:89.75;

timeinterval = 3
tstart = 732; tend = 8766;
#tstart = 6; tend = 6;
timesteps = (tstart - timeinterval/2):timeinterval:(tend - timeinterval/2)
nsteps = length(timesteps)
timeinfname = lpad.(string.(Integer.(collect((timesteps.+timeinterval/2).*24))),10,'0')
timeunits = "days since 1992-1-1 0:0:0"
timestart = DateTime(1992,01,01)
dep = -1 .* collect([-5 -15 -25 -35 -45 -55 -65 -75.0049972534180 -85.0250015258789 -95.0950012207031 -105.309997558594 -115.870002746582 -127.150001525879 -139.740005493164 -154.470001220703 -172.399993896484 -194.735000610352 -222.710006713867 -257.470001220703 -299.929992675781 -350.679992675781 -409.929992675781 -477.470001220703 -552.710021972656 -634.734985351563 -722.400024414063 -814.469970703125 -909.739990234375 -1007.15502929688 -1105.90502929688 -1205.53503417969 -1306.20495605469 -1409.15002441406  -1517.09497070313 -1634.17504882813 -1765.13500976563 -1914.15002441406 -2084.03491210938 -2276.22509765625 -2491.25000000000 -2729.25000000000 -2990.25000000000 -3274.25000000000 -3581.25000000000 -3911.25000000000 -4264.25000000000 -4640.25000000000 -5039.25000000000 -5461.25000000000 -5906.25000000000]')
n1,n2,n3 = (length(lon),length(lat),length(dep))

dimdict = Dict{AbstractString,NCvar}([
    "lon_c" => NCvar("lon_c","degrees_east",size(lon),lon,Dict("long_name" => "longitude"),NCDatasets),
    "lat_c" => NCvar("lat_c","degrees_north",size(lat),lat,Dict("long_name" => "latitude"),NCDatasets),
    "dep_c" => NCvar("dep_c","m",size(dep),dep,Dict("long_name" => "depth","standard_name" => "depth","positive" => "down"),NCDatasets),
    "time" => NCvar("time",timeunits,Inf,timesteps,Dict(("long_name" => "time","standard_name" => "time")),NCDatasets)
])

dims = [NCvar("lon_c","degrees_east",size(lon),lon,Dict("long_name" => "longitude"),NCDatasets),
        NCvar("lat_c","degrees_north",size(lat),lat,Dict("long_name" => "latitude"),NCDatasets),
        NCvar("dep_c","m",size(dep),dep,Dict("long_name" => "depth","standard_name" => "depth","positive" => "down"),NCDatasets),
        NCvar("time",timeunits,Inf,timesteps,Dict(("long_name" => "time","standard_name" => "time")),NCDatasets)]

function createTimestep(timestep,idx,group,flds,timestart,fnameprefix,README,dimdict)
    thistime = timestart + Dates.Day(floor(timestep))

    yyyyddd = @sprintf("%i%03i",year(thistime),dayofyear(thistime))

    thisfilename = join((fnameprefix,lowercase(group),yyyyddd),"_")*".nc"
    if isfile(thisfilename)
        try
            ds = Dataset(thisfilename)
            ds["time"]
            println(thisfilename*" already done")
            return
        catch
            rm(thisfilename)
        end
    end
    ds,fieldvars,dimlist = createfile(thisfilename,flds,README)

    # Add field and dimension data and close the file
    for k in keys(flds)
        addData(ds[k],flds[k][idx])
    end

    if haskey(dimdict,"time")
        hastimedim = true
        timedim = pop!(dimdict,"time")
    else
        hastimedim = false
    end

    addDimData.(Ref(ds),collect(values(dimdict)))
    if hastimedim
        addDimData(ds,timedim[idx])
        dimdict["time"] = timedim
    end

    close(ds)
    println("finished "*thisfilename)
end

for group in groups
    println(group)
    groupindir = joinpath(indir,group)
    groupsavedir = joinpath(savedir,group)
    if !isdir(groupsavedir); mkpath(groupsavedir); end

    selectfields = filter(x -> isdir(joinpath(groupindir,x)),readdir(groupindir))

    flds = Dict{AbstractString,NCvar}()

    timestepidx = []

    for fldname in selectfields
        fullpath = joinpath(groupindir,fldname)
        fnames_timerange = fldname*'.'.*timeinfname.*".data"
        fnames_avail = filter(x -> occursin(".data",x), readdir(fullpath))
        fnames = joinpath.(Ref(fullpath),intersect(fnames_timerange,fnames_avail))
        timestepidx = [findfirst(occursin.(f,fnames_timerange)) for f in fnames_avail]
        timestepidx = timestepidx[.!isa.(timestepidx,Nothing)]
        metafile = joinpath.(Ref(fullpath),fldname*'.'.*timeinfname.*".meta")
        #filter(x -> occursin(".meta",x), readdir(fullpath))[1]
        metafile = parsemeta(metafile[1])
        diaginfo = readAvailDiagnosticsLog(availdiagsfname,fldname)

        #timesteps = parse.(Int,getindex.(split.(fnames,'.'),2))./24 .- timeinterval/2

        # Rename if needed
        if any(occursin.(fldname,collect(keys(rename))))
            fldname = rename[fldname]
        end

        prec = eval(Meta.parse(metafile["dataprec"]))
        units = get(unitsrename,diaginfo["units"],diaginfo["units"])
        longname = diaginfo["title"]

        mydims = Array{NCvar,1}()
        for i in 1:metafile["nDims"]
            dimidx = getindex.(getfield.(dims,:dims),1) .== metafile["dimList"][i,1]
            mydims = cat(mydims,dims[dimidx],dims=1)
        end

        iosize = Tuple([d.dims[1] for d in mydims])

        mydims = cat(mydims,dimdict["time"],dims=1)

        fielddata = BinData(fnames,prec,iosize)
        flds[fldname] = NCvar(fldname,units,mydims,fielddata,
            Dict("long_name" => longname),NCDatasets)

    end

    # Set up NCvars
    filename = joinpath(savedir,join([fnameprefix,lowercase(group)],"_")*".nc")
    println(filename)
    if isfile(filename); rm(filename); end

    # Create the NetCDF file and populate with dimension and field info
    ds,fieldvars,dimlist = createfile(filename,flds,README)

    # Add field and dimension data and close the file
    for k in keys(flds)
        addData(ds[k],flds[k])
    end

    addDimData.(Ref(ds),dims)
    close(ds)

    createTimestep.(timesteps[timestepidx],timestepidx,Ref(group),Ref(flds),Ref(timestart),Ref(joinpath(groupsavedir,fnameprefix)),Ref(README),Ref(dimdict))
    #createTimestep.(dtsteps,didx,Ref(group),Ref(flds),Ref(timestart),Ref(ncdir*group*"/"*fnameprefix),Ref(README))

end


text:
function can_cut(c, k, as)
    sum([ceil(Int, a/c) - 1 for a in as]) ≤ k
end

function solve()
    n, k = [parse(Int, x) for x in split(readline())]
    as = [parse(Int, x) for x in split(readline())]

    lb, ub = 0, maximum(as)
    while lb + 1 < ub
        c = ceil(Int, (ub + lb) / 2)
        if can_cut(c, k, as)
            ub = c
        else
            lb = c
        end
    end
    ceil(Int, ub)
end

println(solve())

max_stars_repo_name: aishikawa/atcoder-julia

max_issues_repo_name: aishikawa/atcoder-julia

max_forks_repo_name: aishikawa/atcoder-julia