library(lme4);library(tidyverse) #file.rename("~/.R/Makevars.win", "~/.R/Makevars.win.bak")
#library(MuMIn);library(car);
library(brms)
#library(rcompanion);library(ggpubr)
library(readxl)
library(ggplot2);library(cowplot);theme_set(theme_cowplot())

setwd("c:/users/walkerro/onedrive - university of missouri/desktop/")
df <- read_excel("data.xlsx", sheet = 1) #, na = "na")
colSums(is.na(df))

table(df$sex)
str(df$sex)
#df$sex <- ifelse(df$sex == "non-binary", "NA", df$sex)

hist(df$atlatl_velocity_mph, 20)
hist(df$spear_velocity_mph, 20)
cor(df$spear_velocity_mph, df$atlatl_velocity_mph)

ggplot(df, aes(x=spear_velocity_mph*0.44704, y = atlatl_velocity_mph*0.44704)) + 
  geom_point(aes(color=sex)) + geom_smooth(method=lm,se=T) + theme_cowplot() +
  ylab("Atlatl velocity (m/s)") +
  xlab("Javelin velocity (m/s)") + theme(legend.position = "top", legend.title=element_blank())
ggsave("correlation.pdf") #, units = "in", height = 7, width=7)

a <- ggplot(df, aes(x=grip, y = atlatl_velocity_mph*0.44704, color=sex)) + geom_point() + 
  geom_smooth(method=lm,se=F) + theme_cowplot()  + scale_y_continuous(limits = c(5,20)) +
  ylab("Atlatl velocity (m/s)") + xlab ("Grip strength") +theme(legend.position = "top", legend.title=element_blank())
a
ggplot(df, aes(x=as.numeric(wt_lbs), y = atlatl_velocity_mph*0.44704, color=sex)) + geom_point() + 
  geom_smooth() + theme_cowplot() +
  ylab("Atlatl velocity (m/s)") + xlab ("wt")

df <- df %>%
  separate(ht,c('feet', 'inches'), sep = "'", convert = TRUE, remove = FALSE) %>%
  mutate(feet = 12*as.numeric(feet) + as.numeric(inches)) %>%
  select(-inches)
ggplot(df, aes(x=as.numeric(feet), y = spear_velocity_mph*0.44704, color=sex)) + geom_point() + 
  geom_smooth() + theme_cowplot() +
  ylab("Atlatl velocity (mph)") 

ggplot(df, aes(x=as.numeric(pinch), y = spear_velocity_mph*0.44704, color=sex)) + geom_point() + 
  geom_smooth() + theme_cowplot() +
  ylab("Atlatl velocity (mph)") 

ggplot(df, aes(x=as.numeric(wt_lbs), y = spear_velocity_mph*0.44704, color=sex)) + geom_point() + 
  geom_smooth(se=F) + theme_cowplot() 
ggplot(df, aes(x=as.numeric(arm_length), y = spear_velocity_mph*0.44704, color=sex)) + geom_point() + 
  geom_smooth(se=F) + theme_cowplot() 

ggplot(df, aes(x=grip, y = spear_velocity_mph*0.44704)) + geom_point() + 
  geom_smooth(method=lm,se=T) + theme_cowplot()

b <- ggplot(df, aes(x=grip, y = spear_velocity_mph*0.44704, color = sex)) + geom_point() + 
  geom_smooth(method=lm,se=F) + theme_cowplot() +  scale_y_continuous(limits = c(5,20)) +
  ylab("Javelin velocity (m/s)") + xlab ("Grip strength") +theme(legend.position = "top", legend.title=element_blank())
b
ggplot(df, aes(x=bicep, y = spear_velocity_mph*0.44704, color = sex)) + geom_point() + 
  geom_smooth(method=lm,se=T) + theme_cowplot() +
  ylab("Javelin velocity (m/s)") + xlab ("bicep")

c <- ggplot(df, aes(x=Age, y = atlatl_velocity_mph*0.44704)) + geom_point(aes(color=sex)) + 
  geom_smooth(se=T) + theme_cowplot() + scale_y_continuous(limits = c(5,25)) +
  ylab("Atlatl velocity (m/s)") + xlab("Age") +theme(legend.position = "top", legend.title=element_blank())
