### A Pluto.jl notebook ###
# v0.12.21

using Markdown
using InteractiveUtils

# ╔═╡ 3f57a160-9042-11eb-2981-a58c990f6dfe
begin
    import Pkg
    Pkg.activate(mktempdir())

    Pkg.add([
        Pkg.PackageSpec(name="Pluto"),
        Pkg.PackageSpec(name="PlutoUI"),
        Pkg.PackageSpec(name="CSV"),
        Pkg.PackageSpec(name="DataFrames"),
        Pkg.PackageSpec(name="FreqTables"),
        Pkg.PackageSpec(name="Plots"),
        Pkg.PackageSpec(name="StatsPlots"),
        Pkg.PackageSpec(name="Pipe"),
        Pkg.PackageSpec(name="Statistics"),
        Pkg.PackageSpec(name="DisplayAs"),
		Pkg.PackageSpec(name="MixedModels", rev="main"),
    ])
	
    using Pluto 
	using PlutoUI
	using CSV
	using DataFrames
	using FreqTables
	using Plots
	using StatsPlots
	using Pipe
	using Statistics
	using MixedModels
	using DisplayAs
end

# ╔═╡ 92256604-8f75-11eb-0e65-4df8abfdc276
TableOfContents()

# ╔═╡ e385fbc8-8f75-11eb-08bf-232a909b8db2
md"""
# 0. Load Packages and Set WD
"""

# ╔═╡ ecb582ce-8fa8-11eb-0a7a-6398e820bfa4
theme(:wong)

# ╔═╡ 35723342-8d59-11eb-28ea-3f5af50234e9
cd("/Users/lzhan/Desktop/ITOM/Data"); pwd()

# ╔═╡ 2e42988c-903d-11eb-1f06-9f74eaa45252
md"""
**Levels of `Agent` variable**

- Ex1: LN - Left Normal; RN - Right Normal
- Ex2: LN/M - Left Normal/Mirror; RN/M - Right Normal/Mirror
- Ex3: LA/H - Left Arrow / Human; RA/H - Right Arrow / Human
"""

# ╔═╡ e1eb18d4-8de3-11eb-1d26-4b637d2ab921
md"""
# 1. Experiment One
"""

# ╔═╡ 6299cd52-8ecc-11eb-1558-27598f1704f1
fm1 = @formula(rt ~ 1 + agent + (1 + agent | participant) + (1 + agent | item));

# ╔═╡ e4516da4-8ecd-11eb-274c-2d51c0dd2ad3
contr1 = Dict(:agent => DummyCoding(base = "__"));

# ╔═╡ 79c1fa5c-8ed3-11eb-02ec-ab660761b467
md"""
# 2. Experiment Two
"""

# ╔═╡ 4c56aec6-902e-11eb-3fa7-e5b250746180
contr21 = Dict(:agent => DummyCoding(base = "LM"));

# ╔═╡ aa510800-902e-11eb-2db0-3bf83a5d517f
contr22 = Dict(:agent => DummyCoding(base = "RM"));

# ╔═╡ be05135c-8eec-11eb-3e6a-c3bd9c8a1950
md"""
# 3. Experiment Three
"""

# ╔═╡ 40e48996-902b-11eb-1699-a38768e1b11a
contr3 = Dict(:agent => DummyCoding(base = "LH"));

# ╔═╡ e8045e32-8f74-11eb-08d7-0781a63175a3
md"""
# 4. Appendixes
"""

# ╔═╡ 6110d00c-903e-11eb-2b38-99a816047bc3
md"""
**Column names and their meanings in the data**
- participant: Participant Number;
- type: Letter Type, N - Normal; M - Mirror;
- Orientation: Degree of rotation;
- human (Exp3 - face_orientation): L - Left; R -  Right; _ - No human;
- face_type: N - faced table; M - back(Ex2); _ - No human;
- Condition(Ex3): H - Human(faced_table); A - Arrow; __ - No;
- key\_JUDGE.keys (Ex3: key\_judge.keys): left - normal; right - mirror
- key\_JUDGE.rt (Ex3: key\_judge.rt): Response latency
- Number: Image Number
"""

# ╔═╡ 692a8fc4-8f96-11eb-0614-b1fd9fe4fe56
function key_2_TF(letter_type, key)
	if letter_type == "M"
		return key ∈ ["down", "right"] ? 1 : 0
	elseif letter_type == "N"
		return key ∈ ["up",    "left"] ? 1 : 0
	end
