geposan/R/clusteriness.R

79 lines
2.2 KiB
R
Raw Normal View History

2021-10-19 13:39:55 +02:00
# Perform a cluster analysis.
#
# This function will cluster the data using `hclust` and `cutree` (with the
# specified height). Every cluster with at least two members qualifies for
# further analysis. Clusters are then ranked based on their size in relation
# to the number of values. The return value is a final score between zero and
# one. Lower ranking clusters contribute less to this score.
clusteriness_priv <- function(data, height = 1000000) {
n <- length(data)
# Return a score of 0.0 if there is just one or no value at all.
if (n < 2) {
return(0.0)
}
# Cluster the data and compute the cluster sizes.
tree <- stats::hclust(stats::dist(data))
clusters <- stats::cutree(tree, h = height)
cluster_sizes <- sort(tabulate(clusters), decreasing = TRUE)
# Compute the "clusteriness" score.
score <- 0.0
for (i in seq_along(cluster_sizes)) {
cluster_size <- cluster_sizes[i]
if (cluster_size >= 2) {
cluster_score <- cluster_size / n
score <- score + cluster_score / i
}
}
score
}
# Process genes clustering their distance to telomeres.
2021-11-22 15:16:05 +01:00
clusteriness <- function(preset, progress = NULL) {
2021-10-21 17:25:44 +02:00
species_ids <- preset$species_ids
gene_ids <- preset$gene_ids
2021-10-19 13:39:55 +02:00
2021-11-22 15:16:05 +01:00
cached("clusteriness", c(species_ids, gene_ids), {
2021-10-21 17:25:44 +02:00
results <- data.table(gene = gene_ids)
2021-10-19 13:39:55 +02:00
2021-10-21 17:25:44 +02:00
# Prefilter the input data by species.
distances <- geposan::distances[species %chin% species_ids]
2021-10-19 13:39:55 +02:00
2021-10-21 17:25:44 +02:00
# Add an index for quickly accessing data per gene.
setkey(distances, gene)
2021-10-19 15:03:10 +02:00
2021-10-21 17:25:44 +02:00
genes_done <- 0
genes_total <- length(gene_ids)
2021-10-19 15:03:10 +02:00
2021-10-21 17:25:44 +02:00
# Perform the cluster analysis for one gene.
compute <- function(gene_id) {
2021-11-22 15:16:05 +01:00
data <- distances[gene_id, distance]
score <- clusteriness_priv(data)
2021-10-19 15:03:10 +02:00
2021-10-21 17:25:44 +02:00
if (!is.null(progress)) {
genes_done <<- genes_done + 1
progress(genes_done / genes_total)
}
score
}
2021-10-19 13:39:55 +02:00
2021-11-23 09:56:02 +01:00
structure(
list(
results = results[,
score := compute(gene),
by = gene
]
),
class = "geposan_method_results"
)
2021-10-21 17:25:44 +02:00
})
2021-10-19 13:39:55 +02:00
}