text:
# AUTO GENERATED FILE - DO NOT EDIT

export dash_graph2d

"""
    dash_graph2d(;kwargs...)

A Graph2D component.

Keyword arguments:
- `id` (String; required): The ID used to identify this component in Dash callbacks.
- `key` (String; optional): The key used to identify this component in React
- `graphData` (Dict; required): Graph data structure. Prop which is provided by user.
Can also be used to apply incremental updates. Format {nodes:{}, links:{}}
- `nodeId` (String; optional): Node object accessor attribute for unique node id (used in link objects source/target).
- `linkSource` (String; optional): Link object accessor attribute referring to id of source node.
- `linkTarget` (String; optional): Link object accessor attribute referring to id of target node.
- `backgroundColor` (String; optional): Getter/setter for the canvas background color, default transparent
- `nodeRelSize` (Real; optional): Ratio of node circle area (square px) [2D] or sphere volume (cubic px) [3D] per value unit.
- `nodeIconRelSize` (Real; optional): controls nodeIcon size
- `nodeImgRelSize` (Real; optional): controls nodeImg size
- `nodeLabel` (String; optional): Node object accessor function or attribute for name (shown in label). Supports plain text or HTML content (except in VR).
2D, 3D and VR
- `nodeVal` (Real | String; optional): Ratio of node circle area (square px) [2D] or sphere volume (cubic px) [3D] per value unit.
- `nodeCoordinates` (String | Array of Reals; optional): Ratio of node circle area (square px) [2D] or sphere volume (cubic px) [3D] per value unit.
- `nodeDesc` (String; optional): For VR only. Node object accessor function or attribute for description (shown under label).
- `nodeColor` (String; optional): The node attribute whose value should be used for coloring nodes
- `nodeAutoColorBy` (String; optional): Node object accessor function or attribute to automatically group colors by. Only affects nodes without a color attribute.
- `nodeTextColor` (String; optional): Node text color
- `nodeTextAutoColor` (Bool; optional): Automatically color node text with inverse of backgroundColor
- `nodeOpacity` (Real; optional): Nodes sphere opacity, between [0,1]. 3D, VR, AR
- `nodeResolution` (Real; optional): Geometric resolution of each node's sphere, expressed in how many slice segments to divide the circumference. Higher values yield smoother spheres. Only applicable to 3D modes.
3D, VR, AR
- `linkLabel` (String; optional): Link object accessor function or attribute for name (shown in label). Supports plain text or HTML content (except in VR).
- `linkDesc` (String; optional): For VR only. Link object accessor function or attribute for description (shown under label).
- `linkColor` (String; optional): String giving link color
- `linkAutoColor` (Bool; optional): Automatically color link with inverse of background color
- `linkAutoColorBy` (String; optional): Link object accessor function or attribute to automatically group colors by. Only affects links without a color attribute.
- `linkOpacity` (Real; optional): Line opacity of links, between [0,1]. 3D, VR, AR
- `linkLineDash` (Real | String; optional): Link object accessor function, attribute or number array (e.g. [5, 15]) to determine if a line dash should be applied to this rendered link. Refer to the HTML canvas setLineDash API for example values. Either a falsy value or an empty array will disable dashing.
- `linkWidth` (Real | String; optional): Link object accessor function, attribute or a numeric constant for the link line width.
- `linkResolution` (Real; optional): Geometric resolution of each link 3D line, expressed in how many radial segments to divide the cylinder. Higher values yield smoother cylinders. Applicable only to links with positive width. 3D, VR, AR
- `linkCurvature` (Real; optional): Link object accessor function, attribute or a numeric constant for the curvature radius of the link line. A value of 0 renders a straight line. 1 indicates a radius equal to half of the line length, causing the curve to approximate a semi-circle. For self-referencing links (source equal to target) the curve is represented as a loop around the node, with length proportional to the curvature value.
- `linkDirectionalArrowLength` (Real | String; optional): Link object accessor function, attribute or a numeric constant for the length of the arrow head indicating the link directionality. The arrow is displayed directly over the link line, and points in the direction of source > target. A value of 0 hides the arrow.
- `linkDirectionalArrowColor` (String; optional): Link object accessor function or attribute for the color of the arrow head.
- `linkDirectionalArrowRelPos` (Real | String; optional): Link object accessor function, attribute or a numeric constant for the longitudinal position of the arrow head along the link line, expressed as a ratio between 0 and 1, where 0 indicates immediately next to the source node, 1 next to the target node, and 0.5 right in the middle.
- `linkDirectionalArrowResolution` (Real; optional): Geometric resolution of the arrow head, expressed in how many slice segments to divide the cone base circumference. Higher values yield smoother arrows.
- `linkDirectionalParticles` (Real | String; optional): Link object accessor function, attribute or a numeric constant for the number of particles (small spheres) to display over the link line. The particles are distributed equi-spaced along the line, travel in the direction source > target, and can be used to indicate link directionality.
- `linkDirectionalParticleSpeed` (Real | String; optional): Link object accessor function, attribute or a numeric constant for the directional particles speed, expressed as the ratio of the link length to travel per frame. Values above 0.5 are discouraged.
- `linkDirectionalParticleWidth` (Real | String; optional): Link object accessor function, attribute or a numeric constant for the directional particles width. Values are rounded to the nearest decimal for indexing purposes.
- `linkDirectionalParticleColor` (String; optional): Link object accessor function or attribute for the directional particles color.
- `linkDirectionalParticleResolution` (Real; optional): Geometric resolution of each 3D directional particle, expressed in how many slice segments to divide the circumference. Higher values yield smoother particles.
- `emitParticle` (Dict; optional): An alternative mechanism for generating particles, this method emits a non-cyclical single particle within a specific link. The emitted particle shares the styling (speed, width, color) of the regular particle props. A valid link object that is included in graphData should be passed as a single parameter.
- `rendererConfig` (Dict; optional): Configuration parameters to pass to the ThreeJS WebGLRenderer constructor. This prop only has an effect on component mount. 3D only
- `pauseAnimation` (Bool; optional): Pauses the rendering cycle of the component, effectively freezing the current view and cancelling all user interaction. This method can be used to save performance in circumstances when a static image is sufficient.
- `centerAtZoom` (Dict with Strings as keys and values of type Real; optional): calls centerAt, then zoom. Takes an object with keys "k", "x", "y"
- `zoomToFit` (Array of Reals; optional): Automatically zooms/pans the canvas so that all of the nodes fit inside it. If no nodes are found no action is taken. It accepts two optional arguments: the first defines the duration of the transition (in ms) to animate the canvas motion (default: 0ms). The second argument is the amount of padding (in px) between the edge of the canvas and the outermost node (default: 10px). The third argument specifies a custom node filter: node => <boolean>, which should return a truthy value if the node is to be included. This can be useful for focusing on a portion of the graph. 2D, 3D
- `refresh` (Bool; optional): Redraws all the nodes/links. 3D, VR, AR
- `numDimensions` (Real; optional): Not applicable to 2D mode. Number of dimensions to run the force simulation on. 3D, VR, AR
- `forceEngine` (String; optional): Which force-simulation engine to use (d3 or ngraph).
- `ngraphPhysics` (Dict; optional): Specify custom physics configuration for ngraph, according to its configuration object syntax. Only applicable if using the ngraph simulation engine.
- `warmupTicks` (Real; optional): Number of layout engine cycles to dry-run at ignition before starting to render.
- `cooldownTicks` (Real; optional): How many build-in frames to render before stopping and freezing the layout engine.
- `cooldownTime` (Real; optional): How long (ms) to render for before stopping and freezing the layout engine.
- `fixNodes` (Bool; optional): Whether to fix node coordinates after simulation has cooled
- `linkHoverPrecision` (Real; optional): Whether to display the link label when gazing the link closely (low value) or from far away (high value).
- `zoom` (Array of Reals; optional): Calls zoom() method. ([number], [ms])
- `controlType` (String; optional): Which type of control to use to control the camera on 3D mode. Choice between trackball, orbit or fly.
- `enableZoomPanInteraction` (Bool; optional): Whether to enable zooming and panning user interactions on a 2D canvas.
- `enableNavigationControls` (Bool; optional): Whether to enable the trackball navigation controls used to move the camera using mouse interactions (rotate/zoom/pan).
- `enablePointerInteraction` (Bool; optional): Whether to enable the mouse tracking events. This activates an internal tracker of the canvas mouse position and enables the functionality of object hover/click and tooltip labels, at the cost of performance. If you're looking for maximum gain in your graph performance it's recommended to switch off this property.
- `enableNodeDrag` (Bool; optional): Whether to enable the user interaction to drag nodes by click-dragging. If enabled, every time a node is dragged the simulation is re-heated so the other nodes react to the changes. Only applicable if enablePointerInteraction is true.
- `getGraphBbox` (Bool; optional): Returns the current bounding box of the nodes in the graph, formatted as { x: [<num>, <num>], y: [<num>, <num>], z: [<num>, <num>] }.
If no nodes are found, returns null. Accepts an optional argument to define a custom node filter: node => <boolean>, which should return a truthy value if the node is to be included.
This can be useful to calculate the bounding box of a portion of the graph.
Bounding box is saved as the graphBbox prop
- `heightRatio` (Real; optional): height of component as proportion of container
- `size` (Dict; optional): provided react-sizeme. Contains an object with "width" and "height" attributes
- `active` (Bool; optional): whether or not session is active. Used to enable or disable warning browser dialog when closing
- `useNodeImg` (Bool; optional): Whether or not to use the nodeImg. Overrides nodeIcon
- `nodeImg` (String; optional): The node attribute containing url to image to display for each individual node
- `useNodeIcon` (Bool; optional): Whether or not to use the nodeIcon
- `nodeIcon` (String; optional): The node attribute containing object with icon to display for each individual node.
- `nodeIcon_fontsheets` (Dict; optional): object with keys being fonts (string) and values being CSS sheets
- `linkId` (String; optional): The link attribute containing the unique link id
- `nodeZoomId` (String; optional): id of node to zoom to
- `sortRelsBy1` (String; optional): in zoom view, node attribute to sort relations by first
- `sortRelsBy2` (String; optional): in zoom view, node attribute to sort relations by after first sort
- `sortRoleplayersBy1` (String; optional): in zoom view, node attribute to sort role players by first
- `sortRoleplayersBy2` (String; optional): in zoom view, node attribute to sort role players by after first sort
- `sortRels1Descend` (Bool; optional): sort in descending order?
- `sortRels2Descend` (Bool; optional): sort in descending order?
- `sortRoleplayers1Descend` (Bool; optional): sort in descending order?
- `sortRoleplayers2Descend` (Bool; optional): sort in descending order?
- `nodesSelected` (Array of Dicts; optional): selected (clicked) nodes
- `nodeClicked` (Dict; optional): left-clicked node
- `nodeRightClicked` (Dict; optional): right-clicked node
- `nodeRightClickedViewpointCoordinates` (Dict with Strings as keys and values of type Real; optional): screen coordinates of right-clicked node
- `linkRightClickedViewpointCoordinates` (Dict with Strings as keys and values of type Real; optional)
- `linkRightClicked` (Dict; optional): right-clicked link
- `linksSelected` (Array of Dicts; optional): selected (clicked) links
- `minZoom` (Real; optional): ids of links highlighted due to being dragged
- `maxZoom` (Real; optional)
- `nodeIdsHighlightUser` (Array of Strings; optional): ids of highlighted nodes (through search)
- `nodeIdsInvisibleAuto` (Array of Strings; optional): ids of visible nodes. Not to be supplied by user. Available to allow for saving state
- `nodeIdsInvisibleUser` (Array of Strings; optional): ids of invisible nodes supplied by user as prop
- `linkIdsHighlightUser` (Array of Strings; optional): ids of highlighted links (through search)
- `linkIdsInvisibleAuto` (Array of Strings; optional)
- `linkIdsInvisibleUser` (Array of Strings; optional): ids of visible links
- `externalobject_source` (String; optional): externalobject_source:
- `externalobjectInput` (Real | String | Bool | Array | Dict; optional): externalobject_source:
- `useCoordinates` (Bool; optional): useCoordinates: whether to set nodeCoordinates for node coordinates
- `pixelUnitRatio` (Real; optional): pixelUnitRatio: if node attribute (in some unit of measurement) is used as coordinates, pixel:unit scale
- `showCoordinates` (Bool; optional): showCoordinates: whether or not to show pointer coordinates in hover tooltip (not yet used)
- `invisibleProps` (Array of Strings; optional): node props to hide on hover, in addition to any with prop name prefixed by "__"
- `maxDepth_neighbours_select` (Real; optional): max levels of neighbourhood selection around a node by repeat clicking
- `currentZoomPan` (Dict; optional)
- `updateNeighbours` (Bool; optional)
- `forceRefresh` (Real; optional)
- `n_nodeRightClicks` (Real; optional)
- `n_linkRightClicks` (Real; optional)
"""
function dash_graph2d(; kwargs...)
        available_props = Symbol[:id, :key, :graphData, :nodeId, :linkSource, :linkTarget, :backgroundColor, :nodeRelSize, :nodeIconRelSize, :nodeImgRelSize, :nodeLabel, :nodeVal, :nodeCoordinates, :nodeDesc, :nodeColor, :nodeAutoColorBy, :nodeTextColor, :nodeTextAutoColor, :nodeOpacity, :nodeResolution, :linkLabel, :linkDesc, :linkColor, :linkAutoColor, :linkAutoColorBy, :linkOpacity, :linkLineDash, :linkWidth, :linkResolution, :linkCurvature, :linkDirectionalArrowLength, :linkDirectionalArrowColor, :linkDirectionalArrowRelPos, :linkDirectionalArrowResolution, :linkDirectionalParticles, :linkDirectionalParticleSpeed, :linkDirectionalParticleWidth, :linkDirectionalParticleColor, :linkDirectionalParticleResolution, :emitParticle, :rendererConfig, :pauseAnimation, :centerAtZoom, :zoomToFit, :refresh, :numDimensions, :forceEngine, :ngraphPhysics, :warmupTicks, :cooldownTicks, :cooldownTime, :fixNodes, :linkHoverPrecision, :zoom, :controlType, :enableZoomPanInteraction, :enableNavigationControls, :enablePointerInteraction, :enableNodeDrag, :getGraphBbox, :heightRatio, :size, :active, :useNodeImg, :nodeImg, :useNodeIcon, :nodeIcon, :nodeIcon_fontsheets, :linkId, :nodeZoomId, :sortRelsBy1, :sortRelsBy2, :sortRoleplayersBy1, :sortRoleplayersBy2, :sortRels1Descend, :sortRels2Descend, :sortRoleplayers1Descend, :sortRoleplayers2Descend, :nodesSelected, :nodeClicked, :nodeRightClicked, :nodeRightClickedViewpointCoordinates, :linkRightClickedViewpointCoordinates, :linkRightClicked, :linksSelected, :minZoom, :maxZoom, :nodeIdsHighlightUser, :nodeIdsInvisibleAuto, :nodeIdsInvisibleUser, :linkIdsHighlightUser, :linkIdsInvisibleAuto, :linkIdsInvisibleUser, :externalobject_source, :externalobjectInput, :useCoordinates, :pixelUnitRatio, :showCoordinates, :invisibleProps, :maxDepth_neighbours_select, :currentZoomPan, :updateNeighbours, :forceRefresh, :n_nodeRightClicks, :n_linkRightClicks]
        wild_props = Symbol[]
        return Component("dash_graph2d", "Graph2D", "dash_react_force_graph", available_props, wild_props; kwargs...)