end

# ╔═╡ a110c5fe-8f94-11eb-0f0f-b71e5b9353a6
function read_rename_select(directory, rename_columns, select_columns)
	files = filter(x -> endswith(x, ".csv"), readdir(directory, join = true))
	list = [DataFrame(CSV.File(f))[1:(end-1), :] for f in files]
	for (ind, df) in enumerate(list)
		rename!(df, rename_columns)
		df.participant = string.(df.participant)
		df.item        = string.(df.participant)
		ncol(df) > 40 && (df.rt = df.rt - df.stimulus_duration)
		insertcols!(df, 1, :tf      => key_2_TF.(df.letter_type, df.key));
		insertcols!(df, 1, :agent   => df.agent_position .* df.agent_type);
		list[ind] = df[:, select_columns]
	end
	df = reduce(vcat, list)
	return df
end

# ╔═╡ 89265a5a-8f95-11eb-1d1d-0b9c84742e9b
function filter_data(data, correct_rate, rt_lower, rt_upper)
	participants = @pipe data |>
		groupby(_, :participant) |> 
		combine(_, :tf => mean)  |> 
		filter(:tf_mean => >=(correct_rate), _) |>
		select(_, :participant)
	dt = @pipe data |> 
		dropmissing(_, :rt) |>
		filter(:participant => ∈(participants.participant), _) |>
		# filter(:tf => ==(1), _) |>
		filter(:rt => x -> x >= rt_lower && x <= rt_upper, _)
	return dt
end

# ╔═╡ 00147106-8f98-11eb-34e2-a98d0f6c046a
function summarize_4_plot(dt)
	dtm = @pipe dt |> 
		groupby(_, [:letter_rotation, :agent]) |>
		combine(_, :rt => mean)
	new_rows = insertcols!(dtm[dtm.letter_rotation .== 0, 2:end], 1, 
	:letter_rotation => 360)
	dtmn = vcat(dtm, new_rows)
	return dtmn
end

# ╔═╡ 10acbb8a-8fad-11eb-2d8a-913e1c002326
function polar_plot(dt; lower = 1, upper = 1.4)
	plot(
		(dt.letter_rotation) / 360 * 2π, 
		dt.rt_mean, 
		group = dt.agent, 
		ylim = (lower, upper), 
		seriestype = :line, 
		projection = :polar, 
		theta_direction = -2, 
		set_theta_zero_location = "S",
		linewidth = 1.5,
		marker = 4)
end

# ╔═╡ 083f51ca-8de0-11eb-05d7-513b912438ed
## Experiments 1 and 2
rename1 = Dict(
	:Letter      => "letter",
	:type        => "letter_type",
	:Orientation => "letter_rotation",
	:human       => "agent_position",
	:face_type   => "agent_type",
	Symbol("trials.thisIndex") => "item",
	Symbol("key_JUDGE.keys")   => "key",
	Symbol("key_JUDGE.rt")     => "rt"
);

# ╔═╡ e8ca0eb0-8dd9-11eb-20a5-e1d5e04fa2e8
columns1 = vcat(collect(values(rename1)), 
	"participant", "tf", "agent"); # [[1:4..., 6:7...]]

# ╔═╡ 35b40010-8f93-11eb-3d7a-bbd6941f95dc
ex1_original = read_rename_select("Experiment_1", rename1, columns1);

# ╔═╡ e876a08c-8ef7-11eb-3650-31ae7ed843b7
freqtable(ex1_original, :agent, :letter_rotation)

# ╔═╡ 07386f3e-8f96-11eb-20f4-09d27ddfa926
ex1 = filter_data(ex1_original, 0.8, 0.15, 2);

# ╔═╡ 5ef3d9c0-9031-11eb-3839-e7db22fbf21b
length(unique(ex1.participant))

# ╔═╡ 6ea41f1c-8fad-11eb-193d-dbc8b73fadc2
polar_plot(summarize_4_plot(ex1))

# ╔═╡ 2b3d9e00-8ecd-11eb-3d55-b92db51bd635
fit(MixedModel, fm1, ex1[ex1.letter_rotation .== 135, :], contrasts = contr1)

# ╔═╡ 5503914a-8eeb-11eb-3dca-b96cf673567d
fit(MixedModel, fm1, ex1[ex1.letter_rotation .== 225, :], contrasts = contr1)

