# This file was automatically generated by gwip v{{version}}.

# Load the library.
library(SKAT)

# Read the dosage file.
dosage <- read.table(
    "{{ snp_set_file }}",
    sep=",",
    stringsAsFactors=FALSE,
    header=TRUE,
)
rownames(dosage) <- dosage[, 1]
dosage[, 1] <- NULL

# Make sure type is correct.
for (row in rownames(dosage)) dosage[row, ] <- as.numeric(dosage[row, ])

dosage <- t(dosage)  # We need to transpose so the rows represent the samples.

dosage <- as.matrix(dosage)

{% if covariate_file %}
# Read the covariate file.
covars <- read.table(
    "{{ covariate_file }}",
    sep=",",
    stringsAsFactors=FALSE,
    header=TRUE,
)
rownames(covars) <- covars[, 1]
covars[, 1] <- NULL

# Make sure the type is correct.
for (col in names(covars)) covars[, col] <- as.numeric(covars[, col])

covars <- as.matrix(covars)
{% endif %}

{% if weights %}
# Read the weights for variants.
weights <- read.table(
    "{{ weights }}",
    sep=",",
    stringsAsFactors=FALSE,
    header=FALSE,
)
weights <- as.numeric(weights[, 1])
{% endif %}

# Read the outcome file.
outcome <- read.table(
    "{{ outcome_file }}",
    sep=",",
    stringsAsFactors=FALSE,
    header=TRUE,
)
rownames(outcome) <- outcome[, 1]
outcome[, 1] <- NULL
outcome[, 1] <- as.numeric(outcome[, 1])

# Make sure that all the rownames are identical (no sample mismatch).
if (! (all(rownames(dosage) == rownames(covars)) &&
       all(rownames(covars) == rownames(outcome))) ) {
    stop("The row names do not match for all the matrices (sample mismatch).")
}

# Run the analysis.
{% if covariate_file %}
obj <- SKAT_Null_Model(outcome[, 1] ~ covars, out_type="{{ outcome_type }}")
{% else %}
obj <- SKAT_Null_Model(outcome[, 1] ~ 1, out_type="{{ outcome_type }}")
{% endif %}

results <- SKAT(
    dosage,
    obj, 
    {% if skat_o %}method="optimal.adj",{% endif %}
    {% if weights %}weights=weights,{% endif %}
    is_dosage=TRUE
)

# The p value
p.value <- results$p.value
cat("_PYTHON_HOOK_PVAL:[", p.value,  "]\n", sep="")  # Parsed by gwip.

# The Q value
q.value <- as.numeric(results$Q)
cat("_PYTHON_HOOK_QVAL:[", q.value,  "]\n", sep="")  # Parsed by gwip.