end

max_stars_repo_name: JonThom/dash-react-force-graph

max_issues_repo_name: JonThom/dash-react-force-graph

max_forks_repo_name: JonThom/dash-react-force-graph


text:
using XAM
using BioSequences
using ProgressMeter
using DataFrames
using Serialization
# using Serialization
# using GLMakie
# using StatsBase

#%%

filename_ancient = "../data/AltaiNea.hg19_1000g.1.dq.bam"
filename_modern = "../data/MMS8_HGDP00521_French.paired.qualfilt.rmdup.entropy1.0.sort.bam"
# do_augment_data = false
do_augment_data = true

#%%

# function get_seq_lengths(filename)
#     reader = open(BAM.Reader, filename)
#     progress = ProgressUnknown("Getting sequence lengths for $filename:", spinner = true)
#     Ls = Int64[]
#     record = BAM.Record()
#     while !eof(reader)
#         empty!(record)
#         read!(reader, record)
#         ProgressMeter.next!(progress)
#         push!(Ls, BAM.seqlength(record))
#     end
#     ProgressMeter.finish!(progress)
#     close(reader)
#     return Ls
# end
# # Ls = get_seq_lengths(filename_ancient)

function is_reverse(record::BAM.Record)::Bool
    return !BAM.ispositivestrand(record)
end

function contains_N(seq::LongDNASeq)::Bool
    return !isnothing(findfirst(DNA_N, seq))
end

function has_ACGT(seq::LongDNASeq)::Bool
    return occursin(biore"[A]"dna, seq) &&
           occursin(biore"[C]"dna, seq) &&
           occursin(biore"[G]"dna, seq) &&
           occursin(biore"[T]"dna, seq)
end

function is_specific_chromosome(record::BAM.Record, chromosome)
    if chromosome == ""
        return true
    elseif chromosome == BAM.refname(record)
        return true
    else
        return false
    end
end

function passes_requirements(
    seq::LongDNASeq,
    record::BAM.Record,
    chromosome;
    seqlen = 76,
)::Bool
    return is_specific_chromosome(record, chromosome) &&
           length(seq) == seqlen &&
           has_ACGT(seq) &&
           !contains_N(seq)
end

function get_sequences(
    filename;
    get_forward_sequence = true,
    max_sequences = -1,
    chromosome = "",
)

    # Open a BAM file.
    reader = open(BAM.Reader, filename)

    # Initialize a record, to be reused later
    record = BAM.Record()

    # Prepare vector of sequences
    sequences = LongDNASeq[]

    # Initialize spinner
    progress = ProgressUnknown("Reading $filename:", spinner = true)

    # Iterate over BAM records.
    while !eof(reader)
        empty!(record)
        read!(reader, record)
        ProgressMeter.next!(progress)

        sequence = BAM.sequence(record)
        if get_forward_sequence && is_reverse(record)
            reverse_complement!(sequence)
        end

        if passes_requirements(sequence, record, chromosome)
            push!(sequences, sequence)
        end

        if 0 < max_sequences && max_sequences <= length(sequences)
            break
        end

    end

    ProgressMeter.finish!(progress)
    close(reader)

    return sequences
end

seqs_ancient = get_sequences(filename_ancient; chromosome = "1")
seqs_modern = get_sequences(
    filename_modern;
    chromosome = "chr1",
    max_sequences = length(seqs_ancient),
)

if do_augment_data
    seqs_ancient = [seqs_ancient; reverse_complement.(seqs_ancient)]
    seqs_modern = [seqs_modern; reverse_complement.(seqs_modern)]
end

sequences = [seqs_ancient; seqs_modern]
labels = [
    ones(Int8, length(seqs_ancient))
    zeros(Int8, length(seqs_modern))
]

# hist(
#     Ls,
#     bins = 50,
#     color = :red,
#     strokewidth = 1,
#     strokecolor = :black,
#     normalization = :pdf,
# )

#%%

df_y = DataFrame(y = labels)
df_X = DataFrame(permutedims(hcat(collect.(sequences)...)), :auto)

df = hcat(df_y, df_X)

filename_out = "./df.data"
serialize(filename_out, (df = df,))

ext: jl

max_stars_repo_name: ChristianMichelsen/reference-free

max_issues_repo_name: ChristianMichelsen/reference-free

max_forks_repo_name: ChristianMichelsen/reference-free


text:
# AUTO GENERATED FILE - DO NOT EDIT

export 'feffery'_antdformitem

"""
    'feffery'_antdformitem(;kwargs...)
    'feffery'_antdformitem(children::Any;kwargs...)
    'feffery'_antdformitem(children_maker::Function;kwargs...)

An AntdFormItem component.

Keyword arguments:
- `children` (a list of or a singular dash component, string or number; optional): The content of the tab - will only be displayed if this tab is selected
- `id` (String; optional)
- `className` (String; optional)
- `colon` (Bool; optional)
- `extra` (String; optional)
- `help` (String; optional)
- `hidden` (Bool; optional)
- `label` (String; optional)
- `labelAlign` (a value equal to: 'left', 'right'; optional)
- `labelCol` (optional): . labelCol has the following type: lists containing elements 'span', 'offset'.
Those elements have the following types:
  - `span` (Real; optional)
  - `offset` (Real; optional)
- `loading_state` (optional): . loading_state has the following type: lists containing elements 'is_loading', 'prop_name', 'component_name'.
Those elements have the following types:
  - `is_loading` (Bool; optional): Determines if the component is loading or not
  - `prop_name` (String; optional): Holds which property is loading
  - `component_name` (String; optional): Holds the name of the component that is loading
- `required` (Bool; optional)
- `style` (Dict; optional)
- `tooltip` (String; optional)
- `validateStatus` (a value equal to: 'success', 'warning', 'error', 'validating'; optional)
- `wrapperCol` (optional): . wrapperCol has the following type: lists containing elements 'span', 'offset'.
Those elements have the following types:
  - `span` (Real; optional)
  - `offset` (Real; optional)
"""
function 'feffery'_antdformitem(; kwargs...)
        available_props = Symbol[:children, :id, :className, :colon, :extra, :help, :hidden, :label, :labelAlign, :labelCol, :loading_state, :required, :style, :tooltip, :validateStatus, :wrapperCol]
        wild_props = Symbol[]
        return Component("'feffery'_antdformitem", "AntdFormItem", "feffery_antd_components", available_props, wild_props; kwargs...)
end

'feffery'_antdformitem(children::Any; kwargs...) = 'feffery'_antdformitem(;kwargs..., children = children)
'feffery'_antdformitem(children_maker::Function; kwargs...) = 'feffery'_antdformitem(children_maker(); kwargs...)

max_stars_repo_name: ReilYoung/feffery-antd-components

max_issues_repo_name: ReilYoung/feffery-antd-components

max_forks_repo_name: ReilYoung/feffery-antd-components


text:
# Note that this script can accept some limited command-line arguments, run
# `julia build_tarballs.jl --help` to see a usage message.
using BinaryBuilder, Pkg

name = "Birch"

# Birch's version is `(git describe --long || echo) | sed -E 's/v([0-9]+)-([0-9]+)-g[0-9a-f]+/\1.\2/'`
# (see https://github.com/JuliaPackaging/Yggdrasil/pull/2156#discussion_r528224861)
version = v"1.104"

# Collection of sources required to complete build
sources = [
    GitSource("https://github.com/lawmurray/Birch.git", "25154eac433bdeaf55dffda2432c666659286350"),
]

# Bash recipe for building across all platforms
script = raw"""
# install the driver
cd ${WORKSPACE}/srcdir/Birch/driver/
autoreconf -vi
CPPFLAGS="-I${prefix}/include" ./configure --prefix=${prefix} --build=${MACHTYPE} --host=${target}
make -j${nproc}
make install

# install license
install_license LICENSE
"""

# These are the platforms we will build for by default, unless further
# platforms are passed in on the command line
platforms = expand_cxxstring_abis(supported_platforms())

# GLOB_NOMAGIC is not supported by musl
filter!(p -> libc(p) != "musl", platforms)

# Native support for Windows is not yet provided
filter!(!Sys.iswindows, platforms)

# The products that we will ensure are always built
products = [
    ExecutableProduct("birch", :birch),
]

# Dependencies that must be installed before this package can be built
dependencies = Dependency[
    Dependency("boost_jll"),
    Dependency("LibYAML_jll"),
]

# Build the tarballs, and possibly a `build.jl` as well.
build_tarballs(ARGS, name, version, sources, script, platforms, products, dependencies,
               preferred_gcc_version=v"5")

max_stars_repo_name: waralex/Yggdrasil

