
# ==================================================
# Title:  Gender stereotypes do not affect acceptability judgments: 
#         Experimental evidence from Russian syntax
# Authors: Anonymized
# ==================================================
# Data Processing and Analysis
# Supplementary Materials
# ==================================================

library(ggplot2)
library(dplyr)
library(tidyr)
library(lme4)
library(lmerTest)
library(emmeans) 

# Set working directory (modify path as needed)
setwd("/path/to/your/data/directory")

# ==================================================
# 1. DATA IMPORT FROM PCIBEX
# ==================================================

# Function to read PCIbex output files
read.pcibex <- function(filepath, auto.colnames=TRUE, fun.col=function(col,cols){cols[cols==col]<-paste(col,"Ibex",sep=".");return(cols)}) {
  n.cols <- max(count.fields(filepath,sep=",",quote=NULL),na.rm=TRUE)
  if (auto.colnames){
    cols <- c()
    con <- file(filepath, "r")
    while ( TRUE ) {
      line <- readLines(con, n = 1, warn=FALSE)
      if ( length(line) == 0) {
        break
      }
      m <- regmatches(line,regexec("^# (\\d+)\\. (.+)\\.$",line))[[1]]
      if (length(m) == 3) {
        index <- as.numeric(m[2])
        value <- m[3]
        if (is.function(fun.col)){
          cols <- fun.col(value,cols)
        }
        cols[index] <- value
        if (index == n.cols){
          break
        }
      }
    }
    close(con)
    return(read.csv(filepath, comment.char="#", header=FALSE, col.names=cols))
  }
  else{
    return(read.csv(filepath, comment.char="#", header=FALSE, col.names=seq(1:n.cols)))
  }
}

# Import raw results
results <- read.pcibex("raw_results.csv")

# Save raw results for reference
write.csv(results, 'results_read.csv', row.names = FALSE)

# ==================================================
# 2. DATA EXTRACTION AND INITIAL CLEANING
# ==================================================

# Read the saved data (optional, if restarting here)
# results <- read.csv("results_read.csv", header = TRUE, stringsAsFactors = TRUE)

# Check IP address distribution (participant uniqueness)
length(levels(as.factor(results$MD5.hash.of.participant.s.IP.address)))  # 65 (matches the total number of participants plus one test run)
length(levels(as.factor(results$ParticipantID)))  # 66 (includes "NULL" value)

# ==================================================
# 2.1 Extract acceptability judgment data
# ==================================================

results_judgments <- subset(results, 
                            PennElementType == "Controller-AcceptabilityJudgment" &
                              Parameter == "NULL")
results_judgments <- droplevels(results_judgments)

# Verify number of trials per participant
trials_per_participant <- length(results_judgments$ParticipantID) / 
  length(levels(as.factor(results_judgments$ParticipantID)))
trials_per_participant # 116

# ==================================================
# 2.2 Extract question data (attention checks)
# ==================================================

results_questions <- subset(results, 
                            PennElementType == "Controller-Question")
results_questions <- droplevels(results_questions)

# Verify questions per participant
questions_per_participant <- length(results_questions$ParticipantID) / 
  length(levels(as.factor(results_questions$ParticipantID)))
questions_per_participant # 4

# ==================================================
# 2.3 Extract demographic questionnaire data
# ==================================================

results_anketa <- subset(results, 
                         (PennElementName == "id_response" | 
                            PennElementName == "age_response" | 
                            PennElementName == "gender_response" | 
                            PennElementName == "gorod1_response" | 
                            PennElementName == "gorod2_response" | 
                            PennElementName == "lang_edu_response" | 
                            PennElementName == "lang_response") & 
                           (Parameter == "Final" | Parameter == "Choice"))
results_anketa <- droplevels(results_anketa)

# Save demographic data
write.csv(results_anketa, 'results_anketa.csv', row.names = FALSE)

# ==================================================
# 2.4 Create final judgment dataset
# ==================================================

judgement <- results_judgments[, c("ParticipantID", 
                                   "group", 
                                   "sentence_id",
                                   "Label",
                                   "filler_type",
                                   "lexicalization",
                                   "predicate",
                                   "to",
                                   "prototype",
                                   "gender",
                                   "Value",
                                   "Time.taken.to.answer.")]

# Rename columns for consistency
colnames(judgement)[which(names(judgement) == "ParticipantID")] <- "id"
colnames(judgement)[which(names(judgement) == "Value")] <- "response"
colnames(judgement)[which(names(judgement) == "Time.taken.to.answer.")] <- "time"

# ==================================================
# 2.5 Create final question dataset
# ==================================================

question <- results_questions[, c("ParticipantID", 
                                  "Value",
                                  "Whether.or.not.answer.was.correct..NULL.if.N.A.")]

colnames(question)[which(names(question) == "ParticipantID")] <- "id"
colnames(question)[which(names(question) == "Value")] <- "response"
colnames(question)[which(names(question) == "Whether.or.not.answer.was.correct..NULL.if.N.A.")] <- "correct"

# ==================================================
# 2.6 Clean response values
# ==================================================

# Convert NULL to NA in judgments
judgement$response[judgement$response == "NULL"] <- NA
judgement$response <- droplevels(as.factor(judgement$response))
judgement$response <- as.numeric(as.character(judgement$response))

# ==================================================
# 3. WITHIN-PARTICIPANT NORMALIZATION (Z-SCORES)
# ==================================================

# Exclude training data
working_data <- subset(judgement, group != "T")
working_data <- droplevels(working_data)

# Sort by participant ID
sorted_data <- working_data[with(working_data, order(id)), ]

# Split by participant for normalization
split_by_respondent <- split(sorted_data$response, f = sorted_data$id)

# Apply z-score transformation
normalized_scores <- lapply(split_by_respondent, scale)

# Reconstruct data frame with normalized scores
sorted_data$z_scores <- unsplit(normalized_scores, f = sorted_data$id)

# Create dataset with excluded training data
excluded_data <- subset(judgement, group == "T")
excluded_data$z_scores <- NA

# Combine processed data with excluded data
full_data <- rbind(sorted_data, excluded_data)
full_data <- full_data[order(full_data$id), ]

full_data <- full_data %>%
  mutate(across(where(is.character), as.factor))

# Save raw results for reference
# write.csv(full_data, 'full_data.csv', row.names = FALSE)

# ==================================================
# 4. OUTLIER DETECTION AND PARTICIPANT FILTERING
# ==================================================

# Read the saved data (optional, if restarting here)
# full_data <- read.csv("full_data.csv", header = TRUE, stringsAsFactors = TRUE)

# ==================================================
# 4.1 Training Trials Analysis: Comparison with Standards
# ==================================================

training_data <- subset(full_data, Label == "training_trials")
training_data <- droplevels(training_data)

# Set standard values: 2 for ungrammatical, 6 for grammatical
training_data$standard[training_data$filler_type == "bad"] <- 2
training_data$standard[training_data$filler_type == "good"] <- 6
training_data$standard <- as.numeric(training_data$standard)

# Calculate deviation from standard
training_data$difference <- training_data$response - training_data$standard

# Function to calculate sum of squares
sum_squares <- function(x) {
  sum(x^2, na.rm = TRUE)
}

# Calculate sum of squares per participant
training_resp <- with(training_data,
                      aggregate(list(sumsquares = difference),
                                list(subject = id), sum_squares))
training_resp <- training_resp[with(training_resp, order(sumsquares)), ]

# Identify outliers (> 2 SD from mean)
training_resp_mean <- mean(training_resp$sumsquares)
training_resp_sd <- sd(training_resp$sumsquares)
training_criterion <- training_resp_mean + (2 * training_resp_sd)
training_outliers <- training_resp[training_resp$sumsquares > training_criterion, ]

# ==================================================
# 4.2 Fillers Analysis: Comparison with Standards
# ==================================================

filler_data <- subset(full_data, Label == "filler1" | Label == "filler2")
filler_data <- droplevels(filler_data)

# Set standard values
filler_data$standard[filler_data$filler_type == "ungram"] <- 2
filler_data$standard[filler_data$filler_type == "gram"] <- 6
filler_data$standard <- as.numeric(filler_data$standard)

# Calculate deviation
filler_data$difference <- filler_data$response - filler_data$standard

# Calculate sum of squares per participant
filler_resp <- with(filler_data,
                    aggregate(list(sumsquares = difference),
                              list(subject = id), sum_squares))
filler_resp <- filler_resp[with(filler_resp, order(sumsquares)), ]

# Identify outliers
filler_resp_mean <- mean(filler_resp$sumsquares)
filler_resp_sd <- sd(filler_resp$sumsquares)
filler_criterion <- filler_resp_mean + (2 * filler_resp_sd)
filler_outliers <- filler_resp[filler_resp$sumsquares > filler_criterion, ]

# ==================================================
# 4.3 Fillers Analysis: Deviation from Item Means (Z-scores)
# ==================================================

