text:
@doc raw"""
    SpecialLinear{n,𝔽} <:
        AbstractGroupManifold{𝔽,MultiplicationOperation,DefaultEmbeddingType}

The special linear group ``\mathrm{SL}(n,𝔽)`` that is, the group of all invertible matrices
with unit determinant in ``𝔽^{n×n}``.

The Lie algebra ``𝔰𝔩(n, 𝔽) = T_e \mathrm{SL}(n,𝔽)`` is the set of all matrices in
``𝔽^{n×n}`` with trace of zero. By default, tangent vectors ``X_p ∈ T_p \mathrm{SL}(n,𝔽)``
for ``p ∈ \mathrm{SL}(n,𝔽)`` are represented with their corresponding Lie algebra vector
``X_e = p^{-1}X_p ∈ 𝔰𝔩(n, 𝔽)``.

The default metric is the same left-``\mathrm{GL}(n)``-right-``\mathrm{O}(n)``-invariant
metric used for [`GeneralLinear(n, 𝔽)`](@ref). The resulting geodesic on
``\mathrm{GL}(n,𝔽)`` emanating from an element of ``\mathrm{SL}(n,𝔽)`` in the direction of
an element of ``𝔰𝔩(n, 𝔽)`` is a closed subgroup of ``\mathrm{SL}(n,𝔽)``. As a result, most
metric functions forward to `GeneralLinear`.
"""
struct SpecialLinear{n,𝔽} <:
       AbstractGroupManifold{𝔽,MultiplicationOperation,TransparentIsometricEmbedding} end

SpecialLinear(n, 𝔽::AbstractNumbers=ℝ) = SpecialLinear{n,𝔽}()

function allocation_promotion_function(::SpecialLinear{n,ℂ}, f, args::Tuple) where {n}
    return complex
end

function check_point(G::SpecialLinear{n,𝔽}, p; kwargs...) where {n,𝔽}
    mpv = check_point(Euclidean(n, n; field=𝔽), p; kwargs...)
    mpv === nothing || return mpv
    detp = det(p)
    if !isapprox(detp, 1; kwargs...)
        return DomainError(
            detp,
            "The matrix $(p) does not lie on $(G), since it does not have a unit " *
            "determinant.",
        )
    end
    return nothing
end
check_point(::GT, ::Identity{GT}; kwargs...) where {GT<:SpecialLinear} = nothing
function check_point(G::SpecialLinear, e::Identity; kwargs...)
    return DomainError(e, "The identity element $(e) does not belong to $(G).")
end

function check_vector(G::SpecialLinear, p, X; kwargs...)
    mpv = check_vector(decorated_manifold(G), p, X; kwargs...)
    mpv === nothing || return mpv
    trX = tr(inverse_translate_diff(G, p, p, X, LeftAction()))
    if !isapprox(trX, 0; kwargs...)
        return DomainError(
            trX,
            "The matrix $(X) does not lie in the tangent space of $(G) at $(p), since " *
            "its Lie algebra representation is not traceless.",
        )
    end
    return nothing
end

decorated_manifold(::SpecialLinear{n,𝔽}) where {n,𝔽} = GeneralLinear(n, 𝔽)

default_metric_dispatch(::SpecialLinear, ::EuclideanMetric) = Val(true)
default_metric_dispatch(::SpecialLinear, ::LeftInvariantMetric{EuclideanMetric}) = Val(true)

inverse_translate_diff(::SpecialLinear, p, q, X, ::LeftAction) = X
inverse_translate_diff(::SpecialLinear, p, q, X, ::RightAction) = p * X / p

function inverse_translate_diff!(G::SpecialLinear, Y, p, q, X, conv::ActionDirection)
    return copyto!(Y, inverse_translate_diff(G, p, q, X, conv))
end

function manifold_dimension(G::SpecialLinear)
    return manifold_dimension(decorated_manifold(G)) - real_dimension(number_system(G))
end

@doc raw"""
    project(G::SpecialLinear, p)

Project ``p ∈ \mathrm{GL}(n, 𝔽)`` to the [`SpecialLinear`](@ref) group
``G=\mathrm{SL}(n, 𝔽)``.

Given the singular value decomposition of ``p``, written ``p = U S V^\mathrm{H}``, the
formula for the projection is

````math
\operatorname{proj}_{\mathrm{SL}(n, 𝔽)}(p) = U S D V^\mathrm{H},
````
where

````math
D_{ij} = δ_{ij} \begin{cases}
    1            & \text{ if } i ≠ n \\
    \det(p)^{-1} & \text{ if } i = n
\end{cases}.
````
"""
project(::SpecialLinear, p)

function project!(::SpecialLinear{n}, q, p) where {n}
    detp = det(p)
    isapprox(detp, 1) && return copyto!(q, p)
    F = svd(p)
    q .= F.U .* F.S'
    q[:, n] ./= detp
    mul!_safe(q, q, F.Vt)
    return q
end

@doc raw"""
    project(G::SpecialLinear, p, X)

Orthogonally project ``X ∈ 𝔽^{n × n}`` onto the tangent space of ``p`` to the
[`SpecialLinear`](@ref) ``G = \mathrm{SL}(n, 𝔽)``. The formula reads
````math
\operatorname{proj}_{p}
    = (\mathrm{d}L_p)_e ∘ \operatorname{proj}_{𝔰𝔩(n, 𝔽)} ∘ (\mathrm{d}L_p^{-1})_p
    \colon X ↦ X - \frac{\operatorname{tr}(X)}{n} I,
````
where the last expression uses the tangent space representation as the Lie algebra.
"""
project(::SpecialLinear, p, X)

function project!(G::SpecialLinear{n}, Y, p, X) where {n}
    inverse_translate_diff!(G, Y, p, p, X, LeftAction())
    Y[diagind(n, n)] .-= tr(Y) / n
    translate_diff!(G, Y, p, p, Y, LeftAction())
    return Y
end

function decorator_transparent_dispatch(::typeof(project), ::SpecialLinear, args...)
    return Val(:parent)
end

Base.show(io::IO, ::SpecialLinear{n,𝔽}) where {n,𝔽} = print(io, "SpecialLinear($n, $𝔽)")

translate_diff(::SpecialLinear, p, q, X, ::LeftAction) = X
translate_diff(::SpecialLinear, p, q, X, ::RightAction) = p \ X * p

function translate_diff!(G::SpecialLinear, Y, p, q, X, conv::ActionDirection)
    return copyto!(Y, translate_diff(G, p, q, X, conv))
end


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

using Markdown
using InteractiveUtils

# ╔═╡ 0d09e2e8-f6fd-11eb-0ce7-995afaa52c9f
using CSV

# ╔═╡ ba0d30d4-e44a-46a1-99b1-0c7cfd127398
using Dates

# ╔═╡ 4aeb90c8-73ac-4c04-a32c-b41db6951ed6
using Plots

# ╔═╡ b17e0e48-f25c-421a-bde6-0003dde62d46
md"""
The code in this notebook accompanies the essay "Riding the Covid Coaster," by Brian Hayes, published 17 August 2021 at [http://bit-player.org/2021/riding-the-covid-coaster](http://bit-player.org/2021/riding-the-covid-coaster). It explores various approaches to understanding the trajectory of the Covid-19 epidemic in the United States during its first 18 months.

This is one of three notebooks with code for the project:

* covidcurve.jl covers the reconstruction of the Covid-19 incidence curve and attempts to apply Fourier methods, looking for periodic signals in the data. Also a look at time derivatives. Includes code for figures 1, 3, 4, 5, 6, 7, 8, 9, 10, 12, 16.

* SIR_model.jl deals with exponential growth in epidemic processes, and models based on that idea. Figures 11, 13, 14, 17, 18, 19, 20, 21, 23, 24.

* us_states_data.jl breaks down the national Covid data set into records for inividual states and regions. Code for Figure 22.

The underlying data for most of this work was collected and curated by _The New York Times_. The archive is available at [https://github.com/nytimes/covid-19-data](https://github.com/nytimes/covid-19-data). The version I used in the code below, including data from 21 January 2020 through 20 July 2021, is commit c3ab8c1beba1f4728d284c7b1e58d7074254aff8. You can access the identical set of files at [https://github.com/nytimes/covid-19-data/tree/c3ab8c1beba1f4728d284c7b1e58d7074254aff8](https://github.com/nytimes/covid-19-data/tree/c3ab8c1beba1f4728d284c7b1e58d7074254aff8). But you should probably get the most up-to-date version, with the latest data.

Within the _Times_ archive I have used the files within a folder named "rolling-averages," which has daily new cases rather than cumulative cases, and has precomputed the seven-day trailing average of the data sequences.

The code is written in the [Julia programming language](https://julialang.org/) and organized in [Pluto.jl notebooks](https://github.com/fonsp/Pluto.jl).

Instructions:

1. You'll need a working installation of Julia with the Pluto.jl package installed. Version 0.15.1 or later is needed to automatically find, load, and install packages.

2. In a terminal window, cd to the directory where you have stored this file. Start Julia, then at the "julia>" prompt, type "using Pluto; Pluto.run('covidcurve.jl')".

3. A browser window will open with this notebook displayed. Pluto will then download all the necessary packages and their dependencies, and will evaluate the cells in the proper order. This can take several minutes, and it can rev up your CPU fan. But then you're done.

"""

# ╔═╡ 0dc3dd14-a874-4974-b9f9-4426c0c6b81f
# Load data from Times archive on state-by-state case numbers.
# Each row gives the number of new cases on a single date for a
# single state. If a state did not report cases on a given date,
# no entry for that state appears. In the period from 2020-01-21
# to 2021-07-20 there are 27,789 entries.

state_data = CSV.File("covid-19-data/rolling-averages/us-states.csv"; select = [:date, :state, :cases_avg])

# ╔═╡ 85ab8b6e-dbf8-49ad-9dcc-1174e2d560eb
md"""
#### Data wrangling

The chronological list is not exactly handy for analysis. What we really want is a matrix with columns indexed by state and rows by date.

I tried doing this the right way, with the DataFrames package, but I couldn't get it to work. That's probably my fault, and at some point I must figure out where I went wrong. Meanwhile I've cobbled together something that works.
"""

# ╔═╡ 918efb32-b482-45f4-ae95-6939a7a22182
# Extract the list of state names from the archive, remove duplicates ("Set"),
# convert to an array ("collect") and alphabetize ("sort").

state_names = sort(collect(Set(state_data.state)))

# ╔═╡ cdcb9cd4-6773-4214-9888-b8a21df59a64
md"""
#### Define regions.

I started out with 10 regions but then did some conolidating to get it down to six.
"""

# ╔═╡ 2b828285-a134-4767-b269-561dc7192f72
new_england = ["Connecticut", "Maine", "Massachusetts", "New Hampshire", "Rhode Island", "Vermont"]

# ╔═╡ 751cbc3d-66b9-41cc-8f71-62f52b18e3f3
mid_atlantic = ["Delaware", "District of Columbia", "Maryland", "New Jersey", "New York", "Pennsylvania"]

# ╔═╡ 659eb69a-8da8-4efd-9b10-4b65c86607be
southeast = ["Florida", "Georgia", "North Carolina", "South Carolina", "Tennessee", "Virginia", "West Virginia"]

# ╔═╡ dcef4817-d70a-48ca-a244-3e5df02920f0
midwest = ["Illinois", "Indiana", "Kentucky", "Michigan", "Missouri", "Ohio", "Wisconsin"]

# ╔═╡ 0411bc2d-51a0-49e1-99d9-d01b488e01c6
south_central = ["Alabama", "Arkansas", "Louisiana", "Mississippi"]

# ╔═╡ 31baf162-0876-436d-b488-10ce92422b82
great_plains = ["Iowa", "Kansas", "Minnesota", "Nebraska", "North Dakota", "Oklahoma", "South Dakota"]

# ╔═╡ 699924a6-3ce4-4255-8a76-e2caf758af96
rocky_mountains = ["Colorado", "Idaho", "Montana", "Utah", "Wyoming"]

# ╔═╡ cb18cf99-5b6b-4c0c-967c-be8237744d7d
southwest = ["Arizona", "Nevada", "New Mexico", "Texas"]

# ╔═╡ 926bacfb-5017-40e7-a3c7-30d5436a3db2
california = ["California"]

# ╔═╡ 7ecff87e-f071-4fab-b0e8-9d66b506c1e2
cascadia = ["Oregon", "Washington"]

# ╔═╡ a1664656-fce9-4e1c-aa84-959b74510dbb
md"""
The six regions are midwest and southwest (both defined above), plus northeast, south, plains and mountains, and westcoast (all defined below by combining smaller categories).
"""

# ╔═╡ 4174e65a-a212-42fb-9a26-b0e958a55081
northeast = vcat(new_england, mid_atlantic)

# ╔═╡ 8a04eead-c372-4821-b182-207659c8695b
south = vcat(southeast, south_central)

# ╔═╡ 60d0fa98-c255-4ad4-8f06-43b309ac635d
plains_and_mountains = vcat(great_plains, rocky_mountains)

# ╔═╡ 97cafd6c-7652-4663-8f4b-15d9486184d1
westcoast = vcat(california, cascadia)

# ╔═╡ 094ecc07-0a40-45e9-a7fe-c992bc526fb3
md"""
#### Building the data matrix
"""

# ╔═╡ f011d6f9-5e10-4822-9eea-b980d5c9312b
# Given a state name, we need to be able to retrieve the corresponding
# data, which will be indexed by the state's position in the alphabetized
# list. So let's build a dictionary that maps a name to an array index.

state_name_dict = Dict([(n, findfirst(x->x==n, state_names)) for n in state_names])

# ╔═╡ bd35653b-f47e-4c1a-adfc-21d42efc8211
# Rows of the matrix correspond to dates, so we need the means to convert
# a given date to an integer index into the array.

start_date = minimum(state_data.date)

# ╔═╡ c9f463c2-a4d1-4fd8-9cf9-82e1f06fb4ed
end_date = maximum(state_data.date)

# ╔═╡ ab170dda-4d4b-41aa-a4c1-70ea9f9bd0f7
function date_to_index(d)
	Dates.value(d) - Dates.value(start_date) + 1
end

# ╔═╡ a360dacc-4303-4468-ad6c-cfeb7b9970c4
# The data matrix has 547 rows (the number of dates in the data set,
# from 2020-01-21 through 2021-07-20) and 55 rows (the number of "states").
# The matrix entries are floating-point numbers representing averaged
# case counts.

# The strategy here is to first create a matrix with all 0.0 entries,
# then loop through the 27,789 entries in the data archive, filling in
# entries at the appropriate row and column address. Date/state combinations
# for which we have no data retain their 0.0 values.

state_data_matrix =
begin
	m = zeros(Float64, date_to_index(end_date), length(state_names))
	for record in state_data
		row = date_to_index(record.date)
		col = state_name_dict[record.state]
		val = record.cases_avg
		m[row, col] = val
	end
	m
end

# ╔═╡ 52cfce07-5819-4e95-b656-fe7ccb751302
md"""
#### Draw the figure

(The labeling of most-prominent states was done by hand.)
"""

# ╔═╡ 0914f935-6d03-4601-9668-4097059ffd73
# savefig(regions_curves, "regions_curves.svg")

