text:
# Julia wrapper for header: jconfig.h
# Automatically generated using Clang.jl

# Julia wrapper for header: jmorecfg.h
# Automatically generated using Clang.jl

# Julia wrapper for header: jerror.h
# Automatically generated using Clang.jl

# Julia wrapper for header: jpeglib.h
# Automatically generated using Clang.jl

function jpeg_std_error(err)
    ccall((:jpeg_std_error, libturbojpeg), Ptr{jpeg_error_mgr}, (Ptr{jpeg_error_mgr},), err)
end

function jpeg_CreateCompress(cinfo, version, structsize)
    ccall((:jpeg_CreateCompress, libturbojpeg), Cvoid, (j_compress_ptr, Cint, Cint), cinfo, version, structsize)
end

function jpeg_CreateDecompress(cinfo, version, structsize)
    ccall((:jpeg_CreateDecompress, libturbojpeg), Cvoid, (j_decompress_ptr, Cint, Cint), cinfo, version, structsize)
end

function jpeg_destroy_compress(cinfo)
    ccall((:jpeg_destroy_compress, libturbojpeg), Cvoid, (j_compress_ptr,), cinfo)
end

function jpeg_destroy_decompress(cinfo)
    ccall((:jpeg_destroy_decompress, libturbojpeg), Cvoid, (j_decompress_ptr,), cinfo)
end

function jpeg_stdio_dest(cinfo, outfile)
    ccall((:jpeg_stdio_dest, libturbojpeg), Cvoid, (j_compress_ptr, Ptr{Cint}), cinfo, outfile)
end

function jpeg_stdio_src(cinfo, infile)
    ccall((:jpeg_stdio_src, libturbojpeg), Cvoid, (j_decompress_ptr, Ptr{Cint}), cinfo, infile)
end

function jpeg_mem_dest(cinfo, outbuffer, outsize)
    ccall((:jpeg_mem_dest, libturbojpeg), Cvoid, (j_compress_ptr, Ptr{Ptr{Cuchar}}, Ptr{Culong}), cinfo, outbuffer, outsize)
end

function jpeg_mem_src(cinfo, inbuffer, insize)
    ccall((:jpeg_mem_src, libturbojpeg), Cvoid, (j_decompress_ptr, Ptr{Cuchar}, Culong), cinfo, inbuffer, insize)
end

function jpeg_set_defaults(cinfo)
    ccall((:jpeg_set_defaults, libturbojpeg), Cvoid, (j_compress_ptr,), cinfo)
end

function jpeg_set_colorspace(cinfo, colorspace)
    ccall((:jpeg_set_colorspace, libturbojpeg), Cvoid, (j_compress_ptr, J_COLOR_SPACE), cinfo, colorspace)
end

function jpeg_default_colorspace(cinfo)
    ccall((:jpeg_default_colorspace, libturbojpeg), Cvoid, (j_compress_ptr,), cinfo)
end

function jpeg_set_quality(cinfo, quality, force_baseline)
    ccall((:jpeg_set_quality, libturbojpeg), Cvoid, (j_compress_ptr, Cint, boolean), cinfo, quality, force_baseline)
end

function jpeg_set_linear_quality(cinfo, scale_factor, force_baseline)
    ccall((:jpeg_set_linear_quality, libturbojpeg), Cvoid, (j_compress_ptr, Cint, boolean), cinfo, scale_factor, force_baseline)
end

function jpeg_add_quant_table(cinfo, which_tbl, basic_table, scale_factor, force_baseline)
    ccall((:jpeg_add_quant_table, libturbojpeg), Cvoid, (j_compress_ptr, Cint, Ptr{UInt32}, Cint, boolean), cinfo, which_tbl, basic_table, scale_factor, force_baseline)
end

function jpeg_quality_scaling(quality)
    ccall((:jpeg_quality_scaling, libturbojpeg), Cint, (Cint,), quality)
end

function jpeg_simple_progression(cinfo)
    ccall((:jpeg_simple_progression, libturbojpeg), Cvoid, (j_compress_ptr,), cinfo)
end

function jpeg_suppress_tables(cinfo, suppress)
    ccall((:jpeg_suppress_tables, libturbojpeg), Cvoid, (j_compress_ptr, boolean), cinfo, suppress)
end

function jpeg_alloc_quant_table(cinfo)
    ccall((:jpeg_alloc_quant_table, libturbojpeg), Ptr{JQUANT_TBL}, (j_common_ptr,), cinfo)
end

function jpeg_alloc_huff_table(cinfo)
    ccall((:jpeg_alloc_huff_table, libturbojpeg), Ptr{JHUFF_TBL}, (j_common_ptr,), cinfo)
end

function jpeg_start_compress(cinfo, write_all_tables)
    ccall((:jpeg_start_compress, libturbojpeg), Cvoid, (j_compress_ptr, boolean), cinfo, write_all_tables)
end

function jpeg_write_scanlines(cinfo, scanlines, num_lines)
    ccall((:jpeg_write_scanlines, libturbojpeg), JDIMENSION, (j_compress_ptr, JSAMPARRAY, JDIMENSION), cinfo, scanlines, num_lines)
end

function jpeg_finish_compress(cinfo)
    ccall((:jpeg_finish_compress, libturbojpeg), Cvoid, (j_compress_ptr,), cinfo)
end

function jpeg_write_raw_data(cinfo, data, num_lines)
    ccall((:jpeg_write_raw_data, libturbojpeg), JDIMENSION, (j_compress_ptr, JSAMPIMAGE, JDIMENSION), cinfo, data, num_lines)
end

function jpeg_write_marker(cinfo, marker, dataptr, datalen)
    ccall((:jpeg_write_marker, libturbojpeg), Cvoid, (j_compress_ptr, Cint, Ptr{JOCTET}, UInt32), cinfo, marker, dataptr, datalen)
end

function jpeg_write_m_header(cinfo, marker, datalen)
    ccall((:jpeg_write_m_header, libturbojpeg), Cvoid, (j_compress_ptr, Cint, UInt32), cinfo, marker, datalen)
end

function jpeg_write_m_byte(cinfo, val)
    ccall((:jpeg_write_m_byte, libturbojpeg), Cvoid, (j_compress_ptr, Cint), cinfo, val)
end

function jpeg_write_tables(cinfo)
    ccall((:jpeg_write_tables, libturbojpeg), Cvoid, (j_compress_ptr,), cinfo)
end

function jpeg_write_icc_profile(cinfo, icc_data_ptr, icc_data_len)
    ccall((:jpeg_write_icc_profile, libturbojpeg), Cvoid, (j_compress_ptr, Ptr{JOCTET}, UInt32), cinfo, icc_data_ptr, icc_data_len)
end

function jpeg_read_header(cinfo, require_image)
    ccall((:jpeg_read_header, libturbojpeg), Cint, (j_decompress_ptr, boolean), cinfo, require_image)
end

function jpeg_start_decompress(cinfo)
    ccall((:jpeg_start_decompress, libturbojpeg), boolean, (j_decompress_ptr,), cinfo)
end

function jpeg_read_scanlines(cinfo, scanlines, max_lines)
    ccall((:jpeg_read_scanlines, libturbojpeg), JDIMENSION, (j_decompress_ptr, JSAMPARRAY, JDIMENSION), cinfo, scanlines, max_lines)
end

function jpeg_skip_scanlines(cinfo, num_lines)
    ccall((:jpeg_skip_scanlines, libturbojpeg), JDIMENSION, (j_decompress_ptr, JDIMENSION), cinfo, num_lines)
end

function jpeg_crop_scanline(cinfo, xoffset, width)
    ccall((:jpeg_crop_scanline, libturbojpeg), Cvoid, (j_decompress_ptr, Ptr{JDIMENSION}, Ptr{JDIMENSION}), cinfo, xoffset, width)
end

function jpeg_finish_decompress(cinfo)
    ccall((:jpeg_finish_decompress, libturbojpeg), boolean, (j_decompress_ptr,), cinfo)
end

function jpeg_read_raw_data(cinfo, data, max_lines)
    ccall((:jpeg_read_raw_data, libturbojpeg), JDIMENSION, (j_decompress_ptr, JSAMPIMAGE, JDIMENSION), cinfo, data, max_lines)
end

function jpeg_has_multiple_scans(cinfo)
    ccall((:jpeg_has_multiple_scans, libturbojpeg), boolean, (j_decompress_ptr,), cinfo)
end

function jpeg_start_output(cinfo, scan_number)
    ccall((:jpeg_start_output, libturbojpeg), boolean, (j_decompress_ptr, Cint), cinfo, scan_number)
end

function jpeg_finish_output(cinfo)
    ccall((:jpeg_finish_output, libturbojpeg), boolean, (j_decompress_ptr,), cinfo)
end

function jpeg_input_complete(cinfo)
    ccall((:jpeg_input_complete, libturbojpeg), boolean, (j_decompress_ptr,), cinfo)
end

function jpeg_new_colormap(cinfo)
    ccall((:jpeg_new_colormap, libturbojpeg), Cvoid, (j_decompress_ptr,), cinfo)
end

function jpeg_consume_input(cinfo)
    ccall((:jpeg_consume_input, libturbojpeg), Cint, (j_decompress_ptr,), cinfo)
end

function jpeg_calc_output_dimensions(cinfo)
    ccall((:jpeg_calc_output_dimensions, libturbojpeg), Cvoid, (j_decompress_ptr,), cinfo)
end