filler_data <- subset(full_data, Label == "filler1" | Label == "filler2")
filler_data <- droplevels(filler_data)

# Sort by item
dataset_filler <- filler_data[with(filler_data, order(lexicalization)), ]

# Calculate item means and SDs
split_sentences <- split(dataset_filler$z_scores, f = dataset_filler$lexicalization)
split_sentences_mean <- lapply(split_sentences, mean, na.rm = TRUE)
split_sentences_sd <- lapply(split_sentences, sd, na.rm = TRUE)

# Add means and SDs to dataframe
dataset_filler$means <- unsplit(split_sentences_mean, f = dataset_filler$lexicalization)
dataset_filler$sds <- unsplit(split_sentences_sd, f = dataset_filler$lexicalization)

# Define acceptable range (±1 SD)
dataset_filler$upper <- dataset_filler$means + 2 * dataset_filler$sds
dataset_filler$lower <- dataset_filler$means - 2 * dataset_filler$sds

# Flag outliers
dataset_filler <- dataset_filler %>% 
  mutate(outlier = z_scores < lower | z_scores > upper)

# Examine outlier counts per participant
outlier_by_participant <- dataset_filler %>%
  group_by(id) %>%
  summarise(
    total_trials = n(),
    outlier_count = sum(outlier == TRUE, na.rm = TRUE),
    outlier_percentage = (outlier_count / total_trials) * 100
  ) %>%
  filter(outlier_count > 0) %>%
  arrange(desc(outlier_count))

# Identify participants with high percentage of outliers (>20%)
bad_participants_filler <- outlier_by_participant %>%
  filter(outlier_percentage > 20) %>%
  pull(id)

# ==================================================
# 4.4 Training Trials Analysis: Deviation from Item Means
# ==================================================

training_data <- subset(full_data, Label == "training_trials")
training_data <- droplevels(training_data)

# Sort by item
dataset_training <- training_data[with(training_data, order(sentence_id)), ]

# Calculate item means and SDs
split_sentences <- split(dataset_training$response, f = dataset_training$sentence_id)
split_sentences_mean <- lapply(split_sentences, mean, na.rm = TRUE)
split_sentences_sd <- lapply(split_sentences, sd, na.rm = TRUE)

# Add means and SDs to dataframe
dataset_training$means <- unsplit(split_sentences_mean, f = dataset_training$sentence_id)
dataset_training$sds <- unsplit(split_sentences_sd, f = dataset_training$sentence_id)

# Define acceptable range
dataset_training$upper <- dataset_training$means + dataset_training$sds
dataset_training$lower <- dataset_training$means - dataset_training$sds

# Flag outliers
dataset_training <- dataset_training %>% 
  mutate(outlier = response < lower | response > upper)

# Examine outlier counts per participant
outlier_by_participant_training <- dataset_training %>%
  group_by(id) %>%
  summarise(
    total_trials = n(),
    outlier_count = sum(outlier == TRUE, na.rm = TRUE),
    outlier_percentage = (outlier_count / total_trials) * 100
  ) %>%
  filter(outlier_count > 0) %>%
  arrange(desc(outlier_count))

# Identify participants with high percentage of outliers (>20%)
bad_participants_training <- outlier_by_participant_training %>%
  filter(outlier_percentage > 50) %>%
  pull(id)

# ==================================================
# 4.5 Attention Check Questions
# ==================================================

# Create answer_is_correct variable (assuming 1 = correct)
question$answer_is_correct <- as.numeric(as.character(question$correct))

# Calculate correct answers per participant
control_results <- with(question,
                        aggregate(list(correct_answers = answer_is_correct),
                                  list(subject = id), sum, na.rm = TRUE))

# Identify participants with ≤ 2 correct answers
participants_low_attention <- subset(control_results, correct_answers <= 2)$subject

# ==================================================
# 4.6 Response Time Analysis
# ==================================================

# Identify fast responses (< 500 ms)
if("time" %in% colnames(full_data)) {
  fast_responses <- subset(full_data, time < 500)
  fast_responses <- droplevels(fast_responses)
  
  # Count fast responses per participant
  fast_response_counts <- table(fast_responses$id)
  
  # Identify participants with > 10 fast responses
  participants_fast_responses <- names(fast_response_counts[fast_response_counts > 10])
}

# ==================================================
# 4.7 Scale Use Analysis
# ==================================================

# Analyze response distribution per participant
response_distribution <- xtabs(~ id + response, full_data)

# Participants using only one scale value
single_value_ids <- rownames(response_distribution)[rowSums(response_distribution > 0) == 1]

# Analyze scale range usage (for 1-7 scale)
scale_usage <- full_data %>%
  group_by(id) %>%
  summarise(
    unique_scores = n_distinct(response),
    score_range = max(response, na.rm = TRUE) - min(response, na.rm = TRUE),
    uses_low = any(response <= 3, na.rm = TRUE),
    uses_mid = any(response >= 4 & response <= 5, na.rm = TRUE),
    uses_high = any(response >= 6, na.rm = TRUE),
    healthy_pattern = uses_low & uses_high
  )

# Identify participants using only one range
participants_single_range <- scale_usage %>%
  mutate(
    ranges_used = as.numeric(uses_low) + as.numeric(uses_mid) + as.numeric(uses_high)
  ) %>%
  filter(ranges_used == 1) %>%
  pull(id)

# ==================================================
# 4.8 Missing Responses Analysis
# ==================================================

# Create missing response indicator
full_data$missing <- ifelse(is.na(full_data$response), TRUE, FALSE)

# Count missing responses per participant
missing_counts <- xtabs(~ id + missing, full_data)
missing_stats <- as.data.frame(missing_counts)
missing_stats <- missing_stats[missing_stats$missing == "TRUE", ]

# Identify participants with > 10 missing responses
if(nrow(missing_stats) > 0) {
  participants_missing <- as.character(missing_stats$id[missing_stats$Freq > 10])
} else {
  participants_missing <- character(0)
}

# ==================================================
# 5. PARTICIPANT EXCLUSION
# ==================================================

# Collect all problematic participants
excluded_participants <- unique(c(
  participants_missing,
  single_value_ids,
  participants_single_range,
  participants_fast_responses,
  participants_low_attention,
  as.character(filler_outliers$subject),
  as.character(training_outliers$subject),
  bad_participants_filler,
  bad_participants_training
))

excluded_participants <- sort(excluded_participants)
print(paste("Number of excluded participants:", length(excluded_participants)))

# Define "not in" operator
'%!in%' <- function(x, y) !('%in%'(x, y))

# Remove outliers
clean_data <- subset(full_data, id %!in% excluded_participants)
clean_data <- droplevels(clean_data)

# Check participant count after exclusion
print(paste("Original participants:", length(levels(full_data$id))))
print(paste("Clean participants:", length(levels(clean_data$id))))

# Save cleaned dataset
# write.csv(clean_data, file = "judgments_clean.csv", row.names = FALSE)

# ==================================================
# 5.1 Save excluded participant list
# ==================================================

# Save as CSV
excluded_df <- data.frame(
  excluded_participant_id = excluded_participants,
  stringsAsFactors = FALSE
)
# write.csv(excluded_df, "excluded_participants.csv", row.names = FALSE)

# ==================================================
# 5.2 Detailed exclusion log with reasons
# ==================================================

# Create data frame with all participants and exclusion status
all_participants <- unique(full_data$id)

exclusion_log <- data.frame(
  participant_id = all_participants,
  excluded = ifelse(all_participants %in% excluded_participants, "YES", "NO"),
  reason_missing_responses = ifelse(all_participants %in% participants_missing, "YES", "NO"),
  reason_single_range = ifelse(all_participants %in% participants_single_range, "YES", "NO"),
  reason_single_value = ifelse(all_participants %in% single_value_ids, "YES", "NO"),
  reason_fast_responses = ifelse(all_participants %in% participants_fast_responses, "YES", "NO"),
  reason_low_attention = ifelse(all_participants %in% participants_low_attention, "YES", "NO"),
  reason_filler_outlier = ifelse(all_participants %in% as.character(filler_outliers$subject), "YES", "NO"),
  reason_training_outlier = ifelse(all_participants %in% as.character(training_outliers$subject), "YES", "NO"),
  reason_high_percent_outlier = ifelse(all_participants %in% bad_participants_filler, "YES", "NO"),
  reason_high_percent_outlier_training = ifelse(all_participants %in% bad_participants_training, "YES", "NO"),
  stringsAsFactors = FALSE
)

# Add combined reasons column
exclusion_log$all_reasons <- apply(
  exclusion_log[, 3:11], 
  1, 
  function(x) {
    reasons <- names(x)[x == "YES"]
    if(length(reasons) == 0) return("")
    gsub("reason_", "", paste(reasons, collapse = ", "))
  }
)

# Extract only excluded
excluded_only <- exclusion_log[exclusion_log$excluded == "YES", 
                               c("participant_id", "all_reasons")]