# ╔═╡ 56a57220-8eeb-11eb-2cce-ed6739c33c9d
fit(MixedModel, fm1, ex1[ex1.letter_rotation .== 315, :], contrasts = contr1)

# ╔═╡ 308ef3b4-8f94-11eb-293f-2d2ddb3ace9f
ex2_original = read_rename_select("Experiment_2", rename1, columns1);

# ╔═╡ 83cb4264-8ef7-11eb-33be-69bced1d6db1
freqtable(ex2_original, :agent, :letter_rotation)

# ╔═╡ 2b93a9e8-8f96-11eb-3c59-5155ec37e662
ex2 = filter_data(ex2_original, 0.80, 0.15, 2);

# ╔═╡ 7de82660-9036-11eb-1c3f-49b8e64e495b
length(unique(ex2.participant))

# ╔═╡ ff604e88-902d-11eb-2481-751fb18eed11
ex2L = ex2[findall(∈(["LM", "LN"]), ex2.agent), :];

# ╔═╡ 2a97c1e8-8f56-11eb-3c7d-bdee7918a422
fit(MixedModel, fm1, ex2L[ex2L.letter_rotation .== 90, :], contrasts = contr21)

# ╔═╡ 67951164-902e-11eb-024f-eb45dfaeac7c
fit(MixedModel, fm1, ex2L[ex2L.letter_rotation .== 270, :], contrasts = contr21)

# ╔═╡ 8f26ab3e-902e-11eb-1b83-ed1c24af3325
fit(MixedModel, fm1, ex2L[ex2L.letter_rotation .== 315, :], contrasts = contr21)

# ╔═╡ 0f1791ec-902e-11eb-1927-2bdc219c0976
ex2R = ex2[findall(∈(["RM", "RN"]), ex2.agent), :];

# ╔═╡ c798e31c-8faa-11eb-22c3-69269a304f67
plot(polar_plot(summarize_4_plot(ex2L)), 
	 polar_plot(summarize_4_plot(ex2R)), layout = 2)

# ╔═╡ 3a63a3ec-8f55-11eb-390f-b5262e5f8646
fit(MixedModel, fm1, ex2R[ex2R.letter_rotation .== 270, :], contrasts = contr22)

# ╔═╡ 9c771fc6-8f57-11eb-2408-33b89126fa4d
## Experiments 3
rename3 = Dict(
	:Letter      => "letter",
	:type        => "letter_type",
	:Orientation => "letter_rotation",
	Symbol("trials.thisIndex") => "item",
	Symbol("key_judge.keys")   => "key",
	Symbol("key_judge.rt")     => "rt",
	Symbol("face_orientation") => "agent_position",
	:Condition   => "agent_type"
);

# ╔═╡ fb0dfa1e-8f57-11eb-306d-bf0057bc7e12
columns3 = vcat(collect(values(rename3)), "participant", "tf", "agent"); # [[1,2,4,5,7,8]]

# ╔═╡ 53c5a418-8f94-11eb-21ed-6905d9a227ae
ex3_original = read_rename_select("Experiment_3", rename3, columns3);

# ╔═╡ 9b1b7fcc-8f58-11eb-1b2a-e1104e001cb7
freqtable(ex3_original, :agent, :letter_rotation)

# ╔═╡ 3a73aeae-8f96-11eb-0a03-f147003a4128
ex3 = filter_data(ex3_original, 0.8, 0.15, 2);

# ╔═╡ 66990d2e-9031-11eb-2cc7-09cdde9af93b
length(unique(ex3.participant))

# ╔═╡ 9771d9fa-902c-11eb-3ff5-0fec27d703f1
ex3L = ex3[findall(∈(["LA", "LH"]), ex3.agent), :];

# ╔═╡ 634aeff8-902d-11eb-31aa-4121d2a7c318
fit(MixedModel, fm1, ex3L[ex3L.letter_rotation .== 0, :], contrasts = contr3)

# ╔═╡ c4537ec6-8f62-11eb-25b5-b5a7ea79f741
fit(MixedModel, fm1, ex3L[ex3L.letter_rotation .== 315, :], contrasts = contr3)

# ╔═╡ 85ae5cde-902c-11eb-282c-79a93395e5f0
ex3R = ex3[findall(∈(["RA", "RH"]), ex3.agent), :];

# ╔═╡ d74bde4c-8fad-11eb-20d7-41b985c55506
plot(polar_plot(summarize_4_plot(ex3L), lower = 0.5, upper = 0.9), 
	 polar_plot(summarize_4_plot(ex3R), lower = 0.5, upper = 0.9), 
	 layout = 2)