max_issues_repo_name: waralex/Yggdrasil

max_forks_repo_name: waralex/Yggdrasil


text:
using BinaryBuilder

name = "Qemu"
version = v"2.12.50"

# Collection of sources required to build libffi
sources = [
    "https://github.com/Keno/qemu.git" =>
    "2ed3b3c2f2c79208b689673a257ab04a6aa984a3",
]

# Bash recipe for building across all platforms
script = raw"""
cd $WORKSPACE/srcdir/qemu
./configure --target-list=x86_64-softmmu --disable-cocoa --prefix=$prefix
echo '#!/bin/true ' > /usr/bin/SetFile
echo '#!/bin/true ' > /usr/bin/Rez
chmod +x /usr/bin/Rez
chmod +x /usr/bin/SetFile
make -j${nproc}
make install
"""

# These are the platforms we will build for by default, unless further
# platforms are passed in on the command line
platforms = [
    # For now, only build for MacOS
    BinaryProvider.MacOS(),
]

# The products that we will ensure are always built
products(prefix) = [
    LibraryProduct(prefix, "x86_64-softmmu/qemu-system-x86_64", :qemu_x86_64)
]

# Dependencies that must be installed before this package can be built
dependencies = [
    # We need Pixman
    "https://github.com/staticfloat/PixmanBuilder/releases/download/v0.34.0-0/build.jl",
    # We need Glib
    "https://github.com/staticfloat/GlibBuilder/releases/download/v2.54.2-2/build.jl",
    # We need Pcre
    "https://github.com/staticfloat/PcreBuilder/releases/download/v8.41-0/build.jl",
    # We need gettext
    "https://github.com/staticfloat/GettextBuilder/releases/download/v0.19.8-0/build.jl",
    # .....which needs libffi
    "https://github.com/staticfloat/libffiBuilder/releases/download/v3.2.1-0/build.jl",
    # .....which needs zlib
    "https://github.com/staticfloat/ZlibBuilder/releases/download/v1.2.11-3/build.jl",
]

# Build the tarballs, and possibly a `build.jl` as well.
build_tarballs(ARGS, name, version, sources, script, platforms, products, dependencies)

max_stars_repo_name: UnofficialJuliaMirror/Keno-QemuBuilder

max_issues_repo_name: UnofficialJuliaMirror/Keno-QemuBuilder

max_forks_repo_name: UnofficialJuliaMirror/Keno-QemuBuilder


text:
import BlockArrays

struct FieldVector{T, M} <: BlockArrays.AbstractBlockVector{T}
    values::M
end
FieldVector{T}(values::M) where {T, M} = FieldVector{T, M}(values)

_values(fv::FieldVector) = getfield(fv, :values)
_parent_values(fv::FieldVector) = map(parent, _values(fv))

BlockArrays.blockaxes(fv::FieldVector) =
    (BlockArrays.BlockRange(1:length(_values(fv))),)
Base.axes(fv::FieldVector) =
    (BlockArrays.blockedrange(map(length ∘ parent, Tuple(_values(fv)))),)

Base.getindex(fv::FieldVector, block::BlockArrays.Block{1}) =
    parent(_values(fv)[block.n...])
Base.getindex(fv::FieldVector, bidx::BlockArrays.BlockIndex{1}) =
    fv[BlockArrays.block(bidx)][bidx.α...]
Base.getindex(fv::FieldVector, i::Integer) =
    getindex(fv, BlockArrays.findblockindex(axes(fv, 1), i))

function Base.setindex!(fv::FieldVector, val, bidx::BlockArrays.BlockIndex{1})
    X = fv[BlockArrays.block(bidx)]
    X[bidx.α...] = val
end
Base.setindex!(fv::FieldVector, val, i::Integer) =
    setindex!(fv, val, BlockArrays.findblockindex(axes(fv, 1), i))

function FieldVector(; kwargs...)
    values = NamedTuple(kwargs)
    T = promote_type(
        map(RecursiveArrayTools.recursive_bottom_eltype, values)...,
    )
    return FieldVector{T}(values)
end

Base.propertynames(fv::FieldVector) = propertynames(_values(fv))
@inline function Base.getproperty(fv::FieldVector, name::Symbol)
    getfield(_values(fv), name)
end

Base.similar(fv::FieldVector{T}) where {T} =
    FieldVector{T}(map(similar, _values(fv)))
Base.similar(fv::FieldVector{T}, ::Type{T}) where {T} =
    FieldVector{T}(map(similar, _values(fv)))
function Base.similar(fv::FieldVector{T}, ::Type{FT}) where {T, FT}
    FieldVector{FT}(
        map(_values(fv)) do x
            Field(DataLayouts.replace_basetype(field_values(x), FT), axes(x))
        end,
    )
end

Base.copy(fv::FieldVector{T}) where {T} = FieldVector{T}(map(copy, _values(fv)))
Base.zero(fv::FieldVector{T}) where {T} = FieldVector{T}(map(zero, _values(fv)))

struct FieldVectorStyle <: Base.Broadcast.AbstractArrayStyle{1} end

Base.Broadcast.BroadcastStyle(::Type{<:FieldVector}) = FieldVectorStyle()

Base.Broadcast.BroadcastStyle(
    fs::FieldVectorStyle,
    as::Base.Broadcast.DefaultArrayStyle{0},
) = fs
Base.Broadcast.BroadcastStyle(
    fs::FieldVectorStyle,
    as::Base.Broadcast.AbstractArrayStyle{0},
) = fs
Base.Broadcast.BroadcastStyle(
    fs::FieldVectorStyle,
    as::Base.Broadcast.DefaultArrayStyle,
) = as
Base.Broadcast.BroadcastStyle(
    fs::FieldVectorStyle,
    as::Base.Broadcast.AbstractArrayStyle,
) = as

function Base.similar(
    bc::Base.Broadcast.Broadcasted{FieldVectorStyle},
    ::Type{T},
) where {T}
    for arg in bc.args
        if arg isa FieldVector ||
           arg isa Base.Broadcast.Broadcasted{FieldVectorStyle}
            return similar(arg, T)
        end
    end
    error("Cannot construct FieldVector")
end

Base.mapreduce(f, op, fv::FieldVector) =
    mapreduce(x -> mapreduce(f, op, x), op, _parent_values(fv))

Base.any(f, fv::FieldVector) = any(x -> any(f, x), _parent_values(fv))
Base.any(f::Function, fv::FieldVector) = # avoid ambiguities
    any(x -> any(f, x), _parent_values(fv))
Base.any(fv::FieldVector) = any(identity, A)

Base.all(f, fv::FieldVector) = all(x -> all(f, x), _parent_values(fv))
Base.all(f::Function, fv::FieldVector) = all(x -> all(f, x), _parent_values(fv))
Base.all(fv::FieldVector) = all(identity, fv)

# TODO: figure out a better way to handle these
# https://github.com/JuliaArrays/BlockArrays.jl/issues/185
LinearAlgebra.ldiv!(
    x::FieldVector,
    A::LinearAlgebra.QRCompactWY,
    b::FieldVector,
) = x .= LinearAlgebra.ldiv!(A, Vector(b))

LinearAlgebra.ldiv!(x::FieldVector, A::LinearAlgebra.LU, b::FieldVector) =
    x .= LinearAlgebra.ldiv!(A, Vector(b))

LinearAlgebra.ldiv!(A::LinearAlgebra.LU, x::FieldVector) =
    x .= LinearAlgebra.ldiv!(A, Vector(x))


text:
abstract type AbstractInitialConditions end

"""
    Elements{T<:AbstractFloat} <: AbstractInitialConditions

Orbital elements of a binary, and mass of a 'outer' body. See [Tutorials](@ref) for units and conventions.

# Fields
- `m::T` : Mass of outer body.
- `P::T` : Period [Days].
- `t0::T` : Initial time of transit [Days].
- `ecosϖ` : Eccentricity vector x-component (eccentricity times cosine of the longitude of periastron)
- `esinϖ` : Eccentricity vector y-component (eccentricity times sine of the longitude of periastron)
- `I::T` : Inclination, as measured from sky-plane [Radians].
- `Ω::T` : Longitude of ascending node, as measured from +x-axis [Radians].
- `a::T` : Orbital semi-major axis [AU].
- `e::T` : Eccentricity.
- `ϖ::T` : Longitude of periastron [Radians].
"""
struct Elements{T<:AbstractFloat} <: AbstractInitialConditions
    m::T
    P::T
    t0::T
    ecosϖ::T
    esinϖ::T
    I::T
    Ω::T
    a::T
    e::T
    ϖ::T
end

"""
    Elements(m,P,t0,ecosϖ,esinϖ,I,Ω)

Main [`Elements`](@ref) constructor. May use keyword arguments, see [Tutorials](@ref).
"""
function Elements(m::T,P::T,t0::T,ecosϖ::T,esinϖ::T,I::T,Ω::T) where T<:Real
    e = sqrt(ecosϖ^2 + esinϖ^2)
    ϖ = atan(esinϖ,ecosϖ)
    Elements(m,P,t0,ecosϖ,esinϖ,I,Ω,0.0,e,ϖ)
end

function Base.show(io::IO, ::MIME"text/plain" ,elems::Elements{T}) where T <: Real
    fields = fieldnames(typeof(elems))
    vals = Dict([fn => getfield(elems,fn) for fn in fields])
    println(io, "Elements{$T}")
    for key in keys(vals)
        println(io,key,": ",vals[key])
    end
    if elems.a == 0.0
        println(io, "Semi-major axis: undefined")
    end
    return
end

"""Allows keyword arguments"""
Elements(;m::T=0.0,P::T=0.0,t0::T=0.0,ecosϖ::T=0.0,esinϖ::T=0.0,I::T=0.0,Ω::T=0.0) where T<:Real = Elements(m,P,t0,ecosϖ,esinϖ,I,Ω)

"""Abstract type for initial conditions specifications."""
abstract type InitialConditions{T} end

"""
    ElementsIC{T<:AbstractFloat} <: InitialConditions{T}

Initial conditions, specified by a hierarchy vector and orbital elements.

# Fields
- `elements::Matrix{T}` : Masses and orbital elements.
- `ϵ::Matrix{T}` : Matrix of Jacobi coordinates
- `amat::Matrix{T}` : 'A' matrix from [Hamers and Portegies Zwart 2016](https://doi.org/10.1093/mnras/stw784).
- `nbody::Int64` : Number of bodies.
- `m::Vector{T}` : Masses of bodies.
- `t0::T` : Initial time [Days].
"""
struct ElementsIC{T<:AbstractFloat} <: InitialConditions{T}
    elements::Matrix{T}
    ϵ::Matrix{T}
    amat::Matrix{T}
    nbody::Int64
    m::Vector{T}
    t0::T
    der::Bool

    function ElementsIC(t0::T, H::Matrix{T}, elements::Matrix{T}; der::Bool=true) where T<:AbstractFloat
        nbody = size(H)[1]
        m = elements[1:nbody, 1]
        A = amatrix(H, m)
        return new{T}(elements, H, A, nbody, m, t0, der)
    end
end
ElementsIC(t0::T, H::Matrix{<:Real}, elements::Matrix{T}) where T<:Real = ElementsIC(t0, T.(H), elements)