# View the result
print("=== EXCLUDED PARTICIPANTS (from exclusion_log) ===")
print(excluded_only)

# Save detailed log
write.csv(exclusion_log, "exclusion_log_detailed.csv", row.names = FALSE)
write.csv(excluded_only, "exclusion_log_excluded.csv", row.names = FALSE)

# ==================================================
# 5.3 Exclusion summary
# ==================================================

exclusion_summary <- data.frame(
  criterion = c(
    "Missing responses (>10)",
    "Single range use only",
    "Single value use only",
    "Fast responses (>10 under 400ms)",
    "Low attention (≤2 correct answers)",
    "Filler outlier (sum of squares >2SD)",
    "Training outlier (sum of squares >2SD)",
    "High outlier percentage in fillers (>20%)",
    "High outlier percentage in training (>20%)",
    "TOTAL UNIQUE PARTICIPANTS EXCLUDED"
  ),
  count = c(
    length(participants_missing),
    length(participants_single_range),
    length(single_value_ids),
    length(participants_fast_responses),
    length(participants_low_attention),
    nrow(filler_outliers),
    nrow(training_outliers),
    length(bad_participants_filler),
    length(bad_participants_training),
    length(excluded_participants)
  ),
  percentage = c(
    length(participants_missing) / length(all_participants) * 100,
    length(participants_single_range) / length(all_participants) * 100,
    length(single_value_ids) / length(all_participants) * 100,
    length(participants_fast_responses) / length(all_participants) * 100,
    length(participants_low_attention) / length(all_participants) * 100,
    nrow(filler_outliers) / length(all_participants) * 100,
    nrow(training_outliers) / length(all_participants) * 100,
    length(bad_participants_filler) / length(all_participants) * 100,
    length(bad_participants_training) / length(all_participants) * 100,
    length(excluded_participants) / length(all_participants) * 100
  ),
  stringsAsFactors = FALSE
)

# Round percentages
exclusion_summary$percentage <- round(exclusion_summary$percentage, 2)

print("=== EXCLUSION SUMMARY ===")
print(exclusion_summary)

# criterion count percentage
# 1                     Missing responses (>10)     2       3.08
# 2                       Single range use only     1       1.54
# 3                       Single value use only     1       1.54
# 4            Fast responses (>10 under 400ms)     2       3.08
# 5          Low attention (≤2 correct answers)     6       9.23
# 6        Filler outlier (sum of squares >2SD)     0       0.00
# 7      Training outlier (sum of squares >2SD)     5       7.69
# 8   High outlier percentage in fillers (>20%)     0       0.00
# 9  High outlier percentage in training (>20%)     2       3.08
# 10         TOTAL UNIQUE PARTICIPANTS EXCLUDED    12      18.46

# Since the sample included one test run that was also excluded, 
# the total number of unique participants removed stands at 11 (17.19%).

# Save summary
write.csv(exclusion_summary, "exclusion_summary.csv", row.names = FALSE)

# ==================================================
# 6. PARTICIPANT DEMOGRAPHICS
# ==================================================

# Read demographic data
results_anketa <- read.csv("results_anketa.csv", 
                           header = TRUE, 
                           stringsAsFactors = TRUE)

# ==================================================
# 6.1 Reshape demographic data
# ==================================================

demographics <- results_anketa %>%
  select(ParticipantID, PennElementName, Value) %>%
  distinct() %>%
  pivot_wider(
    id_cols = ParticipantID,
    names_from = PennElementName,
    values_from = Value
  )

# Rename columns for clarity
colnames(demographics) <- c("id", 
                            "gender", 
                            "lang_education", 
                            "age", 
                            "participant_id_response", 
                            "language", 
                            "city1", "city2")

# Remove redundant column
demographics$participant_id_response <- NULL

# ==================================================
# 6.2 Clean demographic data
# ==================================================

# Convert age to numeric
demographics$age <- as.numeric(as.character(demographics$age))

# Standardize gender categories
demographics$participant_gender <- case_when(
  tolower(demographics$gender) %in% c("женский") ~ "Female",
  tolower(demographics$gender) %in% c("мужской") ~ "Male",
  tolower(demographics$gender) %in% c("другое") ~ "Other",
  TRUE ~ "Not specified"
)

# ==================================================
# 6.3 Filter demographics to include only clean participants
# ==================================================

demographics_clean <- demographics %>%
  filter(id %!in% excluded_participants)

# Save clean demographics
write.csv(demographics_clean, "participant_demographics_clean.csv", row.names = FALSE)

# ==================================================
# 6.4 Demographic statistics for clean sample
# ==================================================

# Age statistics
age_stats_clean <- demographics_clean %>%
  summarise(
    n_valid_age = sum(!is.na(age)),
    n_missing_age = sum(is.na(age)),
    mean_age = mean(age, na.rm = TRUE),
    sd_age = sd(age, na.rm = TRUE),
    median_age = median(age, na.rm = TRUE),
    min_age = min(age, na.rm = TRUE),
    max_age = max(age, na.rm = TRUE)
  )

print("=== AGE STATISTICS (CLEAN SAMPLE) ===")
print(age_stats_clean)
# n_valid_age n_missing_age mean_age sd_age median_age min_age max_age
# <int>         <int>    <dbl>  <dbl>      <dbl>   <dbl>   <dbl>
#   1          53             0     39.9   12.9         37      20      76

# Gender statistics
gender_stats_clean <- demographics_clean %>%
  group_by(participant_gender) %>%
  summarise(
    count = n(),
    percentage = (n() / nrow(demographics_clean)) * 100
  ) %>%
  arrange(desc(count))

print("=== GENDER STATISTICS (CLEAN SAMPLE) ===")
print(gender_stats_clean)
# gender_clean  count percentage
# <chr>         <int>      <dbl>
# 1 Male             28      52.8 
# 2 Female           24      45.3 
# 3 Not specified     1       1.89

# ==================================================
# 7. ADD PARTICIPANT DEMOGRAPHICS TO RESULTS DATASET
# ==================================================

clean_data <- read.csv("judgments_clean.csv", 
                           header = TRUE, 
                           stringsAsFactors = TRUE)

# Add gender information
clean_data <- clean_data %>%
  left_join(demographics_clean %>% select(id, participant_gender, age), by = "id")

# Create age groups
clean_data <- clean_data %>%
  mutate(
    age_group = cut(age, 
                    breaks = c(-Inf, 28, 38, 48, Inf),
                    labels = c("18-28", "29-38", "39-48", "49+"),
                    right = TRUE)
  )

clean_data$age_group <- factor(clean_data$age_group, 
                               levels = c("18-28", "29-38", "39-48", "49+"),
                               ordered = TRUE)

# Save dataset with demographics
write.csv(clean_data, "judgments_with_demographics.csv", row.names = FALSE)

# ==================================================
# 8. DATA PREPARATION FOR VISUALIZATION
# ==================================================

# Use clean_data for all subsequent analyses
clean_data <- read.csv("judgments_with_demographics.csv", 
                       header = TRUE, 
                       stringsAsFactors = TRUE)
results <- clean_data  # Rename for consistency with plotting code
head(results)

# ==================================================
# 8.1 Create stereotype condition variable
# ==================================================

results$stereotype <- NA

# Define stereotypical combinations
results$stereotype[results$prototype == "female_prototype" & results$gender == "female"] <- "stereotypical"
results$stereotype[results$prototype == "female_prototype" & results$gender == "male"] <- "non_stereotypical"
results$stereotype[results$prototype == "male_prototype" & results$gender == "female"] <- "non_stereotypical"
results$stereotype[results$prototype == "male_prototype" & results$gender == "male"] <- "stereotypical"
results$stereotype[results$prototype == "control"] <- "control"

# ==================================================
# 8.2 Create factor variables for different visualization needs
# ==================================================

# var1: Grammaticality and "to" presence/absence
results$var1 <- NA
results$var1[results$filler_type == "good"] <- "gram"
results$var1[results$filler_type == "bad"] <- "ungram"
results$var1[results$to == "yes_to"] <- "yes_to"
results$var1[results$to == "no_to"] <- "no_to"

# var2: Main condition types
results$var2 <- NA
results$var2[results$stereotype == "stereotypical"] <- "stereotypical"
results$var2[results$stereotype == "non_stereotypical"] <- "non_stereotypical"
results$var2[results$stereotype == "control"] <- "control"
results$var2[results$filler_type %in% c("good", "bad")] <- "filler"

# var3: Filler vs "to" conditions
results$var3 <- NA
results$var3[results$filler_type %in% c("good", "bad")] <- "filler"
results$var3[results$to == "yes_to"] <- "yes_to"
results$var3[results$to == "no_to"] <- "no_to"

