#au: smc
#ti: ISLS - Topic Modeling - LDAvis
#cr: 11-1-2023
#mod: 11-1-2023

utterances <- read.csv("isls_data_sample.csv")
#str(utterances)
utterances <- utterances$utterance
library(tm)
## Loading required package: NLP
stop_words <- stopwords("SMART")

# pre-processing:
utterances <- gsub("'", "", utterances)  # remove apostrophes
utterances <- gsub("[[:punct:]]", " ", utterances)  # replace punctuation with space
utterances <- gsub("[[:cntrl:]]", " ", utterances)  # replace control characters with space
utterances <- gsub("^[[:space:]]+", "", utterances) # remove whitespace at beginning of documents
utterances <- gsub("[[:space:]]+$", "", utterances) # remove whitespace at end of documents
utterances <- tolower(utterances)  # force to lowercase

# tokenize on space and output as a list:
doc.list <- strsplit(utterances, "[[:space:]]+")

# compute the table of terms:
term.table <- table(unlist(doc.list))
term.table <- sort(term.table, decreasing = TRUE)

# remove terms that are stop words or occur fewer than 5 times:
del <- names(term.table) %in% stop_words | term.table < 5
term.table <- term.table[!del]
vocab <- names(term.table)

# now put the documents into the format required by the lda package:
get.terms <- function(x) {
  index <- match(x, vocab)
  index <- index[!is.na(index)]
  rbind(as.integer(index - 1), as.integer(rep(1, length(index))))
}
documents <- lapply(doc.list, get.terms)
#LDA Fitting
library(lda)
# Compute some statistics related to the data set:
D <- length(documents)  # number of documents (2,000)
W <- length(vocab)  # number of terms in the vocab (14,568)
doc.length <- sapply(documents, function(x) sum(x[2, ]))  # number of tokens per document [312, 288, 170, 436, 291, ...]
N <- sum(doc.length)  # total number of tokens in the data (546,827)
term.frequency <- as.integer(term.table)  # frequencies of terms in the corpus
# MCMC and model tuning parameters:
K <- 20
G <- 5000 #Gibbs sampling running for 5000 iterations
alpha <- 0.02 #document-topic distributions (α= 0.02)
eta <- 0.02 #prior for the topic-term distributions (eta = 0.02)

# Fit the model:
set.seed(357)
t1 <- Sys.time()
fit <- lda.collapsed.gibbs.sampler(documents = documents, K = K, vocab = vocab, 
                                   num.iterations = G, alpha = alpha, 
                                   eta = eta, initial = NULL, burnin = 0,
                                   compute.log.likelihood = TRUE)
t2 <- Sys.time()
t2 - t1  # less than a minute
## Time difference of 39.66413 secs
#Calling on LDAvis
theta <- t(apply(fit$document_sums + alpha, 2, function(x) x/sum(x)))
phi <- t(apply(t(fit$topics) + eta, 2, function(x) x/sum(x)))

attributions <- list(phi = phi,
                     theta = theta,
                     doc.length = doc.length,
                     vocab = vocab,
                     term.frequency = term.frequency)
# create the JSON object to feed the visualization:
#install.packages("LDAvis")
library(LDAvis)
#install.packages("servr")
library(servr)
json <- createJSON(phi = attributions$phi, 
                   theta = attributions$theta, 
                   doc.length = attributions$doc.length, 
                   vocab = attributions$vocab, 
                   term.frequency = attributions$term.frequency)
serVis(json, out.dir = 'ISLS_sampleVisNew', open.browser = FALSE)
## Warning in dir.create(out.dir): 'ISLS_sampleVisNew' already exists