"""
    ElementsIC(t0,H,elems)

Collects `Elements` and produces an `ElementsIC` struct.

# Arguments
- `t0::T` : Initial time [Days].
- `H` : Hierarchy specification.
- `elems` : The orbital elements and masses of the system.

------------
There are a number of way to specify the initial conditions. Below we've described the arguments `ElementsIC` takes. Any combination of `H` and `elems` may be used. For a concrete example see [Tutorials](@ref).

# Elements
- `elems...` : A sequence of `Elements{T}`. Elements should be passed in the order they appear in the hierarchy (left to right).
- `elems::Vector{Elements}` : A vector of `Elements`. As above, Elements should be in order.
- `elems::Matrix{T}` : An matrix containing the masses and orbital elements.
- `elems::String` : Name of a file containing the masses and orbital elements.

Each method is simply populating the `ElementsIC.elements` field, which is a `Matrix{T}`.

# Hierarchy
- Number of bodies: `H::Int64`: The system will be given by a 'fully-nested' Keplerian.

`H = 4` corresponds to:
```raw
3        ____|____
        |         |
2    ___|___      d
    |       |
1 __|__     c
 |     |
 a     b
```
- Hierarchy Vector: `H::Vector{Int64}`: The first elements is the number of bodies. Each subsequent is the number of binaries on a level of the hierarchy.

`H = [4,2,1]`. Two binaries on level 1, one on level 2.
```raw
2    ____|____
    |         |
1 __|__     __|__
 |     |   |     |
 a     b   c     d
```
- Full Hierarchy Matrix: `H::Matrix{<:Real}`: Provide the hierarchy matrix, directly.

`H = [-1 1 0 0; 0 0 -1 1; -1 -1 1 1; -1 -1 -1 -1]`. Produces the same system as `H = [4,2,1]`.
"""
function ElementsIC(t0::T, H::Matrix{<:Real}, elems::Elements{T}...) where T<:AbstractFloat
    elements = zeros(T,size(H)[1],7)
    fields = [:m, :P, :t0, :ecosϖ, :esinϖ, :I, :Ω]
    for i in eachindex(elems)
        elements[i,:] .= [getfield(elems[i],f) for f in fields]
    end
    return ElementsIC(t0,T.(H),elements)
end

"""Allows for vector of `Elements` argument."""
ElementsIC(t0::T,H::Matrix{<:Real},elems::Vector{Elements{T}}) where T<:AbstractFloat = ElementsIC(t0,T.(H),elems...)

"""Allow user to pass a file containing orbital elements."""
function ElementsIC(t0::T,H::Matrix{<:Real},elems::String) where T<:AbstractFloat
    elements = T.(readdlm(elems, ',', comments=true)[1:size(H)[1],:])
    return ElementsIC(t0, T.(H), elements)
end

## Let user pass hierarchy vector; dispatch on different elements ##
ElementsIC(t0::T,H::Vector{Int64},elems::Elements{T}...) where T <: AbstractFloat = ElementsIC(t0,hierarchy(H),elems...)
ElementsIC(t0::T,H::Vector{Int64},elems::Vector{Elements{T}}) where T<:AbstractFloat = ElementsIC(t0,hierarchy(H),elems...)
ElementsIC(t0::T,H::Vector{Int64},elems::Matrix{T}) where T<:AbstractFloat = ElementsIC(t0,hierarchy(H),elems)
ElementsIC(t0::T,H::Vector{Int64},elems::String) where T<:AbstractFloat = ElementsIC(t0,hierarchy(H),elems)

## Let user specify only the number of bodies; the hierarchy is filled in as fully-nested; dispatch on different elements ##
ElementsIC(t0::T,H::Int64,elems::Elements{T}...) where T<:AbstractFloat = ElementsIC(t0,[H, ones(Int64,H-1)...],elems...)
ElementsIC(t0::T,H::Int64,elems::Vector{Elements{T}}) where T<:AbstractFloat = ElementsIC(t0,[H, ones(Int64,H-1)...],elems...)
ElementsIC(t0::T,H::Int64,elems::Matrix{T}) where T<:AbstractFloat = ElementsIC(t0,[H, ones(Int64,H-1)...],elems)
ElementsIC(t0::T,H::Int64,elems::String) where T<:AbstractFloat = ElementsIC(t0,[H, ones(Int64, H-1)...],elems)

"""Shows the elements array."""
Base.show(io::IO,::MIME"text/plain",ic::ElementsIC{T}) where {T} = begin
println(io,"ElementsIC{$T}\nOrbital Elements: "); show(io,"text/plain",ic.elements); end;

"""
    CartesianIC{T<:AbstractFloat} <: InitialConditions{T}

Initial conditions, specified by the Cartesian coordinates and masses of each body.

# Fields
- `x::Matrix{T}` : Positions of each body [dimension, body].
- `v::Matrix{T}` : Velocities of each body [dimension, body].
- `m::Vector{T}` : masses of each body.
- `nbody::Int64` : Number of bodies in system.
- `t0::T` : Initial time.
"""
struct CartesianIC{T<:AbstractFloat} <: InitialConditions{T}
    x::Matrix{T}
    v::Matrix{T}
    m::Vector{T}
    nbody::Int64
    t0::T
end

"""Allow user to pass matrix of row-vectors for `CartesianIC`."""
function CartesianIC(t0::T, N::Int64, coords::Matrix{T}) where T<:AbstractFloat
    m = coords[1:N,1]
    x = permutedims(coords[1:N,2:4])
    v = permutedims(coords[1:N,5:7])
    return CartesianIC(x,v,m,N,t0)
end

"""Allow input of Cartesian coordinate file."""
function CartesianIC(t0::T, N::Int64, coordinateFile::String) where T <: AbstractFloat
    coords = readdlm(coordinateFile,',')
    m = coords[1:N,1]
    x = permutedims(coords[1:N,2:4])
    v = permutedims(coords[1:N,5:7])
    return CartesianIC(x,v,m,N,t0)
end

# Include ics source files
const ics = ["kepler","kepler_init","setup_hierarchy","init_nbody"]
for i in ics; include("$(i).jl"); end


text:
module MLTools

##############################################################################
##
## Dependencies
##
##############################################################################

using DataFrames
using Gadfly
set_default_plot_size(15cm, 15cm)
using Colors

##############################################################################
##
## Exported methods and types
##
##############################################################################

export
    # information
	entropy,
	jointEntropy,
    mutualInformation,

	# normalise
    normalise,
    normalise!,

    # polynomial
    polynomial_features,

    # accuracy
    confusion_matrix,
    plot_confusion_matrix,
    print_binary_accuracy,

    # roc
    plot_ROC_curve

#=
    TODO
    kFoldClassPropnPrep,
    kFoldClassPropnArrays,
    shufflePartition2,
    shufflePartition3,
    propnPartition2,
=#

##############################################################################
##
## Load source files
##
##############################################################################

include("normalise.jl")
include("information.jl")
include("polynomial.jl")
include("accuracy.jl")
include("roc.jl")
include("crossvalidation.jl")

end # module


text:
include("imports.jl")  #src
# ## Testing `base.jl`
# Since we haven't defined any items or real transforms
# yet, we test the interface with test versions of each.

struct TestItem <: Item
    data::Any
end

struct Add <: Transform
    n::Int
end

apply(tfm::Add, item::TestItem; randstate=getrandstate(tfm)) =
    TestItem(item.data + tfm.n)

compose(add1::Add, add2::Add) = Add(add1.n + add2.n)

# Now we can perform some sanity checks for the basic interface.

@testset ExtendedTestSet "Basic interface" begin
    tfm = Add(0)
    item = TestItem(10)

    @test itemdata(item) == 10
    @test itemdata(apply(tfm, item)) === itemdata(item)
    @test itemdata(apply(tfm, (item, item))) === itemdata((item, item))
    @test isnothing(getrandstate(tfm))
end

# And composition:

@testset ExtendedTestSet "`compose`" begin
    data = 1
    item = TestItem(data)

    @test compose(Identity(), Identity()) == Identity()
    @test compose(Identity(), Add(10)) == Add(10)
    @test compose(Add(10), Add(10)) == Add(20)
    @test compose(Add(10), Add(10)) == Add(10) |> Add(10)

    t = Add(10)
    @test compose(t, t, t, t) == t |> t |> t |> t
end

@testset ExtendedTestSet "`Sequence`" begin
    seq = Sequence(Add(10), Add(10))
    @test apply(seq, TestItem(10)) == TestItem(30)
    @test apply(seq, (TestItem(10),)) == (TestItem(30),)
end

# `setdata` should copy, not modify.

@testset ExtendedTestSet "`setdata`" begin
    item = TestItem(10)
    @test setdata(item, 20) == TestItem(20)
    @test setdata(item, 20) !== item
end


text:
#
#      Powermanifold – an array of points of _one_ manifold
#
# Manopt.jl, R. Bergmann, 2018-06-26
import Base: exp, log, show, getindex, setindex!, copy, size, cat, hcat, vcat, repeat, ndims

export Power, PowPoint, PowTVector
export distance, dot, exp, log, manifoldDimension, norm, parallelTransport
export zeroTVector
export typeofMPoint, typeofTVector, randomMPoint, randomTVector
export validateMPoint, validateTVector
export show, getValue, setindex!, getindex,copy, size, repeat, ndims
@doc doc"""
    Power{M<:Manifold} <: Manifold

A power manifold $\mathcal M = \mathcal N^n$, where $n$ can be an integer or an
integer vector.

# Abbreviation

`Pow`

# Constructors
    Power(M,n)

construct the power manifold $\mathcal M^n$ for a [`Manifold`](@ref) `M`
and a natural number `n`.

    Power(M,n)

construct the power manifold $\mathcal M^{n_1\times n_2\times\cdots\times n_d}$
for a [`Manifold`](@ref) `M` and a `Tuple` or `Array` `n` of natural numbers.

"""
struct Power{mT <: Manifold} <: Manifold
  name::String
  manifold::mT
  powerSize::NTuple{N,Int} where N
  abbreviation::String
  Power{mT}(M::mT, pSize::NTuple{N,Int}) where {mT <: Manifold,N} = new(string("The Power Manifold of ",repr(M),
    " to the power ",repr(pSize),"."), M, pSize, string("Pow(",M.abbreviation,"^",repr(pSize),")")
  )
end
Power(M::mT, n::Int ) where {mT <: Manifold} = Power{mT}(M, (n,) )
Power(M::mT, n::NTuple{N,<:Int}) where {mT <: Manifold,N} = Power{mT}(M, n)
@doc doc"""
    PowPoint <: MPoint

A point on the power manifold $\mathcal M = \mathcal N^n$ represented by
an array (of size `n`) of [`MPoint`](@ref)s.
"""
struct PowPoint{P,N} <: MPoint where {P <: MPoint,N}
  value::Array{P,N}
  PowPoint{P,N}(v) where { P <: MPoint,N} = new(v)
end
PowPoint(v::Array{P,N}) where {P <: MPoint,N} = PowPoint{P,N}(v)
getValue(x::PowPoint{P,N}) where {P <: MPoint, N} = x.value;
getindex(x::PowPoint, i...) = PowPoint(getindex( getValue(x) ,i...))
getindex(x::PowPoint, i::Union{Integer, CartesianIndex},
  I::Union{Integer, CartesianIndex}...) = getindex(getValue(x),i,I...)
setindex!(x::PowPoint, y::PowPoint, kv...) = setindex!(getValue(x),getValue(y),kv...)
setindex!(x::PowPoint, kv...) = setindex!(getValue(x),kv...)
@inline ndims(x::PowPoint{P,N}) where {P<:MPoint,N} = ndims(x.value)
function repeat(x::PowPoint{P,N}; inner=ntuple(y->1, Val(ndims(x))), outer=ntuple(y->1, Val(ndims(x))) ) where {P<:MPoint,N}
    b = repeat(x.value; inner=inner, outer=outer)
    return PowPoint(b)
end
repeat(x::PowPoint, counts::Integer...) = repeat(x; outer=counts)
size(x::PowPoint,k...) = size(getValue(x),k...)
copy(x::PowPoint) = PowPoint(copy(getValue(x)))
ndims(x::PowPoint) = ndims( getValue(x) )
@doc doc"""
    PowTVector <: TVector

A tangent vector on the power manifold $\mathcal M = \mathcal N^n$ represented
by an array (of size `n`) of [`TVector`](@ref)s.
"""
struct PowTVector{T,N} <: TVector where {T <: TVector, N}
  value::Array{T,N}
  PowTVector{T,N}(v) where {T <: TVector, N} = new(v)
end
PowTVector(v::Array{T,N}) where {T <: TVector, N} = PowTVector{T,N}(v)
getValue(ξ::PowTVector{T,N}) where {T <: TVector, N} = ξ.value
getindex(ξ::PowTVector,i...) = PowTVector(getindex(ξ.value,i...))
getindex(ξ::PowTVector, i::Union{Integer, CartesianIndex},
  I::Union{Integer, CartesianIndex}...) = getindex(getValue(ξ),i,I...)