# ╔═╡ Cell order:
# ╟─92256604-8f75-11eb-0e65-4df8abfdc276
# ╟─e385fbc8-8f75-11eb-08bf-232a909b8db2
# ╠═3f57a160-9042-11eb-2981-a58c990f6dfe
# ╠═ecb582ce-8fa8-11eb-0a7a-6398e820bfa4
# ╠═35723342-8d59-11eb-28ea-3f5af50234e9
# ╟─2e42988c-903d-11eb-1f06-9f74eaa45252
# ╟─e1eb18d4-8de3-11eb-1d26-4b637d2ab921
# ╠═35b40010-8f93-11eb-3d7a-bbd6941f95dc
# ╠═e876a08c-8ef7-11eb-3650-31ae7ed843b7
# ╠═07386f3e-8f96-11eb-20f4-09d27ddfa926
# ╠═5ef3d9c0-9031-11eb-3839-e7db22fbf21b
# ╠═6ea41f1c-8fad-11eb-193d-dbc8b73fadc2
# ╠═6299cd52-8ecc-11eb-1558-27598f1704f1
# ╠═e4516da4-8ecd-11eb-274c-2d51c0dd2ad3
# ╠═2b3d9e00-8ecd-11eb-3d55-b92db51bd635
# ╠═5503914a-8eeb-11eb-3dca-b96cf673567d
# ╠═56a57220-8eeb-11eb-2cce-ed6739c33c9d
# ╟─79c1fa5c-8ed3-11eb-02ec-ab660761b467
# ╠═308ef3b4-8f94-11eb-293f-2d2ddb3ace9f
# ╠═83cb4264-8ef7-11eb-33be-69bced1d6db1
# ╠═2b93a9e8-8f96-11eb-3c59-5155ec37e662
# ╠═7de82660-9036-11eb-1c3f-49b8e64e495b
# ╠═ff604e88-902d-11eb-2481-751fb18eed11
# ╠═0f1791ec-902e-11eb-1927-2bdc219c0976
# ╠═c798e31c-8faa-11eb-22c3-69269a304f67
# ╠═4c56aec6-902e-11eb-3fa7-e5b250746180
# ╠═2a97c1e8-8f56-11eb-3c7d-bdee7918a422
# ╠═67951164-902e-11eb-024f-eb45dfaeac7c
# ╠═8f26ab3e-902e-11eb-1b83-ed1c24af3325
# ╠═aa510800-902e-11eb-2db0-3bf83a5d517f
# ╠═3a63a3ec-8f55-11eb-390f-b5262e5f8646
# ╟─be05135c-8eec-11eb-3e6a-c3bd9c8a1950
# ╠═53c5a418-8f94-11eb-21ed-6905d9a227ae
# ╠═9b1b7fcc-8f58-11eb-1b2a-e1104e001cb7
# ╠═3a73aeae-8f96-11eb-0a03-f147003a4128
# ╠═66990d2e-9031-11eb-2cc7-09cdde9af93b
# ╠═9771d9fa-902c-11eb-3ff5-0fec27d703f1
# ╠═85ae5cde-902c-11eb-282c-79a93395e5f0
# ╠═d74bde4c-8fad-11eb-20d7-41b985c55506
# ╠═40e48996-902b-11eb-1699-a38768e1b11a
# ╠═634aeff8-902d-11eb-31aa-4121d2a7c318
# ╠═c4537ec6-8f62-11eb-25b5-b5a7ea79f741
# ╟─e8045e32-8f74-11eb-08d7-0781a63175a3
# ╟─6110d00c-903e-11eb-2b38-99a816047bc3
# ╠═a110c5fe-8f94-11eb-0f0f-b71e5b9353a6
# ╠═692a8fc4-8f96-11eb-0614-b1fd9fe4fe56
# ╠═89265a5a-8f95-11eb-1d1d-0b9c84742e9b
# ╠═00147106-8f98-11eb-34e2-a98d0f6c046a
# ╠═10acbb8a-8fad-11eb-2d8a-913e1c002326
# ╠═083f51ca-8de0-11eb-05d7-513b912438ed
# ╠═e8ca0eb0-8dd9-11eb-20a5-e1d5e04fa2e8
# ╠═9c771fc6-8f57-11eb-2408-33b89126fa4d
# ╠═fb0dfa1e-8f57-11eb-306d-bf0057bc7e12