function jpeg_save_markers(cinfo, marker_code, length_limit)
    ccall((:jpeg_save_markers, libturbojpeg), Cvoid, (j_decompress_ptr, Cint, UInt32), cinfo, marker_code, length_limit)
end

function jpeg_set_marker_processor(cinfo, marker_code, routine)
    ccall((:jpeg_set_marker_processor, libturbojpeg), Cvoid, (j_decompress_ptr, Cint, jpeg_marker_parser_method), cinfo, marker_code, routine)
end

function jpeg_read_coefficients(cinfo)
    ccall((:jpeg_read_coefficients, libturbojpeg), Ptr{jvirt_barray_ptr}, (j_decompress_ptr,), cinfo)
end

function jpeg_write_coefficients(cinfo, coef_arrays)
    ccall((:jpeg_write_coefficients, libturbojpeg), Cvoid, (j_compress_ptr, Ptr{jvirt_barray_ptr}), cinfo, coef_arrays)
end

function jpeg_copy_critical_parameters(srcinfo, dstinfo)
    ccall((:jpeg_copy_critical_parameters, libturbojpeg), Cvoid, (j_decompress_ptr, j_compress_ptr), srcinfo, dstinfo)
end

function jpeg_abort_compress(cinfo)
    ccall((:jpeg_abort_compress, libturbojpeg), Cvoid, (j_compress_ptr,), cinfo)
end

function jpeg_abort_decompress(cinfo)
    ccall((:jpeg_abort_decompress, libturbojpeg), Cvoid, (j_decompress_ptr,), cinfo)
end

function jpeg_abort(cinfo)
    ccall((:jpeg_abort, libturbojpeg), Cvoid, (j_common_ptr,), cinfo)
end

function jpeg_destroy(cinfo)
    ccall((:jpeg_destroy, libturbojpeg), Cvoid, (j_common_ptr,), cinfo)
end

function jpeg_resync_to_restart(cinfo, desired)
    ccall((:jpeg_resync_to_restart, libturbojpeg), boolean, (j_decompress_ptr, Cint), cinfo, desired)
end

function jpeg_read_icc_profile(cinfo, icc_data_ptr, icc_data_len)
    ccall((:jpeg_read_icc_profile, libturbojpeg), boolean, (j_decompress_ptr, Ptr{Ptr{JOCTET}}, Ptr{UInt32}), cinfo, icc_data_ptr, icc_data_len)
end
# Julia wrapper for header: turbojpeg.h
# Automatically generated using Clang.jl

function tjInitCompress()
    ccall((:tjInitCompress, libturbojpeg), tjhandle, ())
end

function tjCompress2(handle, srcBuf, width, pitch, height, pixelFormat, jpegBuf, jpegSize, jpegSubsamp, jpegQual, flags)
    ccall((:tjCompress2, libturbojpeg), Cint, (tjhandle, Ptr{Cuchar}, Cint, Cint, Cint, Cint, Ptr{Ptr{Cuchar}}, Ptr{Culong}, Cint, Cint, Cint), handle, srcBuf, width, pitch, height, pixelFormat, jpegBuf, jpegSize, jpegSubsamp, jpegQual, flags)
end

function tjCompressFromYUV(handle, srcBuf, width, pad, height, subsamp, jpegBuf, jpegSize, jpegQual, flags)
    ccall((:tjCompressFromYUV, libturbojpeg), Cint, (tjhandle, Ptr{Cuchar}, Cint, Cint, Cint, Cint, Ptr{Ptr{Cuchar}}, Ptr{Culong}, Cint, Cint), handle, srcBuf, width, pad, height, subsamp, jpegBuf, jpegSize, jpegQual, flags)
end

function tjCompressFromYUVPlanes(handle, srcPlanes, width, strides, height, subsamp, jpegBuf, jpegSize, jpegQual, flags)
    ccall((:tjCompressFromYUVPlanes, libturbojpeg), Cint, (tjhandle, Ptr{Ptr{Cuchar}}, Cint, Ptr{Cint}, Cint, Cint, Ptr{Ptr{Cuchar}}, Ptr{Culong}, Cint, Cint), handle, srcPlanes, width, strides, height, subsamp, jpegBuf, jpegSize, jpegQual, flags)
end

function tjBufSize(width, height, jpegSubsamp)
    ccall((:tjBufSize, libturbojpeg), Culong, (Cint, Cint, Cint), width, height, jpegSubsamp)
end

function tjBufSizeYUV2(width, pad, height, subsamp)
    ccall((:tjBufSizeYUV2, libturbojpeg), Culong, (Cint, Cint, Cint, Cint), width, pad, height, subsamp)
end

function tjPlaneSizeYUV(componentID, width, stride, height, subsamp)
    ccall((:tjPlaneSizeYUV, libturbojpeg), Culong, (Cint, Cint, Cint, Cint, Cint), componentID, width, stride, height, subsamp)
end

function tjPlaneWidth(componentID, width, subsamp)
    ccall((:tjPlaneWidth, libturbojpeg), Cint, (Cint, Cint, Cint), componentID, width, subsamp)
end

function tjPlaneHeight(componentID, height, subsamp)
    ccall((:tjPlaneHeight, libturbojpeg), Cint, (Cint, Cint, Cint), componentID, height, subsamp)
end

function tjEncodeYUV3(handle, srcBuf, width, pitch, height, pixelFormat, dstBuf, pad, subsamp, flags)
    ccall((:tjEncodeYUV3, libturbojpeg), Cint, (tjhandle, Ptr{Cuchar}, Cint, Cint, Cint, Cint, Ptr{Cuchar}, Cint, Cint, Cint), handle, srcBuf, width, pitch, height, pixelFormat, dstBuf, pad, subsamp, flags)
end

function tjEncodeYUVPlanes(handle, srcBuf, width, pitch, height, pixelFormat, dstPlanes, strides, subsamp, flags)
    ccall((:tjEncodeYUVPlanes, libturbojpeg), Cint, (tjhandle, Ptr{Cuchar}, Cint, Cint, Cint, Cint, Ptr{Ptr{Cuchar}}, Ptr{Cint}, Cint, Cint), handle, srcBuf, width, pitch, height, pixelFormat, dstPlanes, strides, subsamp, flags)
end

function tjInitDecompress()
    ccall((:tjInitDecompress, libturbojpeg), tjhandle, ())
end

function tjDecompressHeader3(handle, jpegBuf, jpegSize, width, height, jpegSubsamp, jpegColorspace)
    ccall((:tjDecompressHeader3, libturbojpeg), Cint, (tjhandle, Ptr{Cuchar}, Culong, Ptr{Cint}, Ptr{Cint}, Ptr{Cint}, Ptr{Cint}), handle, jpegBuf, jpegSize, width, height, jpegSubsamp, jpegColorspace)
end

function tjGetScalingFactors(numscalingfactors)
    ccall((:tjGetScalingFactors, libturbojpeg), Ptr{tjscalingfactor}, (Ptr{Cint},), numscalingfactors)
end

function tjDecompress2(handle, jpegBuf, jpegSize, dstBuf, width, pitch, height, pixelFormat, flags)
    ccall((:tjDecompress2, libturbojpeg), Cint, (tjhandle, Ptr{Cuchar}, Culong, Ptr{Cuchar}, Cint, Cint, Cint, Cint, Cint), handle, jpegBuf, jpegSize, dstBuf, width, pitch, height, pixelFormat, flags)
end

function tjDecompressToYUV2(handle, jpegBuf, jpegSize, dstBuf, width, pad, height, flags)
    ccall((:tjDecompressToYUV2, libturbojpeg), Cint, (tjhandle, Ptr{Cuchar}, Culong, Ptr{Cuchar}, Cint, Cint, Cint, Cint), handle, jpegBuf, jpegSize, dstBuf, width, pad, height, flags)
end

function tjDecompressToYUVPlanes(handle, jpegBuf, jpegSize, dstPlanes, width, strides, height, flags)
    ccall((:tjDecompressToYUVPlanes, libturbojpeg), Cint, (tjhandle, Ptr{Cuchar}, Culong, Ptr{Ptr{Cuchar}}, Cint, Ptr{Cint}, Cint, Cint), handle, jpegBuf, jpegSize, dstPlanes, width, strides, height, flags)
end

function tjDecodeYUV(handle, srcBuf, pad, subsamp, dstBuf, width, pitch, height, pixelFormat, flags)
    ccall((:tjDecodeYUV, libturbojpeg), Cint, (tjhandle, Ptr{Cuchar}, Cint, Cint, Ptr{Cuchar}, Cint, Cint, Cint, Cint, Cint), handle, srcBuf, pad, subsamp, dstBuf, width, pitch, height, pixelFormat, flags)
end

function tjDecodeYUVPlanes(handle, srcPlanes, strides, subsamp, dstBuf, width, pitch, height, pixelFormat, flags)
    ccall((:tjDecodeYUVPlanes, libturbojpeg), Cint, (tjhandle, Ptr{Ptr{Cuchar}}, Ptr{Cint}, Cint, Ptr{Cuchar}, Cint, Cint, Cint, Cint, Cint), handle, srcPlanes, strides, subsamp, dstBuf, width, pitch, height, pixelFormat, flags)
end

function tjInitTransform()
    ccall((:tjInitTransform, libturbojpeg), tjhandle, ())
end

function tjTransform(handle, jpegBuf, jpegSize, n, dstBufs, dstSizes, transforms, flags)
    ccall((:tjTransform, libturbojpeg), Cint, (tjhandle, Ptr{Cuchar}, Culong, Cint, Ptr{Ptr{Cuchar}}, Ptr{Culong}, Ptr{tjtransform}, Cint), handle, jpegBuf, jpegSize, n, dstBufs, dstSizes, transforms, flags)