# var4: Stereotypical gender vs. gender of protagonist
results$var4 <- NA
results$var4[results$prototype == "female_prototype" & results$gender == "female"] <- "female stereotype\nfemale protagonist"
results$var4[results$prototype == "female_prototype" & results$gender == "male"] <- "female stereotype\nmale protagonist"
results$var4[results$prototype == "male_prototype" & results$gender == "female"] <- "male stereotype\nfemale protagonist"
results$var4[results$prototype == "male_prototype" & results$gender == "male"] <- "male stereotype\nmale protagonist"
results$var4[results$filler_type == "good"] <- "grammatical"
results$var4[results$filler_type == "bad"] <- "ungrammatical"
results$var4[results$stereotype == "control"] <- "control"

# var5: Gender comparison
results$var5 <- NA
results$var5[results$filler_type %in% c("good", "bad")] <- "filler"
results$var5[results$gender == "female"] <- "female"
results$var5[results$gender == "male"] <- "male"

# Convert to factors
results$var1 <- as.factor(results$var1)
results$var2 <- as.factor(results$var2)
results$var3 <- as.factor(results$var3)
results$var4 <- as.factor(results$var4)
results$var5 <- as.factor(results$var5)

# ==================================================
# 8.3 Factor level reordering for plots
# ==================================================

# Reorder var1
results$var1 <- factor(results$var1, levels = c("gram", "ungram", "yes_to", "no_to"))
levels(results$var1) <- c("grammatical", "ungrammatical", "to present", "to absent")

# Reorder var2
results$var2 <- factor(results$var2, levels = c("filler", "stereotypical", "non_stereotypical", "control"))
levels(results$var2) <- c("filler", "stereotype", "non-stereotype", "control")

# Reorder var3
results$var3 <- factor(results$var3, levels = c("filler", "yes_to", "no_to"))
levels(results$var3) <- c("filler", "to present", "to absent")

# Reorder var4
results$var4 <- factor(results$var4, levels = c(
  "grammatical",
  "ungrammatical",
  "female stereotype\nfemale protagonist",
  "female stereotype\nmale protagonist",
  "male stereotype\nfemale protagonist",
  "male stereotype\nmale protagonist",
  "control"
))

# Reorder var5
results$var5 <- factor(results$var5, levels = c("filler", "female", "male"))
levels(results$var5) <- c("filler", "female", "male")

# Save prepared data for plotting
write.csv(results, file = "judgments_for_plots.csv", row.names = FALSE)

# ==================================================
# 9. INTERACTION PLOTS (BLACK & WHITE)
# ==================================================

# ==================================================
# 9.1 Main interaction plot: Condition × Stereotypicality
# ==================================================

# Calculate means and standard errors
results_means <- results %>%
  group_by(var1, var2) %>%
  summarize(
    condition.mean = mean(z_scores, na.rm = TRUE),
    condition.stdev = sd(z_scores, na.rm = TRUE),
    condition.se = sd(z_scores, na.rm = TRUE) / sqrt(n()),
    .groups = "drop"
  )

# Create interaction plot
interaction_bw <- ggplot(results_means, 
                         aes(x = var1, 
                             y = condition.mean, 
                             group = var2,
                             linetype = var2)) + 
  geom_line(linewidth = 0.8) + 
  geom_point(size = 2) + 
  geom_errorbar(aes(ymin = condition.mean - condition.se, 
                    ymax = condition.mean + condition.se), 
                width = 0.3) + 
  labs(title = "", 
       x = "", 
       linetype = "Is stereotypical?", 
       y = "z-scores") +
  theme_light(base_size = 14, base_family = "CMU Serif") +
  scale_linetype_manual(values = c("dotdash", "solid", "dotted", "twodash")) +
  theme(
    legend.position = "bottom"
  )

print(interaction_bw)
ggsave(filename = "interaction_bw.png", 
       plot = interaction_bw, 
       width = 20, height = 10, units = "cm", dpi = 300)

# ==================================================
# 9.2 Interaction plot by Participant Gender
# ==================================================

results$participant_gender_binary <- NA
results$participant_gender_binary[results$participant_gender == "Female"] <- "Female"
results$participant_gender_binary[results$participant_gender == "Male"] <- "Male"
results$participant_gender_binary <- factor(results$participant_gender_binary)

# Calculate means by participant gender
results_means_gender <- results %>%
  filter(!is.na(participant_gender_binary)) %>%
  group_by(var1, var2, participant_gender_binary) %>%
  summarize(
    condition.mean = mean(z_scores, na.rm = TRUE),
    condition.stdev = sd(z_scores, na.rm = TRUE),
    condition.se = sd(z_scores, na.rm = TRUE) / sqrt(n()),
    .groups = "drop"
  )

# Create readable gender labels
results_means_gender$participant_gender_label <- paste0(results_means_gender$participant_gender_binary, " participants")

# Plot by participant gender
interaction_gender_bw <- ggplot(results_means_gender, 
                             aes(x = var1, 
                                 y = condition.mean, 
                                 group = var2, 
                                 linetype = var2)) + 
  geom_line(size = 0.8) + 
  geom_point(size = 2) + 
  geom_errorbar(aes(ymin = condition.mean - condition.se, 
                    ymax = condition.mean + condition.se), 
                width = 0.3) + 
  labs(title = "", 
       x = "", 
       linetype = "Is stereotypical?", 
       y = "z-scores") +
  theme_light(base_size = 14, base_family = "CMU Serif") +
  scale_linetype_manual(values = c("dotdash", "solid", "dotted", "twodash")) +
  theme(
    legend.position = "bottom"
  ) +
  facet_wrap(~ participant_gender_label)

interaction_gender_bw
ggsave(filename = "interaction_gender_bw.png", 
       plot = interaction_gender_bw, 
       width = 26, height = 10, units = "cm", dpi = 300)

# ==================================================
# 9.3 Interaction plot by Age Group
# ==================================================

# Calculate means by age group
results_means_age_group <- results %>%
  filter(!is.na(age_group)) %>%
  group_by(var1, var2, age_group) %>%
  summarize(
    condition.mean = mean(z_scores, na.rm = TRUE),
    condition.stdev = sd(z_scores, na.rm = TRUE),
    condition.se = sd(z_scores, na.rm = TRUE) / sqrt(n()),
    .groups = "drop"
  )

# Create descriptive age group labels
results_means_age_group$age_group_label <- paste0(results_means_age_group$age_group, " years")

# Plot by age group
interaction_age_group_bw <- ggplot(results_means_age_group, 
                                   aes(x = var1, 
                                       y = condition.mean, 
                                       group = var2, 
                                       linetype = var2)) + 
  geom_line(size = 0.8) + 
  geom_point(size = 2) + 
  geom_errorbar(aes(ymin = condition.mean - condition.se, 
                    ymax = condition.mean + condition.se), 
                width = 0.3) + 
  labs(title = "", 
       x = "", 
       linetype = "Is stereotypical?", 
       y = "z-scores") +
  theme_light(base_size = 14, base_family = "CMU Serif") +
  scale_linetype_manual(values = c("dotdash", "solid", "dotted", "twodash")) +
  theme(
    legend.position = "bottom"
  ) +
  facet_wrap(~ age_group_label, nrow = 2)

interaction_age_group_bw
ggsave(filename = "interaction_age_group_bw.png", 
       plot = interaction_age_group_bw, 
       width = 26, height = 16, units = "cm", dpi = 300)

# ==================================================
# 9.4 Interaction plot by Predicate Type
# ==================================================

# Calculate means by predicate type
results_means_predicate <- results %>%
  group_by(var1, var2, predicate) %>%
  summarize(
    condition.mean = mean(z_scores, na.rm = TRUE),
    condition.stdev = sd(z_scores, na.rm = TRUE),
    condition.se = sd(z_scores, na.rm = TRUE) / sqrt(n()),
    .groups = "drop"
  )

# Exclude filler items for predicate analysis
results_means_predicate <- subset(results_means_predicate, var2 != "filler")

# Create descriptive predicate labels
results_means_predicate$predicate_label <- case_when(
  results_means_predicate$predicate == "agression_agent" ~ "Agent of aggression",
  results_means_predicate$predicate == "agression_patient" ~ "Patient of aggression",
  results_means_predicate$predicate == "asthenic_experiencer" ~ "Experiencer of asthenic emotion",
  results_means_predicate$predicate == "housework_agent" ~ "Agent of housework",
  results_means_predicate$predicate == "profession_agent" ~ "Agent of profession",
  results_means_predicate$predicate == "sthenic_experiencer" ~ "Experiencer of sthenic emotion",
  results_means_predicate$predicate == "uncontrolled_patient" ~ "Patient of uncontrolled action",
  TRUE ~ as.character(results_means_predicate$predicate)
)