setindex!(ξ::PowTVector, ν::T where {T <: TVector},i...) = setindex!(ξ.value,ν,i...)
function repeat(ξ::PowTVector{T,N}; inner=ntuple(t->1, Val(ndims(ξ))), outer=ntuple(t->1, Val(ndims(ξ))) ) where {T <: TVector,N}
    b = repeat(ξ.value; inner=inner, outer=outer)
    return PowTVector(b)
end
repeat(ξ::PowTVector, counts::Integer...) = repeat(ξ; outer=counts)
ndims(ξ::PowTVector) = ndims( getValue(ξ) )
size(ξ::PowTVector) = size(getValue(ξ))
copy(ξ::PowTVector) = PowTVector(copy(ξ.value))
# Functions
# ---
function adjointJacobiField(M::Power,x::PowPoint,y::PowPoint,t::Float64,η::PowTVector,β::Function=βDgx)::PowTVector
    return PowTVector( adjointJacobiField.(Ref(M.manifold), x.value, y.value, Ref(t), η.value ,Ref(β) ) )
end

"""
    distance(M,x,y)

compute a vectorized version of distance on the [`Power`] manifold `M` for two
[`PowPoint`](@ref) `x` and `y`.
"""
distance(M::Power, x::PowPoint, y::PowPoint) = sqrt(sum( abs.(distance.( Ref(M.manifold), x.value, y.value )).^2 ))

"""
    dot(M,x,ξ,ν)

compute the inner product as sum of the component inner products on the
[`Power`](@ref) manifold `M`.
"""
dot(M::Power, x::PowPoint, ξ::PowTVector, ν::PowTVector) = sum(dot.(Ref(M.manifold), x.value, ξ.value, ν.value ))

"""
    exp(M,x,ξ[, t=1.0])

compute the product exponential map on the [`Power`](@ref) manifold `M` and
return the corresponding [`PowPoint`](@ref).
"""
exp(M::Power, x::PowPoint, ξ::PowTVector, t::Float64=1.0) = PowPoint(
    exp.(Ref(M.manifold), x.value, ξ.value,t)
)

function jacobiField(M::Power,x::PowPoint,y::PowPoint,t::Float64,η::PowTVector,β::Function=βDgx)::PowTVector
    return PowTVector(
        jacobiField.(Ref(M.manifold), x.value, y.value, Ref(t), η.value, Ref(β))
    )
end

"""
    log(M,x,y)

compute the product logarithmic map on the [`Power`](@ref) manifold `M` and
return the corresponding [`PowTVector`](@ref).
"""
log(M::Power, x::PowPoint, y::PowPoint)::PowTVector = PowTVector(log.(Ref(M.manifold), getValue(x), getValue(y) ))

"""
    manifoldDimension(x)

return the (product of) dimension(s) of the [`Power`](@ref) the
[`PowPoint`](@ref)`x` belongs to.
"""
manifoldDimension(x::PowPoint) = sum(manifoldDimension.( getValue(x) ) )

"""
    manifoldDimension(M)

return the (product of) dimension(s) of the [`Power`](@ref) manifold `M`.
"""
manifoldDimension(M::Power) = prod(M.powerSize) * manifoldDimension(M.manifold)

"""
    norm(M,x,ξ)

compute the norm of the [`PowTVector`] `ξ` induced by the metric on the manifold
components of the [`Power`](@ref) manifold `M`.
"""
norm(M::Power, x::PowPoint, ξ::PowTVector) = sqrt( dot(M,x,ξ,ξ) )

"""
    parallelTransport(M,x,y,ξ)

compute the product parallelTransport map on the [`Power`](@ref) manifold `M`
from the [`PowPoint`](@ref) `x` to `y` of the [`PowTVector`](@ref) `ξ`.
"""
parallelTransport(M::Power, x::PowPoint, y::PowPoint, ξ::PowTVector) =
    PowTVector( parallelTransport.(Ref(M.manifold), getValue(x), getValue(y), getValue(ξ)) )

@doc doc"""
    randomMPoint(M)

construct a random point on the [`Power`](@ref) manifold `M`, by creating
`n` points on the
[`Manifold`](@ref) `M.manifold` as corresponding [`PowPoint`](@ref).
Optional values are passed down.
"""
randomMPoint(M::Power,options...) = PowPoint( [randomMPoint(M.manifold,options...) for i in CartesianIndices(M.powerSize)] )

@doc doc"""
    randomTVector(M,x)

construct a random tangent vector on the [`Power`](@ref) manifold `M`, by creating
`n` tangent vectors on the
[`Manifold`](@ref) `M.manifold` at the enrties of the [`PowPoint`](@ref) `x`.
Optional values are passed down.
"""
randomTVector(M::Power,x::PowPoint,options...) = PowTVector(
    [randomTVector(M.manifold, getValue(x)[i] , options...)
        for i in CartesianIndices(getValue(x)) ]
)
randomTVector(M::Power,x::PowPoint,s::Symbol,options...) = PowTVector(
    [randomTVector(M.manifold, getValue(x)[i],s,options...)
        for i in CartesianIndices(getValue(x)) ]
)

@doc doc"""
    (Ξ,κ) = tangentONB(M,x,y)

compute an ONB within the tangent space $T_x\mathcal M$ such that $\xi=\log_xy$
is the first vector and compute the eigenvalues of the curvature tensor
$R(\Xi,\dot g)\dot g$, where $g=g_{x,\xi}$ is the geodesic with $g(0)=x$, $\dot
g(0) = \xi$, i.e. $\kappa_1$ corresponding to $\Xi_1=\xi$ is zero.

# See also
 [`jacobiField`](@ref), [`adjointJacobiField`](@ref).
"""
tangentONB(M::Power, x::PowPoint, y::PowPoint) = tangentONB(M,x,log(M,x,y))
function tangentONB(M::Power, x::PowPoint, ξ::PowTVector)
    A = collect(zip( tangentONB.(Ref(M.manifold),getValue(x), getValue(ξ) )... ) )
    κ = vcat( A[2]... )
    Ξ = [ zeroTVector(M,x) for i in Tuple(CartesianIndices(M.powerSize)) for j=1:manifoldDimension(M.manifold)]
    l = 1
    for i in Tuple(CartesianIndices(M.powerSize))
        for j=1:manifoldDimension(M.manifold)
            Ξ[l][i] = A[1][i][j]
            l=l+1
        end
    end
    return Ξ,κ
end
doc"""
    typeofTVector(P)

returns the type of the [`PowTVector`](@ref) that all tangent vectors of the
[`PowPoint`](@ref) `P` have.
"""
typeofTVector(::Type{PowPoint{P,N}}) where {P <: MPoint, N} = PowTVector{typeofTVector(P),N}
doc"""
    typeofMPoint(T)

return the type of the [`PowPoint`](@ref) that is the base point of the
[`PowTVector`](@ref) `T`.
"""
typeofMPoint(::Type{PowTVector{T,N}}) where {T <: TVector, N} = PowPoint{typeofMPoint(T),N}

"""
    typicalDistance(M)

returns the typical distance on the [`Power`](@ref) manifold `M`, which is
based on the elementwise manifold.
"""
typicalDistance(M::Power) = sqrt( prod(M.powerSize) ) * typicalDistance(M.manifold)

doc"""
    validateMPoint(M,x)

validate, that the [`PowPoint`](@ref) `x` is a point on the [`Power`](@ref)
manifold `M`, i.e. that the array dimensions are correct and that all elements
are valid points on the elements manifold.
"""
function validateMPoint(M::Power, x::PowPoint)
    if size(getValue(x)) ≠ M.powerSize
        throw( DomainError(
        " The power manifold point $x is not on $(M.name) since its array dimensions of the elements ($(size(getValue(x)))) does not fit the power ($(M.powerSize))."
        ))
    end
    validateMPoint.(Ref(M.manifold),getValue(x))
    return true
end

doc"""
    validateTVector(M,x,ξ)

validate, that the [`ProdTVector`](@ref) `ξ` is a valid tangent vector to the
[`ProdPoint`](@ref) `x` on the [`Product`](@ref) manifold `M`, i.e. that all
three array dimensions match and this validation holds elementwise.
"""
function validateTVector(M::Power, x::PowPoint, ξ::PowTVector)
    if (size(getValue(x)) ≠ size(getValue(ξ))) || (size(getValue(ξ)) ≠ M.powerSize)
        throw( DomainError(
        "The three dimensions of the $(M.name), the point x ($(size(getValue(x)))), and the tangent vector ($(size(getValue(ξ)))) don't match."
        ))
    end
    validateTVector.(Ref(M.manifold),getValue(x),getValue(ξ))
    return true
end

@doc doc"""
    ξ = zeroTVector(M,x)

returns a zero vector in the tangent space $T_x\mathcal M$ of the
[`PowPoint`](@ref) $x\in\mathcal M$ on the [`Power`](@ref) manifold `M`.
"""
zeroTVector(M::Power{Mt}, x::PowPoint{P,N}) where {Mt <: Manifold, P <: MPoint, N} = PowTVector{typeofTVector(P),N}( zeroTVector.(Ref(M.manifold), getValue(x) )  )
#
#
# Display functions for the structs
show(io::IO, M::Power) = print(io,string("The Power Manifold of ",repr(M.manifold), " of size ",repr(M.powerSize),".") );
show(io::IO, p::PowPoint) = print(io,string("Pow[",join(repr.(p.value),", "),"]"));
show(io::IO, ξ::PowTVector) = print(io,string("PowT[", join(repr.(ξ.value),", "),"]"));


text:
using Base.LineEdit

a_foo = 0

const foo_keymap = {
    'a' => :( global a_foo; a_foo += 1)
}

b_foo = 0

const foo2_keymap = {
    'b' => :( global b_foo; b_foo += 1)
}

a_bar = 0
b_bar = 0

const bar_keymap = {
    'a' => :( global a_bar; a_bar += 1),
    'b' => :( global b_bar; b_bar += 1)
}

test1_func = @eval @LineEdit.keymap $foo_keymap

function run_test(f,buf)
    global a_foo, a_bar, b_bar
    a_foo = a_bar = b_bar = 0
    while !eof(buf)
        f(buf,nothing)
    end
end

run_test(test1_func,IOBuffer("aa"))
@test a_foo == 2

test2_func = @eval @LineEdit.keymap $([foo2_keymap, foo_keymap])

run_test(test2_func,IOBuffer("aaabb"))
@test a_foo == 3
@test b_foo == 2

test3_func = @eval @LineEdit.keymap $([bar_keymap, foo_keymap])

run_test(test3_func,IOBuffer("aab"))
@test a_bar == 2
@test b_bar == 1

## edit_move_{up,down} ##

buf = IOBuffer("type X\n    a::Int\nend")
for i = 0:6
    seek(buf,i)
    @test !LineEdit.edit_move_up(buf)
    @test position(buf) == i
    seek(buf,i)
    @test LineEdit.edit_move_down(buf)
    @test position(buf) == i+7
end
for i = 7:17
    seek(buf,i)
    @test LineEdit.edit_move_up(buf)
    @test position(buf) == min(i-7,6)
    seek(buf,i)
    @test LineEdit.edit_move_down(buf)
    @test position(buf) == min(i+11,21)
end
for i = 18:21
    seek(buf,i)
    @test LineEdit.edit_move_up(buf)
    @test position(buf) == i-11
    seek(buf,i)
    @test !LineEdit.edit_move_down(buf)
    @test position(buf) == i
end

buf = IOBuffer("type X\n\n")
seekend(buf)
@test LineEdit.edit_move_up(buf)
@test position(buf) == 7
@test LineEdit.edit_move_up(buf)
@test position(buf) == 0
@test !LineEdit.edit_move_up(buf)
@test position(buf) == 0
seek(buf,0)
@test LineEdit.edit_move_down(buf)
@test position(buf) == 7
@test LineEdit.edit_move_down(buf)
@test position(buf) == 8
@test !LineEdit.edit_move_down(buf)
@test position(buf) == 8