c
d <- ggplot(df, aes(x=Age, y = spear_velocity_mph*0.44704)) + geom_point(aes(color=sex)) +
  geom_smooth(se=T) + theme_cowplot() + scale_y_continuous(limits = c(5,25)) +
  ylab("Javelin velocity (m/s)") + xlab("Age") +theme(legend.position = "top", legend.title=element_blank())
library(ggpubr)
figure <- ggarrange(d, c ,
                    labels = c("A", "B"),
                    ncol = 2, nrow = 1, align="hv")
figure
ggsave("age.pdf", units = "in", height = 4.5, width=7.5)

library(cowplot);library(ggplot2)
e <- ggplot(df, aes(x = factor(sex), y = atlatl_velocity_mph*0.44704)) +
  geom_boxplot(fill = "grey92", outlier.shape = NA) +
  #geom_point( size = 2, alpha = .3, 
   #           position = position_jitter(seed = 1, height = 0, width = .2)) +
  scale_y_continuous(limits = c(5,24.5)) +
  theme_cowplot() + xlab("") + ylab("Atlatl velocity (m/s)")

f <- ggplot(df, aes(x = factor(sex), y = spear_velocity_mph*0.44704)) +
  geom_boxplot(fill = "grey92", outlier.shape = NA) +
  #geom_point( size = 2, alpha = .3, 
  #            position = position_jitter(seed = 1, height = 0, width = .2)) +
  scale_y_continuous(limits = c(5,24.5)) +
  theme_cowplot() + xlab("") + ylab("Javelin velocity (m/s)") 

library(ggpubr)
figure <- ggarrange(f, e ,
                    labels = c("A", "B"),
                    ncol = 2, nrow = 1, align="hv")
figure
ggsave("sex.pdf", units = "in", height = 4, width=7)

library(ggpubr)
figure <- ggarrange(b, a ,
                    labels = c("A", "B"),
                    ncol = 2, nrow = 1, align="hv")
figure
ggsave("fig.pdf", units = "in", height = 4.5, width=7.5)

summary(lm(atlatl_velocity_mph ~ spear_velocity_mph + grip, df))

summary(lm(atlatl_velocity_mph ~ sex + Age + grip, df))
summary(lm(atlatl_velocity_mph ~  sex, df))
summary(lm(atlatl_velocity_mph ~  grip, df))
summary(lm(atlatl_velocity_mph ~  grip + sex, df))
summary(lm(spear_velocity_mph ~ sex + Age + grip, df))
summary(lm(spear_velocity_mph ~ sex + grip, df))

library(brms); library(tidybayes); library(ggstance); library(tidyr); library(dplyr)
library(lme4); library(tidyverse); library(readxl); library(cowplot); library(modelr)
library(magrittr); library(purrr); library(forcats); library(ggplot2); library(ggridges)
library(rstan); library(ggrepel); library(RColorBrewer); library(gganimate)
theme_set(theme_tidybayes() + panel_border())
rstan_options(auto_write = TRUE)
options(mc.cores = parallel::detectCores())

velocity <- c(df$atlatl_velocity_mph, df$spear_velocity_mph)
weapon <- c(rep("atlatl", nrow(df)), rep("spear", nrow(df) ))
long <- data.frame(weapon, velocity)
long$vel_mps <- long$velocity /2.237
priors = c(#set_prior("normal(0, 5)", class = "Intercept"),
  set_prior("normal(30, 5)", class = "b"),
  set_prior("cauchy(0, 1)", class = "b", dpar = "sigma"),
  set_prior("exponential(1.0/29)", class = "nu"))
vs <- brm(bf(vel_mps ~ 0 + weapon, sigma ~ 0+weapon), 
          data = long, save_all_pars = TRUE, 
          family = student, #gaussian(link = "identity"), 
          iter = 1e4, chains = 4, cores = 4, 
          control = list(adapt_delta = .999, max_treedepth = 20),
          prior = priors #backend='cmdstanr'
)
#stancode(vc)
prior_summary(vs)
vs
pl <- plot(vs, N = 4, ask = FALSE) #Trace and Density Plots for MCMC Samples
posterior_summary(vs)
bayes_R2(vs) #.58
conditional_effects(vs, points=T)
saveRDS(vs,"vs.Rds")
vs <- readRDS("vs.Rds")
pp_check(vs)
#ranef(vs)#launch_shinystan(m)