# Plot by predicate type
interaction_predicate_bw <- ggplot(results_means_predicate, 
                                   aes(x = var1, 
                                       y = condition.mean, 
                                       group = var2, 
                                       linetype = var2)) + 
  geom_line(size = 0.8) + 
  geom_point(size = 2) + 
  geom_errorbar(aes(ymin = condition.mean - condition.se, 
                    ymax = condition.mean + condition.se), 
                width = 0.3) + 
  labs(title = "", 
       x = "", 
       linetype = "Is stereotypical?", 
       y = "z-scores") +
  theme_light(base_size = 14, base_family = "CMU Serif") +
  scale_linetype_manual(values = c("solid", "dotted", "twodash")) +
  theme(
    legend.position = "bottom"
  ) +
  facet_wrap(~ predicate_label, nrow = 2)

interaction_predicate_bw
ggsave(filename = "interaction_predicate_bw.png", 
       plot = interaction_predicate_bw, 
       width = 32, height = 16, units = "cm", dpi = 300)

# ==================================================
# 9.5 Interaction plot: Participant Gender × Protagonist Gender
# ==================================================

results_means_participant_protagonist_gender = results %>%
  group_by(var5, var1) %>%
  summarize(condition.mean = mean(z_scores, na.rm=TRUE), 
            сondition.stdev = sd(z_scores, na.rm=TRUE), 
            condition.se = sd(z_scores, na.rm=TRUE)/sqrt(n()))
results_means_participant_protagonist_gender

interaction_participant_protagonist_gender = ggplot(results_means_participant_protagonist_gender, 
                                                    aes(x = var1, 
                                                        y = condition.mean, 
                                                        group = var5, 
                                                        linetype = var5)) + 
  geom_line()+ 
  geom_point()+ 
  geom_errorbar(aes(ymin=condition.mean-condition.se, ymax=condition.mean+condition.se), width = 0.3)+ 
  # scale_y_continuous(limits=c(-1.5,2)) +
  labs(title = "", x = "", linetype = "The gender of protagonist", y = "z-scores") +
  theme_light(base_size = 14, base_family = "CMU Serif") +
  scale_linetype_manual(values=c("dotdash", "solid","dotted","twodash"))+
  theme(legend.position="bottom")
interaction_participant_protagonist_gender
ggsave(filename = "interaction_participant_protagonist_gender.png", plot = interaction_participant_protagonist_gender, width = 20, height = 10, units = c("cm"), dpi = 300)

# ==================================================
# 9.6 Interaction plot: Stereotypical Gender × Protagonist Gender
# ==================================================

# Calculate means for prototype-gender combinations
results_means_prototype_protagonist_gender <- results %>%
  group_by(var4, var3) %>%
  summarize(
    condition.mean = mean(z_scores, na.rm = TRUE),
    condition.stdev = sd(z_scores, na.rm = TRUE),
    condition.se = sd(z_scores, na.rm = TRUE) / sqrt(n()),
    .groups = "drop"
  )

# Plot prototype-gender combinations
interaction_prototype_protagonist_gender_bw <- ggplot(results_means_prototype_protagonist_gender, 
                                          aes(x = var4, 
                                              y = condition.mean, 
                                              group = var3, 
                                              linetype = var3)) + 
  geom_line(size = 0.8) + 
  geom_point(size = 2) + 
  geom_errorbar(aes(ymin = condition.mean - condition.se, 
                    ymax = condition.mean + condition.se), 
                width = 0.3) + 
  labs(title = "", 
       x = "", 
       linetype = "Presence of to", 
       y = "z-scores") +
  theme_light(base_size = 14, base_family = "CMU Serif") +
  scale_linetype_manual(values = c("dotdash", "solid", "dotted")) +
  theme(
    legend.position = "bottom"
  )

interaction_prototype_protagonist_gender_bw
ggsave(filename = "interaction_prototype_protagonist_gender_bw.png", 
       plot = interaction_prototype_protagonist_gender_bw, 
       width = 25, height = 10, units = "cm", dpi = 300)

# ==================================================
# 9.7 Interaction plot: Stereotypical Gender × Protagonist Gender x Participant Gender
# ==================================================

# Calculate means for prototype-gender combinations
results_means_prototype_protagonist_gender_participant_gender <- results %>%
  group_by(participant_gender, var4, var3) %>%
  filter(participant_gender != "Not specified") %>%
  summarize(
    condition.mean = mean(z_scores, na.rm = TRUE),
    condition.stdev = sd(z_scores, na.rm = TRUE),
    condition.se = sd(z_scores, na.rm = TRUE) / sqrt(n()),
    .groups = "drop"
  )

# Plot prototype-gender combinations
interaction_prototype_protagonist_gender_participant_gender_bw <- ggplot(results_means_prototype_protagonist_gender_participant_gender, 
                                                      aes(x = var4, 
                                                          y = condition.mean, 
                                                          group = var3, 
                                                          linetype = var3)) + 
  geom_line(size = 0.8) + 
  geom_point(size = 2) + 
  geom_errorbar(aes(ymin = condition.mean - condition.se, 
                    ymax = condition.mean + condition.se), 
                width = 0.3) + 
  labs(title = "", 
       x = "", 
       linetype = "Presence of to", 
       y = "z-scores") +
  theme_light(base_size = 14, base_family = "CMU Serif") +
  scale_linetype_manual(values = c("dotdash", "solid", "dotted")) +
  theme(
    legend.position = "bottom"
  )+
  facet_wrap(~ participant_gender, nrow = 2)

interaction_prototype_protagonist_gender_participant_gender_bw
ggsave(filename = "interaction_prototype_protagonist_gender_participant_gender_bw.png", 
       plot = interaction_prototype_protagonist_gender_participant_gender_bw, 
       width = 25, height = 15, units = "cm", dpi = 300)

# ==================================================
# 10. LINEAR MIXED EFFECTS MODELS
# ==================================================

# Load data
clean_data <- read.csv("judgments_with_demographics.csv", 
                       header = TRUE, 
                       stringsAsFactors = TRUE)
results <- clean_data  # Rename for consistency
head(results)
str(results)
# Create subsets for analysis

# Define stereotypical combinations
results$stereotype <- NA
results$stereotype[results$prototype == "female_prototype" & results$gender == "female"] <- "stereotypical"
results$stereotype[results$prototype == "female_prototype" & results$gender == "male"] <- "non_stereotypical"
results$stereotype[results$prototype == "male_prototype" & results$gender == "female"] <- "non_stereotypical"
results$stereotype[results$prototype == "male_prototype" & results$gender == "male"] <- "stereotypical"
results$stereotype[results$prototype == "control"] <- "control"
results$stereotype <- as.factor(results$stereotype)

results_stimul <- subset(results, group != "F")
results_without_control <- subset(results_stimul, prototype != "control")
results_without_control <- droplevels(results_without_control)
str(results_without_control)

# Create dataset with unique participants (one row per id)
unique_participants <- results_without_control %>%
  group_by(id) %>%
  summarise(
    group = first(group),  # group is constant per participant
    age_group = first(age_group),  # age_group is constant per participant
    participant_gender = first(participant_gender),
    age = first(age),
    n_observations = n()  # count how many times each participant appears
  )

# Analysis of group and age_group Intersection
table(unique_participants$group, unique_participants$age_group)

# 18-28 29-38 39-48 49+
# A     3     4     3   4
# B     3     5     3   3
# C     3     5     3   4
# D     3     3     2   2

table(unique_participants$group, unique_participants$participant_gender)
# Female Male Not specified
# A      6    8             0
# B      6    7             1
# C      7    8             0
# D      5    5             0

####################### MODEL COMPARISON #######################

# ==================================================
# 10.1 Searching for random effects structure
# ==================================================

# Testing different random effects structures while keeping fixed effects constant:
# z_scores ~ 1 + stereotype * to

# Maximal model - failed to converge
# Convergence warning: boundary (singular) fit
model_full_0 <- lmer(z_scores ~ 1 + stereotype * to 
                     + (1 + stereotype * to | id) 
                     + (1 + stereotype * to | sentence_id), 
                     data = results_without_control)

# Failed to converge
model_full_1 <- lmer(z_scores ~ 1 + stereotype * to 
                       + (1 + stereotype + to | id) 
                       + (1 + stereotype * to | sentence_id), 
                       data = results_without_control)

# Failed to converge
# Convergence warning: boundary (singular) fit
model_full_2 <- lmer(z_scores ~ 1 + stereotype * to 
                     + (1 + stereotype | id) 
                     + (1 + stereotype * to | sentence_id), 
                     data = results_without_control)

# Failed to converge
model_full_3 <- lmer(z_scores ~ 1 + stereotype * to 
                       + (1 + to | id) 
                       + (1 + stereotype * to | sentence_id), 
                       data = results_without_control)

# Failed to converge
model_full_4 <- lmer(z_scores ~ 1 + stereotype * to 
                       + (1 | id) 
                       + (1 + stereotype * to | sentence_id), 
                       data = results_without_control)

# Failed to converge
# Convergence warning: boundary (singular) fit
model_full_5 <- lmer(z_scores ~ 1 + stereotype * to 
                       + (1 + stereotype * to | id) 
                       + (1 + stereotype + to  | sentence_id), 
                       data = results_without_control)