# ╔═╡ cc7b1c43-8ee1-4ed6-a758-25f796e92188
monthly_xticks = ([Dates.value(Date(2020,1,1)), Dates.value(Date(2020,2,1)), Dates.value(Date(2020,3,1)), Dates.value(Date(2020,4,1)), Dates.value(Date(2020,5,1)), Dates.value(Date(2020,6,1)), Dates.value(Date(2020,7,1)), Dates.value(Date(2020,8,1)), Dates.value(Date(2020,9,1)), Dates.value(Date(2020,10,1)), Dates.value(Date(2020,11,1)), Dates.value(Date(2020,12,1)), Dates.value(Date(2021,1,1)), Dates.value(Date(2021,2,1)), Dates.value(Date(2021,3,1)), Dates.value(Date(2021,4,1)), Dates.value(Date(2021,5,1)), Dates.value(Date(2021,6,1)), Dates.value(Date(2021,7,1)), ], ["J", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D", "J", "F", "M", "A", "M", "J", "J"])

# ╔═╡ e8609be6-cc0c-4eed-8e2f-df3e7d7cf26b
# Figure 22

regions_curves =
plot([Dates.value(Date(2020,1,21)):Dates.value(Date(2021,7,20))], 				                       [state_data_matrix[:, [state_name_dict[st] for st in northeast]],
		17000 .+ state_data_matrix[:, [state_name_dict[st] for st in midwest]],
		30000 .+ state_data_matrix[:, [state_name_dict[st] for st in plains_and_mountains]],
		40000 .+ state_data_matrix[:, [state_name_dict[st] for st in south]],
		60000 .+ state_data_matrix[:, [state_name_dict[st] for st in southwest]],
		85000 .+ state_data_matrix[:, [state_name_dict[st] for st in westcoast]]],
	size = (640, 800),
	legend = false,
	ylims = [0, 140000],
	xlims = [Dates.value(Date(2020,1,1)), Dates.value(Date(2021,7,31))],
	fontfamily = "helvetica",
	guidefontsize = 12,
	tickfontsize = 11,
	yticks = false,
	xticks = monthly_xticks,
	xlabel = "     2020                                       2021",
	framestyle = :axis,
	linewidth = 0.75,
	linecolor = "#dd4411",
	widen = true)

# ╔═╡ 00000000-0000-0000-0000-000000000001
PLUTO_PROJECT_TOML_CONTENTS = """
[deps]
CSV = "336ed68f-0bac-5ca0-87d4-7b16caf5d00b"
Dates = "ade2ca70-3891-5945-98fb-dc099432e06a"
Plots = "91a5bcdd-55d7-5caf-9e0b-520d859cae80"

[compat]
CSV = "~0.8.5"
Plots = "~1.20.0"
"""

# ╔═╡ 00000000-0000-0000-0000-000000000002
PLUTO_MANIFEST_TOML_CONTENTS = """
# This file is machine-generated - editing it directly is not advised

[[Adapt]]
deps = ["LinearAlgebra"]
git-tree-sha1 = "84918055d15b3114ede17ac6a7182f68870c16f7"
uuid = "79e6a3ab-5dfb-504d-930d-738a2a938a0e"
version = "3.3.1"

[[ArgTools]]
uuid = "0dad84c5-d112-42e6-8d28-ef12dabb789f"

[[Artifacts]]
uuid = "56f22d72-fd6d-98f1-02f0-08ddc0907c33"

[[Base64]]
uuid = "2a0f44e3-6c83-55bd-87e4-b1978d98bd5f"

[[Bzip2_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "c3598e525718abcc440f69cc6d5f60dda0a1b61e"
uuid = "6e34b625-4abd-537c-b88f-471c36dfa7a0"
version = "1.0.6+5"

[[CSV]]
deps = ["Dates", "Mmap", "Parsers", "PooledArrays", "SentinelArrays", "Tables", "Unicode"]
git-tree-sha1 = "b83aa3f513be680454437a0eee21001607e5d983"
uuid = "336ed68f-0bac-5ca0-87d4-7b16caf5d00b"
version = "0.8.5"

[[Cairo_jll]]
deps = ["Artifacts", "Bzip2_jll", "Fontconfig_jll", "FreeType2_jll", "Glib_jll", "JLLWrappers", "LZO_jll", "Libdl", "Pixman_jll", "Pkg", "Xorg_libXext_jll", "Xorg_libXrender_jll", "Zlib_jll", "libpng_jll"]
git-tree-sha1 = "e2f47f6d8337369411569fd45ae5753ca10394c6"
uuid = "83423d85-b0ee-5818-9007-b63ccbeb887a"
version = "1.16.0+6"

[[ColorSchemes]]
deps = ["ColorTypes", "Colors", "FixedPointNumbers", "Random", "StaticArrays"]
git-tree-sha1 = "ed268efe58512df8c7e224d2e170afd76dd6a417"
uuid = "35d6a980-a343-548e-a6ea-1d62b119f2f4"
version = "3.13.0"

[[ColorTypes]]
deps = ["FixedPointNumbers", "Random"]
git-tree-sha1 = "024fe24d83e4a5bf5fc80501a314ce0d1aa35597"
uuid = "3da002f7-5984-5a60-b8a6-cbb66c0b333f"
version = "0.11.0"

[[Colors]]
deps = ["ColorTypes", "FixedPointNumbers", "Reexport"]
git-tree-sha1 = "417b0ed7b8b838aa6ca0a87aadf1bb9eb111ce40"
uuid = "5ae59095-9a9b-59fe-a467-6f913c188581"
version = "0.12.8"

[[Compat]]
deps = ["Base64", "Dates", "DelimitedFiles", "Distributed", "InteractiveUtils", "LibGit2", "Libdl", "LinearAlgebra", "Markdown", "Mmap", "Pkg", "Printf", "REPL", "Random", "SHA", "Serialization", "SharedArrays", "Sockets", "SparseArrays", "Statistics", "Test", "UUIDs", "Unicode"]
git-tree-sha1 = "344f143fa0ec67e47917848795ab19c6a455f32c"
uuid = "34da2185-b29b-5c13-b0c7-acf172513d20"
version = "3.32.0"

[[CompilerSupportLibraries_jll]]
deps = ["Artifacts", "Libdl"]
uuid = "e66e0078-7015-5450-92f7-15fbd957f2ae"

[[Contour]]
deps = ["StaticArrays"]
git-tree-sha1 = "9f02045d934dc030edad45944ea80dbd1f0ebea7"
uuid = "d38c429a-6771-53c6-b99e-75d170b6e991"
version = "0.5.7"

[[DataAPI]]
git-tree-sha1 = "ee400abb2298bd13bfc3df1c412ed228061a2385"
uuid = "9a962f9c-6df0-11e9-0e5d-c546b8b5ee8a"
version = "1.7.0"

[[DataStructures]]
deps = ["Compat", "InteractiveUtils", "OrderedCollections"]
git-tree-sha1 = "4437b64df1e0adccc3e5d1adbc3ac741095e4677"
uuid = "864edb3b-99cc-5e75-8d2d-829cb0a9cfe8"
version = "0.18.9"

[[DataValueInterfaces]]
git-tree-sha1 = "bfc1187b79289637fa0ef6d4436ebdfe6905cbd6"
uuid = "e2d170a0-9d28-54be-80f0-106bbe20a464"
version = "1.0.0"

[[Dates]]
deps = ["Printf"]
uuid = "ade2ca70-3891-5945-98fb-dc099432e06a"

[[DelimitedFiles]]
deps = ["Mmap"]
uuid = "8bb1440f-4735-579b-a4ab-409b98df4dab"

[[Distributed]]
deps = ["Random", "Serialization", "Sockets"]
uuid = "8ba89e20-285c-5b6f-9357-94700520ee1b"

[[Downloads]]
deps = ["ArgTools", "LibCURL", "NetworkOptions"]
uuid = "f43a241f-c20a-4ad4-852c-f6b1247861c6"

[[EarCut_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "92d8f9f208637e8d2d28c664051a00569c01493d"
uuid = "5ae413db-bbd1-5e63-b57d-d24a61df00f5"
version = "2.1.5+1"

[[Expat_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "b3bfd02e98aedfa5cf885665493c5598c350cd2f"
uuid = "2e619515-83b5-522b-bb60-26c02a35a201"
version = "2.2.10+0"

[[FFMPEG]]
deps = ["FFMPEG_jll"]
git-tree-sha1 = "b57e3acbe22f8484b4b5ff66a7499717fe1a9cc8"
uuid = "c87230d0-a227-11e9-1b43-d7ebe4e7570a"
version = "0.4.1"

[[FFMPEG_jll]]
deps = ["Artifacts", "Bzip2_jll", "FreeType2_jll", "FriBidi_jll", "JLLWrappers", "LAME_jll", "LibVPX_jll", "Libdl", "Ogg_jll", "OpenSSL_jll", "Opus_jll", "Pkg", "Zlib_jll", "libass_jll", "libfdk_aac_jll", "libvorbis_jll", "x264_jll", "x265_jll"]
git-tree-sha1 = "3cc57ad0a213808473eafef4845a74766242e05f"
uuid = "b22a6f82-2f65-5046-a5b2-351ab43fb4e5"
version = "4.3.1+4"

[[FixedPointNumbers]]
deps = ["Statistics"]
git-tree-sha1 = "335bfdceacc84c5cdf16aadc768aa5ddfc5383cc"
uuid = "53c48c17-4a7d-5ca2-90c5-79b7896eea93"
version = "0.8.4"

[[Fontconfig_jll]]
deps = ["Artifacts", "Bzip2_jll", "Expat_jll", "FreeType2_jll", "JLLWrappers", "Libdl", "Libuuid_jll", "Pkg", "Zlib_jll"]
git-tree-sha1 = "35895cf184ceaab11fd778b4590144034a167a2f"
uuid = "a3f928ae-7b40-5064-980b-68af3947d34b"
version = "2.13.1+14"

[[Formatting]]
deps = ["Printf"]
git-tree-sha1 = "8339d61043228fdd3eb658d86c926cb282ae72a8"
uuid = "59287772-0a20-5a39-b81b-1366585eb4c0"
version = "0.4.2"

[[FreeType2_jll]]
deps = ["Artifacts", "Bzip2_jll", "JLLWrappers", "Libdl", "Pkg", "Zlib_jll"]
git-tree-sha1 = "cbd58c9deb1d304f5a245a0b7eb841a2560cfec6"
uuid = "d7e528f0-a631-5988-bf34-fe36492bcfd7"
version = "2.10.1+5"

[[FriBidi_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "aa31987c2ba8704e23c6c8ba8a4f769d5d7e4f91"
uuid = "559328eb-81f9-559d-9380-de523a88c83c"
version = "1.0.10+0"

[[Future]]
deps = ["Random"]
uuid = "9fa8497b-333b-5362-9e8d-4d0656e87820"

[[GLFW_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Libglvnd_jll", "Pkg", "Xorg_libXcursor_jll", "Xorg_libXi_jll", "Xorg_libXinerama_jll", "Xorg_libXrandr_jll"]
git-tree-sha1 = "dba1e8614e98949abfa60480b13653813d8f0157"
uuid = "0656b61e-2033-5cc2-a64a-77c0f6c09b89"
version = "3.3.5+0"

[[GR]]
deps = ["Base64", "DelimitedFiles", "GR_jll", "HTTP", "JSON", "Libdl", "LinearAlgebra", "Pkg", "Printf", "Random", "Serialization", "Sockets", "Test", "UUIDs"]
git-tree-sha1 = "182da592436e287758ded5be6e32c406de3a2e47"
uuid = "28b8d3ca-fb5f-59d9-8090-bfdbd6d07a71"
version = "0.58.1"

[[GR_jll]]
deps = ["Artifacts", "Bzip2_jll", "Cairo_jll", "FFMPEG_jll", "Fontconfig_jll", "GLFW_jll", "JLLWrappers", "JpegTurbo_jll", "Libdl", "Libtiff_jll", "Pixman_jll", "Pkg", "Qt5Base_jll", "Zlib_jll", "libpng_jll"]
git-tree-sha1 = "d59e8320c2747553788e4fc42231489cc602fa50"
uuid = "d2c73de3-f751-5644-a686-071e5b155ba9"
version = "0.58.1+0"

[[GeometryBasics]]
deps = ["EarCut_jll", "IterTools", "LinearAlgebra", "StaticArrays", "StructArrays", "Tables"]
git-tree-sha1 = "58bcdf5ebc057b085e58d95c138725628dd7453c"
uuid = "5c1252a2-5f33-56bf-86c9-59e7332b4326"
version = "0.4.1"

[[Gettext_jll]]
deps = ["Artifacts", "CompilerSupportLibraries_jll", "JLLWrappers", "Libdl", "Libiconv_jll", "Pkg", "XML2_jll"]
git-tree-sha1 = "9b02998aba7bf074d14de89f9d37ca24a1a0b046"
uuid = "78b55507-aeef-58d4-861c-77aaff3498b1"
version = "0.21.0+0"

[[Glib_jll]]
deps = ["Artifacts", "Gettext_jll", "JLLWrappers", "Libdl", "Libffi_jll", "Libiconv_jll", "Libmount_jll", "PCRE_jll", "Pkg", "Zlib_jll"]
git-tree-sha1 = "7bf67e9a481712b3dbe9cb3dac852dc4b1162e02"
uuid = "7746bdde-850d-59dc-9ae8-88ece973131d"
version = "2.68.3+0"

[[Grisu]]
git-tree-sha1 = "53bb909d1151e57e2484c3d1b53e19552b887fb2"
uuid = "42e2da0e-8278-4e71-bc24-59509adca0fe"
version = "1.0.2"

[[HTTP]]
deps = ["Base64", "Dates", "IniFile", "Logging", "MbedTLS", "NetworkOptions", "Sockets", "URIs"]
git-tree-sha1 = "44e3b40da000eab4ccb1aecdc4801c040026aeb5"
uuid = "cd3eb016-35fb-5094-929b-558a96fad6f3"
version = "0.9.13"

[[IniFile]]
deps = ["Test"]
git-tree-sha1 = "098e4d2c533924c921f9f9847274f2ad89e018b8"
uuid = "83e8ac13-25f8-5344-8a64-a9f2b223428f"
version = "0.5.0"

[[InteractiveUtils]]
deps = ["Markdown"]
uuid = "b77e0a4c-d291-57a0-90e8-8db25a27a240"

[[IterTools]]
git-tree-sha1 = "05110a2ab1fc5f932622ffea2a003221f4782c18"
uuid = "c8e1da08-722c-5040-9ed9-7db0dc04731e"
version = "1.3.0"

[[IteratorInterfaceExtensions]]
git-tree-sha1 = "a3f24677c21f5bbe9d2a714f95dcd58337fb2856"
uuid = "82899510-4779-5014-852e-03e436cf321d"
version = "1.0.0"

[[JLLWrappers]]
deps = ["Preferences"]
git-tree-sha1 = "642a199af8b68253517b80bd3bfd17eb4e84df6e"
uuid = "692b3bcd-3c85-4b1f-b108-f13ce0eb3210"
version = "1.3.0"

[[JSON]]
deps = ["Dates", "Mmap", "Parsers", "Unicode"]
git-tree-sha1 = "8076680b162ada2a031f707ac7b4953e30667a37"
uuid = "682c06a0-de6a-54ab-a142-c8b1cf79cde6"
version = "0.21.2"

[[JpegTurbo_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "d735490ac75c5cb9f1b00d8b5509c11984dc6943"
uuid = "aacddb02-875f-59d6-b918-886e6ef4fbf8"
version = "2.1.0+0"

[[LAME_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "f6250b16881adf048549549fba48b1161acdac8c"
uuid = "c1c5ebd0-6772-5130-a774-d5fcae4a789d"
version = "3.100.1+0"

[[LZO_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "e5b909bcf985c5e2605737d2ce278ed791b89be6"
uuid = "dd4b983a-f0e5-5f8d-a1b7-129d4a5fb1ac"
version = "2.10.1+0"

[[LaTeXStrings]]
git-tree-sha1 = "c7f1c695e06c01b95a67f0cd1d34994f3e7db104"
uuid = "b964fa9f-0449-5b57-a5c2-d3ea65f4040f"
version = "1.2.1"

[[Latexify]]
deps = ["Formatting", "InteractiveUtils", "LaTeXStrings", "MacroTools", "Markdown", "Printf", "Requires"]
git-tree-sha1 = "a4b12a1bd2ebade87891ab7e36fdbce582301a92"
uuid = "23fbe1c1-3f47-55db-b15f-69d7ec21a316"
version = "0.15.6"

[[LibCURL]]
deps = ["LibCURL_jll", "MozillaCACerts_jll"]
uuid = "b27032c2-a3e7-50c8-80cd-2d36dbcbfd21"

[[LibCURL_jll]]
deps = ["Artifacts", "LibSSH2_jll", "Libdl", "MbedTLS_jll", "Zlib_jll", "nghttp2_jll"]
uuid = "deac9b47-8bc7-5906-a0fe-35ac56dc84c0"

[[LibGit2]]
deps = ["Base64", "NetworkOptions", "Printf", "SHA"]
uuid = "76f85450-5226-5b5a-8eaa-529ad045b433"

[[LibSSH2_jll]]
deps = ["Artifacts", "Libdl", "MbedTLS_jll"]
uuid = "29816b5a-b9ab-546f-933c-edad1886dfa8"

[[LibVPX_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "12ee7e23fa4d18361e7c2cde8f8337d4c3101bc7"
uuid = "dd192d2f-8180-539f-9fb4-cc70b1dcf69a"
version = "1.10.0+0"

[[Libdl]]
uuid = "8f399da3-3557-5675-b5ff-fb832c97cbdb"

[[Libffi_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "761a393aeccd6aa92ec3515e428c26bf99575b3b"
uuid = "e9f186c6-92d2-5b65-8a66-fee21dc1b490"
version = "3.2.2+0"

[[Libgcrypt_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Libgpg_error_jll", "Pkg"]
git-tree-sha1 = "64613c82a59c120435c067c2b809fc61cf5166ae"
uuid = "d4300ac3-e22c-5743-9152-c294e39db1e4"
version = "1.8.7+0"

[[Libglvnd_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_libX11_jll", "Xorg_libXext_jll"]
git-tree-sha1 = "7739f837d6447403596a75d19ed01fd08d6f56bf"
uuid = "7e76a0d4-f3c7-5321-8279-8d96eeed0f29"
version = "1.3.0+3"

[[Libgpg_error_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "c333716e46366857753e273ce6a69ee0945a6db9"
uuid = "7add5ba3-2f88-524e-9cd5-f83b8a55f7b8"
version = "1.42.0+0"

[[Libiconv_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "42b62845d70a619f063a7da093d995ec8e15e778"
uuid = "94ce4f54-9a6c-5748-9c1c-f9c7231a4531"
version = "1.16.1+1"

[[Libmount_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "9c30530bf0effd46e15e0fdcf2b8636e78cbbd73"
uuid = "4b2f31a3-9ecc-558c-b454-b3730dcb73e9"
version = "2.35.0+0"

[[Libtiff_jll]]
deps = ["Artifacts", "JLLWrappers", "JpegTurbo_jll", "Libdl", "Pkg", "Zlib_jll", "Zstd_jll"]
git-tree-sha1 = "340e257aada13f95f98ee352d316c3bed37c8ab9"
uuid = "89763e89-9b03-5906-acba-b20f662cd828"
version = "4.3.0+0"

[[Libuuid_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "7f3efec06033682db852f8b3bc3c1d2b0a0ab066"
uuid = "38a345b3-de98-5d2b-a5d3-14cd9215e700"
version = "2.36.0+0"

[[LinearAlgebra]]
deps = ["Libdl"]
uuid = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e"

[[Logging]]
uuid = "56ddb016-857b-54e1-b83d-db4d58db5568"

[[MacroTools]]
deps = ["Markdown", "Random"]
git-tree-sha1 = "0fb723cd8c45858c22169b2e42269e53271a6df7"
uuid = "1914dd2f-81c6-5fcd-8719-6d5c9610ff09"
version = "0.5.7"

[[Markdown]]
deps = ["Base64"]
uuid = "d6f4376e-aef5-505a-96c1-9c027394607a"

[[MbedTLS]]
deps = ["Dates", "MbedTLS_jll", "Random", "Sockets"]
git-tree-sha1 = "1c38e51c3d08ef2278062ebceade0e46cefc96fe"
uuid = "739be429-bea8-5141-9913-cc70e7f3736d"
version = "1.0.3"

[[MbedTLS_jll]]
deps = ["Artifacts", "Libdl"]
uuid = "c8ffd9c3-330d-5841-b78e-0817d7145fa1"

[[Measures]]
git-tree-sha1 = "e498ddeee6f9fdb4551ce855a46f54dbd900245f"
uuid = "442fdcdd-2543-5da2-b0f3-8c86c306513e"
version = "0.3.1"

[[Missings]]
deps = ["DataAPI"]
git-tree-sha1 = "4ea90bd5d3985ae1f9a908bd4500ae88921c5ce7"
uuid = "e1d29d7a-bbdc-5cf2-9ac0-f12de2c33e28"
version = "1.0.0"

[[Mmap]]
uuid = "a63ad114-7e13-5084-954f-fe012c677804"

[[MozillaCACerts_jll]]
uuid = "14a3606d-f60d-562e-9121-12d972cd8159"

[[NaNMath]]
git-tree-sha1 = "bfe47e760d60b82b66b61d2d44128b62e3a369fb"
uuid = "77ba4419-2d1f-58cd-9bb1-8ffee604a2e3"
version = "0.3.5"

[[NetworkOptions]]
uuid = "ca575930-c2e3-43a9-ace4-1e988b2c1908"

[[Ogg_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "7937eda4681660b4d6aeeecc2f7e1c81c8ee4e2f"
uuid = "e7412a2a-1a6e-54c0-be00-318e2571c051"
version = "1.3.5+0"

[[OpenSSL_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "15003dcb7d8db3c6c857fda14891a539a8f2705a"
uuid = "458c3c95-2e84-50aa-8efc-19380b2a3a95"
version = "1.1.10+0"

[[Opus_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "51a08fb14ec28da2ec7a927c4337e4332c2a4720"
uuid = "91d4177d-7536-5919-b921-800302f37372"
version = "1.3.2+0"

[[OrderedCollections]]
git-tree-sha1 = "85f8e6578bf1f9ee0d11e7bb1b1456435479d47c"
uuid = "bac558e1-5e72-5ebc-8fee-abe8a469f55d"
version = "1.4.1"

[[PCRE_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "b2a7af664e098055a7529ad1a900ded962bca488"
uuid = "2f80f16e-611a-54ab-bc61-aa92de5b98fc"
version = "8.44.0+0"

[[Parsers]]
deps = ["Dates"]
git-tree-sha1 = "bfd7d8c7fd87f04543810d9cbd3995972236ba1b"
uuid = "69de0a69-1ddd-5017-9359-2bf0b02dc9f0"
version = "1.1.2"

[[Pixman_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "b4f5d02549a10e20780a24fce72bea96b6329e29"
uuid = "30392449-352a-5448-841d-b1acce4e97dc"
version = "0.40.1+0"

[[Pkg]]
deps = ["Artifacts", "Dates", "Downloads", "LibGit2", "Libdl", "Logging", "Markdown", "Printf", "REPL", "Random", "SHA", "Serialization", "TOML", "Tar", "UUIDs", "p7zip_jll"]
uuid = "44cfe95a-1eb2-52ea-b672-e2afdf69b78f"

[[PlotThemes]]
deps = ["PlotUtils", "Requires", "Statistics"]
git-tree-sha1 = "a3a964ce9dc7898193536002a6dd892b1b5a6f1d"
uuid = "ccf2f8ad-2431-5c83-bf29-c5338b663b6a"
version = "2.0.1"

[[PlotUtils]]
deps = ["ColorSchemes", "Colors", "Dates", "Printf", "Random", "Reexport", "Statistics"]
git-tree-sha1 = "501c20a63a34ac1d015d5304da0e645f42d91c9f"
uuid = "995b91a9-d308-5afd-9ec6-746e21dbc043"
version = "1.0.11"

[[Plots]]
deps = ["Base64", "Contour", "Dates", "FFMPEG", "FixedPointNumbers", "GR", "GeometryBasics", "JSON", "Latexify", "LinearAlgebra", "Measures", "NaNMath", "PlotThemes", "PlotUtils", "Printf", "REPL", "Random", "RecipesBase", "RecipesPipeline", "Reexport", "Requires", "Scratch", "Showoff", "SparseArrays", "Statistics", "StatsBase", "UUIDs"]
git-tree-sha1 = "e39bea10478c6aff5495ab522517fae5134b40e3"
uuid = "91a5bcdd-55d7-5caf-9e0b-520d859cae80"
version = "1.20.0"

[[PooledArrays]]
deps = ["DataAPI", "Future"]
git-tree-sha1 = "cde4ce9d6f33219465b55162811d8de8139c0414"
uuid = "2dfb63ee-cc39-5dd5-95bd-886bf059d720"
version = "1.2.1"

[[Preferences]]
deps = ["TOML"]
git-tree-sha1 = "00cfd92944ca9c760982747e9a1d0d5d86ab1e5a"
uuid = "21216c6a-2e73-6563-6e65-726566657250"
version = "1.2.2"

[[Printf]]
deps = ["Unicode"]
uuid = "de0858da-6303-5e67-8744-51eddeeeb8d7"

[[Qt5Base_jll]]
deps = ["Artifacts", "CompilerSupportLibraries_jll", "Fontconfig_jll", "Glib_jll", "JLLWrappers", "Libdl", "Libglvnd_jll", "OpenSSL_jll", "Pkg", "Xorg_libXext_jll", "Xorg_libxcb_jll", "Xorg_xcb_util_image_jll", "Xorg_xcb_util_keysyms_jll", "Xorg_xcb_util_renderutil_jll", "Xorg_xcb_util_wm_jll", "Zlib_jll", "xkbcommon_jll"]
git-tree-sha1 = "ad368663a5e20dbb8d6dc2fddeefe4dae0781ae8"
uuid = "ea2cea3b-5b76-57ae-a6ef-0a8af62496e1"
version = "5.15.3+0"

[[REPL]]
deps = ["InteractiveUtils", "Markdown", "Sockets", "Unicode"]
uuid = "3fa0cd96-eef1-5676-8a61-b3b8758bbffb"

[[Random]]
deps = ["Serialization"]
uuid = "9a3f8284-a2c9-5f02-9a11-845980a1fd5c"

[[RecipesBase]]
git-tree-sha1 = "b3fb709f3c97bfc6e948be68beeecb55a0b340ae"
uuid = "3cdcf5f2-1ef4-517c-9805-6587b60abb01"
version = "1.1.1"

[[RecipesPipeline]]
deps = ["Dates", "NaNMath", "PlotUtils", "RecipesBase"]
git-tree-sha1 = "2a7a2469ed5d94a98dea0e85c46fa653d76be0cd"
uuid = "01d81517-befc-4cb6-b9ec-a95719d0359c"
version = "0.3.4"

[[Reexport]]
git-tree-sha1 = "5f6c21241f0f655da3952fd60aa18477cf96c220"
uuid = "189a3867-3050-52da-a836-e630ba90ab69"
version = "1.1.0"

[[Requires]]
deps = ["UUIDs"]
git-tree-sha1 = "4036a3bd08ac7e968e27c203d45f5fff15020621"
uuid = "ae029012-a4dd-5104-9daa-d747884805df"
version = "1.1.3"

[[SHA]]
uuid = "ea8e919c-243c-51af-8825-aaa63cd721ce"

[[Scratch]]
deps = ["Dates"]
git-tree-sha1 = "0b4b7f1393cff97c33891da2a0bf69c6ed241fda"
uuid = "6c6a2e73-6563-6170-7368-637461726353"
version = "1.1.0"

[[SentinelArrays]]
deps = ["Dates", "Random"]
git-tree-sha1 = "a3a337914a035b2d59c9cbe7f1a38aaba1265b02"
uuid = "91c51154-3ec4-41a3-a24f-3f23e20d615c"
version = "1.3.6"

[[Serialization]]
uuid = "9e88b42a-f829-5b0c-bbe9-9e923198166b"

[[SharedArrays]]
deps = ["Distributed", "Mmap", "Random", "Serialization"]
uuid = "1a1011a3-84de-559e-8e89-a11a2f7dc383"

[[Showoff]]
deps = ["Dates", "Grisu"]
git-tree-sha1 = "91eddf657aca81df9ae6ceb20b959ae5653ad1de"
uuid = "992d4aef-0814-514b-bc4d-f2e9a6c4116f"
version = "1.0.3"

[[Sockets]]
uuid = "6462fe0b-24de-5631-8697-dd941f90decc"

[[SortingAlgorithms]]
deps = ["DataStructures"]
git-tree-sha1 = "b3363d7460f7d098ca0912c69b082f75625d7508"
uuid = "a2af1166-a08f-5f64-846c-94a0d3cef48c"
version = "1.0.1"

[[SparseArrays]]
deps = ["LinearAlgebra", "Random"]
uuid = "2f01184e-e22b-5df5-ae63-d93ebab69eaf"

[[StaticArrays]]
deps = ["LinearAlgebra", "Random", "Statistics"]
git-tree-sha1 = "b28f39450421d07d89ab5d126fd15e5246350e8a"
uuid = "90137ffa-7385-5640-81b9-e52037218182"
version = "1.2.11"

[[Statistics]]
deps = ["LinearAlgebra", "SparseArrays"]
uuid = "10745b16-79ce-11e8-11f9-7d13ad32a3b2"

[[StatsAPI]]
git-tree-sha1 = "1958272568dc176a1d881acb797beb909c785510"
uuid = "82ae8749-77ed-4fe6-ae5f-f523153014b0"
version = "1.0.0"

[[StatsBase]]
deps = ["DataAPI", "DataStructures", "LinearAlgebra", "Missings", "Printf", "Random", "SortingAlgorithms", "SparseArrays", "Statistics", "StatsAPI"]
git-tree-sha1 = "fed1ec1e65749c4d96fc20dd13bea72b55457e62"
uuid = "2913bbd2-ae8a-5f71-8c99-4fb6c76f3a91"
version = "0.33.9"

[[StructArrays]]
deps = ["Adapt", "DataAPI", "StaticArrays", "Tables"]
git-tree-sha1 = "000e168f5cc9aded17b6999a560b7c11dda69095"
uuid = "09ab397b-f2b6-538f-b94a-2f83cf4a842a"
version = "0.6.0"

[[TOML]]
deps = ["Dates"]
uuid = "fa267f1f-6049-4f14-aa54-33bafae1ed76"

[[TableTraits]]
deps = ["IteratorInterfaceExtensions"]
git-tree-sha1 = "c06b2f539df1c6efa794486abfb6ed2022561a39"
uuid = "3783bdb8-4a98-5b6b-af9a-565f29a5fe9c"
version = "1.0.1"

[[Tables]]
deps = ["DataAPI", "DataValueInterfaces", "IteratorInterfaceExtensions", "LinearAlgebra", "TableTraits", "Test"]
git-tree-sha1 = "d0c690d37c73aeb5ca063056283fde5585a41710"
uuid = "bd369af6-aec1-5ad0-b16a-f7cc5008161c"
version = "1.5.0"

[[Tar]]
deps = ["ArgTools", "SHA"]
uuid = "a4e569a6-e804-4fa4-b0f3-eef7a1d5b13e"

[[Test]]
deps = ["InteractiveUtils", "Logging", "Random", "Serialization"]
uuid = "8dfed614-e22c-5e08-85e1-65c5234f0b40"

[[URIs]]
git-tree-sha1 = "97bbe755a53fe859669cd907f2d96aee8d2c1355"
uuid = "5c2747f8-b7ea-4ff2-ba2e-563bfd36b1d4"
version = "1.3.0"

[[UUIDs]]
deps = ["Random", "SHA"]
uuid = "cf7118a7-6976-5b1a-9a39-7adc72f591a4"

[[Unicode]]
uuid = "4ec0a83e-493e-50e2-b9ac-8f72acf5a8f5"

[[Wayland_jll]]
deps = ["Artifacts", "Expat_jll", "JLLWrappers", "Libdl", "Libffi_jll", "Pkg", "XML2_jll"]
git-tree-sha1 = "3e61f0b86f90dacb0bc0e73a0c5a83f6a8636e23"
uuid = "a2964d1f-97da-50d4-b82a-358c7fce9d89"
version = "1.19.0+0"

[[Wayland_protocols_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Wayland_jll"]
git-tree-sha1 = "2839f1c1296940218e35df0bbb220f2a79686670"
uuid = "2381bf8a-dfd0-557d-9999-79630e7b1b91"
version = "1.18.0+4"

[[XML2_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Libiconv_jll", "Pkg", "Zlib_jll"]
git-tree-sha1 = "1acf5bdf07aa0907e0a37d3718bb88d4b687b74a"
uuid = "02c8fc9c-b97f-50b9-bbe4-9be30ff0a78a"
version = "2.9.12+0"

[[XSLT_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Libgcrypt_jll", "Libgpg_error_jll", "Libiconv_jll", "Pkg", "XML2_jll", "Zlib_jll"]
git-tree-sha1 = "91844873c4085240b95e795f692c4cec4d805f8a"
uuid = "aed1982a-8fda-507f-9586-7b0439959a61"
version = "1.1.34+0"

[[Xorg_libX11_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_libxcb_jll", "Xorg_xtrans_jll"]
git-tree-sha1 = "5be649d550f3f4b95308bf0183b82e2582876527"
uuid = "4f6342f7-b3d2-589e-9d20-edeb45f2b2bc"
version = "1.6.9+4"

[[Xorg_libXau_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "4e490d5c960c314f33885790ed410ff3a94ce67e"
uuid = "0c0b7dd1-d40b-584c-a123-a41640f87eec"
version = "1.0.9+4"

[[Xorg_libXcursor_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_libXfixes_jll", "Xorg_libXrender_jll"]
git-tree-sha1 = "12e0eb3bc634fa2080c1c37fccf56f7c22989afd"
uuid = "935fb764-8cf2-53bf-bb30-45bb1f8bf724"
version = "1.2.0+4"

[[Xorg_libXdmcp_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "4fe47bd2247248125c428978740e18a681372dd4"
uuid = "a3789734-cfe1-5b06-b2d0-1dd0d9d62d05"
version = "1.1.3+4"

[[Xorg_libXext_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_libX11_jll"]
git-tree-sha1 = "b7c0aa8c376b31e4852b360222848637f481f8c3"
uuid = "1082639a-0dae-5f34-9b06-72781eeb8cb3"
version = "1.3.4+4"

[[Xorg_libXfixes_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_libX11_jll"]
git-tree-sha1 = "0e0dc7431e7a0587559f9294aeec269471c991a4"
uuid = "d091e8ba-531a-589c-9de9-94069b037ed8"
version = "5.0.3+4"

[[Xorg_libXi_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_libXext_jll", "Xorg_libXfixes_jll"]
git-tree-sha1 = "89b52bc2160aadc84d707093930ef0bffa641246"
uuid = "a51aa0fd-4e3c-5386-b890-e753decda492"
version = "1.7.10+4"

[[Xorg_libXinerama_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_libXext_jll"]
git-tree-sha1 = "26be8b1c342929259317d8b9f7b53bf2bb73b123"
uuid = "d1454406-59df-5ea1-beac-c340f2130bc3"
version = "1.1.4+4"

[[Xorg_libXrandr_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_libXext_jll", "Xorg_libXrender_jll"]
git-tree-sha1 = "34cea83cb726fb58f325887bf0612c6b3fb17631"
uuid = "ec84b674-ba8e-5d96-8ba1-2a689ba10484"
version = "1.5.2+4"

[[Xorg_libXrender_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_libX11_jll"]
git-tree-sha1 = "19560f30fd49f4d4efbe7002a1037f8c43d43b96"
uuid = "ea2f1a96-1ddc-540d-b46f-429655e07cfa"
version = "0.9.10+4"

[[Xorg_libpthread_stubs_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "6783737e45d3c59a4a4c4091f5f88cdcf0908cbb"
uuid = "14d82f49-176c-5ed1-bb49-ad3f5cbd8c74"
version = "0.1.0+3"

[[Xorg_libxcb_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "XSLT_jll", "Xorg_libXau_jll", "Xorg_libXdmcp_jll", "Xorg_libpthread_stubs_jll"]
git-tree-sha1 = "daf17f441228e7a3833846cd048892861cff16d6"
uuid = "c7cfdc94-dc32-55de-ac96-5a1b8d977c5b"
version = "1.13.0+3"

[[Xorg_libxkbfile_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_libX11_jll"]
git-tree-sha1 = "926af861744212db0eb001d9e40b5d16292080b2"
uuid = "cc61e674-0454-545c-8b26-ed2c68acab7a"
version = "1.1.0+4"

[[Xorg_xcb_util_image_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_xcb_util_jll"]
git-tree-sha1 = "0fab0a40349ba1cba2c1da699243396ff8e94b97"
uuid = "12413925-8142-5f55-bb0e-6d7ca50bb09b"
version = "0.4.0+1"

[[Xorg_xcb_util_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_libxcb_jll"]
git-tree-sha1 = "e7fd7b2881fa2eaa72717420894d3938177862d1"
uuid = "2def613f-5ad1-5310-b15b-b15d46f528f5"
version = "0.4.0+1"

[[Xorg_xcb_util_keysyms_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_xcb_util_jll"]
git-tree-sha1 = "d1151e2c45a544f32441a567d1690e701ec89b00"
uuid = "975044d2-76e6-5fbe-bf08-97ce7c6574c7"
version = "0.4.0+1"

[[Xorg_xcb_util_renderutil_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_xcb_util_jll"]
git-tree-sha1 = "dfd7a8f38d4613b6a575253b3174dd991ca6183e"
uuid = "0d47668e-0667-5a69-a72c-f761630bfb7e"
version = "0.3.9+1"

[[Xorg_xcb_util_wm_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_xcb_util_jll"]
git-tree-sha1 = "e78d10aab01a4a154142c5006ed44fd9e8e31b67"
uuid = "c22f9ab0-d5fe-5066-847c-f4bb1cd4e361"
version = "0.4.1+1"

[[Xorg_xkbcomp_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_libxkbfile_jll"]
git-tree-sha1 = "4bcbf660f6c2e714f87e960a171b119d06ee163b"
uuid = "35661453-b289-5fab-8a00-3d9160c6a3a4"
version = "1.4.2+4"

[[Xorg_xkeyboard_config_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Xorg_xkbcomp_jll"]
git-tree-sha1 = "5c8424f8a67c3f2209646d4425f3d415fee5931d"
uuid = "33bec58e-1273-512f-9401-5d533626f822"
version = "2.27.0+4"

[[Xorg_xtrans_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "79c31e7844f6ecf779705fbc12146eb190b7d845"
uuid = "c5fb5394-a638-5e4d-96e5-b29de1b5cf10"
version = "1.4.0+3"

[[Zlib_jll]]
deps = ["Libdl"]
uuid = "83775a58-1f1d-513f-b197-d71354ab007a"

[[Zstd_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "cc4bf3fdde8b7e3e9fa0351bdeedba1cf3b7f6e6"
uuid = "3161d3a3-bdf6-5164-811a-617609db77b4"
version = "1.5.0+0"

[[libass_jll]]
deps = ["Artifacts", "Bzip2_jll", "FreeType2_jll", "FriBidi_jll", "JLLWrappers", "Libdl", "Pkg", "Zlib_jll"]
git-tree-sha1 = "acc685bcf777b2202a904cdcb49ad34c2fa1880c"
uuid = "0ac62f75-1d6f-5e53-bd7c-93b484bb37c0"
version = "0.14.0+4"

[[libfdk_aac_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "7a5780a0d9c6864184b3a2eeeb833a0c871f00ab"
uuid = "f638f0a6-7fb0-5443-88ba-1cc74229b280"
version = "0.1.6+4"

[[libpng_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Zlib_jll"]
git-tree-sha1 = "94d180a6d2b5e55e447e2d27a29ed04fe79eb30c"
uuid = "b53b4c65-9356-5827-b1ea-8c7a1a84506f"
version = "1.6.38+0"

[[libvorbis_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Ogg_jll", "Pkg"]
git-tree-sha1 = "c45f4e40e7aafe9d086379e5578947ec8b95a8fb"
uuid = "f27f6e37-5d2b-51aa-960f-b287f2bc3b7a"
version = "1.3.7+0"

[[nghttp2_jll]]
deps = ["Artifacts", "Libdl"]
uuid = "8e850ede-7688-5339-a07c-302acd2aaf8d"

[[p7zip_jll]]
deps = ["Artifacts", "Libdl"]
uuid = "3f19e933-33d8-53b3-aaab-bd5110c3b7a0"

[[x264_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "d713c1ce4deac133e3334ee12f4adff07f81778f"
uuid = "1270edf5-f2f9-52d2-97e9-ab00b5d0237a"
version = "2020.7.14+2"

[[x265_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "487da2f8f2f0c8ee0e83f39d13037d6bbf0a45ab"
uuid = "dfaa095f-4041-5dcd-9319-2fabd8486b76"
version = "3.0.0+3"

[[xkbcommon_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg", "Wayland_jll", "Wayland_protocols_jll", "Xorg_libxcb_jll", "Xorg_xkeyboard_config_jll"]
git-tree-sha1 = "ece2350174195bb31de1a63bea3a41ae1aa593b6"
uuid = "d8fb68d0-12a3-5cfd-a85a-d49703b185fd"
version = "0.9.1+5"
"""

# ╔═╡ Cell order:
# ╟─b17e0e48-f25c-421a-bde6-0003dde62d46
# ╠═0d09e2e8-f6fd-11eb-0ce7-995afaa52c9f
# ╠═ba0d30d4-e44a-46a1-99b1-0c7cfd127398
# ╠═4aeb90c8-73ac-4c04-a32c-b41db6951ed6
# ╠═0dc3dd14-a874-4974-b9f9-4426c0c6b81f
# ╟─85ab8b6e-dbf8-49ad-9dcc-1174e2d560eb
# ╠═918efb32-b482-45f4-ae95-6939a7a22182
# ╟─cdcb9cd4-6773-4214-9888-b8a21df59a64
# ╠═2b828285-a134-4767-b269-561dc7192f72
# ╠═751cbc3d-66b9-41cc-8f71-62f52b18e3f3
# ╠═659eb69a-8da8-4efd-9b10-4b65c86607be
# ╠═dcef4817-d70a-48ca-a244-3e5df02920f0
# ╠═0411bc2d-51a0-49e1-99d9-d01b488e01c6
# ╠═31baf162-0876-436d-b488-10ce92422b82
# ╠═699924a6-3ce4-4255-8a76-e2caf758af96
# ╠═cb18cf99-5b6b-4c0c-967c-be8237744d7d
# ╠═926bacfb-5017-40e7-a3c7-30d5436a3db2
# ╠═7ecff87e-f071-4fab-b0e8-9d66b506c1e2
# ╟─a1664656-fce9-4e1c-aa84-959b74510dbb
# ╠═4174e65a-a212-42fb-9a26-b0e958a55081
# ╠═8a04eead-c372-4821-b182-207659c8695b
# ╠═60d0fa98-c255-4ad4-8f06-43b309ac635d
# ╠═97cafd6c-7652-4663-8f4b-15d9486184d1
# ╟─094ecc07-0a40-45e9-a7fe-c992bc526fb3
# ╠═f011d6f9-5e10-4822-9eea-b980d5c9312b
# ╠═bd35653b-f47e-4c1a-adfc-21d42efc8211
# ╠═c9f463c2-a4d1-4fd8-9cf9-82e1f06fb4ed
# ╠═ab170dda-4d4b-41aa-a4c1-70ea9f9bd0f7
# ╠═a360dacc-4303-4468-ad6c-cfeb7b9970c4
# ╟─52cfce07-5819-4e95-b656-fe7ccb751302
# ╠═e8609be6-cc0c-4eed-8e2f-df3e7d7cf26b
# ╠═0914f935-6d03-4601-9668-4097059ffd73
# ╠═cc7b1c43-8ee1-4ed6-a758-25f796e92188
# ╟─00000000-0000-0000-0000-000000000001
# ╟─00000000-0000-0000-0000-000000000002

ext: jl

max_stars_repo_name: bit-player/Covidcurve

max_issues_repo_name: bit-player/Covidcurve

max_forks_repo_name: bit-player/Covidcurve


text:
using Flux, StochasticDiffEq
using NeuralPDE
using Plots
using CUDA

function phi(xi)
    y = Float64[]
    K = 100
    for x in eachcol(xi)
        val = max(K - maximum(x) , 0.00)
        y = push!(y , val)
    end
    y = reshape(y , 1 , size(y)[1] )
    return y
end

d = 1
r = 0.04
sigma = 0.2
xspan = (80.00 , 115.0)
tspan = (0.0 , 1.0)
σ(du , u , p , t) = du .= sigma.*u
μ(du , u , p , t) = du .= r.*u
prob = KolmogorovPDEProblem(μ , σ , phi , xspan , tspan, d)

sdealg = EM()
ensemblealg = EnsembleThreads()
dt = 0.01
dx = 0.01
trajectories = 100000

m = Chain(Dense(d, 64, elu),Dense(64, 128, elu),Dense(128 , 16 , elu) , Dense(16 , 1))
use_gpu = false
if CUDA.functional() == true
  m = fmap(CUDA.cu , m)
  use_gpu = true
end
opt = Flux.ADAM(0.0005)

@time sol = solve(prob, NeuralPDE.NNKolmogorov(m, opt, sdealg, ensemblealg), verbose = true, dt = dt,
            dx = dx , trajectories = trajectories , abstol=1e-6, maxiters = 1000 , use_gpu = use_gpu)

monte_carlo_sol = []
x_out = collect(85:2.00:110.00)
for x in x_out
  u₀= [x]
  g_val(du , u , p , t) = du .= 0.2.*u
  f_val(du , u , p , t) = du .= 0.04.*u
  dt = 0.01
  tspan = (0.0,1.0)
  prob = SDEProblem(f_val,g_val,u₀,tspan)
  output_func(sol,i) = (sol[end],false)
  ensembleprob_val = EnsembleProblem(prob , output_func = output_func )
  sim_val = solve(ensembleprob_val, EM(), EnsembleThreads() , dt=0.01, trajectories=100000,adaptive=false)
  s = reduce(hcat , sim_val.u)
  mean_phi = sum(phi(s))/length(phi(s))
  global monte_carlo_sol = push!(monte_carlo_sol , mean_phi)
end

x_model = reshape(x_out, 1 , size(x_out)[1])
if use_gpu == true
  m = fmap(cpu , m)
end
y_out = m(x_model)
y_out = reshape(y_out , 13 , 1)

plot(x_out , y_out , lw = 3 ,  xaxis="Initial Stock Price", yaxis="Payoff" , label = "NNKolmogorov")
plot!(x_out , monte_carlo_sol , lw = 3 ,  xaxis="Initial Stock Price", yaxis="Payoff" ,label = "Monte Carlo Solutions")

using SciMLTutorials
SciMLTutorials.tutorial_footer(WEAVE_ARGS[:folder],WEAVE_ARGS[:file])

max_stars_repo_name: SciML/SciMLTutorialsOutput

max_issues_repo_name: SciML/SciMLTutorialsOutput

max_forks_repo_name: SciML/SciMLTutorialsOutput


text:
using Roots

# @everywhere function Yfind(Q,P,H)
# @everywhere Hamil(XX,YY,QQ,PP)=( (QQ-XX)^2+(PP-YY)^2 )*( (QQ+XX)^2+(PP+YY)^2 )/((PP^4+2*PP^2*(XX^2-1)+( 1+XX^2)^2 )*(QQ^4+2*QQ^2*(YY^2+1)+(YY^2-1)^2 ))
#
#     @everywhere Y_find1(y)=Hamil(BigInt(0),y,Q,P)-H
#     try
#         Y=find_zero(Y_find1,BigFloat(".1"))
#     catch
#         Y=zeros(BigInt,0)
#     end
# end
function YfindBIG(Q,P,H)
    Y_find1(y)=Hamil(BigFloat("0"),y,Q,P)-H
    try
        Y=find_zero(Y_find1,BigFloat(".1"), maxeval=100,maxfnevals=300,tol=1e-15)
     catch
        Y=zeros(0)
    end
end


text:
TIMERS = Dict{Any,Base.RefValue{Float64}}()

"""
TODO
"""
GetTimer(key) = Base.getindex(TIMERS[key])

"""
TODO
"""
SetTimer(key, time::Number) = (TIMERS[key] = Ref{Float64}(time))

SetTimer("FRAME_TIMER", Dates.time())

"""
TODO
"""
function UpdateTimers()
  global TIMERS
  time = GetTimer("FRAME_TIMER")

  LOCAL_TIMERS = filter(tuple -> (f=first(tuple); isa(f,AbstractFloat) || isa(f,Integer)), collect(TIMERS))
  for (milisec,prevTime) in LOCAL_TIMERS
    r=(time - Base.getindex(prevTime)) >= milisec
    if r Base.setindex!(prevTime, time) end
  end
  SetTimer("FRAME_TIMER", Dates.time())
end

"""
TODO
"""
function OnTime(milisec::Number)
  global TIMERS

  if !haskey(TIMERS,milisec)
    prevTime = 0.0
    SetTimer(milisec, 0.0)
  else
    prevTime = GetTimer(milisec)
  end

  (GetTimer("FRAME_TIMER") - prevTime) >= milisec
end

"""
TODO
"""
function OnTime(milisec::Number, prevTime::Ref{Float64}, time)
  r = (time - Base.getindex(prevTime)) >= milisec
  if r Base.setindex!(prevTime,time) end
  r
end

max_stars_repo_name: Gilga/JuliaOpenGL

max_issues_repo_name: Gilga/JuliaOpenGL

max_forks_repo_name: Gilga/JuliaOpenGL


text:
using Test

include("model.jl")
include("io.jl")

max_stars_repo_name: nnhjy/JuMP-project-template

max_issues_repo_name: nnhjy/JuMP-project-template

max_forks_repo_name: nnhjy/JuMP-project-template


text:
#!/usr/bin/env julia

using Luxor

using Test

using Random
Random.seed!(42)

w, h = 600, 600

fname = "stars.png"
Drawing(w, h, fname)
origin()
cols = [RGB(rand(3)...) for i in 1:50]
background("grey20")
x = -w/2
for y in 100 * randn(h, 1)
    setcolor(cols[rand(1:end)])
    # star(x::Real, y::Real, radius::Real, npoints::Int=5, ratio::Real=0.5, orientation=0, action=:nothing; vertices = false, reversepath=false)
    star(x, y, 10, rand(4:7), rand(3:7)/10, 0, :fill)
    global x += 2
end
@test finish() == true
println("...finished test: output in $(fname)")


text:
"""
    MovingWindowSolution <: AbstractMovingWindowSolution

A composite type for an [`AbstractMovingWindowSolution`](@ref) obtained using an [`AbstractMovingWindowSolver`](@ref).

# Constructors
```julia
MovingWindowSolution(windows, restarts)
MovingWindowSolution(problem::AbstractInitialValueProblem, mowa::MovingWindowSolver)
```

## Arguments
- `windows :: AbstractVector{𝕊} where 𝕊<:AbstractTimeParallelSolution`
- `restarts :: AbstractVector{ℤ} where ℤ<:Integer` : counts window restarts in adaptive loop.

# Functions
- [`firstindex`](@ref) : first index.
- [`getindex`](@ref) : get window.
- [`lastindex`](@ref) : last index.
- [`length`](@ref) : number of windows.
- [`setindex!`](@ref) : set window.
"""
mutable struct MovingWindowSolution{windows_T<:(AbstractVector{𝕊} where 𝕊<:AbstractTimeParallelSolution), restarts_T<:(AbstractVector{ℤ} where ℤ<:Integer)} <: AbstractMovingWindowSolution
    windows::windows_T
    restarts::restarts_T
end

function MovingWindowSolution(problem::AbstractInitialValueProblem, mowa::MovingWindowSolver)
    @↓ (t0, tN) ← tspan = problem
    @↓ τ, Δτ = mowa
    # Δτ == 0 => T = τ => M = 1
    M = Δτ > 0 ? trunc(Integer, (tN - τ) / Δτ) + 1 : 1
    windows = Vector{AbstractTimeParallelSolution}(undef, M)
    restarts = zeros(Integer, M)
    return MovingWindowSolution(windows, restarts)
end

#####
##### Functions
#####

"""
    length(solution::MovingWindowSolution)

returns the number of windows of `solution`.
"""
Base.length(solution::MovingWindowSolution) = length(solution.windows)

"""
    getindex(solution::MovingWindowSolution, m::Int)

returns the `m`-th window of `solution`.
"""
Base.getindex(solution::MovingWindowSolution, m::Integer) = solution.windows[m]

"""
    setindex!(solution::MovingWindowSolution, timeparallelsolution::AbstractTimeParallelSolution, m::Int)

stores a `timeparallelsolution` as the `m`-th window of `solution`.
"""
Base.setindex!(solution::MovingWindowSolution, timeparallelsolution::AbstractTimeParallelSolution, m::Integer) = solution.windows[m] = timeparallelsolution

"""
    firstindex(solution::MovingWindowSolution)

returns the first index of `solution`.
"""
Base.firstindex(solution::MovingWindowSolution) = firstindex(solution.windows)

"""
    lastindex(solution::MovingWindowSolution)

returns the last index of `solution`.
"""
Base.lastindex(solution::MovingWindowSolution) = lastindex(solution.windows)


text:
using Color, Images, FixedPointNumbers

w = 70
h = 50

a = zeros(RGB{Ufixed8}, h, w)
img = Image(a)

img["x", 10:40, "y", 5:35] = color("skyblue")
for i in 45:65, j in (i-25):40
    img["x", i, "y", j] = color("sienna1")
end

imwrite(img, "bitmap_write.ppm")
imwrite(img, "bitmap_write.png")

max_stars_repo_name: ethansaxenian/RosettaDecode

max_issues_repo_name: ethansaxenian/RosettaDecode

max_forks_repo_name: ethansaxenian/RosettaDecode


text:
using GeoMakie, Shapefile

shp = Shapefile.Table("/Users/anshul/Downloads/ne_110m_land/ne_110m_land.shp") |> Shapefile.shapes |> skipmissing |> collect

points = rec_point(coordinates.(shp))

source = LonLat()

dest = Projection("+proj=fouc")

meshes = GeoMakie.toMesh.(rec_project(source, dest, points))

geoaxis(-180, 180, -90, 90; show_axis = false, crs = (dest = dest,))

mesh!(meshes)


text:
using NeurDS
using Test

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


text:
a = "alo"

while a
println("tchau")
end


text:
# computes GARCH(1,1) log likelihood
using Statistics
function garch11(theta, y)
    # dissect the parameter vector
    mu = theta[1]
    rho = theta[2]
    omega = theta[3]
    alpha = theta[4]
    beta = theta[5]
    resid = y[2:end] .- mu .- rho*y[1:end-1]
    n = size(resid,1)
    h = zeros(n)
    # initialize variance; either of these next two are reasonable choices
    h[1] = var(y[1:10])
    #h[1] = var(y)
    rsq = resid.^2.0
    for t = 2:n
        h[t] = omega + alpha*rsq[t-1] + beta*h[t-1]
    end
    logL = -log(sqrt(2.0*pi)) .- 0.5*log.(h) .- 0.5*rsq./h
end

max_stars_repo_name: nilshg/Econometrics

max_issues_repo_name: nilshg/Econometrics

max_forks_repo_name: nilshg/Econometrics


text:
ur2() = uppercase(randstring(2))

# Acceptable type codes in :misc
OK = UInt8[0x00, 0x01,
      0x10, 0x11, 0x12, 0x13, 0x14,
      0x20, 0x21, 0x22, 0x23, 0x24,
      0x30, 0x31, 0x32,
      0x50, 0x51, 0x52, 0x53, 0x54,
      0x60, 0x61, 0x62, 0x63, 0x64,
      0x70, 0x71, 0x72,
      0x80, 0x81,
      0x90, 0x91, 0x92, 0x93, 0x94,
      0xa0, 0xa1, 0xa2, 0xa3, 0xa4,
      0xb0, 0xb1, 0xb2,
      0xd0, 0xd1, 0xd2, 0xd3, 0xd4,
      0xe0, 0xe1, 0xe2, 0xe3, 0xe4,
      0xf0, 0xf1, 0xf2]

# Fill :misc with garbage
function pop_rand_dict!(D::Dict{String,Any}, N::Int)
  for n = 1:N
    t = code2typ(rand(OK))
    k = randstring(rand(2:12))
    if Bool(t <: Real) == true
      D[k] = rand(t)
    elseif Bool(t <: Complex) == true
      D[k] = rand(Complex{real(t)})
    elseif Bool(t <: Array) == true
      y = eltype(t)
      if Bool(y <: Number) == true
        D[k] = rand(y, rand(1:1000))
      end
    end
  end
  if haskey(D, "hc")
    delete!(D, "hc")
  end
  return D
end

"""
   (i,c,u) = getyp2codes(b::Char, s=false::Bool)

Using band code `b`, generate quasi-sane random instrument char code (`i`)
and channel char code (`c`), plus unit string `u`. if s=true, use only seismic
data codes.
"""
function getyp2codes(b::Char, s=false::Bool)
  if s
    # Neglecting gravimeters ('G') and mass position sensors ('M')
    i = rand(['H','L','N'])
    if rand() > 0.2
      c = rand(['Z','N','E'])
    else
      c = rand(['A','B','C','1','2','3','U','V','W'])
    end
    if Base.in(i, ['H','L'])
      u = rand(["m", "m/s"])
    else
      u = "m/s2"
    end
  else
    i = rand(['A','B','D','F','G','I','J','K','M','O','P','Q','R','S','T','U','V','W','Z'])
    if i == 'A' # tiltmeter
      c = rand(['N','E'])
      u = "rad"
    elseif i == 'B' # creep meter
      c = '_'
      u = "m"
      # C is calibration input
    elseif i == 'D' # pressure (barometer, infrasound, hydrophone ∈ 'D')
      c = rand(['O','I','D','F','H','U'])
      u = "Pa"
      # E is an electronic test point
    elseif i == 'F' # magnetometer
      c = rand(['Z','N','E'])
      u = "T"
    elseif i == 'G' # tiltmeter
        c = rand(['A','B','C','1','2','3','U','V','W'])
        u = "m/s2"
    elseif i == 'I' # humidity
      c = rand(['O','I','D'])
      u = "%"
    elseif i == 'J' # rotational seismometer
      c = rand(['Z','N','E','A','B','C','T','R','1','2','3','U','V','W'])
      u = rand(["rad", "rad/s", "rad/s2"])
    elseif i == 'K' # thermal (thermometer or radiometer)
      c = rand(['O', 'I', 'D'])
      u = rand(["Cel","K"])
    elseif i == 'M' # mass position sensor
        c = rand(['A','B','C','1','2','3','U','V','W'])
        u = "m"
    elseif i == 'O' # current gauge
      c = '_'
      u = "m/s"
    elseif i == 'P' # very short-period geophone
      c = rand(['Z','N','E'])
      u = rand(["m", "m/s", "m/s2"])
    elseif i == 'Q' # voltmeter
      c = '_'
      u = "V"
    elseif i == 'R' # rain gauge
      c = '_'
      u = rand(["m", "m/s"])
    elseif i == 'S' # strain gauge
      c = rand(['Z','N','E'])
      u = "m/m"
    elseif i == 'T' # tide gauge
      c = 'Z'
      u = "m"
    elseif i == 'U' # bolometer
      c = '_'
      u = "%{cloud_cover}"
    elseif i == 'V' # volumetric strainmeter
      c = '_'
      u = "m3/m3"
    elseif i == 'W' # wind speed ('S') or direction ('D')
      c = rand(['S','D'])
      u = c == 'S' ? "m/s" : "{direction_vector}"

    # X, Y are instrument-specific...excluded

    elseif i == 'Z' # synthesized beam or stack
      c = rand(['I','C','F','O'])
      u = rand(["m", "m/s", "m/s2"])
    end
  end
  return i,c,u
end


text:
module LeastSquaresOptim

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

using Base: copyto!, fill!, eltype, length, size
using LinearAlgebra: LinearAlgebra, mul!, rmul!, norm, cholesky!, qr!, Symmetric, dot, eigen, axpy!, svd, ldiv!, Transpose, adjoint, Adjoint
using LinearAlgebra.BLAS: gemm!
if VERSION >= v"1.7.0"
    using LinearAlgebra: ColumnNorm
end
using Printf: @printf, @sprintf
using Statistics: mean
using ForwardDiff: JacobianConfig, Chunk, checktag, jacobian!
using FiniteDiff: JacobianCache, finite_difference_jacobian!
import Optim: optimize
if Base.USE_GPL_LIBS
    using SuiteSparse.SPQR: QRSparse
    using SparseArrays: SparseMatrixCSC, sparse, nzrange, nonzeros
end

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

export optimize!,
LeastSquaresProblem,
LeastSquaresProblemAllocated,
LeastSquaresResult,
Dogleg,
LevenbergMarquardt,
optimize

##############################################################################
##
## Load files
##
##############################################################################

include("utils/lsmr.jl")
include("utils/utils.jl")

include("types.jl")
include("optimizer/levenberg_marquardt.jl")
include("optimizer/dogleg.jl")

include("solver/dense_qr.jl")
include("solver/dense_cholesky.jl")
include("solver/iterative_lsmr.jl")

end

max_stars_repo_name: matthieugomez/LeastSquares

max_issues_repo_name: matthieugomez/LeastSquares

max_forks_repo_name: matthieugomez/LeastSquares


text:
using SV, Statistics, Calculus, LinearAlgebra, DelimitedFiles

function main()
# setup
θtrue = [exp(-0.736/2.0), 0.9, 0.363] # true param values, on param space
lb = [0.0, 0.0, 0.0]
ub = [3.0, 0.99, 3.0]
n = 1000
burnin = 100
# load the example data
y = readdlm("svdata.txt")
m0 =  sqrt(n)*aux_stat(y) # statistic
# or use a new draw
#m0 = SVmodel(θtrue, n, randn(n+100), randn(n+100), true)
# Estimation by indirect inference
S = 100 # number of simulation reps
shocks_u = randn(n+burnin,S)
shocks_e = randn(n+burnin,S)
ms = θ -> SVmoments(m0, n, θ, shocks_u, shocks_e)
# the estimation of the covariance is unstable when volatility is
# high, so first, identity weight, then efficient, with tighter bounds
weight = θ -> 1.0
m = θ -> vec(mean(ms(θ),dims=1)) # 1Xg
obj = θ -> m(θ)'*weight(θ)*m(θ)
θinit = (lb + ub)./2.0
θhat, objvalue, converged, details = samin(obj, θinit, lb, ub; ns = 5, verbosity = 3, rt = 0.5)
lb2 = 0.9.*θhat
ub2 = 1.1.*θhat
lb = max.(lb,lb2)
ub = min.(ub, ub2)
weight = θ -> inv(cov(ms(θ)))
θhat, objvalue, converged, details = samin(obj, θhat, lb, ub; ns = 5, verbosity = 3, rt = 0.5)
# compute the estimated standard errors and CIs
D = (Calculus.jacobian(m, vec(θhat), :central))
W = weight(θhat)
V = inv(D'*W*D)
se = sqrt.(diag(V))
println("true values, estimates, st. error, and limits of 95% CI")
prettyprint([θtrue θhat se θhat-1.96*se θhat+1.96*se],["true value", "estimate", "std. err.", "CI lower", "CI upper"])
end
main()

max_stars_repo_name: manuelmontesinos/Econometrics

max_issues_repo_name: manuelmontesinos/Econometrics

max_forks_repo_name: manuelmontesinos/Econometrics


text:
const refinements = 5
const Lx = 2.0
const Ly = 1.0


text:
# package list from https://www.reddit.com/r/IAmA/comments/97jdb9/weve_spent_the_past_9_years_developing_a_new/e48olwm/
using Pkg
Pkg.add(Pkg.PackageSpec(url="https://github.com/juliacn/BenchmarkTools.jl"))
Pkg.add(Pkg.PackageSpec(url="https://github.com/juliacn/StaticArrays.jl"))
Pkg.add(Pkg.PackageSpec(url="https://github.com/juliacn/UnicodePlots.jl"))
using BenchmarkTools
using StaticArrays
using UnicodePlots

max_stars_repo_name: dev-juliacn/ubuntu

max_issues_repo_name: dev-juliacn/ubuntu

max_forks_repo_name: dev-juliacn/ubuntu


text:
# ------------------------------------------------------------------
# Copyright (c) 2015, Júlio Hoffimann Mendes <juliohm@stanford.edu>
# Licensed under the ISC License. See LICENCE in the project root.
# ------------------------------------------------------------------

const GPU = nothing

function get_imfilter_impl(GPU)
  if GPU ≠ nothing
    imfilter_gpu
  else
    imfilter_cpu
  end
end

cart2lin(dims, ind...) = LinearIndices(dims)[ind...]
lin2cart(dims, ind)    = CartesianIndices(dims)[ind]

function convdist(img::AbstractArray, kern::AbstractArray;
                  weights::AbstractArray=fill(1.0, size(kern)))
  # choose among imfilter implementations
  imfilter_impl = get_imfilter_impl(GPU)

  wkern = weights.*kern

  A² = imfilter_impl(img.^2, weights)
  AB = imfilter_impl(img, wkern)
  B² = sum(abs2, wkern)

  D = abs.(A² .- 2AB .+ B²)

  parent(D) # always return a plain simple array
end

function genpath(extent::Dims{N}, kind::Symbol, datum=[]) where {N}
  path = Vector{Int}()

  if kind == :raster
    for ind in LinearIndices(extent)
      push!(path, ind)
    end
  end

  if kind == :random
    nelm = prod(extent)
    path = nthperm!(collect(1:nelm), rand(1:factorial(big(nelm))))
  end

  if kind == :dilation
    nelm = prod(extent)
    pivot = rand(1:nelm)

    grid = falses(extent)
    grid[pivot] = true
    push!(path, pivot)

    while !all(grid)
      dilated = dilate(grid)
      append!(path, findall(vec(dilated .& .!grid)))
      grid = dilated
    end
  end

  if kind == :datum
    @assert !isempty(datum) "datum path cannot be generated without data"

    shuffle!(datum)

    grid = falses(extent)
    for pivot in datum
      grid[pivot] = true
      push!(path, LinearIndices(extent)[pivot])
    end

    while !all(grid)
      dilated = dilate(grid)
      append!(path, findall(vec(dilated .& .!grid)))
      grid = dilated
    end
  end

  path
end


text:
module VertexEliminationOrder

using LightGraphs
using DataStructures
using StatsBase
using Parameters
using SparseArrays
using Random

include("utils.jl")
export treewidth_by_elimination!, tree_order!, graph_from_gr, square_lattice_graph
include("heuristics.jl")
export minfill!, minwidth!
include("flowcutter.jl")
export augment_flow!, forward_grow!, piercing_node, flowcutter
include("dissection.jl")
export iterative_dissection
include("mainwrapper.jl")
export order_tw_by_dissections_simple, order_tw_by_dissections_threads

end


text:
#### PrecomputeVars

function update_aux!(grid, q, aux, aux_O2, params, case)
    gm, en, ud, sd, al = allcombinations(q)
    @unpack param_set = params

    update_surface!(aux, q, grid, params, params[:SurfaceModel])
    @inbounds for k in over_elems_real(grid)
        ts = ActiveThermoState(param_set, q, aux, k, gm)
        aux[:θ_ρ, k] = virtual_pottemp(ts)
    end
    params[:zi] = compute_inversion_height(aux, q, grid, params)
    params[:wstar] = compute_convective_velocity(params[:bflux], params[:zi])

    apply_bcs!(grid, q, aux, params, case)
    update_forcing!(aux, q, grid, params, params[:ForcingType])
    grid_mean!(aux, q, :a, (:T, :q_liq, :buoy), grid)
    compute_cloud_base_top_cover!(params[:UpdVar], grid, q, aux)

    diagnose_environment!(q, grid, :a, (:q_tot, :θ_liq, :w))

    saturation_adjustment_sd!(grid, q, aux, params)

    compute_entrainment_detrainment!(
        grid,
        params[:UpdVar],
        aux,
        q,
        params,
        params[:EntrDetrModel],
    )
    compute_cloud_phys!(grid, q, aux, params)
    compute_buoyancy!(grid, q, aux, params)
    compute_pressure!(grid, q, aux, params, params[:PressureModel])

    filter_scalars!(grid, q, aux, params)

    compute_cv_gm!(grid, q, :w, :w, :tke, 0.5)
    compute_mf_gm!(grid, q, aux)
    compute_mixing_length!(grid, q, aux, params, params[:MixingLengthModel])
    compute_eddy_diffusivities_tke!(
        grid,
        q,
        aux,
        params,
        params[:EddyDiffusivityModel],
    )

    compute_tke_buoy!(grid, q, aux, aux_O2, :tke, params)
    compute_cv_entr!(grid, q, aux, aux_O2, :w, :w, :tke, 0.5)
    compute_cv_shear!(grid, q, aux, aux_O2, :w, :w, :tke)
    compute_cv_interdomain_src!(grid, q, aux, aux_O2, :w, :w, :tke, 0.5)
    compute_tke_pressure!(grid, q, aux, aux_O2, :tke, params)
    compute_cv_env!(grid, q, aux, aux_O2, :w, :w, :tke, 0.5)

    cleanup_covariance!(grid, q)

    extrap_0th_order!(aux, :T, grid, gm)
end


text:
using GLMakie: Observable, Figure

"""
    createFigure([; fig, limits])

Adds a 3D axis and a run button to the figure provided through `fig`.
If a figure is not supplied, a new figure is generated within the function.

#### Parameters:
* fig: Figure object to apply Axis3 to.
* limits: Used to set axis limits for Axis3 objects.
"""
function createFigure(; fig::Makie.Figure = Figure(), limits::Observable{NTuple{6, Float64}})

    ax = Axis3(fig[1:2,2], aspect = (1,1,1), autolimitaspect = true, limits = limits[])

    fig[3,1] = buttongrid = GridLayout(tellwidth = false)
    sim_state = Observable("Run")
    run_button = buttongrid[1,1] = Button(fig, label = sim_state)

    run = Observable(false)

    on(run_button.clicks) do clicks
        run[] = !run[]
        sim_state[] = run.val ? "Stop" : "Run"
        notify.((run, sim_state))
    end

    return fig, ax, run
end

"""
    createDropdown!(fig, available_functions)

Creates a dropdown menu of all available functions and applies it to the provided figure.
Returns the menu as an object which can then be observed for selections.
"""
function createDropdown!(fig::Figure, available_functions::Vector{String})
    menu = Menu(fig, options = sort(available_functions))

    fig[1, 1] = vgrid!(Label(fig, "Function", width = nothing), menu, tellheight = false, width = events(fig.scene).window_area[].widths[1]/3)

    return menu
end

function createSliders!(fig, parameters::NamedTuple)
    lsgrid = labelslidergrid!(
        fig,
        [string.(keys(parameters))...],
        [values(parameters)...],
        width = 350,
        tellheight = false
    )

    fig[2,2] = lsgrid.layout

    sliderobservables = [s.value for s in lsgrid.sliders]

    for observable in sliderobservables
        on(observable) do val
            attractor = Swarm(lorenz, lorenz_defaults)
        end
    end

    bars = lift(sliderobservables...) do slvalues...
        [slvalues...]
    end
end


text:
using Documenter
using Cropbox

makedocs(
    format = Documenter.HTML(
        prettyurls = get(ENV, "CI", nothing) == "true",
        canonical = "https://cropbox.github.io/Radish.jl/stable/",
        assets = ["assets/favicon.ico"],
        analytics = "UA-192782823-1",
    ),
    sitename = "Radish.jl",
    pages = [
        "Home" => "index.md",
    ],
)

deploydocs(
    repo = "github.com/cropbox/Radish.jl.git",
    devbranch = "main",
)


text:
export iterable

import Base: show

"""
    iterable(iterator; scheduler::H = AsapScheduler()) where { H <: AbstractScheduler }

Creation operator for the `IterableObservable` that wraps given iterator into an observable object.

# Arguments
- `iterator`: an iterator object to be wrapped an observable
- `scheduler`: optional, scheduler-like object

# Note
`iterable` operators does not create a copy of iterator.
Any changes in the `iterator` object might be visible in the created observable.
For side-effects free behavior consider using `from` creation operator which creates a copy of a given object
with a `collect` function.

# Examples

```jldoctest
using Rocket

source = iterable([ 0, 1, 2 ])
subscribe!(source, logger())
;

# output

[LogActor] Data: 0
[LogActor] Data: 1
[LogActor] Data: 2
[LogActor] Completed
```

```jldoctest
using Rocket

source = iterable("Hello")
subscribe!(source, logger())
;

# output

[LogActor] Data: H
[LogActor] Data: e
[LogActor] Data: l
[LogActor] Data: l
[LogActor] Data: o
[LogActor] Completed
```

See also: [`ScheduledSubscribable`](@ref), [`subscribe!`](@ref), [`from`](@ref)
"""
function iterable(iterator::I; scheduler::H = AsapScheduler()) where { I, H <: AbstractScheduler }
    return IterableObservable{eltype(I), I, H}(iterator, scheduler)
end

struct IterableObservable{D, I, H} <: ScheduledSubscribable{D}
    iterator  :: I
    scheduler :: H
end

getscheduler(observable::IterableObservable) = observable.scheduler

function on_subscribe!(observable::IterableObservable, actor, scheduler)
    state = iterate(observable.iterator)
    while state !== nothing
        next!(actor, state[1], scheduler)
        state = iterate(observable.iterator, state[2])
    end
    complete!(actor, scheduler)
    return voidTeardown
end

Base.show(io::IO, ::IterableObservable{D, I, H}) where { D, I, H } = print(io, "IterableObservable($D, $I, $H)")


text:
export KroneckerProduct

typealias UnitStrideSubVector{T,N,P<:Array,I<:Tuple{Union{Colon,UnitRange{Int}},Vararg{Int}},LD} SubArray{T,N,P,I,LD}
typealias UnitStrideSubMatrix{T,N,P<:Array,I<:Tuple{Colon,Union{Colon,UnitRange{Int}},Vararg{Int}},LD} SubArray{T,N,P,I,LD}
typealias UnitStrideVector Union{Vector,UnitStrideSubVector}
typealias UnitStrideMatrix Union{Matrix,UnitStrideSubMatrix}

function kron!(c::AbstractMatrix, a::AbstractMatrix, b::AbstractMatrix)
    size(c, 1) == size(a,1)*size(b,1) && size(c, 2) == size(a,2)*size(b,2) ||
        throw(DimensionMismatch("output has size $(size(c)) but inputs have size $(size(a)) and $(size(b))"))
    @inbounds for j = 1:size(a,2), l = 1:size(b,2), i = 1:size(a,1)
        aij = a[i,j]
        @simd for k = 1:size(b,1)
            @inbounds c[(i-1)*size(b, 1)+k, (j-1)*size(b, 2)+l] = aij*b[k,l]
        end
    end
    c
end

type KroneckerProduct{T,S<:AbstractMatrix,V<:AbstractMatrix,RA<:AbstractMatrix,RB<:AbstractMatrix} <: AbstractMatrix{T}
    A::S
    B::V
    multmp::Matrix{T}
    Arowtensor::RA
    Browtensor::RB

    KroneckerProduct(A, B) = new(A, B)
end
KroneckerProduct{S,V}(A::AbstractMatrix{S}, B::AbstractMatrix{V}) =
    KroneckerProduct{promote_type(S, V),typeof(A),typeof(B),rowtensor_type(A),rowtensor_type(B)}(A, B)

Base.size(X::KroneckerProduct) = (size(X.A, 1)*size(X.B, 1), size(X.A, 2)*size(X.B, 2))
Base.linearindexing{T<:KroneckerProduct}(::Type{T}) = Base.LinearSlow()

function Base.getindex(X::KroneckerProduct, i1::Int, i2::Int)
    blk1, j1 = divrem(i1-1, size(X.B, 1))
    blk2, j2 = divrem(i2-1, size(X.B, 2))
    X.A[blk1+1, blk2+1]*X.B[j1+1, j2+1]
end

Base.convert{T}(::Type{Matrix{T}}, X::KroneckerProduct) = convert(Matrix{T}, kron(X.A, X.B))
Base.convert{T}(::Type{Matrix}, X::KroneckerProduct{T}) = convert(Matrix{T}, X)

function multmp!{T}(X::KroneckerProduct{T})
    isdefined(X, :multmp) && return X.multmp
    X.multmp = Array(T, size(X.B, 1), size(X.A, 2))
end

function Base.A_mul_B!(out::UnitStrideVector, X::KroneckerProduct, v::AbstractVector)
    # v = (A ⊗ B)x <==> V = B*X*A'
    length(v) == size(X, 2) || throw(DimensionMismatch("X has size $(size(X)) but v has length $(length(v))"))
    A_mul_Bt!(pointer_to_array(pointer(out), (size(X.B, 1), size(X.A, 1))),
              A_mul_B!(multmp!(X), X.B, reshape(v, size(X.B, 2), size(X.A, 2))), X.A)
    out
end
function Base.A_mul_B!(out::StridedMatrix, X::KroneckerProduct, Y::AbstractMatrix)
    for i = 1:size(Y, 2)
        A_mul_B!(sub(out, :, i), X, sub(Y, :, i))
    end
    out
end

function Base.At_mul_B!(out::UnitStrideVector, X::KroneckerProduct, v::AbstractVector)
    # v = (A ⊗ B)'x <==> V = B'*X*A
    length(v) == size(X, 1) || throw(DimensionMismatch("X has size $(size(X)) but v has length $(length(v))"))
    At_mul_B!(pointer_to_array(pointer(out), (size(X.B, 2), size(X.A, 2))), X.B,
              A_mul_B!(multmp!(X), reshape(v, size(X.B, 1), size(X.A, 1)), X.A))
    out
end
function Base.At_mul_B!(out::StridedMatrix, X::KroneckerProduct, Y::AbstractMatrix)
    for i = 1:size(Y, 2)
        At_mul_B!(sub(out, :, i), X, sub(Y, :, i))
    end
    out
end
function Base.At_mul_B!(out::StridedMatrix, X::KroneckerProduct, Y::KroneckerProduct)
    kron!(out, X.A.'Y.A, X.B.'Y.B)
end

function Base.At_mul_B!(out::UnitStrideVector, v::AbstractVector, X::KroneckerProduct)
    # v = x'(A ⊗ B) <==> V = (B'*X*A)' = (X*A)'*B
    length(v) == size(X, 1) || throw(DimensionMismatch("X has size $(size(X)) but v has length $(length(v))"))
    A_mul_Bt!(pointer_to_array(pointer(out), (size(X.B, 2), size(X.A, 2))),
              A_mul_B!(multmp!(X), reshape(v, size(X.B, 1), size(X.A, 1)), X.A), X.B)
    out
end

Base.Ac_mul_B!{T<:Real}(out::StridedMatrix, X::KroneckerProduct{T}, Y::AbstractMatrix) =
    At_mul_B!(out, X, Y)
for T in (StridedMatrix, AbstractMatrix)
    @eval begin
        Base.At_mul_B(X::KroneckerProduct, Y::$T) =
            At_mul_B!(Array(promote_type(eltype(X), eltype(Y)), size(X, 2), size(Y, 2)), X, Y)
        Base.Ac_mul_B{T<:Real}(X::KroneckerProduct{T}, Y::$T) =
            At_mul_B!(Array(promote_type(eltype(X), eltype(Y)), size(X, 2), size(Y, 2)), X, Y)
    end
end
Base.At_mul_B(X::KroneckerProduct, Y::AbstractVector) =
    At_mul_B!(Array(promote_type(eltype(X), eltype(Y)), size(X, 2)), X, Y)
Base.Ac_mul_B{T<:Real}(X::KroneckerProduct{T}, Y::AbstractVector) =
    At_mul_B!(Array(promote_type(eltype(X), eltype(Y)), size(X, 2)), X, Y)
Base.At_mul_B(X::AbstractVector, Y::KroneckerProduct) =
    At_mul_B!(Array(promote_type(eltype(X), eltype(Y)), size(X, 2)), X, Y)
Base.Ac_mul_B{T<:Real}(Y::AbstractVector{T}, X::KroneckerProduct) =
    At_mul_B!(Array(promote_type(eltype(X), eltype(Y)), size(X, 2)), X, Y)

rowtensor_type{T}(::StridedMatrix{T}) = Matrix{T}
function rowtensor(X::StridedMatrix)
    out = zeros(eltype(X), size(X, 1), size(X, 2)^2)
    for k = 1:size(X, 2), j = 1:size(X, 2)
        @simd for i = 1:size(X, 1)
            @inbounds out[i, (k-1)*size(X, 2)+j] = X[i, j]*X[i, k]
        end
    end
    out
end

# Compute X'WX, where W = diagm(w)
function weightmul!(out::AbstractMatrix, X::AbstractMatrix, w::AbstractVector)
    # This would avoid a temporary, but BLAS is still substantially faster
#     for k = 1:size(X, 2), j = 1:k
#         v = zero(promote_type(eltype(X), eltype(w)))
#         @simd for i = 1:size(X, 1)
#             @inbounds v += X[i, j]*X[i, k]*w[i]
#         end
#         @inbounds out[j, k] = v
#     end
    Ac_mul_B!(out, scale(w, X), X)
end

function weightmul!(out::UnitStrideMatrix, X::KroneckerProduct, w::AbstractVector)
    if !isdefined(X, :Arowtensor)
        X.Arowtensor = rowtensor(X.A)
        X.Browtensor = rowtensor(X.B)
    end
    length(w) == size(X, 1) || throw(DimensionMismatch("X has size $(size(X)) but w has length $(length(w))"))
    size(out, 1) == size(out, 2) == size(X, 2) ||
        throw(DimensionMismatch("X has $(size(X, 2)) columns but output has size $(size(out))"))
    tmp = A_mul_B!(similar(X, (size(X.B, 2)^2, size(X.A, 2)^2)),
                   X.Browtensor'*reshape(w, size(X.B, 1), size(X.A, 1)), X.Arowtensor)
    permutedims!(pointer_to_array(pointer(out), (size(X.B, 2), size(X.A, 2), size(X.B, 2), size(X.A, 2))),
                 reshape(tmp, size(X.B, 2), size(X.B, 2), size(X.A, 2), size(X.A, 2)), (1, 3, 2, 4))
    out
end
weightmul!(out::AbstractMatrix, X::KroneckerProduct, w::AbstractVector) = copy!(out, weightmul(X, w))

weightmul{T,S}(X::AbstractMatrix{T}, w::AbstractVector{S}) =
    weightmul!(similar(X, promote_type(T, S), size(X, 2), size(X, 2)), X, w)


text:
# This file is auto-generated by AWSMetadata.jl
using AWS
using AWS.AWSServices: connect_contact_lens
using AWS.Compat
using AWS.UUIDs

"""
    ListRealtimeContactAnalysisSegments()

Provides a list of analysis segments for a real-time analysis session.

# Required Parameters
- `ContactId`: The identifier of the contact.
- `InstanceId`: The identifier of the Amazon Connect instance.

# Optional Parameters
- `MaxResults`: The maximimum number of results to return per page.
- `NextToken`: The token for the next set of results. Use the value returned in the previous response in the next request to retrieve the next set of results.
"""
list_realtime_contact_analysis_segments(ContactId, InstanceId; aws_config::AWSConfig=global_aws_config()) = connect_contact_lens("POST", "/realtime-contact-analysis/analysis-segments", Dict{String, Any}("ContactId"=>ContactId, "InstanceId"=>InstanceId); aws_config=aws_config)
list_realtime_contact_analysis_segments(ContactId, InstanceId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = connect_contact_lens("POST", "/realtime-contact-analysis/analysis-segments", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("ContactId"=>ContactId, "InstanceId"=>InstanceId), args)); aws_config=aws_config)


text:
"""
    Double integrator
"""

struct DoubleIntegrator
    n::Int
    m::Int
    d::Int
end

function fd(model::DoubleIntegrator, x⁺, x, u, w, h, t)
    x⁺ - [x[1] + x[2] + w[1]; x[2] + u[1] + w[2]]
end

function get_dynamics(model::DoubleIntegrator)
    A = @SMatrix [1.0 1.0; 0.0 1.0]
    B = @SMatrix [0.0; 1.0]

    return A, B
end

n, m, d = 2, 1, 2
model = DoubleIntegrator(n, m, d)

max_stars_repo_name: zacmanchester/DirectMotionPlanning

max_issues_repo_name: zacmanchester/DirectMotionPlanning

max_forks_repo_name: zacmanchester/DirectMotionPlanning


text:
using Dash

app = dash()
app.layout = html_div(id="outer-div") do
    html_div("A div", id="first-inner-div"),
    html_br(),
    html_div("Another div", id="second-inner-div")
end

run_server(app)


text:
using DelimitedFiles

function read_fluxo_sol(filename)
    f = readdlm(filename)
    polydeg, total_cells = f[1, 1:2]
    x, y, rho, u, v, p = ntuple(_ -> zeros((polydeg + 1)^2, total_cells), 6)
    sk = 1
    sk_u = 1
    for i in 2:size(f, 1)
        if mod(i, 2) == 0
            x[sk] = f[i, 1]
            y[sk] = f[i, 2]
            sk += 1
        else
            rho[sk_u], u[sk_u], v[sk_u], p[sk_u] = f[i, 1:4]
            sk_u += 1
        end
    end
    return polydeg, total_cells, x, y, rho, u, v, p
end

# specialize for FLUXO outputs
function convert_to_Cartesian_arrays(polydeg, total_cells, x, y, rho, u, v, p)

    # This scales the node positions to create an equispaced grid of nodes which avoids
    # boundary evaluations. The solution sampled at these points can be used to compute
    # the FFT and the turbulent energy spectra
    h = 1 / (polydeg + 1)
    equispaced_fft_nodes_1D = LinRange(-1 + h, 1 - h, polydeg + 1)
    LGL_nodes = Trixi.StartUpDG.gauss_lobatto_quad(0, 0, polydeg)[1]
    interp_matrix_fft_1D = Trixi.polynomial_interpolation_matrix(LGL_nodes, equispaced_fft_nodes_1D)
    interp_matrix_fft_nodes = kron(interp_matrix_fft_1D, interp_matrix_fft_1D)

    # interpolate solution to FFT points
    x, y, rho, u, v, p = map(u -> interp_matrix_fft_nodes * u, (x, y, rho, u, v, p))

    cells_per_dimension = Int(sqrt(total_cells)) # assume uniform Cartesian mesh
    rho_cartesian = convert_dg2D_array_to_Cartesian(x, y, rho, polydeg, cells_per_dimension)
    u_cartesian   = convert_dg2D_array_to_Cartesian(x, y, u, polydeg, cells_per_dimension)
    v_cartesian   = convert_dg2D_array_to_Cartesian(x, y, v, polydeg, cells_per_dimension)
    p_cartesian   = convert_dg2D_array_to_Cartesian(x, y, p, polydeg, cells_per_dimension)
    return rho_cartesian, u_cartesian, v_cartesian, p_cartesian, x, y
end


text:
function SeisEnvelope(d)

	D = fft(d,1)
	D[1:Int(floor(size(d,1)/2)),:] = 0.0
	return 2*abs(ifft(D,1))

end

function SeisEnvelope(A,h::Array{Header,1})
	for itrace = 1 : size(A[:,:],2)
		A[:,itrace] = SeisEnvelope(A[:,itrace])
	end
	return A,h
end

function SeisEnvelope(in::AbstractString,out::AbstractString)
	@compat parameters = Dict()
	SeisProcess(in,out,[SeisEnvelope],[parameters];group="some",ntrace=100000)
end


text:
using DataFrames, Query, NamedTuples

source_df_nulls = DataFrame(name=@data(["John", "Sally", NA, "Kirk"]), age=[23., 42., 54., 59.], children=@data([3,NA,8,2]))
q = @from i in source_df_nulls begin
    @select i
    @collect DataFrame
end

println(q)


text:
# docs/make.jl
# Make Documentation for BoundedRationals.jl

push!(LOAD_PATH, "../src/")

using Documenter, BoundedRationals

makedocs(
    modules   = [BoundedRationals],
    doctest   = true,
    clean     = false,
    linkcheck = false,
    format    = Documenter.HTML(prettyurls=!("local" in ARGS)),
    sitename  = "BoundedRationals.jl",
    authors   = "Brandon H Gomes",
    pages     = [
        "Home" => "index.md",
    ],
)

deploydocs(
    repo = "github.com/bhgomes/BoundedRationals.jl.git",
    target = "build",
    deps = nothing,
    make = nothing,
)


text:
#Import oligotype counts and MVCO data - combine to form one DataFrame
#Kristen Hunter-Cevera, Marine Biological Laboratory, Spring 2020

using DataFrames, CSV
using Statistics
using JLD2
using Dates

## IMPORT OLIGO AND SYN COUNTS:

filename="/home/kristen/Documents/V6V8_analysis/analysis_products/syn_oligotyping/mvco_syn/mvco_syn_timeseries_for_oligotyping_pynast_aligned-c19-s1-a0.0-A0-M200/MATRIX-COUNT.txt"  #taxbyseq_nov2018_only.tsv"
#filename="/home/kristen/Documents/V6V8_analysis/data/synseqs/test-c25-s1-a0.0-A100-M40/MATRIX-COUNT.txt"  #taxbyseq_nov2018_only.tsv"
oligo_counts_df = CSV.File(filename, header=1) |> DataFrame!

for j=2:size(oligo_counts_df,2) #rename columns
    rename!(oligo_counts_df,:($j) => "Oligo$(j-1)")
end

#detect and add event number as separate column:
nums=map(x-> match(r"(363[A,B])|(\d{3})",x),oligo_counts_df[:,1]) #special handling for 363A and 363B - event numbers
nums2=string.(collect(m.match for m in nums))
oligo_counts_df[:event]=nums2 #make it into a column!

oligo_counts_df.samples=map(x -> replace(x,"Sample-" => ""),oligo_counts_df[!,:samples])

# ugh=string.(oligo_counts_df[!,:samples])
# [replace(row,"Sample-" => "") for row in ugh]

oligo_counts_df=oligo_counts_df[!,[1;size(oligo_counts_df,2);2:(size(oligo_counts_df,2)-1)]] #reshuffle column names

# Import total syn reads and total seq reads....syn counts for the moment comes from o-get-sample...but should have this as out when prints oligo seqs!
filename="/home/kristen/Documents/V6V8_analysis/analysis_products/syn_sequences/mvco_total_and_syn_counts.csv"  #taxbyseq_nov2018_only.tsv"
total_syncounts_df = CSV.File(filename, header=1) |> DataFrame!
rename!(total_syncounts_df,:event => :samples)
rename!(total_syncounts_df,:count => :syncounts)
rename!(total_syncounts_df,:totals => :totalcount)
oligo_counts_df=join(oligo_counts_df,total_syncounts_df, on = :samples)

# Finished importing oligo and syn counts!

## Combine, tr (trial run) and rd (redo) samples:

eventlist=unique(oligo_counts_df[:,:event])
ind_rec=[]

for q=1:size(eventlist,1)
    ind=findall(map(x->occursin(Regex(eventlist[q]),x),oligo_counts_df[:,:event]))

    if size(ind,1) > 1
        @show q
        append!(ind_rec,ind)
        #@show B[q,:event]
        combo=sum.(eachcol(oligo_counts_df[ind,3:size(oligo_counts_df,2)]))
        A=[string("Sample-MV", oligo_counts_df[ind[1],:event],"_combined"),oligo_counts_df[ind[1],:event],combo...]
        push!(oligo_counts_df,A)
        deleterows!(oligo_counts_df,ind)
        #can push rows as NamedTuples
    end
end

##FINALLY..................................................................

########## MATCH TO MVCO DATES, TEMPERATURE, LIGHT, ETC #############################
#from MVCO_nut_reps, match event number to date, from date match temp, light, nutrients

#load in MVCO environmental and syn data:
@load "/home/kristen/Documents/V6V8_analysis/analysis_products/mvco_nut_data.jld2"

#There is a real different between NaN and missing; NaN is for calc like Num/0 or something
#Missing truly refers to a missing value....
## replace NaN's with missing values:
for q=7:19
    @. MVCO_nut_reps[isnan(MVCO_nut_reps[:,q]),q] = missing
end
#database entry mistake?
ii=findall(map(x -> occursin(r"273",x),MVCO_nut_reps[:,1]))
MVCO_nut_reps[ii[1],7]=0.0

# a[isnan.(a)] .= 0
# or you can use the @. macro to dot everything for you:
# @. a[isnan(a)] = 0

nutrient_indexes=collect(findall(map(x->occursin(Regex(n),x),MVCO_nut_reps[:,1])) for n in oligo_counts_df[:,:event])
missing_a_date=findall(map(x->size(x,1) == 0,nutrient_indexes))
#seems 272 does not have an entry in MVCO_nut_reps!

## DATES AND NUTRIENTS:
 #event_dates=Dict() #as a dictionary, yes...but want in dataframe:
datevec=Array{DateTime}(undef,size(nutrient_indexes,1))
NO3vec=Array{Union{Float64,Missing}}(undef,size(nutrient_indexes,1))
NH4vec=Array{Union{Float64,Missing}}(undef,size(nutrient_indexes,1))
PO4vec=Array{Union{Float64,Missing}}(undef,size(nutrient_indexes,1))
SiOHvec=Array{Union{Float64,Missing}}(undef,size(nutrient_indexes,1))
NO3vecsurf=Array{Union{Float64,Missing}}(undef,size(nutrient_indexes,1))
NH4vecsurf=Array{Union{Float64,Missing}}(undef,size(nutrient_indexes,1))
PO4vecsurf=Array{Union{Float64,Missing}}(undef,size(nutrient_indexes,1))
SiOHvecsurf=Array{Union{Float64,Missing}}(undef,size(nutrient_indexes,1))

for j =1:size(nutrient_indexes,1)
    if !isempty(nutrient_indexes[j])
        #@show j
        datevec[j]=Date(split(MVCO_nut_reps[nutrient_indexes[j][1],3]," ")[1],"yyyy-mm-dd")
        #event_dates[nums2[j]]=Date(split(MVCO_nut_reps[t[j][1],3]," ")[1],"yyyy-mm-dd") #for dictionary

        #average of all depths:
        NO3vec[j]=mean(skipmissing(MVCO_nut_reps[nutrient_indexes[j],8:10]))
        NH4vec[j]=mean(skipmissing(MVCO_nut_reps[nutrient_indexes[j],11:13]))
        PO4vec[j]=mean(skipmissing(MVCO_nut_reps[nutrient_indexes[j],17:19]))
        SiOHvec[j]=mean(skipmissing(MVCO_nut_reps[nutrient_indexes[j],14:16]))

        #average of 'surface' measurements < 6m deep
        temp_ind=nutrient_indexes[j][findall(map(x -> x<=6, MVCO_nut_reps[nutrient_indexes[j],7]))]
        @show j
        @show temp_ind
        NO3vecsurf[j]=mean(skipmissing(MVCO_nut_reps[temp_ind,8:10]))
        NH4vecsurf[j]=mean(skipmissing(MVCO_nut_reps[temp_ind,11:13]))
        PO4vecsurf[j]=mean(skipmissing(MVCO_nut_reps[temp_ind,17:19]))
        SiOHvecsurf[j]=mean(skipmissing(MVCO_nut_reps[temp_ind,14:16]))

    else
         @show j
         println("Special case for event 272")
         datevec[j]=Date("2011-08-06","yyyy-mm-dd")
         NO3vec[j]=missing
         NH4vec[j]=missing
         PO4vec[j]=missing
         SiOHvec[j]=missing
         NO3vecsurf[j]=missing
         NH4vecsurf[j]=missing
         PO4vecsurf[j]=missing
         SiOHvecsurf[j]=missing
         #event_dates[nums2[j]]=Date("2011-08-06","yyyy-mm-dd") #for dictionary
    end
end

# collect(d[1] for d in t) #would have worked if not for empty vector....
oligo_counts_df[:date]=datevec
oligo_counts_df[:NO3]=NO3vec
oligo_counts_df[:NH4]=NH4vec
oligo_counts_df[:PO4]=PO4vec
oligo_counts_df[:SiOH]=SiOHvec
oligo_counts_df[:NO3surf]=NO3vecsurf
oligo_counts_df[:NH4surf]=NH4vecsurf
oligo_counts_df[:PO4surf]=PO4vecsurf
oligo_counts_df[:SiOHsurf]=SiOHvecsurf
## woo-hoo!

## MATCH TO SYN ABND, LIGHT AND TEMPERATURE!
@load "/home/kristen/Documents/V6V8_analysis/analysis_products/mvco_envdata.jld2" Tbeam_corr light_int
@load "/home/kristen/Documents/V6V8_analysis/analysis_products/mvco_syndata.jld2" time_syn daily_syn
# ind=findall(map(x -> x == datevec[1],time_syn))
# daily_syn[ind] #yes! this works!
##
ind=collect(findall(map(x -> x == dd,time_syn)) for dd in datevec) #use date as the index....

synvec=Array{Float64}(undef,size(nutrient_indexes,1))
tempvec=Array{Float64}(undef,size(nutrient_indexes,1))
lightvec=Array{Float64}(undef,size(nutrient_indexes,1))
lightvec_wkavg=Array{Float64}(undef,size(nutrient_indexes,1))

Tbeam_corr=recode(Tbeam_corr, NaN => missing)
light_int=recode(light_int, NaN => missing)

light_avg=vcat((mean(skipmissing(x)) for x in eachrow(light_int))...) #thanks stackoverflow!
temp_avg=vcat((mean(skipmissing(x)) for x in eachrow(Tbeam_corr))...) #thanks stackoverflow!

for j=1:size(ind,1)

    i0=LinearIndices(light_int)[ind[j]]
    i0=i0[1]
    i1=ind[j][1][1] #row index
    i2=ind[j][1][2] #col index

    synvec[j]=daily_syn[i0]

    if ismissing(Tbeam_corr[i0])
        @show j
        tempvec[j]=mean(skipmissing(Tbeam_corr[i0-1:i0+1]))
        #println("missing temp")
        #println(tempvec[j])

        if ismissing(tempvec[j]) | isnan(tempvec[j]) #and in case do not have even surrounding data:
            @show j
            tempvec[j]=temp_avg[i1]
            println("too much missing for temp!")
            println(tempvec[j])
        end

    else
        tempvec[j]=Tbeam_corr[i0]
    end

    if ismissing(light_int[i0])

        lightvec[j]=light_avg[i1]
        #println("missing light")
        #println(lightvec[j])
    else
        lightvec[j]=light_int[i0]
    end

    lightvec_wkavg[j] = mean(skipmissing(light_int[i0-7:i0]))  #averages the week before the sample time point

end

##
oligo_counts_df[:synconc]=synvec
oligo_counts_df[:temp]=tempvec
oligo_counts_df[:light]=lightvec
oligo_counts_df[:lightweek]=lightvec_wkavg
#Got it! Now syn oligos with matching env data is complete!

sort!(oligo_counts_df,:date)
oligo_counts_df.month=@. Dates.month(oligo_counts_df[:,:date])

@save "/home/kristen/Documents/V6V8_analysis/analysis_products/mvco_syn_oligo_counts_plus_env_data.jld2" oligo_counts_df

#plotting..............................
# gr()
# scatter([1;2],[3;4])
# ugh=plot(B[:,:date], B[:,:Oligo1])
# savefig(ugh,"test.png")
# scatter!(B[:date], B[:synconc],yscale = :log10)
# xaxis!("Year day",(0, 366),0:100:360,font(12, "Times"))

max_stars_repo_name: hsosik/NES-LTER

max_issues_repo_name: hsosik/NES-LTER

max_forks_repo_name: hsosik/NES-LTER


text:
using BenchmarkTools
using Printf
using Transducers

struct BagCount
    n::Int64
    color::String
end

struct BagRule
    color::String
    contains::Array{BagCount, 1}
end

function parseBagDescriptor(s)
    p = findfirst(r"\s+bags?$", s)
    isnothing(p) && throw(DomainError(s, "invalid bag descriptor"))
    s[1:p.start-1]
end

function toBagCount(s)
    parts = split(s, " "; limit = 2)
    BagCount(parse(Int64, parts[1]), parseBagDescriptor(parts[2]))
end

function toBagRule(s)
    s = rstrip(s, '.')
    p = findfirst(" contain ", s)
    bagDescriptor = parseBagDescriptor(s[1:p.start-1])
    contents = s[p.stop+1:length(s)]
    BagRule(bagDescriptor, contents == "no other bags" ? [] : [toBagCount(content) for content = split(contents, ", ")])
end

####

exampleBagRules = readlines("src/advent/day7/example.txt") |> Map(line -> toBagRule(line)) |> collect
inputBagRules = readlines("src/advent/day7/input.txt") |> Map(line -> toBagRule(line)) |> collect

#### part 1

function canBeContainedBy(bagRules, color)
    entries = bagRules |> Map(rule -> [(entry.color, rule.color) for entry ∈ rule.contains]) |> Iterators.flatten |> collect
    dict = Dict(entry[1] => Set{String}() for entry ∈ entries)
    foreach(entry -> union!(dict[entry[1]], Set([entry[2]])), entries)

    function _canBeContainedBy(color)
        answer = Set{String}()
        !haskey(dict, color) && return answer
        foreach(child -> union!(answer, Set([child]), _canBeContainedBy(child)), dict[color])
        answer
    end

    _canBeContainedBy(color)
end

@assert length(canBeContainedBy(exampleBagRules, "shiny gold")) == 4
@printf("part1 = %d\n", length(canBeContainedBy(inputBagRules, "shiny gold")))
#@btime length(canBeContainedBy(inputBagRules, "shiny gold"));

#### part 2

function countBags(bagRules, color)
    bagRuleDict = Dict(bagRule.color => bagRule for bagRule ∈ bagRules)
    _countBags(color) = haskey(bagRuleDict, color) ? reduce(+, bagCount.n * (1 + _countBags(bagCount.color)) for bagCount ∈ bagRuleDict[color].contains; init = 0) : 0
    _countBags(color)
end

@assert countBags(exampleBagRules, "faded blue") == 0
@assert countBags(exampleBagRules, "dotted black") == 0
@assert countBags(exampleBagRules, "vibrant plum") == 11
@assert countBags(exampleBagRules, "dark olive") == 7
@assert countBags(exampleBagRules, "shiny gold") == 32

@printf("part2 = %d\n", countBags(inputBagRules, "shiny gold"))
#@btime countBags(inputBagRules, "shiny gold");


text:
using JuLearn,Plots
plotlyjs()
@Eval lr=1e-1 momentum=0. batchsize=100 λ=0. ▽max=0.1
include("dataProvider.jl")
include("predict.jl")

inputBase,outputBase=dataProvider()
net=chain([:d,:h,:h,:p,:l],[2 2;2 10;10 2;2 2;2 2],:classification)
@time err=backprop(net,inputBase,outputBase,nIter=1000)
display(plot(err).o)


text:
import Base: size, length, iterate, getindex, setindex!, lastindex
using Base: @propagate_inbounds

import Adapt
using OffsetArrays

import Oceananigans.Architectures: architecture
import Oceananigans.Utils: datatuple

using Oceananigans: AbstractGrid
using Oceananigans.Architectures: @hascuda, CPU, GPU

@hascuda using CuArrays

"""
    AbstractField{A, G}

Abstract supertype for fields stored on an architecture `A` and defined on a grid `G`.
"""
abstract type AbstractField{A, G} end

"""
    AbstractLocatedField{X, Y, Z, A, G}

Abstract supertype for fields located at `(X, Y, Z)`, stored on an architecture `A`,
and defined on a grid `G`.
"""
abstract type AbstractLocatedField{X, Y, Z, A, G} <: AbstractField{A, G} end

"""
    Cell

A type describing the location at the center of a grid cell.
"""
struct Cell end

"""
	Face

A type describing the location at the face of a grid cell.
"""
struct Face end

"""
    Field{X, Y, Z, A, G} <: AbstractLocatedField{X, Y, Z, A, G}

A field defined at the location (`X`, `Y`, `Z`) which can be either `Cell` or `Face`.
"""
struct Field{X, Y, Z, A, G} <: AbstractLocatedField{X, Y, Z, A, G}
    data :: A
    grid :: G
    function Field{X, Y, Z}(data, grid) where {X, Y, Z}
        return new{X, Y, Z, typeof(data), typeof(grid)}(data, grid)
    end
end

Adapt.adapt_structure(to, field::Field{X, Y, Z}) where {X, Y, Z} =
    Field{X, Y, Z}(adapt(to, data), field.grid)

"""
	Field(L::Tuple, data::AbstractArray, grid)

Construct a `Field` on `grid` using the array `data` with location defined by the tuple `L`
of length 3 whose elements are `Cell` or `Face`.
"""
Field(L::Tuple, data::AbstractArray, grid) = Field{L[1], L[2], L[3]}(data, grid)

"""
    Field(L::Tuple, arch, grid)

Construct a `Field` on architecture `arch` and `grid` at location `L`,
where `L` is a tuple of `Cell` or `Face` types.
"""
Field(L::Tuple, arch, grid) = Field{L[1], L[2], L[3]}(zeros(arch, grid), grid)

"""
    Field(X, Y, Z, arch, grid)

Construct a `Field` on architecture `arch` and `grid` at location `X`, `Y`, `Z`,
where each of `X, Y, Z` is `Cell` or `Face`.
"""
Field(X, Y, Z, arch, grid) =  Field((X, Y, Z), arch, grid)

"""
    CellField([T=eltype(grid)], arch, grid)

Return a `Field{Cell, Cell, Cell}` on architecture `arch` and `grid`.
Used for tracers and pressure fields.
"""
CellField(T, arch, grid) = Field{Cell, Cell, Cell}(zeros(T, arch, grid), grid)

"""
    FaceFieldX([T=eltype(grid)], arch, grid)

Return a `Field{Face, Cell, Cell}` on architecture `arch` and `grid`.
Used for the x-velocity field.
"""
FaceFieldX(T, arch, grid) = Field{Face, Cell, Cell}(zeros(T, arch, grid), grid)

"""
    FaceFieldY([T=eltype(grid)], arch, grid)

Return a `Field{Cell, Face, Cell}` on architecture `arch` and `grid`.
Used for the y-velocity field.
"""
FaceFieldY(T, arch, grid) = Field{Cell, Face, Cell}(zeros(T, arch, grid), grid)

"""
    FaceFieldZ([T=eltype(grid)], arch, grid)

Return a `Field{Cell, Cell, Face}` on architecture `arch` and `grid`.
Used for the z-velocity field.
"""
FaceFieldZ(T, arch, grid) = Field{Cell, Cell, Face}(zeros(T, arch, grid), grid)

 CellField(arch, grid) = Field((Cell, Cell, Cell), arch, grid)
FaceFieldX(arch, grid) = Field((Face, Cell, Cell), arch, grid)
FaceFieldY(arch, grid) = Field((Cell, Face, Cell), arch, grid)
FaceFieldZ(arch, grid) = Field((Cell, Cell, Face), arch, grid)

location(a) = nothing
location(::AbstractLocatedField{X, Y, Z}) where {X, Y, Z} = (X, Y, Z)

architecture(f::Field) = architecture(f.data)
architecture(o::OffsetArray) = architecture(o.parent)

@inline size(f::AbstractField) = size(f.grid)
@inline length(f::Field) = length(f.data)

@propagate_inbounds getindex(f::Field, inds...) = @inbounds getindex(f.data, inds...)
@propagate_inbounds setindex!(f::Field, v, inds...) = @inbounds setindex!(f.data, v, inds...)

@inline lastindex(f::Field) = lastindex(f.data)
@inline lastindex(f::Field, dim) = lastindex(f.data, dim)

"Returns `f.data` for `f::Field` or `f` for `f::AbstractArray."
@inline data(a) = a
@inline data(f::Field) = f.data

# Endpoint for recursive `datatuple` function:
@inline datatuple(obj::AbstractField) = data(obj)

"Returns `f.data.parent` for `f::Field`."
@inline Base.parent(f::Field) = f.data.parent

"Returns a view over the interior points of the `field.data`."
@inline interior(f::Field) = view(f.data, 1:f.grid.Nx, 1:f.grid.Ny, 1:f.grid.Nz)

"Returns a reference to the interior points of `field.data.parent.`"
@inline interiorparent(f::Field) = @inbounds f.data.parent[1+f.grid.Hx:f.grid.Nx+f.grid.Hx,
                                                           1+f.grid.Hy:f.grid.Ny+f.grid.Hy,
                                                           1+f.grid.Hz:f.grid.Nz+f.grid.Hz]

iterate(f::Field, state=1) = iterate(f.data, state)

@inline xnode(::Type{Cell}, i, grid) = @inbounds grid.xC[i]
@inline xnode(::Type{Face}, i, grid) = @inbounds grid.xF[i]

@inline ynode(::Type{Cell}, j, grid) = @inbounds grid.yC[j]
@inline ynode(::Type{Face}, j, grid) = @inbounds grid.yF[j]

@inline znode(::Type{Cell}, k, grid) = @inbounds grid.zC[k]
@inline znode(::Type{Face}, k, grid) = @inbounds grid.zF[k]

@inline xnode(i, ϕ::Field{X, Y, Z}) where {X, Y, Z} = xnode(X, i, ϕ.grid)
@inline ynode(j, ϕ::Field{X, Y, Z}) where {X, Y, Z} = ynode(Y, j, ϕ.grid)
@inline znode(k, ϕ::Field{X, Y, Z}) where {X, Y, Z} = znode(Z, k, ϕ.grid)

xnodes(ϕ::AbstractField) = reshape(ϕ.grid.xC, ϕ.grid.Nx, 1, 1)
ynodes(ϕ::AbstractField) = reshape(ϕ.grid.yC, 1, ϕ.grid.Ny, 1)
znodes(ϕ::AbstractField) = reshape(ϕ.grid.zC, 1, 1, ϕ.grid.Nz)

xnodes(ϕ::Field{Face})                    = reshape(ϕ.grid.xF[1:end-1], ϕ.grid.Nx, 1, 1)
ynodes(ϕ::Field{X, Face}) where X         = reshape(ϕ.grid.yF[1:end-1], 1, ϕ.grid.Ny, 1)
znodes(ϕ::Field{X, Y, Face}) where {X, Y} = reshape(ϕ.grid.zF[1:end-1], 1, 1, ϕ.grid.Nz)

nodes(ϕ) = (xnodes(ϕ), ynodes(ϕ), znodes(ϕ))

# Niceties
const AbstractCPUField =
    AbstractField{A, G} where {A<:OffsetArray{T, D, <:Array} where {T, D}, G}

@hascuda const AbstractGPUField =
    AbstractField{A, G} where {A<:OffsetArray{T, D, <:CuArray} where {T, D}, G}

#####
##### Creating fields by dispatching on architecture
#####

function OffsetArray(underlying_data, grid)
    # Starting and ending indices for the offset array.
    i1, i2 = 1 - grid.Hx, grid.Nx + grid.Hx
    j1, j2 = 1 - grid.Hy, grid.Ny + grid.Hy
    k1, k2 = 1 - grid.Hz, grid.Nz + grid.Hz

    return OffsetArray(underlying_data, i1:i2, j1:j2, k1:k2)
end

function Base.zeros(T, ::CPU, grid)
    underlying_data = zeros(T, grid.Tx, grid.Ty, grid.Tz)
    return OffsetArray(underlying_data, grid)
end

function Base.zeros(T, ::GPU, grid)
    underlying_data = CuArray{T}(undef, grid.Tx, grid.Ty, grid.Tz)
    underlying_data .= 0  # Gotta do this otherwise you might end up with a few NaN values!
    return OffsetArray(underlying_data, grid)
end

Base.zeros(T, ::CPU, grid, Nx, Ny, Nz) = zeros(T, Nx, Ny, Nz)
Base.zeros(T, ::GPU, grid, Nx, Ny, Nz) = zeros(T, Nx, Ny, Nz) |> CuArray

# Default to type of Grid
Base.zeros(arch, grid::AbstractGrid{T}) where T = zeros(T, arch, grid)
Base.zeros(arch, grid::AbstractGrid{T}, Nx, Ny, Nz) where T = zeros(T, arch, grid, Nx, Ny, Nz)