end

function tjDestroy(handle)
    ccall((:tjDestroy, libturbojpeg), Cint, (tjhandle,), handle)
end

function tjAlloc(bytes)
    ccall((:tjAlloc, libturbojpeg), Ptr{Cuchar}, (Cint,), bytes)
end

function tjLoadImage(filename, width, align, height, pixelFormat, flags)
    ccall((:tjLoadImage, libturbojpeg), Ptr{Cuchar}, (Cstring, Ptr{Cint}, Cint, Ptr{Cint}, Ptr{Cint}, Cint), filename, width, align, height, pixelFormat, flags)
end

function tjSaveImage(filename, buffer, width, pitch, height, pixelFormat, flags)
    ccall((:tjSaveImage, libturbojpeg), Cint, (Cstring, Ptr{Cuchar}, Cint, Cint, Cint, Cint, Cint), filename, buffer, width, pitch, height, pixelFormat, flags)
end

function tjFree(buffer)
    ccall((:tjFree, libturbojpeg), Cvoid, (Ptr{Cuchar},), buffer)
end

function tjGetErrorStr2(handle)
    ccall((:tjGetErrorStr2, libturbojpeg), Cstring, (tjhandle,), handle)
end

function tjGetErrorCode(handle)
    ccall((:tjGetErrorCode, libturbojpeg), Cint, (tjhandle,), handle)
end

function TJBUFSIZE(width, height)
    ccall((:TJBUFSIZE, libturbojpeg), Culong, (Cint, Cint), width, height)
end

function TJBUFSIZEYUV(width, height, jpegSubsamp)
    ccall((:TJBUFSIZEYUV, libturbojpeg), Culong, (Cint, Cint, Cint), width, height, jpegSubsamp)
end

function tjBufSizeYUV(width, height, subsamp)
    ccall((:tjBufSizeYUV, libturbojpeg), Culong, (Cint, Cint, Cint), width, height, subsamp)
end

function tjCompress(handle, srcBuf, width, pitch, height, pixelSize, dstBuf, compressedSize, jpegSubsamp, jpegQual, flags)
    ccall((:tjCompress, libturbojpeg), Cint, (tjhandle, Ptr{Cuchar}, Cint, Cint, Cint, Cint, Ptr{Cuchar}, Ptr{Culong}, Cint, Cint, Cint), handle, srcBuf, width, pitch, height, pixelSize, dstBuf, compressedSize, jpegSubsamp, jpegQual, flags)
end

function tjEncodeYUV(handle, srcBuf, width, pitch, height, pixelSize, dstBuf, subsamp, flags)
    ccall((:tjEncodeYUV, libturbojpeg), Cint, (tjhandle, Ptr{Cuchar}, Cint, Cint, Cint, Cint, Ptr{Cuchar}, Cint, Cint), handle, srcBuf, width, pitch, height, pixelSize, dstBuf, subsamp, flags)
end

function tjEncodeYUV2(handle, srcBuf, width, pitch, height, pixelFormat, dstBuf, subsamp, flags)
    ccall((:tjEncodeYUV2, libturbojpeg), Cint, (tjhandle, Ptr{Cuchar}, Cint, Cint, Cint, Cint, Ptr{Cuchar}, Cint, Cint), handle, srcBuf, width, pitch, height, pixelFormat, dstBuf, subsamp, flags)
end

function tjDecompressHeader(handle, jpegBuf, jpegSize, width, height)
    ccall((:tjDecompressHeader, libturbojpeg), Cint, (tjhandle, Ptr{Cuchar}, Culong, Ptr{Cint}, Ptr{Cint}), handle, jpegBuf, jpegSize, width, height)
end

function tjDecompressHeader2(handle, jpegBuf, jpegSize, width, height, jpegSubsamp)
    ccall((:tjDecompressHeader2, libturbojpeg), Cint, (tjhandle, Ptr{Cuchar}, Culong, Ptr{Cint}, Ptr{Cint}, Ptr{Cint}), handle, jpegBuf, jpegSize, width, height, jpegSubsamp)
end

function tjDecompress(handle, jpegBuf, jpegSize, dstBuf, width, pitch, height, pixelSize, flags)
    ccall((:tjDecompress, libturbojpeg), Cint, (tjhandle, Ptr{Cuchar}, Culong, Ptr{Cuchar}, Cint, Cint, Cint, Cint, Cint), handle, jpegBuf, jpegSize, dstBuf, width, pitch, height, pixelSize, flags)
end

function tjDecompressToYUV(handle, jpegBuf, jpegSize, dstBuf, flags)
    ccall((:tjDecompressToYUV, libturbojpeg), Cint, (tjhandle, Ptr{Cuchar}, Culong, Ptr{Cuchar}, Cint), handle, jpegBuf, jpegSize, dstBuf, flags)
end

function tjGetErrorStr()
    ccall((:tjGetErrorStr, libturbojpeg), Cstring, ())
end


text:
export hchebyshevcenter, vchebyshevcenter, chebyshevcenter
using JuMP

"""
    hchebyshevcenter(p::HRep[, solver])

Return a tuple with the center and radius of the largest euclidean ball contained in the polyhedron `p`.
Throws an error if the polyhedron is empty or if the radius is infinite.
"""
function hchebyshevcenter(p::HRep, solver=Polyhedra.default_solver(p; T=Float64)) # Need Float64 for `norm(a, 2)`
    model = JuMP.Model(solver)
    c = JuMP.@variable(model, [1:fulldim(p)])
    for hp in hyperplanes(p)
        a = convert(Vector{Float64}, hp.a)
        β = convert(Float64, hp.β)
        JuMP.@constraint(model, dot(a, c) == β)
    end
    JuMP.@variable(model, r[1:nhalfspaces(p)] >= 0)
    for (i, hs) in enumerate(halfspaces(p))
        a = convert(Vector{Float64}, hs.a)
        β = convert(Float64, hs.β)
        JuMP.@constraint(model, dot(a, c) + r[i] * norm(a, 2) <= β)
    end
    JuMP.@variable(model, minr >= 0)
    JuMP.@constraint(model, minr .<= r)
    JuMP.@objective(model, Max, minr)
    JuMP.optimize!(model)
    term = JuMP.termination_status(model)
    if term ∉ [MOI.OPTIMAL, MOI.LOCALLY_SOLVED]
        if term == MOI.INFEASIBLE
            error("An empty polyhedron has no H-Chebyshev center.")
        elseif term == MOI.DUAL_INFEASIBLE
            error("The polyhedron contains euclidean ball of arbitrary large radius.")
        else
            error("Solver returned $term when computing the H-Chebyshev center.")
        end
    end
    JuMP.@constraint(model, minr == JuMP.value(minr))
    JuMP.@variable(model, maxr >= 0)
    JuMP.@constraint(model, maxr .>= r)
    JuMP.@objective(model, Min, maxr)
    JuMP.optimize!(model)
    term = JuMP.termination_status(model)
    if term ∈ [MOI.OPTIMAL, MOI.LOCALLY_SOLVED]
        return (JuMP.value.(c), JuMP.value(minr))
    else
        error("Solver returned $term when computing the H-Chebyshev center.")
    end
end

# TODO solver here should not be VRepOptimizer
"""
    vchebyshevcenter(p::VRep[, solver])

Return a tuple with the center and radius of the smallest euclidean ball containing the polyhedron `p`.
Throws an error if the polyhedron is empty or if the radius is infinite (i.e. `p` is not a polytope, it contains rays).
"""
function vchebyshevcenter(p::VRep, solver=Polyhedra.default_solver(p))
    error("TODO")
end

"""
    chebyshevcenter(p::Rep[, solver])

If `p` is a H-representation or is a polyhedron for which the H-representation has already been computed, calls `hchebyshevcenter`, otherwise, call `vchebyshevcenter`.
"""
function chebyshevcenter(p::Polyhedron, solver=Polyhedra.default_solver(p; T=Float64))
    if hrepiscomputed(p)
        hchebyshevcenter(p, solver)
    else
        vchebyshevcenter(p, solver)
    end
end
chebyshevcenter(p::HRepresentation, solver=Polyhedra.default_solver(p; T=Float64)) = hchebyshevcenter(p, solver)
chebyshevcenter(p::VRepresentation, solver=Polyhedra.default_solver(p; T=Float64)) = vchebyshevcenter(p, solver)

ext: jl


text:
#=
Copyright (c) 2015, Intel Corporation
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
- Redistributions of source code must retain the above copyright notice,
  this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright notice,
  this list of conditions and the following disclaimer in the documentation
  and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
THE POSSIBILITY OF SUCH DAMAGE.
=#

using Compat

println("ParallelAccelerator: build.jl begin.")
println("ParallelAccelerator: Building j2c-array shared library")

ld_library_path = ""
dyld_library_path = ""

if haskey(ENV, "DYLD_LIBRARY_PATH")
    dyld_library_path = ENV["DYLD_LIBRARY_PATH"]
end

if haskey(ENV, "LD_LIBRARY_PATH")
    ld_library_path = ENV["LD_LIBRARY_PATH"]
end

