### A Pluto.jl notebook ###
# v0.20.4

using Markdown
using InteractiveUtils

# ╔═╡ 39aff458-b7ad-11ef-36a8-11479bd3ad79
begin
    using Pkg
    Pkg.activate(".")

    using PSBoardDataBase
    using DataFrames
    using CairoMakie
    using FHist
    using LinearAlgebra
    using Printf
    using Measurements
    using Unitful
    using Statistics
    using Missings
    using PlutoUI
end

# ╔═╡ 775bbe85-0bc3-4a6d-be3d-aa2338cc7091
md"""
# delay unit = 1で待つ時間を変えたときのロックしやすさのスキャン
"""

# ╔═╡ 8c8f15fb-508f-4068-8fc0-d6ad5905891d
df_psboards = DataFrame(
    position = ["B-$(i)-$(j)" for j in 1:9 for i in 0:1],
    psbid = [
        001142,
        000973,
        000990,
        000992,
        001113,
        001030,
        001121,
        001141,
        001050,
        001053,
        001110,
        001248,
        001242,
        001276,
        000872,
        000861,
        000525,
        000862,
    ],
)

# ╔═╡ 4ebadb4f-ba6f-412e-9def-450ca9d3f6b8
df_setups = DataFrame(
    runid = [384, 386, 388, 389, 390, 391, 393, 396, 397, 398, 400, 401],
    firmware = [
        fill("PS_firmware_top_2024_11_27.zip", 6)
        fill("PS_firmware_top_CPdrivability_2b00.zip", 6)
    ],
    wait_length = [
        missing,
        100u"ns",
        1u"μs",
        10u"μs",
        100u"μs",
        1u"ms",
        1u"ms",
        100u"ns",
        10u"μs",
        1u"μs",
        100u"μs",
        100u"μs",
    ],
)

# ╔═╡ 8ae734be-7a93-4257-ad2a-02cdee82066a
df_configs = crossjoin(df_setups, df_psboards)

# ╔═╡ d6da8dca-e7f0-4f9e-88dd-53e91c8c55ad
function get_pllld_counter_hist(slaveresult)
    h1 = Hist1D(; binedges = 1:1:11)
    for asdtp_result in slaveresult.asdtp
        push!(h1, asdtp_result.pllld_fail_counter + 1)
    end
    return h1
end

# ╔═╡ bc78bf6e-2d1f-4922-8b9e-48aaf1e8b0af
df_pllld_fail_counts = transform(
    df_configs,
    [:runid, :psbid] =>
        ByRow(
            (runid, psbid) -> begin
                slavelog = "../test/input/slavelogs/main/$(psbid)_$(runid)_longrun.txt"
                if !ispath(slavelog)
                    @info "file $(slavelog) not found"
                    return missing
                end
                slaveresult =
                    PSBoardDataBase.SlaveLogParser.parse_slavelog_file(slavelog)
                # @info "" slaveresult
                h_pllld_fail_count = get_pllld_counter_hist(slaveresult)
                h_pllld_fail_count
            end,
        ) => :pllld_count,
)

# ╔═╡ 6100e4a6-30ed-4540-9e8d-0171272e41e9
let df
    df = filter(
        [:firmware, :wait_length] => (
            (firmware, wait_length) -> begin
                firmware == "PS_firmware_top_2024_11_27.zip" && ismissing(wait_length)
            end
        ),
        df_pllld_fail_counts,
    )
    @info "" nrow(df) nrow(df) == 18 * 1

    combine(groupby(df, :wait_length), :pllld_count => sum)
end

# ╔═╡ 0100a27a-70a3-4d1d-916e-00be7b436f7e
let df
    fig = Figure()
    ax = Axis(fig[1, 1], xlabel = "number of reset", title = "same setup as 6th QAQC")

    df = filter(
        [:firmware, :wait_length] => (
            (firmware, wait_length) -> begin
                firmware == "PS_firmware_top_2024_11_27.zip" && ismissing(wait_length)
            end
        ),
        df_pllld_fail_counts,
    )

    normhist = normalize(sum(df.pllld_count))
    stephist!(ax, normhist)
    errorbars!(ax, normhist)

    fig