## edit_delete_prev_word ##

buf = IOBuffer("type X\n ")
seekend(buf)
@test LineEdit.edit_delete_prev_word(buf)
@test position(buf) == 5
@test buf.size == 5
@test bytestring(buf.data[1:buf.size]) == "type "

buf = IOBuffer("4 +aaa+ x")
seek(buf,8)
@test LineEdit.edit_delete_prev_word(buf)
@test position(buf) == 3
@test buf.size == 4
@test bytestring(buf.data[1:buf.size]) == "4 +x"

buf = IOBuffer("x = func(arg1,arg2 , arg3)")
seekend(buf)
LineEdit.char_move_word_left(buf)
@test position(buf) == 21
@test LineEdit.edit_delete_prev_word(buf)
@test bytestring(buf.data[1:buf.size]) == "x = func(arg1,arg3)"
@test LineEdit.edit_delete_prev_word(buf)
@test bytestring(buf.data[1:buf.size]) == "x = func(arg3)"
@test LineEdit.edit_delete_prev_word(buf)
@test bytestring(buf.data[1:buf.size]) == "x = arg3)"

max_stars_repo_name: alyst/julia

max_issues_repo_name: alyst/julia

max_forks_repo_name: alyst/julia


text:
include("help.jl")
module NNChessMarker
    using HorizonSideRobots
    import Main.inverse
#=
Предполагается, что в пространстве имен Main определена функция inverse, например, путем вставки из файла "roblib.jl"
=#
    export mark_chess

    X_COORDINATE=0
    Y_COORDINATE=0

    CELL_SIZE = 0 # - размер "шахматной" клеки

    function mark_chess(r::Robot,n::Int)
        global CELL_SIZE
        CELL_SIZE = n # инициализация глобальной переменной

        #УТВ: Робот - в юго-западном углу
        side=Ost
        mark_row(r,side)
        while isborder(r,Nord)==false
            move_decart!(r,Nord)
            side = inverse(side)
            mark_row(r,side)
        end
    end

    function mark_row(r::Robot,size::HorizonSide)
        putmarker_chess!(r)
        while isborder!(r,side)==false
            move_decart!(r,side)
            putmarker_chess!(r)
        end
    end

    function putmarker_chess!(r)
        if (mod(X_COORDINATE, 2*CELL_SIZE) in 0:CELL_SIZE-1) && (mod(Y_COORDINATE, 2*CELL_SIZE) in 0:CELL_SIZE-1)
                putmarker!(r)
        end
    end

    function move_decart!(r,side)
        global X_COORD, Y_COORD
        if side==Nord
            Y_COORD+=1
        elseif side==Sud
            Y_COORD-=1
        elseif side==Ost
            X_COORD+=1
        else # side==West
            X_COORD-=1
        end
        move!(r,side)
    end

end

max_stars_repo_name: MCPavlo/mirea-progs

max_issues_repo_name: MCPavlo/mirea-progs

max_forks_repo_name: MCPavlo/mirea-progs


text:
@testset "688.knight-probability-in-chessboard.jl" begin
    @test knight_probability(3, 2, 0, 0) ≈ 0.0625
    @test isapprox(knight_probability(8, 10, 4, 5), 0.0773899; atol = 6)
end


text:
# MIT License
#
# Copyright (c) 2018 Martin Biel
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

struct RawCor{T <: AbstractFloat}
    name::String
    n::Int
    m₁::Int
    m₂::Int
    vars::OrderedDict{Col, Int}
    rows::OrderedDict{Row, Tuple{Int,Int,Symbol}}
    cols::OrderedDict{Col, Vector{Pair{Symbol,T}}}
    rhs::Dict{Row, T}
    ranges::Dict{Row, T}
    bounds::OrderedDict{Col, Vector{Pair{Symbol,T}}}
    objgiven::Bool
    objname::Symbol
    rhsname::Symbol

    function RawCor(n::Integer, m₁::Integer, m₂::Integer,
                    vars::OrderedDict{Col, Int}, rows::OrderedDict{Row, Tuple{Int,Int,Symbol}},
                    cols::OrderedDict{Col, Vector{Pair{Symbol,T}}}, rhs::Dict{Row, T},
                    ranges::Dict{Row, T}, bounds::OrderedDict{Col, Vector{Pair{Symbol,T}}};
                    objgiven::Bool = false,
                    objname::Symbol = OBJ,
                    rhsname::Symbol = RHS,
                    name::String = "LP") where T <: AbstractFloat
        return new{T}(name,
                      n, m₁, m₂,
                      vars, rows, cols,
                      rhs, ranges, bounds,
                      objgiven, objname, rhsname)
    end
end

function parse_cor(::Type{T}, filename::AbstractString) where T <: AbstractFloat
    # Initialize auxiliary variables
    name       = "SLP"
    mode       = NAME
    rowidx     = 1
    eqrowidx   = 0
    ineqrowidx = 0
    varidx     = 1
    objgiven   = false
    objname    = OBJ
    rhsname    = RHS
    # Define sections
    vars    = OrderedDict{Col, Int}()
    rows    = OrderedDict{Row, Tuple{Int,Int,Symbol}}()
    cols    = OrderedDict{Col, Vector{Pair{Symbol,T}}}()
    rhs     = Dict{Row, T}()
    ranges  = Dict{Row, T}()
    bounds  = OrderedDict{Col, Vector{Pair{Symbol,T}}}()
    # Parse the file
    open(filename) do io
        firstline = split(readline(io))
        if Symbol(firstline[1]) == NAME
            name = join(firstline[2:end], " ")
        else
            throw(ArgumentError("`NAME` field is expected on the first line."))
        end
        for line in eachline(io)
            if mode == END
                # Parse finished
                break
            end
            words = split(line)
            first_word = Symbol(words[1])
            if first_word in COR_MODES && first_word != mode
                mode = first_word
                continue
            end
            if mode == ROWS
                rowsym = Symbol(words[2])
                rows[rowsym] =
                    words[1] == "N" ? (objgiven = true; objname = rowsym; (rowidx, 0, OBJ)) :
                    words[1] == "L" ? (ineqrowidx += 1; (rowidx, ineqrowidx, LEQ))            :
                    words[1] == "G" ? (ineqrowidx += 1; (rowidx, ineqrowidx, GEQ))            :
                    (eqrowidx   += 1; (rowidx, eqrowidx, EQ))
                rowidx += 1
            elseif mode == COLUMNS
                var = Symbol(words[1])
                if get!(vars, var, 0) == 0
                    vars[var] = varidx
                    varidx    += 1
                end
                for idx = 2:2:length(words)
                    push!(get!(cols, var, Pair{Symbol,T}[]),
                          Pair(Symbol(words[idx]), convert(T, parse(Float64, words[idx+1]))))
                end
            elseif mode == RHS
                _rhsname = Symbol(words[1])
                if _rhsname  != RHS && rhsname == RHS
                    rhsname = _rhsname
                end
                rhsname == _rhsname || error("Multiple RHS names given.")
                for idx = 2:2:length(words)
                    rhs[Symbol(words[idx])] = convert(T, parse(Float64, words[idx+1]))
                end
            elseif mode == RANGES
                for idx = 2:2:length(words)
                    ranges[Symbol(words[idx])] = convert(T, parse(Float64, words[idx+1]))
                end
            elseif mode == BOUNDS
                var = Symbol(words[3])
                bnd = words[1] == "LO" ? LOWER :
                      words[1] == "UP" ? UPPER :
                      words[1] == "BV" ? BINARY :
                      words[1] == "I"  ? INTEGER :
                      words[1] == "LI" ? INTEGER_LOWER :
                      words[1] == "UI" ? INTEGER_UPPER :
                      words[1] == "FR" ? FREE  : FIXED
                push!(get!(bounds, var, Pair{Symbol,T}[]),
                      Pair(bnd, convert(T, parse(Float64, bnd in [FREE, BINARY, INTEGER] ? "0" : words[4]))))
            else
                throw(ArgumentError("$(mode) is not a valid cor file mode."))
            end
        end
    end
    # Return raw data
    return RawCor(varidx - 1,
                  eqrowidx,
                  ineqrowidx,
                  vars,
                  rows,
                  cols,
                  rhs,
                  ranges,
                  bounds;
                  objgiven = objgiven,
                  objname = objname,
                  rhsname = rhsname,
                  name = name)
end
parse_cor(filename::AbstractString) = parse_cor(Float64, filename)

function sparsity(cor::RawCor)
    return 1 - length(cor.cols) / (cor.n * (cor.m₁ + cor.m₂))
end


text:
dir_path = @__DIR__
push!(LOAD_PATH, dir_path * "/sim") # simulation
push!(LOAD_PATH, dir_path * "/vis") # visualization
push!(LOAD_PATH, dir_path * "/mdp") # fully observable MDP
push!(LOAD_PATH, dir_path * "/dis") # discretization
push!(LOAD_PATH, dir_path * "/olm") # online methods
using sim
using vis
using mdp
using dis
using olm

using Serialization
using Printf
using DelimitedFiles
using Statistics

include("update_info.jl")

# state space
const pts_per_s = 150
const pts_per_ds = 30
const pts_per_p = 20
const min_s = 0.0
const min_p = -12.0
const max_p = 12.0
const min_ds = 0.0
const max_ds = 50.0

# action space
const pts_per_acc = 10
const pts_per_ste = 3
const min_acc = -15
const max_acc = 5
const min_ste = -1e-1
const max_ste = 1e-1

function discretize_vit(world::World)
  max_s = world.road.path.S[end]
  state_d = Discretization([pts_per_s, pts_per_ds, pts_per_p],
                           [min_s, min_ds, min_p],
                           [max_s, max_ds, max_p])
  ctrl_d = Discretization([pts_per_acc, pts_per_ste],
                          [min_acc, min_ste],
                          [max_acc, max_ste])
  return (state_d, ctrl_d)
end

function discretize_fwds(world::World)
  pts_per_acc = 3
  pts_per_ste = 3
  min_acc = -15
  max_acc = 5
  min_ste = -1e-1
  max_ste = 1e-1
  ctrl_d = Discretization([pts_per_acc, pts_per_ste],
                          [min_acc, min_ste],
                          [max_acc, max_ste])
  return ctrl_d
end

function reward(x, u, nx, agent, world)
  return nx[2]^3 + (abs(x[3]) > 0.5 * world.road.width ? -1e9 : 0.0)
end