# Failed to converge
model_full_6 <- lmer(z_scores ~ 1 + stereotype * to 
                       + (1 + stereotype * to | id) 
                       + (1  + to  | sentence_id), 
                       data = results_without_control)

# Failed to converge
model_full_7 <- lmer(z_scores ~ 1 + stereotype * to 
                       + (1 + stereotype * to | id) 
                       + (1 + stereotype  | sentence_id), 
                       data = results_without_control)

# Failed to converge
# Convergence warning: boundary (singular) fit
model_full_8 <- lmer(z_scores ~ 1 + stereotype * to 
                       + (1 + stereotype * to | id) 
                       + (1  | sentence_id), 
                       data = results_without_control)

# Failed to converge
model_full_9 <- lmer(z_scores ~ 1 + stereotype * to 
                       + (1 + stereotype + to | id) 
                       + (1 + stereotype + to | sentence_id), 
                       data = results_without_control)

# Failed to converge
model_full_10 <- lmer(z_scores ~ 1 + stereotype * to 
                       + (1 + stereotype + to | id) 
                       + (1 + stereotype | sentence_id), 
                       data = results_without_control)

# Failed to converge
model_full_11 <- lmer(z_scores ~ 1 + stereotype * to 
                       + (1 + stereotype + to | id) 
                       + (1 + to| sentence_id), 
                       data = results_without_control)

# !!!! CONVERGED:
model_full_12 <- lmer(z_scores ~ 1 + stereotype * to 
                       + (1 + stereotype + to | id) 
                       + (1 | sentence_id), 
                       data = results_without_control)

# Failed to converge
model_full_13 <- lmer(z_scores ~ 1 + stereotype * to 
                       + (1 + to | id) 
                       + (1 + stereotype + to | sentence_id), 
                       data = results_without_control)

# Failed to converge
# Convergence warning: boundary (singular) fit
model_full_14 <- lmer(z_scores ~ 1 + stereotype * to 
                       + (1 + stereotype | id) 
                       + (1 + stereotype + to  | sentence_id), 
                       data = results_without_control)

# Failed to converge
model_full_15 <- lmer(z_scores ~ 1 + stereotype * to 
                       + (1 | id) 
                       + (1 + stereotype  + to | sentence_id), 
                       data = results_without_control)

# Failed to converge
model_full_16 <- lmer(z_scores ~ 1 + stereotype * to 
                       + (1 + to | id) 
                       + (1 + to | sentence_id), 
                       data = results_without_control)

# Failed to converge
model_full_17 <- lmer(z_scores ~ 1 + stereotype * to 
                       + (1 | id) 
                       + (1 + to | sentence_id), 
                       data = results_without_control)

# !!!! CONVERGED:
model_full_18 <- lmer(z_scores ~ 1 + stereotype * to 
                       + (1 + to | id) 
                       + (1 | sentence_id), 
                       data = results_without_control)

# Failed to converge
# Convergence warning: boundary (singular) fit
model_full_19 <- lmer(z_scores ~ 1 + stereotype * to 
                       + (1 + stereotype | id) 
                       + (1 + stereotype | sentence_id), 
                       data = results_without_control)

# Failed to converge
model_full_20 <- lmer(z_scores ~ 1 + stereotype * to 
                       + (1 | id) 
                       + (1 + stereotype | sentence_id), 
                       data = results_without_control)

# Failed to converge
# Convergence warning: boundary (singular) fit
model_full_21 <- lmer(z_scores ~ 1 + stereotype * to 
                      + (1 + stereotype | id) 
                      + (1 | sentence_id), 
                      data = results_without_control)

# !!!! CONVERGED:
model_full_22 <- lmer(z_scores ~ 1 + stereotype * to 
                      + (1 | id) 
                      + (1 | sentence_id), 
                      data = results_without_control)

# ==================================================
# 10.1.1 Comparing converged models
# ==================================================

# Three models with stereotype * to interaction successfully converged:
# model_full_12 : z_scores ~ 1 + stereotype * to + (1 + stereotype + to | id)  + (1 | sentence_id)
# model_full_18 : z_scores ~ 1 + stereotype * to + (1 + to | id) + (1 | sentence_id)
# model_full_22 : z_scores ~ 1 + stereotype * to + (1 | id) + (1 | sentence_id)

# Check rePCA to ensure random effects structure is not overparameterized                      
summary(rePCA(model_full_12))
summary(rePCA(model_full_18))
summary(rePCA(model_full_22))

# Create comparison table with AIC and BIC
comparison_df <- data.frame(
  Model = c("model_full_12", "model_full_18", "model_full_22"),
  AIC = AIC(model_full_12, model_full_18, model_full_22)$AIC,
  BIC = BIC(model_full_12, model_full_18, model_full_22)$BIC,
  logLik = c(
    logLik(model_full_12),
    logLik(model_full_18),
    logLik(model_full_22)
  ),
  df = c(
    attr(logLik(model_full_12), "df"),
    attr(logLik(model_full_18), "df"),
    attr(logLik(model_full_22), "df")
  )
)

# Sort by AIC (lower is better)
comparison_df <- comparison_df[order(comparison_df$AIC), ]
comparison_df$AIC_diff <- comparison_df$AIC - min(comparison_df$AIC)
comparison_df$BIC_diff <- comparison_df$BIC - min(comparison_df$BIC)

comparison_df
# Model      AIC      BIC    logLik df   AIC_diff BIC_diff
# 2 model_full_18 5155.842 5208.305 -2568.921  9   0.000000   0.0000
# 1 model_full_12 5161.695 5231.646 -2568.847 12   5.852701  23.3404
# 3 model_full_22 5441.375 5482.179 -2713.687  7 285.532616 273.8742

# ==================================================
# 10.1.2 Likelihood ratio tests for random effects
# ==================================================

anova(model_full_18, model_full_22)
# npar    AIC    BIC  logLik -2*log(L)  Chisq Df Pr(>Chisq)    
# model_full_22    7 5423.0 5463.9 -2704.5    5409.0                         
# model_full_18    9 5139.1 5191.6 -2560.6    5121.1 287.95  2  < 2.2e-16 ***

anova(model_full_18, model_full_12)
# npar    AIC    BIC  logLik -2*log(L)  Chisq Df Pr(>Chisq)
# model_full_18    9 5139.1 5191.6 -2560.6    5121.1                     
# model_full_12   12 5145.0 5214.9 -2560.5    5121.0 0.1382  3     0.9869

anova(model_full_12, model_full_22)
# npar  AIC    BIC  logLik -2*log(L)  Chisq Df Pr(>Chisq)    
# model_full_22    7 5423 5463.9 -2704.5      5409                         
# model_full_12   12 5145 5214.9 -2560.5      5121 288.09  5  < 2.2e-16 ***


# MODEL SELECTION RATIONALE:
# model_full_18: (1 + to | id) + (1 | sentence_id)
# - Successfully converged
# - Best fit by both AIC and BIC
# - Significant improvement over simpler structure
# - Not significantly different from more complex structure
# - Theoretically justified: accounts for individual differences in sensitivity to 'to' presence

# ==================================================
# 10.2 Searching for fixed effects structure
# ==================================================

# Using the random effects structure from the selected interaction model (model_full_12):
# (1 + stereotype + to | id) + (1 | sentence_id)
# Testing different fixed effects structures to find the best fit

# Full interaction model
model_full_18_1 <- lmer(z_scores ~ 1 + stereotype * to 
                      + (1 + to | id) 
                      + (1 | sentence_id), 
                      data = results_without_control)

# Additive model (stereotype + to)
model_full_18_2 <- lmer(z_scores ~ 1 + stereotype + to 
                      + (1 + to | id) 
                      + (1 | sentence_id), 
                      data = results_without_control)

# Stereotype-only model
model_full_18_3 <- lmer(z_scores ~ 1 + stereotype 
                      + (1 + to | id) 
                      + (1 | sentence_id), 
                      data = results_without_control)

# 'to'-only model
model_full_18_4 <- lmer(z_scores ~ 1 + to 
                      + (1 + to | id) 
                      + (1 | sentence_id), 
                      data = results_without_control)

# Null model (intercept only)
model_full_18_5 <- lmer(z_scores ~ 1 
                      + (1 + to | id) 
                      + (1 | sentence_id), 
                      data = results_without_control)

# ==================================================
# 10.2.1 Model comparison for fixed effects
# ==================================================

# Compare interaction vs additive
anova(model_full_18_1, model_full_18_2)
# npar    AIC    BIC  logLik -2*log(L)  Chisq Df Pr(>Chisq)
# model_full_18_2    8 5137.2 5183.8 -2560.6    5121.2                     
# model_full_18_1    9 5139.1 5191.6 -2560.6    5121.1 0.0681  1     0.7941