if Compat.is_windows()
    println("Installing ParallelAccelerator for Windows.")

    builddir = dirname(Base.source_path())
    println("Build directory is ", builddir)

    import WinRPM

    println("Installing gcc-c++.")
    WinRPM.install("gcc-c++";yes=true)
    WinRPM.install("gcc";yes=true)
    WinRPM.install("headers";yes=true)

    gpp = Pkg.dir("WinRPM","deps","usr","x86_64-w64-mingw32","sys-root","mingw","bin","g++")
    RPMbindir = Pkg.dir("WinRPM","deps","usr","x86_64-w64-mingw32","sys-root","mingw","bin")
    incdir = Pkg.dir("WinRPM","deps","usr","x86_64-w64-mingw32","sys-root","mingw","include")

    push!(Base.Libdl.DL_LOAD_PATH,RPMbindir)
    ENV["PATH"]=ENV["PATH"]*";"*RPMbindir

    println("Installed gcc is version ")
    run(`$gpp --version`)

    println("Building libj2carray.dll.")
    run(`$gpp -g -shared -std=c++11 -I $incdir -o $builddir\\libj2carray.dll -lm $builddir\\j2c-array.cpp`)

    conf_file = builddir * "\\generated\\config.jl"
    cf = open(conf_file, "w")
    println(cf, "backend_compiler = USE_MINGW")
    println(cf, "openblas_lib = \"\"")
    #println(cf, "openblas_lib = \"", Base.Libdl.find_library([string("libopenblas64_")]), "\"")
    println(cf, "mkl_lib = \"", Base.Libdl.find_library([string("libmkl")]), "\"")

    try
        run(`bcpp`)
        println(cf, "use_bcpp = 1")
    catch some_exception
        println("bcpp not found and will not be used.")
    end

    try
        btest = open("blas_test.cpp","w")
        println(btest,"#include <cblas.h>\nint main(){return 0;}")
        close(btest)
        run(pipeline(`$gpp -I $incdir blas_test.cpp`, stdout=DevNull, stderr=DevNull))
        println(cf, "sys_blas = 1")
    catch some_exception
        println(cf, "sys_blas = 0")
    end

    close(cf)
else
    run(`./build.sh $dyld_library_path $ld_library_path`)
end
println("ParallelAccelerator: build.jl done.")


text:
"""
    count_CpG(seq::String)

Return the count of C and G bases in CpG dinucleotides for a given sequence.
"""
function count_CpG(seq::String)

    m = eachmatch(r"CG"i, seq)
    loc = [i.offset for i in m]
    n = sum( [char for char in seq] .== 'N' )
    obs = length(loc) * 2   #count of all dinuc in CpG
    return obs

end


text:
using DiffEqJump, DiffEqBase, Graphs

"""
prob.u0 must be a Matrix with prob.u0[i,j] being the number of species i at site j
"""
function flatten(ma_jump, prob::DiscreteProblem, spatial_system, hopping_constants; kwargs...)
    tspan = prob.tspan
    u0 = prob.u0
    if ma_jump === nothing
        ma_jump = MassActionJump(Vector{typeof(tspan[1])}(),
                             Vector{Vector{Pair{Int,eltype(u0)}}}(),
                             Vector{Vector{Pair{Int,eltype(u0)}}}())
    end
    netstoch = ma_jump.net_stoch
    reactstoch = ma_jump.reactant_stoch
    if isa(ma_jump, MassActionJump)
        rx_rates = ma_jump.scaled_rates
    elseif isa(ma_jump, SpatialMassActionJump)
        num_nodes = num_sites(spatial_system)
        if isnothing(ma_jump.uniform_rates) && isnothing(ma_jump.spatial_rates)
            rx_rates = zeros(0,num_nodes)
        elseif isnothing(ma_jump.uniform_rates)
            rx_rates = ma_jump.spatial_rates
        elseif isnothing(ma_jump.spatial_rates)
            rx_rates = reshape(repeat(ma_jump.uniform_rates, num_nodes), length(ma_jump.uniform_rates), num_nodes)
        else
            @assert size(ma_jump.spatial_rates, 2) == num_nodes
            rx_rates = cat(dims=1,reshape(repeat(ma_jump.uniform_rates, num_nodes), length(ma_jump.uniform_rates), num_nodes), ma_jump.spatial_rates)
        end
    end
    flatten(netstoch, reactstoch, rx_rates, spatial_system, u0, tspan, hopping_constants; scale_rates = false, kwargs...)
end

"""
if hopping_constants is a matrix, assume hopping_constants[i,j] is the hopping constant of species i from site j to any neighbor
"""
function flatten(netstoch::AbstractArray, reactstoch::AbstractArray, rx_rates::AbstractArray, spatial_system, u0::Matrix{Int}, tspan, hopping_constants::Matrix{F}; kwargs...) where F <: Number
    @assert size(hopping_constants) == size(u0)
    hop_constants = Matrix{Vector{F}}(undef, size(hopping_constants))
    for ci in CartesianIndices(hop_constants)
        (species, site) = Tuple(ci)
        hop_constants[ci] = hopping_constants[species, site] * ones(outdegree(spatial_system, site))
    end
    flatten(netstoch, reactstoch, rx_rates, spatial_system, u0, tspan, hop_constants; kwargs...)
end

"""
if reaction rates is a vector, assume reaction rates are equal across sites
"""
function flatten(netstoch::AbstractArray, reactstoch::AbstractArray, rx_rates::Vector, spatial_system, u0::Matrix{Int}, tspan, hopping_constants::Matrix{Vector{F}}; kwargs...) where F <: Number
    num_nodes = num_sites(spatial_system)
    rates = reshape(repeat(rx_rates, num_nodes), length(rx_rates), num_nodes)
    flatten(netstoch, reactstoch, rates, spatial_system, u0, tspan, hopping_constants; kwargs...)
end

"""
"flatten" the spatial jump problem. Return flattened DiscreteProblem and MassActionJump.
"""
function flatten(netstoch::Vector{R}, reactstoch::Vector{R}, rx_rates::Matrix{F}, spatial_system, u0::Matrix{Int}, tspan, hopping_constants::Matrix{Vector{F}}; scale_rates = true, kwargs...) where {R, F <: Number}
    num_species = size(u0, 1)
    num_nodes = num_sites(spatial_system)
    num_rxs = length(reactstoch)
    @assert size(hopping_constants) == size(u0)
    @assert size(u0, 2) == size(rx_rates, 2) == num_nodes
    @assert length(netstoch) == length(reactstoch) == size(rx_rates, 1) == num_rxs
    spec_CI = CartesianIndices((num_species, num_nodes))
    spec_LI = LinearIndices((num_species, num_nodes))

    sum_outdegrees = sum(outdegree(spatial_system, site) for site in 1:num_nodes)
    num_jumps = num_species*sum_outdegrees + num_nodes*num_rxs
    total_netstoch = R[]; sizehint!(total_netstoch, num_jumps)
    total_reactstoch = R[]; sizehint!(total_reactstoch, num_jumps)
    total_rates = F[]; sizehint!(total_rates, num_jumps)

    #hops
    # assuming hopping_constants isa Matrix{Vector} where hopping_constants[species, src][index] is the hop const of species from src to neighbor at index in neighbors(spatial_system, src)
    for src in 1:num_nodes
        for species in 1:num_species
        hopping_const = hopping_constants[species, src]
            for (i,dst) in enumerate(neighbors(spatial_system, src))
                dst_idx = spec_LI[spec_CI[species,dst]]
                src_idx = spec_LI[spec_CI[species,src]]
                push!(total_netstoch, [dst_idx => 1, src_idx => -1])
                push!(total_reactstoch, [src_idx => 1])
                push!(total_rates, hopping_const[i])
            end
        end
    end

    #reactions
    for site in 1:num_nodes
        for rx in 1:num_rxs
            nstoch = map(p -> Pair(spec_LI[spec_CI[p[1],site]], p[2]), netstoch[rx]) # transform into new indices
            rstoch = map(p -> Pair(spec_LI[spec_CI[p[1],site]], p[2]), reactstoch[rx])
            push!(total_netstoch, nstoch)
            push!(total_reactstoch, rstoch)
        end
    end
    append!(total_rates, vec(rx_rates)) # assuming rx_rates isa Matrix where rx_rates[rx, site] is the rate of rx at site

    # put everything together
    ma_jump = MassActionJump(total_rates, total_reactstoch, total_netstoch; nocopy = true, scale_rates = scale_rates)
    flattened_u0 = vec(u0)
    prob = DiscreteProblem(flattened_u0, tspan, total_rates)
    prob, ma_jump
end


text:
module Flux

using LinearAlgebra
import LinearAlgebra: logdet
import StatsFuns: logsumexp

using Flux, Test
using Flux: Tracker
using Flux.Tracker: @grad, gradcheck, TrackedVector, TrackedMatrix, TrackedVecOrMat
import NNlib

using ..Arr: eye
import ..Math: make_lt, unmake_lt, make_lt_strict, unmake_lt_strict

FLUX_TESTS = false   # perform gradient checks

# Make Lower Triangular Matrix / Can backprop through
# ===================================
# => Moved to Math
# function make_lt(x, d::Int)
#     @assert (length(x) == Int(d*(d+1)/2))
#     M = zeros(d,d)
#     x_i = 1
#     for j=1:d, i=j:d
#         M[i,j] = x[x_i]
#         x_i += 1
#     end
#     return M
# end
#
# function unmake_lt(M, d)
#     return M[tril!(trues(d,d))]
# end

make_lt(x::TrackedArray, d::Int) = Tracker.track(make_lt, x, d)

@grad function make_lt(x, d::Int)
    return make_lt(Tracker.data(x), d), Δ -> (unmake_lt(Δ, d), nothing)
end