# Scenario: Racer scenario
function main()
  # load the graphical context (OpenGL handle, the graphical window, etc.)
  context = vis.setup()
  vis_scaling = 0.01

  # make the road
  path = make_figure8_path()
  road_width = 20.0
  road = Road(path, road_width,
              vis.make_road(context, path.X, path.Y, road_width))
  road.road.T = vis.scale_mat(vis_scaling, vis_scaling)

  # make the world
  world = World(road, [], vis_scaling)
  (state_d, ctrl_d) = discretize_vit(world) # discretize the world

  # make the agents
  x0 = [0.0; 25.0; 0.0]
  agent1 = Agent(1, copy(x0), vis.make_car(context))
  push!(world.agents, agent1)
  agent2 = Agent(2, copy(x0), vis.make_car(context, [1.0, 0.0, 0.0]))
  push!(world.agents, agent2)
  agent3 = Agent(3, copy(x0), vis.make_car(context, [0.0, 1.0, 0.0]))
  push!(world.agents, agent3)

  println("Welcome")
  flush(stdout)
  IT = Int[]
  FLIP = Int[]
  t1 = time_ns()
  S = mdp.make_MDP(agent1, world, reward, state_d, ctrl_d)
  t2 = time_ns()
  println("Building takes $((t2 - t1) / 1e9) s")
  flush(stdout)

  P = Policy(S, 0.999)
  i = 1
  flip = 1
  t1 = time_ns()
  while flip > 0
    (change, nbchange) = mdp.iterate!(P)
    flip = nbchange

    push!(IT, i)
    push!(FLIP, flip)

    println(flip)
    flush(stdout)

    i += 1
  end
  t2 = time_ns()
  println("Iteration takes $((t2 - t1) / 1e9) s")
  flush(stdout)

  writedlm("../data/vlit_it.txt", [IT FLIP])

  return

  # Value Iteration Approach ------------------------------------------------ #
  # read in, iterate and store the policy
  P = nothing
  S = nothing

  policy_file_path = dir_path * "/../data/fr_vi_policy.bin"

  fp = open(policy_file_path, "r")
  (P, state_d, ctrl_d) = deserialize(fp)
  close(fp)

  S = P.S

  # switch agent's trained controller on
  agent1.controller! = mdp.controllerd_interp!
  agent1.custom = (P, state_d, ctrl_d)
  # ------------------------------------------------------------------------- #

  # Forward Search Approach ------------------------------------------------- #
  ctrl_d = discretize_fwds(world)
  agent2.controller! = olm.controller_fwds!
  # ------------------------------------------------------------------------- #

  # MCTS Approach ----------------------------------------------------------- #
  ctrl_d = discretize_fwds(world)
  agent3.controller! = olm.controller_mcts!
  # ------------------------------------------------------------------------- #

  # main loop definititons
  window = true
  h = 1e-2
  t0 = time_ns()
  dt = 1 / 60
  N = round(Int, 20.0 / dt)
  D = 5

  # Accumulated Data -------------------------------------------------------- #
  global T = Array{Float64, 2}(undef, (N, D))

  global Cfwds = Array{Float64, 2}(undef, (N, D))
  global Cmcts = Array{Float64, 2}(undef, (N, D))

  global Vvlit = Array{Float64, 2}(undef, (N, D))
  global Vfwds = Array{Float64, 2}(undef, (N, D))
  global Vmcts = Array{Float64, 2}(undef, (N, D))
  # ------------------------------------------------------------------------- #
  for j in 1:D
    t = 0.0
    agent1.x = copy(x0)
    agent2.x = copy(x0)
    agent3.x = copy(x0)
    for i in 1:N
      # Value Iteration ----------------------------------------------------- #
      Vvlit[i, j] = agent1.x[2]
      # --------------------------------------------------------------------- #

      # Forward Search Approach --------------------------------------------- #
      t1 = time_ns()
      u = olm.plan_fwds(agent2.x, agent2, world, reward, ctrl_d, j)
      t2 = time_ns()
      Cfwds[i, j] = (t2 - t1) / 1e9
      Vfwds[i, j] = agent2.x[2]

      agent2.custom = u
      # --------------------------------------------------------------------- #

      # MCTS Approach ------------------------------------------------------- #
      t1 = time_ns()
      us = olm.plan_mcts(agent3.x, agent3, world, reward, ctrl_d, j)
      t2 = time_ns()
      Cmcts[i, j] = (t2 - t1) / 1e9
      Vmcts[i, j] = agent3.x[2]

      agent3.custom = us
      # --------------------------------------------------------------------- #

      ## advance one frame in time
      advance!(agent1.dynamics!, agent1.x, Pair(agent1, world), 0.0, dt, h)
      advance!(agent2.dynamics!, agent2.x, Pair(agent2, world), 0.0, dt, h)
      advance!(agent3.dynamics!, agent3.x, Pair(agent3, world), 0.0, dt, h)

      T[i, j] = t
      t += dt

      if mod(i, div(N, 10)) == 0
        println("$(j) -> $(t)")
      end
    end
    println("Finished depth = $(j)")
  end
  DATAvlit = fill(0.0, (N, 2 * D))
  DATAfwds = fill(0.0, (N, 3 * D))
  DATAmcts = fill(0.0, (N, 3 * D))
  for i in 1:D
    DATAvlit[:, 2 * (i - 1) + 1] = T[:, i]
    DATAvlit[:, 2 * (i - 1) + 2] = Vvlit[:, i]

    DATAfwds[:, 3 * (i - 1) + 1] = T[:, i]
    DATAfwds[:, 3 * (i - 1) + 2] = Vfwds[:, i]
    DATAfwds[:, 3 * (i - 1) + 3] = Cfwds[:, i]

    DATAmcts[:, 3 * (i - 1) + 1] = T[:, i]
    DATAmcts[:, 3 * (i - 1) + 2] = Vmcts[:, i]
    DATAmcts[:, 3 * (i - 1) + 3] = Cmcts[:, i]
  end

  AVGCfwds = map(i -> mean(DATAfwds[:, 3 * (i - 1) + 3]), 1:D)
  AVGCmcts = map(i -> mean(DATAmcts[:, 3 * (i - 1) + 3]), 1:D)

  AVGVvlit = map(i -> mean(DATAvlit[:, 2 * (i - 1) + 2]), 1:D)
  AVGVfwds = map(i -> mean(DATAfwds[:, 3 * (i - 1) + 2]), 1:D)
  AVGVmcts = map(i -> mean(DATAmcts[:, 3 * (i - 1) + 2]), 1:D)

  writedlm("../data/vlit_data.txt", DATAvlit)
  writedlm("../data/fwds_data.txt", DATAfwds)
  writedlm("../data/mcts_data.txt", DATAmcts)

  writedlm("../data/fwds_avgc.txt", AVGCfwds)
  writedlm("../data/mcts_avgc.txt", AVGCmcts)

  writedlm("../data/vlit_avgv.txt", AVGVvlit)
  writedlm("../data/fwds_avgv.txt", AVGVfwds)
  writedlm("../data/mcts_avgv.txt", AVGVmcts)
end


text:
function predict_new(a_all,a_layer1,x_new,obs,neurons)

    # layer1=zeros(obs,neurons)
    # for i=1:neurons
    #     if i in 1:100:neurons println(Dates.format(now(), "HH:MM:SS"),"applying sigmoid on neuron ",i," of ",neurons) end
    #     # layer1[:,i].=sigm1.([ones(obs) x_new]*a_all[i,:])
    #     layer1[:,i].=sigm1.([ones(obs) x_new]*a_all[i])
    #     # x[i_so,:]*a_all[i,:]
    # end
    # # a_layer1=[sigm1.(layer1) ones(obs)]\y
    # # predl1=[sigm1.(layer1) ones(obs)]*a_layer1
    # predl1=[layer1 ones(obs)]*a_layer1

    layer1=sigm1.([ones(obs) x_new]*reduce(hcat, a_all))
    predl1=[layer1 ones(obs)]*a_layer1

    return predl1,layer1

end


text:
using HDF5

export read_ρ

function read_ρ(data_path::String, data_name::String)
    ρ_real = h5open(data_path, "r") do file
        read(file, "$data_name/real")
    end
    ρ_imag = h5open(data_path, "r") do file
        read(file, "$data_name/imag")
    end

    return complex.(ρ_real', ρ_imag')
end


text:
if Sys.iswindows()
   const LIBGDX = "gdxdclib64"
else
   const LIBGDX = "libgdxdclib64"
end

mutable struct GDXHandle
   cptr::Ref{Ptr{Cvoid}}
   cival::Ref{Cint}
   cival2::Ref{Cint}
   civec::Vector{Cint}
   crvec::Vector{Cdouble}
   buf::Vector{Vector{UInt8}}
   cbuf::Vector{Cstring}

   function GDXHandle()
      cptr = Ref{Ptr{Cvoid}}(C_NULL)
      buf = Vector{Vector{UInt8}}(undef, 20)
      for i = 1:20
         buf[i] = Vector{UInt8}(undef, 256)
         buf[i] .= ' '
      end
      cbuf = pointer.(buf)
      crvec = Vector{Cdouble}(undef, 5)
      civec = Vector{Cint}(undef, 5)
      new(cptr, Ref{Cint}(-1), Ref{Cint}(-1), civec, crvec, buf, cbuf)
   end
end

struct GDXException <: Exception
   msg::String
   n_err::Int
end

Base.showerror(io::IO, e::GDXException) = print(io, "GDX failed: $(e.msg) ($(e.n_err))")

function gdx_create(
   gdx_ptr::Ref{Ptr{Cvoid}}
)
   ccall((:xcreate, LIBGDX), Cvoid,
      (Ptr{Ptr{Cvoid}},),
      gdx_ptr
   )
   if gdx_ptr[] == C_NULL
      throw(GDXException("Can't create GAMS GDX object", 0))
   end
   return
end

function gdx_create(
   gdx::GDXHandle
)
   gdx_create(gdx.cptr)
end

function gdx_free(
   gdx_ptr::Ref{Ptr{Cvoid}}
)
   ccall((:xfree, LIBGDX), Cvoid, (Ptr{Ptr{Cvoid}},), gdx_ptr)
   return
end

function gdx_free(
   gdx::GDXHandle
)
   gdx_free(gdx.cptr)
end

function gdx_open_read(
   gdx_ptr::Ptr{Cvoid},
   file::String,
   n_err::Ref{Cint}
)
   return ccall((:cgdxopenread, LIBGDX), Cint,
      (Ptr{Cvoid}, Cstring, Ref{Cint}),
      gdx_ptr, file, n_err
   )
end

function gdx_open_read(
   gdx::GDXHandle,
   file::String
)
   rc = gdx_open_read(gdx.cptr[], file, gdx.cival)
   if gdx.cival[] != 0 || rc != 1
      throw(GDXException("Can't open file '$file'", gdx.cival[]))
   end
   return
end

function gdx_system_info(
   gdx_ptr::Ptr{Cvoid},
   sym_count::Ref{Cint},
   uel_count::Ref{Cint}
)
   return ccall((:gdxsysteminfo, LIBGDX), Cint,
      (Ptr{Cvoid}, Ref{Cint}, Ref{Cint}),
      gdx_ptr, sym_count, uel_count)
end

function gdx_system_info(
   gdx::GDXHandle
)
   rc = gdx_system_info(gdx.cptr[], gdx.cival, gdx.cival2)
   if rc != 1
      throw(GDXException("Can't read system info", 0))
   end
   return Int(gdx.cival[]), Int(gdx.cival2[])
end

function gdx_symbol_info(
   gdx_ptr::Ptr{Cvoid},
   sym_id::Int,
   name::Cstring,
   dim::Ref{Cint},
   type::Ref{Cint}
)
   return ccall((:cgdxsymbolinfo, LIBGDX), Cint,
      (Ptr{Cvoid}, Cint, Cstring, Ref{Cint}, Ref{Cint}),
      gdx_ptr, sym_id, name, dim, type)
end

function gdx_symbol_info(
   gdx::GDXHandle,
   sym_id::Int
)
   gdx.buf[1][1] = '\0'
   rc = gdx_symbol_info(gdx.cptr[], sym_id, gdx.cbuf[1], gdx.cival, gdx.cival2)
   if rc != 1
      throw(GDXException("Can't read symbol info", 0))
   end
   return unsafe_string(gdx.cbuf[1]), Int(gdx.cival[]), Int(gdx.cival2[])
end

function gdx_data_read_raw_start(
   gdx_ptr::Ptr{Cvoid},
   start::Int,
   n_rec::Ref{Cint}
)
   return ccall((:gdxdatareadrawstart, LIBGDX), Cint,
      (Ptr{Cvoid}, Cint, Ref{Cint}),
      gdx_ptr, start, n_rec
   )
end

function gdx_data_read_raw_start(
   gdx::GDXHandle,
   start::Int
)
   rc = gdx_data_read_raw_start(gdx.cptr[], start, gdx.cival)
   if rc != 1
      throw(GDXException("Can't start GDX read", 0))
   end
   return Int(gdx.cival[])
end

function gdx_data_read_raw(
   gdx_ptr::Ptr{Cvoid},
   idx::Vector{Cint},
   vals::Vector{Cdouble},
   dim::Ref{Cint}
)
   return ccall((:gdxdatareadraw, LIBGDX), Cint,
      (Ptr{Cvoid}, Ptr{Cint}, Ptr{Cdouble}, Ref{Cint}),
      gdx_ptr, idx, vals, dim
   )
end