# Compare additive vs stereotype-only
anova(model_full_18_2, model_full_18_3)
# npar    AIC    BIC  logLik -2*log(L)  Chisq Df Pr(>Chisq)    
# model_full_18_3    7 5223.1 5263.9 -2604.6    5209.1                         
# model_full_18_2    8 5137.2 5183.8 -2560.6    5121.2 87.926  1  < 2.2e-16 ***

# Compare additive vs 'to'-only
anova(model_full_18_2, model_full_18_4)
# npar    AIC    BIC  logLik -2*log(L)  Chisq Df Pr(>Chisq)
# model_full_18_4    7 5135.2 5176.0 -2560.6    5121.2                     
# model_full_18_2    8 5137.2 5183.8 -2560.6    5121.2 0.0385  1     0.8445

# Compare 'to'-only vs null model
anova(model_full_18_4, model_full_18_5)
# npar    AIC    BIC  logLik -2*log(L)  Chisq Df Pr(>Chisq)    
# model_full_18_5    6 5221.1 5256.1 -2604.6    5209.1                         
# model_full_18_4    7 5135.2 5176.0 -2560.6    5121.2 87.926  1  < 2.2e-16 ***

anova(model_full_18_1, model_full_18_4)
# npar    AIC    BIC  logLik -2*log(L)  Chisq Df Pr(>Chisq)
# model_full_18_4    7 5135.2 5176.0 -2560.6    5121.2                     
# model_full_18_1    9 5139.1 5191.6 -2560.6    5121.1 0.1066  2     0.9481

# Create comparison table for fixed effects structures
fixed_comparison <- data.frame(
  Model = c("model_full_18_1 (interaction)", 
            "model_full_18_2 (additive)",
            "model_full_18_3 (stereotype only)",
            "model_full_18_4 (to only)",
            "model_full_18_5 (null)"),
  Fixed_Structure = c(
    "stereotype * to",
    "stereotype + to",
    "stereotype",
    "to",
    "1"
  ),
  AIC = AIC(model_full_18_1, model_full_18_2, model_full_18_3, 
            model_full_18_4, model_full_18_5)$AIC,
  BIC = BIC(model_full_18_1, model_full_18_2, model_full_18_3, 
            model_full_18_4, model_full_18_5)$BIC,
  logLik = c(
    logLik(model_full_18_1),
    logLik(model_full_18_2),
    logLik(model_full_18_3),
    logLik(model_full_18_4),
    logLik(model_full_18_5)
  ),
  df = c(
    attr(logLik(model_full_18_1), "df"),
    attr(logLik(model_full_18_2), "df"),
    attr(logLik(model_full_18_3), "df"),
    attr(logLik(model_full_18_4), "df"),
    attr(logLik(model_full_18_5), "df")
  )
)

# Sort by AIC (lower is better)
fixed_comparison <- fixed_comparison[order(fixed_comparison$AIC), ]
fixed_comparison$AIC_diff <- fixed_comparison$AIC - min(fixed_comparison$AIC)
fixed_comparison$BIC_diff <- fixed_comparison$BIC - min(fixed_comparison$BIC)

fixed_comparison
# Model Fixed_Structure      AIC      BIC    logLik df AIC_diff BIC_diff
# 4         model_full_18_4 (to only)              to 5144.024 5184.829 -2565.012  7  0.00000  0.00000
# 2        model_full_18_2 (additive) stereotype + to 5150.643 5197.277 -2567.322  8  6.61925 12.44848
# 1     model_full_18_1 (interaction) stereotype * to 5155.842 5208.305 -2568.921  9 11.81797 23.47643
# 5            model_full_18_5 (null)               1 5226.800 5261.776 -2607.400  6 82.77638 76.94715
# 3 model_full_18_3 (stereotype only)      stereotype 5233.406 5274.211 -2609.703  7 89.38207 89.38207

# MODEL SELECTION RATIONALE:
# model_full_18_4: z_scores ~ 1 + to + (1 + to | id) + (1 | sentence_id)
# - Lowest AIC mong all models\n")
# - Significantly better than null model (p < 0.001)
# - Not significantly different from more complex models

# ==================================================
# 10.2.4 FINAL MODEL
# ==================================================

# Diagnostics for the selected final model (model_full_18_4)
# Formula: z_scores ~ 1 + to + (1 + to | id) + (1 | sentence_id)

final_model <- model_full_18_4

# Check for multicollinearity (VIF) - not applicable for single predictor
# library(car)
# vif(final_model)

# Examine residual distribution
# Histogram shows approximately normal distribution centered around zero
hist(residuals(final_model), main="")

# Residuals vs fitted plot to check homoscedasticity
# Points should be randomly scattered around zero with no obvious pattern
plot(final_model, col="#00000020", type=c("p", "smooth"), pch=16, id=0.001)

# Visualize random effects with conditional variances
# Each panel shows participant or item deviations from population estimates
require(lattice)
lattice::dotplot(ranef(final_model, condVar=TRUE))

# Evidence ratio (relative likelihood) comparing final model to null model
# Values < 0.05 indicate strong evidence for final model
(exp((AIC(final_model)-AIC(model_full_18_5))/2))
# [1] 1.060075e-18

# Calculate R² for mixed models
# R²m (marginal): variance explained by fixed effects only
# R²c (conditional): variance explained by both fixed and random effects
library(MuMIn)
MuMIn::r.squaredGLMM(final_model)
# R2m       R2c
# [1,] 0.4007689 0.5423643

# Full model summary
summary(final_model)
# Linear mixed model fit by REML. t-tests use Satterthwaite's method ['lmerModLmerTest']
# Formula: z_scores ~ 1 + to + (1 + to | id) + (1 | sentence_id)
#    Data: results_without_control
# 
# REML criterion at convergence: 5130
# 
# Scaled residuals: 
#     Min      1Q  Median      3Q     Max 
# -6.2889 -0.4592  0.0295  0.5030  4.8691 
# 
# Random effects:
#  Groups      Name        Variance Std.Dev. Corr 
#  sentence_id (Intercept) 0.04162  0.2040        
#  id          (Intercept) 0.07912  0.2813        
#              toyes_to    0.28815  0.5368   -0.94
#  Residual                0.39603  0.6293        
# Number of obs: 2513, groups:  sentence_id, 192; id, 53
# 
# Fixed effects:
#             Estimate Std. Error       df t value Pr(>|t|)    
# (Intercept)  0.69215    0.04742 76.02195   14.60   <2e-16 ***
# toyes_to    -1.17759    0.08337 66.74920  -14.12   <2e-16 ***
# ---
# Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
# 
# Correlation of Fixed Effects:
#          (Intr)
# toyes_to -0.870

# ==================================================
# 10.2.5 FULL MODEL
# ==================================================

# Diagnostics for the full interaction model (model_full_18_1)
# Formula: z_scores ~ 1 + stereotype * to + (1 + to | id) + (1 | sentence_id)
full_model <- model_full_18_1

# Check for multicollinearity using Variance Inflation Factor
# VIF values < 5 indicate no problematic multicollinearity
library(car)
vif(full_model)
# stereotype            to stereotype:to 
# 1.999451      1.218305      2.217490 

# Examine residual distribution
hist(residuals(full_model), main="")

# Residuals vs fitted plot
plot(full_model, col="#00000020", type=c("p", "smooth"), pch=16, id=0.001)

# Visualize random effects
require(lattice)
lattice::dotplot(ranef(full_model, condVar=TRUE))

# Evidence ratio comparing full model to null model
(exp((AIC(full_model)-AIC(model_full_18_5))/2))
# [1] 3.904596e-16

# R² for full model
library(MuMIn)
MuMIn::r.squaredGLMM(full_model)
# R2m       R2c
# [1,] 0.4004557 0.5427727

# Full model summary
summary(full_model)
# Linear mixed model fit by REML. t-tests use Satterthwaite's method ['lmerModLmerTest']
# Formula: z_scores ~ 1 + stereotype * to + (1 + to | id) + (1 | sentence_id)
#    Data: results_without_control
# 
# REML criterion at convergence: 5137.8
# 
# Scaled residuals: 
#     Min      1Q  Median      3Q     Max 
# -6.2804 -0.4599  0.0283  0.5033  4.8668 
# 
# Random effects:
#  Groups      Name        Variance Std.Dev. Corr 
#  sentence_id (Intercept) 0.04235  0.2058        
#  id          (Intercept) 0.07913  0.2813        
#              toyes_to    0.28818  0.5368   -0.94
#  Residual                0.39603  0.6293        
# Number of obs: 2513, groups:  sentence_id, 192; id, 53
# 
# Fixed effects:
#                                   Estimate Std. Error        df t value Pr(>|t|)    
# (Intercept)                        0.68330    0.05493 119.74943  12.439   <2e-16 ***
# stereotypestereotypical            0.01769    0.05517 187.42574   0.321    0.749    
# toyes_to                          -1.16748    0.09213  94.47868 -12.672   <2e-16 ***
# stereotypestereotypical:toyes_to  -0.02022    0.07803 187.49537  -0.259    0.796    
# ---
# Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
# 
# Correlation of Fixed Effects:
#             (Intr) strtyp toys_t
# strtypstrty -0.502              
# toyes_to    -0.832  0.299       
# strtypstr:_  0.355 -0.707 -0.423