end

# ╔═╡ d1be7028-6c2d-40bc-8a76-352d59d1f91a
let df
    df = filter(
        [:firmware, :wait_length] => (
            (firmware, wait_length) -> begin
                firmware == "PS_firmware_top_2024_11_27.zip" && !ismissing(wait_length)
            end
        ),
        df_pllld_fail_counts,
    )
    @info "" nrow(df) nrow(df) == 18 * 5

    df_summarized = combine(groupby(df, :wait_length), :pllld_count => sum)

    fig = Figure(size = (600, 1000))
    Label(fig[0, 1], "normal firmware, softreset software for scanning", tellwidth = false)
    for (i, row) in enumerate(eachrow(df_summarized))
        ax = Axis(
            fig[i, 1],
            yscale = log10,
            xlabel = "number of resets",
            ylabel = "fraction",
            title = "$(row.wait_length)",
            limits = ((1, 11), (eps(), 100)),
        )
        normhist = normalize(row.pllld_count_sum)
        stephist!(ax, normhist)
        errorbars!(ax, normhist)
        text!(
            ax,
            bincenters(normhist),
            bincounts(normhist),
            text = [@sprintf "%.4f" r for r in bincounts(normhist)],
        )
    end
    fig
end

# ╔═╡ ae97c43d-34dd-4aad-8cf5-7158b717e5c1
let df
    df = filter(
        [:firmware, :wait_length] => (
            (firmware, wait_length) -> begin
                firmware == "PS_firmware_top_CPdrivability_2b00.zip"
            end
        ),
        df_pllld_fail_counts,
    )
    dropmissing!(df, :pllld_count)
    @info "" nrow(df) nrow(df) == 18 * 6

    df_summarized = combine(groupby(df, :wait_length, sort = true), :pllld_count => sum)

    fig = Figure(size = (600, 1000))
    Label(fig[0, 1], "minimum charge pump bias current", tellwidth = false)
    for (i, row) in enumerate(eachrow(df_summarized))
        ax = Axis(
            fig[i, 1],
            yscale = log10,
            xlabel = "number of resets",
            ylabel = "fraction",
            title = "$(row.wait_length)",
            limits = ((1, 11), (eps(), 100)),
        )
        normhist = normalize(row.pllld_count_sum)
        stephist!(ax, normhist)
        errorbars!(ax, normhist)
        text!(
            ax,
            bincenters(normhist),
            bincounts(normhist),
            text = [@sprintf "%.4f" r for r in bincounts(normhist)],
        )
    end
    fig
end

# ╔═╡ 6206becc-364c-47b6-bfe3-d295b784cade
md"""
TODO: **なぜrun393であんなに時間かかった????**
"""

# ╔═╡ b420835f-0f8c-4561-9662-975dedfe03c4
0.0002 * 1800

# ╔═╡ Cell order:
# ╠═775bbe85-0bc3-4a6d-be3d-aa2338cc7091
# ╠═39aff458-b7ad-11ef-36a8-11479bd3ad79
# ╠═8c8f15fb-508f-4068-8fc0-d6ad5905891d
# ╠═4ebadb4f-ba6f-412e-9def-450ca9d3f6b8
# ╠═8ae734be-7a93-4257-ad2a-02cdee82066a
# ╠═d6da8dca-e7f0-4f9e-88dd-53e91c8c55ad
# ╠═bc78bf6e-2d1f-4922-8b9e-48aaf1e8b0af
# ╠═6100e4a6-30ed-4540-9e8d-0171272e41e9
# ╠═0100a27a-70a3-4d1d-916e-00be7b436f7e
# ╠═d1be7028-6c2d-40bc-8a76-352d59d1f91a
# ╠═ae97c43d-34dd-4aad-8cf5-7158b717e5c1
# ╠═6206becc-364c-47b6-bfe3-d295b784cade
# ╠═b420835f-0f8c-4561-9662-975dedfe03c4