# Make Strictly Lower Triangular Matrix
# ===================================
# => Moved to Math
# function make_lt_strict(x, d::Int)
#     @assert (length(x) == Int(d*(d-1)/2))
#     M = zeros(d,d)
#     x_i = 1
#     for j=1:d-1, i=j+1:d
#         M[i,j] = x[x_i]
#         x_i += 1
#     end
#     return M
# end
#
# function unmake_lt_strict(M, d)
#     return M[tril!(trues(d,d), -1)]
# end

make_lt_strict(x::TrackedArray, d::Int) = Tracker.track(make_lt_strict, x, d)

@grad function make_lt_strict(x, d::Int)
    return make_lt_strict(Tracker.data(x), d), Δ -> (unmake_lt_strict(Δ, d), nothing)
end

# Make Diagonal Matrix (current Flux version is more general but is Tracked{Tracked} :/  ).
# ===================================
function diag0(x::Array{T,1})::Array{T,2} where T <: Real
    d = length(x)
    M = zeros(T, d,d)
    M[diagind(M)] = x
    return M
end

diag0(x::TrackedArray) = Tracker.track(diag0, x)

@grad function diag0(x)
    return diag0(Tracker.data(x)), Δ -> (Δ[diagind(Δ)],)
end

# Gradient Tester Utilities from Flux
gradtest(f, xs::AbstractArray...) = gradcheck((xs...) -> sum(sin.(f(xs...))), xs...)
gradtest(f, dims...) = gradtest(f, rand.(Float64, dims)...)

# For use by logsumexprows/cols. However, using the StatsFuns version with
# usual Flux broadcasting etc. works faster usually!
logsumexp(X::TrackedVector) = Tracker.track(logsumexp, X)