priors = c(set_prior("normal(30, 5)", class = "Intercept"),
  set_prior("normal(0, 1)", class = "b"))

# Fit sEM model in brms
f1 <- bf(grip ~ s(Age) + sex)
f2 <- bf(atlatl_velocity_mph ~ s(Age) + sex + grip)
f3 <- bf(spear_velocity_mph ~ s(Age) + sex + grip)
m <- brm(f1 + f2 + f3 + set_rescor(F),
          prior = priors,
          data = df, save_all_pars = TRUE,
          iter = 1e4, chains = 4, cores = 4, 
          control = list(adapt_delta = .999, max_treedepth = 20)
)
m
prior_summary(m)
pl <- plot(m, N = 4, ask = FALSE) #Trace and Density Plots for MCMC Samples
posterior_summary(m)
conditional_effects(m, points=T)
saveRDS(m,"m.Rds")
m <- readRDS("m.Rds") 

#posterior plots https://cran.r-project.org/web/packages/bayesplot/vignettes/plotting-mcmc-draws.html
posterior <- as.array(m) #full model
dim(posterior)
dimnames(posterior)
library(bayesplot)
plt1 <- mcmc_areas(
  posterior, 
  pars = c(#"b_spearvelocitymph_sexmale",
           #"b_atlatlvelocitymph_sexmale",
           "b_atlatlvelocitymph_grip" ,
           "b_spearvelocitymph_grip" 
           ),
  prob = 0.95, # 80% intervals
  #prob_outer = 0.99, # 99%
  point_est = "mean"
)
plt1
plot1 <- plt1 + annotate(geom="text", x=.1, y=2.7, label="Atlatls",color="black", size=4) +
  annotate(geom="text", x=.3, y=1.5, label="Javelins",color="black", size=4) +
  ylab("Density") + xlab("Grip strength slopes") +
  #scale_y_continuous(expand = c(0,0)) +
  #expand_limits(y = 2) +
  geom_vline(xintercept=0) +
  #ylim(0,1)+
  scale_x_continuous(limits = c(0,.5), breaks = round(seq(0, 1, by = .1),2), expand = c(0, 0)) +
  theme(
    #axis.text.x = element_blank(),
    axis.text.y = element_blank(),
    axis.ticks.y = element_blank())
#axis.title.x=element_blank(),
#axis.text.x=element_blank(), 
#axis.ticks.x=element_blank())
plot1  

#posterior plots https://cran.r-project.org/web/packages/bayesplot/vignettes/plotting-mcmc-draws.html
plt2 <- mcmc_areas(
  posterior, 
  pars = c("b_atlatlvelocitymph_sexmale",
           "b_spearvelocitymph_sexmale"
     
  ),
  prob = 0.95, # 80% intervals
  #prob_outer = 0.99, # 99%
  point_est = "mean"
)
plt2
plot2 <- plt2 + annotate(geom="text", x=2, y=2.7, label="Atlatls",color="black", size=4) +
  annotate(geom="text", x=2, y=1.5, label="Javelins",color="black", size=4) +
  ylab("Density") + xlab("Sex effect (males vs females)") +
  #scale_y_continuous(expand = c(0,0)) +
  #expand_limits(y = 2) +
  geom_vline(xintercept=0, linetype="dotted") +
  #ylim(0,1)+
  scale_x_continuous(limits = c(-4,9), breaks = round(seq(-4, 9, by = 2),1), expand = c(0, 0)) +
  theme(
    #axis.text.x = element_blank(),
    axis.text.y = element_blank(),
    axis.ticks.y = element_blank())
#axis.title.x=element_blank(),
#axis.text.x=element_blank(),
#axis.ticks.x=element_blank())
plot2  

library(ggpubr)
figure <- ggarrange(plot1, plot2 ,
                    labels = c("A", "B"),
                    ncol = 2, nrow = 1, align="hv")
figure
ggsave("posteriors.pdf", units = "in", height = 6, width=8)