# ==================================================
# 10.3 Testing additional predictors (PREDICATE, AGE GROUP, PARTICIPANT GENDER)
# ==================================================

# Using the random effects structure from the best fitting model:
# (1 + to | id) + (1 | sentence_id)
# Testing whether adding PREDICATE, AGE GROUP, or PARTICIPANT GENDER improves model fit

# Base model (best fit from previous analysis)
base_model <- model_full_18_4

# Model with PREDICATE factor
model_with_predicate <- lmer(z_scores ~ 1 + stereotype * to * predicate 
                             + (1 + to | id) 
                             + (1 | sentence_id), 
                             data = results_without_control)

# Model with AGE GROUP
model_with_age_group <- lmer(z_scores ~ 1 + stereotype * to * age_group 
                       + (1 + to | id) 
                       + (1 | sentence_id), 
                       data = results_without_control)

# Model with SELF-REPORTED GENDER
model_with_participant_gender <- lmer(z_scores ~ 1 + stereotype * to * participant_gender 
                          + (1 + to | id) 
                          + (1 | sentence_id), 
                          data = results_without_control)

# ==================================================
# 10.3.1 Model comparison for additional predictors
# ==================================================

# Create comparison table
additional_predictors_comparison <- data.frame(
  Model = c("Base model (to only)", 
            "Full model",
            "With PREDICATE",
            "With AGE GROUP",
            "With SELF-REPORTED GENDER"),
  Predictors = c(
    "to",
    "stereotype * to ",
    "stereotype * to * predicate",
    "stereotype * to * age_group",
    "stereotype * to * participant_gender"
  ),
  AIC = AIC(base_model, full_model, model_with_predicate, model_with_age_group, model_with_participant_gender)$AIC,
  BIC = BIC(base_model, full_model, model_with_predicate, model_with_age_group, model_with_participant_gender)$BIC,
  logLik = c(
    logLik(base_model),
    logLik(full_model),
    logLik(model_with_predicate),
    logLik(model_with_age_group),
    logLik(model_with_participant_gender)
  ),
  df = c(
    attr(logLik(base_model), "df"),
    attr(logLik(full_model), "df"),
    attr(logLik(model_with_predicate), "df"),
    attr(logLik(model_with_age_group), "df"),
    attr(logLik(model_with_participant_gender), "df")
  )
)

# Sort by AIC (lower is better)
additional_predictors_comparison <- additional_predictors_comparison[order(additional_predictors_comparison$AIC), ]
additional_predictors_comparison$AIC_diff <- additional_predictors_comparison$AIC - min(additional_predictors_comparison$AIC)
additional_predictors_comparison$BIC_diff <- additional_predictors_comparison$BIC - min(additional_predictors_comparison$BIC)

print("Comparison of models with additional predictors:")
print(additional_predictors_comparison)

# ==================================================
# 11 Post-hoc pairwise comparisons
# ==================================================

# Calculate estimated marginal means
emmeans(full_model, pairwise ~ stereotype * to)

# $emmeans
# stereotype        to     emmean     SE  df lower.CL upper.CL
# non_stereotypical no_to   0.683 0.0549 119    0.575    0.792
# stereotypical     no_to   0.701 0.0549 119    0.592    0.810
# non_stereotypical yes_to -0.484 0.0555 117   -0.594   -0.374
# stereotypical     yes_to -0.487 0.0556 117   -0.597   -0.377
# 
# Degrees-of-freedom method: kenward-roger 
# Confidence level used: 0.95 
# 
# $contrasts
# contrast                                           estimate     SE    df t.ratio p.value
# non_stereotypical no_to - stereotypical no_to      -0.01769 0.0552 182.6  -0.321  0.9886
# non_stereotypical no_to - non_stereotypical yes_to  1.16748 0.0921  93.9  12.672  <.0001
# non_stereotypical no_to - stereotypical yes_to      1.17001 0.0921  93.9  12.697  <.0001
# stereotypical no_to - non_stereotypical yes_to      1.18517 0.0921  93.8  12.864  <.0001
# stereotypical no_to - stereotypical yes_to          1.18770 0.0921  93.9  12.889  <.0001
# non_stereotypical yes_to - stereotypical yes_to     0.00253 0.0552 182.7   0.046  1.0000
# 
# Degrees-of-freedom method: kenward-roger 
# P value adjustment: tukey method for comparing a family of 4 estimates 

# ==================================================
# 11. COMPARISON WITH FILLER ITEMS
# ==================================================
# This section compares experimental conditions with grammatical and ungrammatical fillers
# to validate that the experimental items pattern as expected

# Load data
clean_data <- read.csv("judgments_with_demographics.csv", 
                       header = TRUE, 
                       stringsAsFactors = TRUE)
results <- clean_data  # Rename for consistency
head(results)
str(results)
# Create subsets for analysis

# Define stereotypical combinations
results$stereotype <- NA
results$stereotype[results$prototype == "female_prototype" & results$gender == "female"] <- "stereotypical"
results$stereotype[results$prototype == "female_prototype" & results$gender == "male"] <- "non_stereotypical"
results$stereotype[results$prototype == "male_prototype" & results$gender == "female"] <- "non_stereotypical"
results$stereotype[results$prototype == "male_prototype" & results$gender == "male"] <- "stereotypical"
results$stereotype[results$prototype == "control"] <- "control"
results$stereotype <- as.factor(results$stereotype)

results$Label <- as.character(results$Label)
results$Label[results$stereotype == "control"] <- "control"
str(results)
results$Label <- as.factor(results$Label)
str(results)

results_without_control <- subset(results, Label != "control")
head(results_without_control)
results_without_control <- droplevels(results_without_control)
str(results_without_control)


# Create combined condition variable (stereotype × 'to' presence)
results_without_control$condition[results_without_control$stereotype == "non_stereotypical" & results_without_control$to == "no_to"] <- "non_stereotypical_no_to"
results_without_control$condition[results_without_control$stereotype == "non_stereotypical" & results_without_control$to == "yes_to"] <- "non_stereotypical_yes_to"
results_without_control$condition[results_without_control$stereotype == "stereotypical" & results_without_control$to == "no_to"] <- "stereotypical_no_to"
results_without_control$condition[results_without_control$stereotype == "stereotypical" & results_without_control$to == "yes_to"] <- "stereotypical_yes_to"

# Create separate dataframes for each experimental condition
non_stereotypical_no_to <- subset(results_without_control, condition == "non_stereotypical_no_to")
non_stereotypical_yes_to <- subset(results_without_control, condition == "non_stereotypical_yes_to")
stereotypical_no_to <- subset(results_without_control, condition == "stereotypical_no_to")
stereotypical_yes_to   <- subset(results_without_control, condition == "stereotypical_yes_to")

# Extract filler conditions
gram <- subset(results_without_control, filler_type == "good")
ungram <- subset(results_without_control, filler_type == "bad")

# ==================================================
# 12.1 Comparison with Grammatical Fillers
# ==================================================
# Testing whether experimental conditions differ from clearly grammatical sentences

t.test(non_stereotypical_no_to$z_scores, gram$z_scores, paired = F)
# t = -0.16423, df = 1236.2, p-value = 0.8696
t.test(non_stereotypical_yes_to$z_scores, gram$z_scores, paired = F)
# t = -32.254, df = 1047.6, p-value < 2.2e-16
t.test(stereotypical_no_to$z_scores, gram$z_scores, paired = F)
# t = 0.40167, df = 1315.6, p-value = 0.6889
t.test(stereotypical_yes_to$z_scores, gram$z_scores, paired = F)
# t = -32.31, df = 1046.1, p-value < 2.2e-16

# ==================================================
# 12.2 Comparison with Ungrammatical Fillers
# ==================================================
# Testing whether experimental conditions differ from clearly ungrammatical sentences

t.test(non_stereotypical_no_to$z_scores, ungram$z_scores, paired = F)
# t = 47.077, df = 1343.8, p-value < 2.2e-16
t.test(non_stereotypical_yes_to$z_scores, ungram$z_scores, paired = F)
# t = 9.9084, df = 1127.4, p-value < 2.2e-16
t.test(stereotypical_no_to$z_scores, ungram$z_scores, paired = F)
# t = 49.568, df = 1431.8, p-value < 2.2e-16
t.test(stereotypical_yes_to$z_scores, ungram$z_scores, paired = F)
# t = 9.9199, df = 1126.1, p-value < 2.2e-16

# Note: 8 comparisons were conducted. Using Bonferroni correction,
# the significance threshold would be α = 0.05/8 = 0.00625.
# All reported significant effects (p < 0.001) remain significant after correction.

# ==================================================
# END OF ANALYSIS
# ==================================================