@grad function logsumexp(X)
  return logsumexp(X.data), Δ -> (NNlib.softmax(X.data) .* Δ',)
end

# Row-wise logsumexp. See math.jl in AxUtil. Gradient is fairly efficient with below.
# ===================================
function logsumexprows(X::AbstractMatrix{T}) where {T<:Real}
    #= iterate over rows of matrix with StatsFuns' logsumexp.
       This is primarily useful since we have a Flux-enabled
       version in the flux src in AxUtil.
    =#
    n = size(X,1)
    out = zeros(n)
    Threads.@threads for i = 1:n
        out[i] = logsumexp(X[i,:])
    end
    return out
end

logsumexprows(X::TrackedArray) = Tracker.track(logsumexprows, X)

@grad function logsumexprows(X)
  return logsumexprows(X.data), Δ -> (Δ .* NNlib.softmax(X.data')',)
end

function logsumexpcols(X::AbstractMatrix{T}) where {T<:Real}
    n = size(X,2)
    out = zeros(n)
    Threads.@threads for i = 1:n
        @views out[i] = logsumexp(X[:,i])
    end
    return out
end

logsumexpcols(X::TrackedArray) = Tracker.track(logsumexpcols, X)

@grad function logsumexpcols(X)
  return logsumexpcols(X.data), Δ -> (NNlib.softmax(X.data) .* Δ',)
end

logdet(X::TrackedMatrix) = Tracker.track(logdet, X)

@grad function logdet(X)
  return logdet(X.data), Δ -> (inv(X)' * Δ,)
end

# # => MOST GAUSSIAN LLH FUNCTIONS CONTAIN CHOLESKY FACTORISATIONS: THIS AVOIDS IT.
# function flux_log_gauss_llh_prec(X, mu, prec)
#     d = size(X,1)
#     exponent = -0.5*sum((X .- mu).*(prec*(X .- mu)), dims=1)[:]
#     lognormconst = -d*log(2*pi)/2 +0.5*logdet(prec)  #.-0.5*(-2*sum(log.(diag(invLT))))
#     return exponent .+ lognormconst
# end

if FLUX_TESTS
    @test gradtest((x, A) -> make_lt(log.(x), 5) * A, 10, (5,5))
    @test gradtest((x, A) -> diag0(cos.(x)) * A, 5, (5,5))
    @test gradtest((X) -> sin.(logsumexp(X .* X)), (6,))
    @test gradtest((X) -> sin.(logsumexprows(X .* X)), (6,10))
    @test gradtest((X) -> sin.(logsumexpcols(X .* X)), (6,10))
    @test gradtest((X) -> sin.(logdet(X .* X)), (6,6))
end

#==================================================================
                Flux Recurrent Cells
==================================================================#

mutable struct LDSCell_simple
    A::Union{AbstractArray, TrackedArray}
    h::Union{Array{T,1}, TrackedVector{T}} where T <: AbstractFloat
end

# Operation
function (m::LDSCell_simple)(h, x)
    A = m.A
    h = m.A * h
    return h, h
end

hidden(m::LDSCell_simple) = m.h

mutable struct LDSCell_simple_u
    A::Union{AbstractArray, TrackedArray}
    B::Union{AbstractArray, TrackedArray}
    h::Array{T,1}  where T <: AbstractFloat
end

# Operation
function (m::LDSCell_simple_u)(h, x)
    A, B = m.A, m.B
    h = A * h + B * x
    return h, h
end

hidden(m::LDSCell_simple_u) = m.h

mutable struct LDSCell_simple_diag_u
    A::Union{AbstractArray, TrackedArray}
    B::Union{AbstractArray, TrackedArray}
    h::Array{T,1}  where T <: AbstractFloat
end

# Operation
function (m::LDSCell_simple_diag_u)(h, x)
    A, B = m.A, m.B
    h = A .* h + B .* x
    return h, h
end

hidden(m::LDSCell_simple_diag_u) = m.h

LDSCell_scalar_u(a::Tracker.TrackedReal, b::Tracker.TrackedReal, h) = LDSCell_scalar_u_track(a, b, h)
LDSCell_scalar_u(a::AbstractFloat, b::AbstractFloat, h) = LDSCell_scalar_u_notrk(a, b, h)

mutable struct LDSCell_scalar_u_notrk
    A::AbstractFloat
    B::AbstractFloat
    h::AbstractFloat
end

# Operation
function (m::LDSCell_scalar_u_notrk)(h, x)
    A, B = m.A, m.B
    h = A * h + B * x
    return h, h
end

hidden(m::LDSCell_scalar_u_notrk) = m.h

mutable struct LDSCell_scalar_u_track
    A::Tracker.TrackedReal
    B::Tracker.TrackedReal
    h::Tracker.TrackedReal
end

# Operation
function (m::LDSCell_scalar_u_track)(h, x)
    A, B = m.A, m.B
    h = A * h + B * x
    return h, h
end

hidden(m::LDSCell_scalar_u_track) = m.h

#==================================================================
                Optimsation
==================================================================#
function zero_grad!(ps)
    for p in ps
        p.tracker.grad .= 0
    end
end;

function normclip!(ps, thrsh)
    g = reduce(vcat, [vec(p.tracker.grad) for p in ps])
    m = norm(g)
    if m > thrsh
        scale = thrsh/m
        for p in ps
            p.tracker.grad .*= scale
        end
        return true
    end
    return false
end

function dryrun_ADAM(o::ADAM, x, Δ)
  η, β = o.eta, o.beta
  mt, vt, βp = get!(o.state, x, (zero(x), zero(x), β))
  m_new = β[1] .* mt + (1 - β[1]) .* Δ
  v_new = β[2] .* vt + (1 - β[2]) .* Δ.^2
  Δ_new =  m_new ./ (1 - βp[1]) ./ (sqrt.(v_new ./ (1 - βp[2])) .+ eps(eltype(Δ))) * η
  return Δ_new
end

end


text:
# module SQLite_Octo.SQL

function arrange(::Type{DefaultArrangement}, io::IO, q::QueryBuilders.Queryable)
    write(io, QueryBuilders.colored_repr(q), "\n")
    write(io, string(SQL.query(q)))
end


text:
B_data = [ -2.5         0.5          0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   5.26957  -2.45701   -0.812567   0.0        0.0         0.0         0.0        0.0         0.0         0.0        0.0         0.0          0.0        0.0         0.0          0.0        0.0        0.0          0.0          0.0
1.0        -3.0          0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   5.26957  -2.45701   -0.812567   0.0        0.0         0.0         0.0        0.0         0.0         0.0        0.0         0.0          0.0        0.0         0.0          0.0        0.0        0.0          0.0          0.0
0.0         0.0         -2.5   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0  -0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   2.0       0.0        0.0        0.0        0.0         0.0         0.0        0.0         0.0         0.728864  -0.283275    0.0544112    0.0        0.0         0.0          0.0        0.0        0.0          0.0          0.0
0.0         0.0          0.0  -2.5  -0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0  -0.0  -0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0       2.0        0.0        0.0        0.0         0.0         0.0        0.0         0.0         1.05443   -0.549114   -0.00531726   0.0        0.0         0.0          0.0        0.0        0.0          0.0          0.0
0.0         0.0          0.0   0.0  -2.5   0.0   0.0   0.0   0.0   0.0   0.0   0.0  -0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0       0.0        2.0        0.0        0.0         0.0         0.0        0.0         0.0         0.564472  -0.211292    0.14682      0.0        0.0         0.0          0.0        0.0        0.0          0.0          0.0
0.0         0.0          0.0   0.0   0.0  -2.5   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0  -0.0   0.0   0.0   0.0   0.0   0.0       0.0        0.0        2.0        0.0         0.0         0.0        0.0         0.0         0.0        0.0         0.0          0.728864  -0.283275    0.0544112    0.0        0.0        0.0          0.0          0.0
0.0         0.0          0.0   0.0   0.0   0.0  -2.5  -0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0  -0.0  -0.0   0.0   0.0   0.0   0.0       0.0        0.0        0.0        2.0         0.0         0.0        0.0         0.0         0.0        0.0         0.0          1.05443   -0.549114   -0.00531726   0.0        0.0        0.0          0.0          0.0
0.0         0.0          0.0   0.0   0.0   0.0   0.0  -2.5   0.0   0.0   0.0   0.0   0.0   0.0   0.0  -0.0   0.0   0.0   0.0   0.0   0.0       0.0        0.0        0.0        0.0         2.0         0.0        0.0         0.0         0.0        0.0         0.0          0.564472  -0.211292    0.14682      0.0        0.0        0.0          0.0          0.0
0.0         0.0          0.0   0.0   0.0   0.0   0.0   0.0  -2.5   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0  -0.0   0.0   0.0       0.0        0.0        0.0        0.0         0.0         2.0        0.0         0.0         0.0        0.0         0.0          0.0        0.0         0.0          0.728864  -0.283275   0.0544112    0.0          0.0
0.0         0.0          0.0   0.0   0.0   0.0   0.0   0.0   0.0  -2.5  -0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0  -0.0  -0.0   0.0       0.0        0.0        0.0        0.0         0.0         0.0        2.0         0.0         0.0        0.0         0.0          0.0        0.0         0.0          1.05443   -0.549114  -0.00531726   0.0          0.0
0.0         0.0          0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0  -2.5   0.0   0.0   0.0   0.0   0.0   0.0   0.0  -0.0   0.0   0.0       0.0        0.0        0.0        0.0         0.0         0.0        0.0         2.0         0.0        0.0         0.0          0.0        0.0         0.0          0.564472  -0.211292   0.14682      0.0          0.0
0.0         0.0          0.0  -0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0  -2.5   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   2.91546  -1.1331     0.217645   0.0        0.0         0.0         0.0        0.0         0.0         0.5        0.0         0.0          0.0        0.0         0.0          0.0        0.0        0.0          0.0          0.0
0.0         0.0          0.0  -0.0  -0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0  -2.5  -0.0   0.0   0.0   0.0   0.0   0.0   0.0   4.21772  -2.19645   -0.021269   0.0        0.0         0.0         0.0        0.0         0.0         0.0        0.5         0.0          0.0        0.0         0.0          0.0        0.0        0.0          0.0          0.0
0.0         0.0          0.0  -0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0  -2.5   0.0   0.0   0.0   0.0   0.0   0.0   2.25789  -0.845166   0.587279   0.0        0.0         0.0         0.0        0.0         0.0         0.0        0.0         0.5          0.0        0.0         0.0          0.0        0.0        0.0          0.0          0.0
0.0         0.0          0.0   0.0   0.0   0.0  -0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0  -2.5   0.0   0.0   0.0   0.0   0.0   0.0       0.0        0.0        2.91546   -1.1331      0.217645    0.0        0.0         0.0         0.0        0.0         0.0          0.5        0.0         0.0          0.0        0.0        0.0          0.0          0.0
0.0         0.0          0.0   0.0   0.0   0.0  -0.0  -0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0  -2.5  -0.0   0.0   0.0   0.0   0.0       0.0        0.0        4.21772   -2.19645    -0.021269    0.0        0.0         0.0         0.0        0.0         0.0          0.0        0.5         0.0          0.0        0.0        0.0          0.0          0.0
0.0         0.0          0.0   0.0   0.0   0.0  -0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0  -2.5   0.0   0.0   0.0   0.0       0.0        0.0        2.25789   -0.845166    0.587279    0.0        0.0         0.0         0.0        0.0         0.0          0.0        0.0         0.5          0.0        0.0        0.0          0.0          0.0
0.0         0.0          0.0   0.0   0.0   0.0   0.0   0.0   0.0  -0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0  -2.5   0.0   0.0   0.0       0.0        0.0        0.0        0.0         0.0         2.91546   -1.1331      0.217645    0.0        0.0         0.0          0.0        0.0         0.0          0.5        0.0        0.0          0.0          0.0
0.0         0.0          0.0   0.0   0.0   0.0   0.0   0.0   0.0  -0.0  -0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0  -2.5  -0.0   0.0       0.0        0.0        0.0        0.0         0.0         4.21772   -2.19645    -0.021269    0.0        0.0         0.0          0.0        0.0         0.0          0.0        0.5        0.0          0.0          0.0
0.0         0.0          0.0   0.0   0.0   0.0   0.0   0.0   0.0  -0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0  -2.5   0.0       0.0        0.0        0.0        0.0         0.0         2.25789   -0.845166    0.587279    0.0        0.0         0.0          0.0        0.0         0.0          0.0        0.0        0.5          0.0          0.0
0.0         0.0          1.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0  -0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0  -3.12854   0.0        0.0        2.97348   -1.38642    -0.458509    0.0        0.0         0.0         1.45773   -0.56655     0.108822     0.0        0.0         0.0          0.0        0.0        0.0          0.0          0.0
0.0         0.0          0.0   1.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0  -0.0  -0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0      -3.12854   -1.16909    6.05379   -2.82266    -0.933492    0.0        0.0         0.0         2.10886   -1.09823    -0.0106345    0.0        0.0         0.0          0.0        0.0        0.0          0.0          0.0
0.0         0.0          0.0   0.0   1.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0  -0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0       1.16909   -3.12854   -0.106837   0.0498141   0.0164742   0.0        0.0         0.0         1.12894   -0.422583    0.29364      0.0        0.0         0.0          0.0        0.0        0.0          0.0          0.0
0.0         0.0          0.0   0.0   0.0   1.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0  -0.0   0.0   0.0   0.0   0.0   0.0       0.0        0.0       -3.12854    0.0         0.0         2.97348   -1.38642    -0.458509    0.0        0.0         0.0          1.45773   -0.56655     0.108822     0.0        0.0        0.0          0.0          0.0
0.0         0.0          0.0   0.0   0.0   0.0   1.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0  -0.0  -0.0   0.0   0.0   0.0   0.0       0.0        0.0        0.0       -3.12854    -1.16909     6.05379   -2.82266    -0.933492    0.0        0.0         0.0          2.10886   -1.09823    -0.0106345    0.0        0.0        0.0          0.0          0.0
0.0         0.0          0.0   0.0   0.0   0.0   0.0   1.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0  -0.0   0.0   0.0   0.0   0.0   0.0       0.0        0.0        0.0        1.16909    -3.12854    -0.106837   0.0498141   0.0164742   0.0        0.0         0.0          1.12894   -0.422583    0.29364      0.0        0.0        0.0          0.0          0.0
0.0         0.0          0.0   0.0   0.0   0.0   0.0   0.0   1.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0  -0.0   0.0   0.0       0.0        0.0        0.0        0.0         0.0        -3.12854    0.0         0.0         0.0        0.0         0.0          0.0        0.0         0.0          1.87766   -0.762349   0.0440691    0.164213     0.804952
0.0         0.0          0.0   0.0   0.0   0.0   0.0   0.0   0.0   1.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0  -0.0  -0.0   0.0       0.0        0.0        0.0        0.0         0.0         0.0       -3.12854    -1.16909     0.0        0.0         0.0          0.0        0.0         0.0          2.96381   -1.49686   -0.142468     0.334325     1.63883
0.0         0.0          0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   1.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0  -0.0   0.0   0.0       0.0        0.0        0.0        0.0         0.0         0.0        1.16909    -3.12854     0.0        0.0         0.0          0.0        0.0         0.0          1.11386   -0.415548   0.295966    -0.00590016  -0.0289219
1.2281      0.256935     0.0  -0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   1.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   3.46291  -1.38836    0.133228   0.0        0.0         0.0         0.0        0.0         0.0        -4.69282    0.0         0.0          0.0        0.0         0.0          0.0        0.0        0.0          0.0          0.0
2.50033     0.523102     0.0  -0.0  -0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   1.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   5.33229  -2.71614   -0.193136   0.0        0.0         0.0         0.0        0.0         0.0         0.0       -4.69282    -1.75364      0.0        0.0         0.0          0.0        0.0        0.0          0.0          0.0
-0.0441258  -0.00923168   0.0  -0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   1.0   0.0   0.0   0.0   0.0   0.0   0.0   2.23822  -0.835995   0.590313   0.0        0.0         0.0         0.0        0.0         0.0         0.0        1.75364    -4.69282      0.0        0.0         0.0          0.0        0.0        0.0          0.0          0.0
0.0         0.0          0.0   0.0   0.0   0.0  -0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   1.0   0.0   0.0   0.0   0.0   0.0   0.0       0.0        0.0        2.91546   -1.1331      0.217645    0.0        0.0         0.0         4.46021   -2.07963    -0.687763    -4.69282    0.0         0.0          0.0        0.0        0.0          0.0          0.0
0.0         0.0          0.0   0.0   0.0   0.0  -0.0  -0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   1.0   0.0   0.0   0.0   0.0   0.0       0.0        0.0        4.21772   -2.19645    -0.021269    0.0        0.0         0.0         9.08068   -4.23399    -1.40024      0.0       -4.69282    -1.75364      0.0        0.0        0.0          0.0          0.0
0.0         0.0          0.0   0.0   0.0   0.0  -0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   1.0   0.0   0.0   0.0   0.0       0.0        0.0        2.25789   -0.845166    0.587279    0.0        0.0         0.0        -0.160255   0.0747212   0.0247113    0.0        1.75364    -4.69282      0.0        0.0        0.0          0.0          0.0
0.0         0.0          0.0   0.0   0.0   0.0   0.0   0.0   0.0  -0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   1.0   0.0   0.0   0.0       0.0        0.0        0.0        0.0         0.0         2.91546   -1.1331      0.217645    0.0        0.0         0.0          4.46021   -2.07963    -0.687763    -4.69282    0.0        0.0          0.0          0.0
0.0         0.0          0.0   0.0   0.0   0.0   0.0   0.0   0.0  -0.0  -0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   1.0   0.0   0.0       0.0        0.0        0.0        0.0         0.0         4.21772   -2.19645    -0.021269    0.0        0.0         0.0          9.08068   -4.23399    -1.40024      0.0       -4.69282   -1.75364      0.0          0.0
0.0         0.0          0.0   0.0   0.0   0.0   0.0   0.0   0.0  -0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   1.0   0.0       0.0        0.0        0.0        0.0         0.0         2.25789   -0.845166    0.587279    0.0        0.0         0.0         -0.160255   0.0747212   0.0247113    0.0        1.75364   -4.69282      0.0          0.0
0.0         0.0          0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0       0.0        0.0        0.0        0.0         0.0         0.0        0.0         0.0         0.0        0.0         0.0          0.0        0.0         0.0          1.31739   -0.614252  -0.203142    -2.5          2.0
0.0         0.0          0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0       0.0        0.0        0.0        0.0         0.0         0.0        0.0         0.0         0.0        0.0         0.0          0.0        0.0         0.0          2.63479   -1.2285    -0.406283     1.0         -2.0]


text:
@testset "Data informed compression - Burgers example" begin
    n = 1000 # spatial discretization
    using DifferentialEquations, LinearAlgebra, SparseArrays, LowRankIntegrators
    m = 10

    r = 15 # approximation rank
    l = π # length of spatial domain
    Δx = l/n # step size
    dt = 10e-3
    x_range = Δx/2:Δx:l-Δx/2 # uniform grid
    t_range = 0:dt:1.0

    # uncertainty realizations
    σ = [0.5,0.5]
    ξs = [(ξ_1,ξ_2) for ξ_1 in range(-1,1,length=m), ξ_2 in range(-1,1,length=m)];

    # generate coefficient matrices and store as global variables
    # boundary conditions
    left(i) = i > 1 ? i - 1 : n
    right(i) = i < n ? i + 1 : 1

    # discretized diff operators
    # laplacian (times viscosity)
    Δ = spzeros(n, n)
    ν = 0.005
    for i in 1:n
        Δ[i,left(i)] = ν/Δx^2
        Δ[i,i] = -2ν/Δx^2
        Δ[i,right(i)] = ν/Δx^2
    end

    # gradient
    ∇ = spzeros(n, n)
    for i in 1:n
        ∇[i,left(i)] = -1/2/Δx
        ∇[i,right(i)] = 1/2/Δx
    end

    # generate the data used for comparison
    ub(x) = 0.5*(exp.(cos.(x)) .- 1.5).*sin.(x .+ 2π*0.37) # deterministic initial condition
    uprime(x,ξ,σ) = σ[1]*ξ[1]*sin.(2π*x) .+ σ[2]*ξ[2]*sin.(3π*x) # stochastic fluctuation

    function burgers(ρ, (Δ,∇), t)
        return Δ*ρ - (∇*ρ) .* ρ
    end
    function burgers!(dρ, ρ, (∇,Δ,C,D), t)
        mul!(C, ∇, ρ)
        mul!(dρ, Δ, ρ)
        D .= C .* ρ
        dρ .-= D
    end
    C, D = ones(n), ones(n)
    true_sols = [zeros(n,m^2) for i in 1:length(t_range)]
    ode_prob = ODEProblem(burgers!, ones(n), (0.0, 1.0), (∇,Δ,C,D))
    for (i,ξ) in enumerate(ξs)
        println(i)
        _prob = remake(ode_prob, u0 = ub(x_range) + uprime(x_range, ξ, σ))
        _sol = Array(DifferentialEquations.solve(_prob, saveat=t_range))
        for k in 1:length(t_range)
            true_sols[k][:,i] .= _sol[:,k]
        end
    end

    # Greedy: data_informed
    X0 = truncated_svd(hcat(true_sols[1], true_sols[2]), 15)
    U0 = X0.U
    Z0 = true_sols[1]'*U0
    function interpolate_data(t, data, t_range, dt)
        idx = min(floor(Int64, t/dt) + 1, length(t_range))
        return data[idx]
    end

    FZ(Z,U,t) = Matrix(burgers(TwoFactorRepresentation(U,Z), (Δ,∇),t)' * U)
    data_informed_prob = MatrixHybridProblem(t -> interpolate_data(t, true_sols, t_range, dt), FZ, TwoFactorRepresentation(U0, Z0), (0.0, 1.0))
    data_informed_sol = LowRankIntegrators.solve(data_informed_prob, GreedyIntegrator(), dt)
    @test norm(true_sols[end] - data_informed_sol.Y[end])/norm(true_sols[end]) <= 0.1
end


text:
using BenchmarkEnvironments
using Test
using Distributions
using DecisionMakingEnvironments

@testset "Simple Chain Tests" begin
    prob = simple_chain(3; stochastic=false, failchance=0.1, randomize=false)
    @test typeof(prob) <: MDP
    @test length(prob.A) == 2
    @test eltype(prob.A) <: Int
    @test length(prob.S) == 3
    @test eltype(prob.S) <: Int
    @test prob.d0() isa Int
    @test prob.d0() == 1
    @test prob.p(prob.d0(),2) isa Int
    @test prob.p(1,2) == 2
    @test prob.p(3,2) == 1
    @test prob.r(1,2,1) isa Float64
    @test prob.r(1,2,1) == -1.0
    @test prob.γ(prob.d0(),2,1) isa Float64
    @test prob.γ(3,1,2) == 1.0
    @test prob.γ(3,2,1) == 0.0
    meta = meta_information(prob)
    @test meta[:minreturn] isa Float64
    @test meta[:minreward] == -1
    @test meta[:maxreturn] == -3
    @test meta[:minhorizon] == 3
    @test meta[:maxhorizon] == Inf
    prob = simple_chain(3, stochastic=true)
    @test prob.p(1,2) isa Int
end

@testset "Simple Chain Finitetime Tests" begin
    prob = simple_chain_finitetime(3, stochastic=false, droptime=false)
    @test typeof(prob) <: SequentialProblem
    maxT = 3*20
    @test length(prob.A) == 2
    @test eltype(prob.A) <: Int
    @test length(prob.S) == 2
    @test length(prob.S[1]) == maxT
    @test length(prob.S[2]) == 3
    @test eltype(prob.S[1]) <: Int
    @test eltype(prob.S[2]) <: Int
    s0, x = prob.d0()
    @test s0 isa Tuple{Int,Int}
    @test s0[1] isa Int
    @test s0[2] isa Int
    @test x == s0
    @test s0[1] == 1
    @test s0[2] == 1
    s1, x, r, γ = sample(prob, s0, 2)

    @test s1 isa Tuple{Int,Int}
    @test x == s1

    prob = simple_chain_finitetime(3, stochastic=false, droptime=true)
    s1, x, r, γ = sample(prob, s0, 2)
    @test s1 isa Tuple{Int,Int}
    @test x isa Int
    @test x == s1[1]

    meta = meta_information(prob)
    @test meta[:minreturn] isa Float64
    @test meta[:minreturn] == -maxT
    @test meta[:minreward] == -1
    @test meta[:maxreward] == -1
    @test meta[:maxreturn] == -3
    @test meta[:minhorizon] == 3
    @test meta[:maxhorizon] == maxT
end


text:
"""
Algorithm for calculating the (x,y) coordinates for
        positions of nodes in decision trees
"""
function positions(tree::Node)

        # convert tree to tabular form, and add position columns
        tree_tab = tree_to_array(tree)
        tree_tab_xy = hcat((tree_tab),zeros(size(tree_tab)[1],2))

        depth = maximum(tree_tab[:,7]) + 1
        nleaf = sum(tree_tab[:,3])
        y_depths = collect(1:-1/(depth-1):0)

        # position of leaf nodes
        tree_tab_xy[tree_tab[:,3] .== true,9] = collect(0.0:1/(nleaf-1):1.0)
        tree_tab_xy[tree_tab[:,3] .== true,10] .= 0.0

        for i in depth:-1:1
                nodes_at_depth_i = tree_tab_xy[tree_tab_xy[:,7] .== (i-1),:]
                for j in 1:size(nodes_at_depth_i)[1]
                        if nodes_at_depth_i[j,3] == false
                                xpos = Statistics.mean(tree_tab_xy[tree_tab_xy[:,2] .== nodes_at_depth_i[j,1],9])
                                ypos = y_depths[i]
                                tree_tab_xy[tree_tab_xy[:,1] .== nodes_at_depth_i[j,1],9] .= xpos
                                tree_tab_xy[tree_tab_xy[:,1] .== nodes_at_depth_i[j,1],10] .= ypos
                        end
                end
        end

        # rescale
        tree_tab_xy[:,9] = tree_tab_xy[:,9] .* 0.9 .+ 0.05
        tree_tab_xy[:,10] = tree_tab_xy[:,10] .* 0.9 .+ 0.05
        # return
        return(tree_tab_xy)
end

"""
Algorithm for
"""
function lines(tree_tab_xy)
        xpos = []
        ypos = []
        for i in 1:size(tree_tab_xy)[1]
                # check not root
                if (tree_tab_xy[i,2] != -1)
                        x = reshape(tree_tab_xy[i,[9,10]],(2))
                        push!(xpos,x)
                        y = reshape(tree_tab_xy[tree_tab_xy[:,1] .== tree_tab_xy[i,2],[9,10]],(2))
                        push!(ypos,y)
                end
        end
        return(xpos,ypos)
end

"""
Add
"""
function add_plot_text(tree_tab_xy)
        txt = repeat(["."],size(tree_tab_xy)[1])
        mskl = convert(Array{Union{Bool},1},tree_tab_xy[:,3] .== true)
        txt[mskl] .= string.(round.(tree_tab_xy[mskl,4],digits=1))
        mskn = convert(Array{Union{Bool},1},tree_tab_xy[:,3] .== false)
        txt[mskn] .= "X" .* string.(tree_tab_xy[mskn,5]) .* " < " .*
                        string.(round.(tree_tab_xy[mskn,6],digits=1)) .*
                        "\nn = " .* string.(tree_tab_xy[mskn,8])
        txt = reshape(txt,(length(txt),1))
        tree_tab_xy = hcat((tree_tab_xy),txt)
        return(tree_tab_xy)
end

"""
Plot a rectangle
"""
function rectangle(w, h, x, y)
        # b = bottom, t = top, l = left, r = right
        bl = (x-w/2,y-h/2)
        br = (x+w/2,y-h/2)
        tr = (x+w/2,y+h/2)
        tl = (x-w/2,y+h/2)
        Plots.Shape([bl,br,tr,tl,bl])
end

"""
Plot a tree
"""
function plot(tree::Tree;split_xsize=1,split_ysize=1,leaf_size=1)
        Plots.pyplot()
        points_xy = positions(tree.tree)
        lines_xy = lines(points_xy)
        points_xy = add_plot_text(points_xy)

        mshape = repeat([:circle],sum(points_xy[:,3]))
        mcolor = repeat([Plots.RGB(230/255,230/255,250/255)],size(points_xy)[1])
        mcolor[points_xy[:,3] .== true] .= Plots.RGB(245/255,222/255,179/255)

        p = Plots.plot()
        # plot lines
        for i in 1:(size(points_xy)[1]-1)
                Plots.plot!(p,[lines_xy[1][i][1],lines_xy[2][i][1]],[lines_xy[1][i][2],lines_xy[2][i][2]],
                linecolor=:black,
                linewidth=3)
        end

        xsize = split_xsize*0.1
        ysize = split_ysize*0.1
        for i in 1:size(points_xy)[1]
                if points_xy[i,3] == false
                        Plots.plot!(p,
                                rectangle(xsize,ysize,
                                points_xy[i,9],points_xy[i,10]),
                                markerstrokealpha = 0.2,
                                linealpha = 1.0,
                                colour=Plots.RGB(230/255,230/255,250/255),
                                annotations=(points_xy[i,9],points_xy[i,10],
                                Plots.text.(points_xy[i,11],10)))
                end
        end

        leafm = convert(Array{Union{Bool},1},points_xy[:,3] .== true)
        Plots.scatter!(p,points_xy[leafm,9],points_xy[leafm,10],
                legend=false,axis=false,
                  markershape=mshape,
                  grid = false,
                  markersize=8*leaf_size,
                  xlims=(-0.05,1.05),
                  ylims=(-0.06,1.06),
                  markercolor=mcolor[leafm],
                  markerstrokealpha=0,
                  annotations=(points_xy[leafm,9],points_xy[leafm,10],
                  Plots.text.(points_xy[leafm,11],10)))

        Plots.annotate!(p,[(points_xy[1,9]-0.16,points_xy[1,10]-0.1,"True")])
        Plots.annotate!(p,[(points_xy[1,9]+0.16,points_xy[1,10]-0.1,"False")])
        display(p)
end


text:
# This file was generated, do not modify it. # hide
fit!(classif)
ŷ = MLJ.predict(classif, X2)
ŷ[1:3]

max_issues_repo_name: alan-turing-institute/MLJTutorials

max_forks_repo_name: alan-turing-institute/MLJTutorials


text:
using CGP
using Logging
using Test

CGP.Config.init("cfg/test.yaml")

@info("Chromosome tests")
include("test/chromosome.jl")
@info("Mutation tests")
include("test/mutation.jl")
@info("Crossover tests")
include("test/crossover.jl")
@info("Distance tests")
include("test/distance.jl")
@info("Evolution tests")
include("test/ea.jl")
@info("Function tests")
include("test/functions.jl")


text:
module Optimize

using LinearAlgebra
using ProximalOperators

abstract type AbstractOptimizer end;
abstract type AbstractSubspaceOptimizer end;

# Pareto
function evaluate_pareto!(current_parameter, tmp_parameter, fg::Function, args...)
    if fg(tmp_parameter, args...) < fg(current_parameter, args...)
        current_parameter .= tmp_parameter
        return true
    else
        return false
    end
end

# Pareto
export evaluate_pareto!

include("./strridge.jl")
include("./admm.jl")
include("./sr3.jl")

#Nullspace for implicit sindy
include("./adm.jl")

export init, init!, fit!, set_threshold!, get_threshold
export STRRidge, ADMM, SR3
export ADM

end


text:
module FieldsTestsAll

using Test

include("FieldsMocks.jl")

include("../CellValuesTests/CellValuesMocks.jl")

include("CellFieldsMocks.jl")

@testset "FieldValues" begin include("FieldValuesTests.jl") end

@testset "FieldsMocks" begin include("FieldsMocksTests.jl") end

@testset "Fields" begin include("FieldsTests.jl") end

@testset "FieldsOperations" begin include("FieldsOperationsTests.jl") end

@testset "AnalyticalFields" begin include("AnalyticalFieldsTests.jl") end

@testset "CellFieldsMocks" begin include("CellFieldsMocksTests.jl") end

@testset "CellFieldsOperations" begin include("CellFieldsOperationsTests.jl") end

@testset "ConstantCellFields" begin include("ConstantCellFieldsTests.jl") end

end # module


text:
//version 1.0.1
import HTTP.URIs: escapeuri

dcd = "http://foo bar/"
enc = escapeuri(dcd)

println(dcd, " => ", enc)

max_stars_repo_name: ethansaxenian/RosettaDecode

max_issues_repo_name: ethansaxenian/RosettaDecode

max_forks_repo_name: ethansaxenian/RosettaDecode


text:
read_data(fn::AbstractString) = vec(readdlm(fn, skipstart=1))
read_cpts(fn::AbstractString) = vec([0; readdlm(fn, Int, skipstart=1)])

dir = "Test_Files"

comp_handler(r::Test.Success) = true
comp_handler(r::Test.Failure) = false
comp_handler(r::Test.Error) = rethrow(r)

function test_cpts(r_cpts, cpts)
    Test.with_handler(comp_handler) do
        if @test r_cpts == cpts
            println("\tSuccess!")
        else
            println("Fail:")
            println("\tR Changepoints: $(r_cpts)")
            println("\tJulia Changepoints: $(cpts)")
        end
    end
end

# Normal mean change

println("Test Normal mean change...")
data = read_data("$(dir)/Normal_change_in_mean_data")
r_cpts = read_cpts("$(dir)/Normal_change_in_mean_cpts")
cpts, cost = @PELT data Normal(?, 1.0) 2*log(length(data))
test_cpts(r_cpts, cpts)

# Normal var change
println("Test Normal variance change...")
data = read_data("$(dir)/Normal_change_in_var_data")
r_cpts = read_cpts("$(dir)/Normal_change_in_var_cpts")
cpts, cost = @PELT data Normal(1.0, ?) 2*log(length(data))
test_cpts(r_cpts, cpts)

# Normal meanvar change
println("Test Normal mean and variance chaange...")
data = read_data("$(dir)/Normal_change_in_meanvar_data")
r_cpts = read_cpts("$(dir)/Normal_change_in_meanvar_cpts")
cpts, cost = @PELT data Normal(?, ?) 4*log(length(data))
test_cpts(r_cpts, cpts)

# Poisson change
println("Test Poisson change...")
data = read_data("$(dir)/Poisson_data")
r_cpts = read_cpts("$(dir)/Poisson_cpts")
cpts, cost = @PELT data Poisson(?) 2*log(length(data))
test_cpts(r_cpts, cpts)

# Exponential change
println("Test Exponential  change...")
data = read_data("$(dir)/Exponential_data")
r_cpts = read_cpts("$(dir)/Exponential_change_in_mean_cpts")
cpts, cost = @PELT data Exponential(?) 2*log(length(data))
test_cpts(r_cpts, cpts)

# Gamma rate changes
println("Test Gamma rate change...")
data = read_data("$(dir)/Gamma_data")
r_cpts = read_cpts("$(dir)/Gamma_cpts")
cpts, cost = @PELT data Gamma(1.0,?) 2*log(length(data))
test_cpts(r_cpts, cpts)

println("Test Nonparametric change...")
data = read_data("$(dir)/Nonparametric_data")
r_cpts = read_cpts("$(dir)/Nonparametric_cpts")
cpts, cost = @PELT data Nonparametric(10) 4*log(length(data))
test_cpts(r_cpts, cpts)


text:
using PolyChaos

function myquad(N::Int64,rec::Function,γ::Float64)
    α, β = rec(N)
    n, w = gauss(N,α,β)
    return n, γ*w
end

N = 10
γ = 0.5
quads = [ n->myquad(n,rm_chebyshev1,γ); n->myquad(n,rm_legendre,1-γ) ]

α, β = mcdiscretization(N,quads;Nmax=300,ε=1e-7,gaussquad=true)