function gdx_data_read_raw(
   gdx::GDXHandle,
   idx::Vector{Int},
   vals::Vector{Float64}
)
   @assert(length(idx) <= length(gdx.civec))
   @assert(length(vals) <= length(gdx.crvec))

   rc = gdx_data_read_raw(gdx.cptr[], gdx.civec, gdx.crvec, gdx.cival)
   if rc != 1
      throw(GDXException("Reading raw data failed", 0))
   end

   for i = 1:length(idx)
      idx[i] = gdx.civec[i]
   end
   for i = 1:length(vals)
      vals[i] = gdx.crvec[i]
   end
   return
end

function gdx_data_read_str_start(
   gdx_ptr::Ptr{Cvoid},
   start::Int,
   n_err::Ref{Cint}
)
   return ccall((:gdxdatareadstrstart, LIBGDX), Cint,
      (Ptr{Cvoid}, Cint, Ref{Cint}),
      gdx_ptr, start, n_err
   )
end

function gdx_data_read_str_start(
   gdx::GDXHandle,
   start::Int
)
   rc = gdx_data_read_str_start(gdx.cptr[], start, gdx.cival)
   if rc != 1
      throw(GDXException("Can't start GDX read", 0))
   end
   return gdx.cival[]
end

function gdx_data_read_str(
   gdx_ptr::Ptr{Cvoid},
   keystr::Vector{Cstring},
   vals::Vector{Cdouble},
   dim_first::Ref{Cint}
)
   return ccall((:cgdxdatareadstr, LIBGDX), Cint,
      (Ptr{Cvoid}, Ptr{Cstring}, Ptr{Cdouble}, Ref{Cint}),
      gdx_ptr, keystr, vals, dim_first
   )
end

function gdx_data_read_str(
   gdx::GDXHandle,
   keystr::Vector{String},
   vals::Vector{Float64}
)
   @assert(length(keystr) <= length(gdx.cbuf))
   @assert(length(vals) <= length(gdx.crvec))

   for b in gdx.buf
      b[1] = '\0'
   end

   rc = gdx_data_read_str(gdx.cptr[], gdx.cbuf, gdx.crvec, gdx.cival)
   if rc != 1
      throw(GDXException("Reading raw data failed", 0))
   end

   for i = 1:length(keystr)
      keystr[i] = unsafe_string(gdx.cbuf[i])
   end
   for i = 1:length(vals)
      vals[i] = gdx.crvec[i]
   end
   return
end

function gdx_data_read_done(
   gdx_ptr::Ptr{Cvoid},
)
   return ccall((:gdxdatareaddone, LIBGDX), Cint, (Ptr{Cvoid},), gdx_ptr)
end

function gdx_data_read_done(
   gdx::GDXHandle
)
   gdx_data_read_done(gdx.cptr[])
   return
end

function gdx_close(
   gdx_ptr::Ptr{Cvoid},
)
   return ccall((:gdxclose, LIBGDX), Cint, (Ptr{Cvoid},), gdx_ptr)
end

function gdx_close(
   gdx::GDXHandle
)
   gdx_close(gdx.cptr[])
   return
end


text:
using MatterPower
using Roots
using Plots, LaTeXStrings
using Dierckx
using DelimitedFiles, Printf

# %% Loop over redshifts
redshift = [0, 0.3, 0.5, 0.7, 1, 1.3, 1.5]
for ired = 1:7
   # %% Read in linear and non-linear power spectra computed by CLASS
   filename = @sprintf("data/matterpower05_z%1d_pk.dat", ired)
   d = readdlm(filename, comments = true)
   pklin_class = Spline1D(d[:, 1], d[:, 2])
   filename = @sprintf("data/matterpower05_z%1d_pk_nl.dat", ired)
   d = readdlm(filename, comments = true)
   pknl_class = Spline1D(d[:, 1], d[:, 2])

   # %% Define a function to return a linear matter power spectrum (in units of Mpc^3/h^3)
   # as a function of the comoving wavenumber, kovh, in units of h/Mpc.
   # Here is an example using Einstein & Hu's analytical transfer function

   # Cosmological parameters
   As, ns, kpivot = 2.097e-9, 0.9652, 0.05
   Ωm, ΩΛ, Ωb = 0.315, 0.685, 0.049
   Ωk = 1 - Ωm - ΩΛ
   h0 = 0.674
   ωm, fb = Ωm * h0^2, Ωb / Ωm

   # Tabulate linear growth factor as a function of scale factor, a
   sol = setup_growth(Ωm, ΩΛ)
   a = 1 / (1 + redshift[ired])
   D1 = sol(a)[1]

   pk(kovh) =
      D1^2 *
      As *
      (kovh * h0 / kpivot)^(ns - 1) *
      (2 * kovh^2 * 2998^2 / 5 / Ωm)^2 *
      t_nowiggle(kovh * h0, ωm, fb)^2 *
      2 *
      π^2 / kovh^3

   # %% Alternatively you may read in pre-computed data and define a spline function
   # using Dierckx
   # pk = Spline1D(tabulated_kovh, tabulated_power_spectrum)

   # %% Compute the r.m.s. mass fluctuation with a top-hat radius Rh
   Rh = 8 # Mpc/h
   σ2 = sigma2(pk, Rh)
   println("σ(R) = ", √σ2, " for R = ", Rh, " Mpc/h")

   # %% Compute the non-linear mass, M*, defined by σ(R*,z) = 1.6865
   # and M* = (4π/3)ρm R*^3 = (4π/3)ρc Ωm R*^3
   # ρc is the present-day critical density of the Universe in units of h^2 M⊙/Mpc^3
   ρc = 2.775e11
   f(x) = √sigma2(pk, x) - 1.6865
   Rstar = find_zero(f, (1e-2, 3), Bisection())
   println("R* = ", Rstar, " h/Mpc")
   Mstar = 4π / 3 * ρc * Ωm * Rstar^3
   println("Non-linear mass M* = ", Mstar, " M⊙/h")

   # %% Compute the non-linear power spectrum using halofit
   # Get three parameters [kσ, neff, C] needed for the halofit transform
   p = kσ, neff, C = setup_halofit(pk)

   # Calculate Ωm(z) = Ωm(z=0)(1+z)^3 / E^2(z), where E^2(z) = H^2(z) / H0^2
   z = redshift[ired]
   E2 = Ωm * (1 + z)^3 + Ωk * (1 + z)^2 + ΩΛ
   Ωmz = Ωm * (1 + z)^3 / E2

   # Define a function to return a halofit non-linear power spectrum
   pknl(kovh) = halofit(pk, p, Ωmz, kovh) # Mpc^3/h^3

   # %% Plot results and save to "comparison_z[1-7].pdf"
   lnk = log(3e-4):1e-2:log(30)
   kovh = exp.(lnk)
   p = plot(
      kovh,
      pknl.(kovh) ./ pknl_class.(kovh) .- 1,
      xaxis = :log,
      lab = "Non-linear P(k)",
      ylab = L"P_{MatterPower}(k)/P_{CLASS}(k) - 1",
      xlab = L"k~[h~Mpc^{-1}]",
      title = @sprintf("Redshift: z = %1.1f", redshift[ired]),
   )
   p = plot!(
      kovh,
      pk.(kovh) ./ pklin_class.(kovh) .- 1,
      ls = :dash,
      lab = "Linear P(k)",
   )
   filename = @sprintf("comparison_z%1d.pdf", ired)
   savefig(filename)
   display(p)

   # %% Compute the halofit power spectrum from CLASS's linear power spectrum
   p = kσ, neff, C = setup_halofit(pklin_class)
   pknl2(kovh) = halofit(pklin_class, p, Ωmz, kovh) # Mpc^3/h^3

   # %% Plot results and save to "halofit_comparison_z[1-7].pdf"
   p = plot(
      kovh,
      pknl2.(kovh) ./ pknl_class.(kovh) .- 1,
      xaxis = :log,
      lab = "Non-linear P(k) from CLASS's linear P(k) and halofit",
      ylab = L"P_{MatterPower}(k)/P_{CLASS}(k) - 1",
      xlab = L"k~[h~Mpc^{-1}]",
      title = @sprintf("Redshift: z = %1.1f", redshift[ired]),
      legend = :bottomleft,
   )
   filename = @sprintf("halofit_comparison_z%1d.pdf", ired)
   savefig(filename)
   display(p)
end


text:
# Solve Project Euler problem 96 (sudoku) to test ExactCovers.
#
# The idea here is to reduce sudoku to the exact cover problem and then use
# ExactCovers to solve that. Because we need to solve multiple sudokus, we
# costruct a general sudoku matrix and then, for each sudoku,
# 1. cover the parts of the matrix that correspond to givens,
# 2. find an exact cover for the partially covered matrix, and finally
# 3. uncover in reverse order.
# This is more efficient (and also easier to write down) than creating a
# specialized matrix for each sudoku.
#
# Each row (subset) in the sudoku matrix corresponds to placing a number into a
# square. The columns (elements) correspond to the individual constraints that
# each placement fulfills. These are:
# * The corresponding square is filled.
# * The corresponding row has the placed number.
# * The corresponding column has the placed number.
# * The corresponding box (3x3-subgrid) has the placed number.
#
# Because the sudoku rules dictate that each of these constraints must be
# satisfied exactly once, an exact cover for that matrix is a solution to
# sudoku. Preselecting (covering) rows (subsets) now makes sure that we are
# actually solving the given sudoku instance, instead of an empty grid.

"Creates the `CoverSet` that represents an empty sudoku grid."
function make_sudoku_matrix()
  box_for(row, column) = (div(row - 1, 3) + 1, div(column - 1, 3) + 1)

  constraints_for(row, column, number) = Set(Any[
    (:square_is_filled, row, column),
    (:row_has, row, number),
    (:column_has, column, number),
    (:box_has, box_for(row, column), number)
  ])

  CoverMatrix(Dict([
    (row, column, number) => constraints_for(row, column, number) for
      row in 1:9,
      column in 1:9,
      number in 1:9
  ]))
end

"""
Preselects the given placements from `sudoku` in `matrix`.
"""
function cover_givens!(sudoku, matrix)
  for row in 1:9, column in 1:9
    if sudoku[row, column] > 0
      cover_subset!(matrix, (row, column, sudoku[row, column]))
    end
  end
end

"""
Reverses the preselection from `sudoku`, so that `matrix` is restored to a
pristine sudoku matrix.
"""
function uncover_givens!(sudoku, matrix)
  for row in 9:-1:1, column in 9:-1:1
    if sudoku[row, column] > 0
      uncover_subset!(matrix, (row, column, sudoku[row, column]))
    end
  end
end

"""
Solves `sudoku`, assuming `matrix` is a sudoku matrix representing an empty
grid. `matrix` will be restored to that state when the call returns.
"""
function solve(sudoku, matrix)
  result = copy(sudoku)
  cover_givens!(sudoku, matrix)
  for entry in find_exact_cover(matrix)
    row, column, number = entry
    result[row, column] = number
  end
  uncover_givens!(sudoku, matrix)

  result
end

"""
Reads the source file containing the sudoku instances to solve.
"""
sudoku_producer() = @task let
  file = open(joinpath(dirname(@__FILE__), "data", "sudokus.txt"))
  while !eof(file)
    readline(file)
    sudoku = Array(Int8, 9, 9)
    for row in 1:9
        sudoku[row, :] = [c - Int8('0') for c in read(file, Int8, 9)]
        readline(file)
    end

    produce(sudoku)
  end
end

# Actually solve Project Euler problem 96. This means solving the sudokus,
# extracting the first three boxes of each, interpreting them as 3-digit
# numbers and adding them up.
let
  result = 0

  matrix = make_sudoku_matrix()
  for sudoku in sudoku_producer()
    sudoku = solve(sudoku, matrix)
    result += 100sudoku[1, 1] + 10sudoku[1, 2] + sudoku[1, 3]
  end

  @test result == 24702
end


text:
using Test
using StatsBase
using CircleFit

@testset "Analytic Fits" begin
    @testset "Pratt" begin
        include("pratt.jl")
    end
    @testset "Taubin" begin
        include("taubin.jl")
    end
    @testset "Kasa" begin
        include("kasa.jl")
    end
    @testset "GRAF" begin
        include("graf.jl")
    end
end
@testset "StatsModel" begin
    include("Circle.jl")
end