| 1 |
alpha_to_hex <- function(alpha) {
|
|
| 2 | ! |
toupper((sprintf("%02s", as.hexmode(round(alpha * 255)))))
|
| 3 |
} |
|
| 4 |
lighten_color <- function(col, amt = 1, alpha = 1) {
|
|
| 5 | ! |
rgb_white <- grDevices::col2rgb("#FFFFFF");
|
| 6 | ||
| 7 | ! |
col_as_rgb <- if(is.character(col)) |
| 8 | ! |
grDevices::col2rgb(col) |
| 9 |
else |
|
| 10 | ! |
col_as_rgb <- col |
| 11 | ||
| 12 |
# rgb_white + (rgb_just_s - rgb_white) * (this_color_hsv$alpha * edge_arrow_saturation_multiplier) |
|
| 13 | ! |
rgb_white + (col_as_rgb - rgb_white) * (alpha * amt) |
| 14 |
} |
|
| 15 |
darken_color <- function(col, amt = 1, alpha = 1) {
|
|
| 16 | ! |
rgb_white <- grDevices::col2rgb("#FFFFFF");
|
| 17 | ||
| 18 | ! |
col_as_rgb <- if(is.character(col)) |
| 19 | ! |
grDevices::col2rgb(col) |
| 20 |
else |
|
| 21 | ! |
col_as_rgb <- col |
| 22 | ||
| 23 | ! |
(rgb_white + (col_as_rgb - rgb_white) * (alpha)) * (1 - -(1 - amt)) |
| 24 |
} |
|
| 25 |
CreatePointByDistance <- function(P1, P2, dist = 0.1) {
|
|
| 26 | ! |
P_dist <- LearnGeom::DistancePoints(P1, P2) |
| 27 | ! |
if(P_dist == 0) {
|
| 28 | ! |
return(P1) |
| 29 |
} |
|
| 30 |
else {
|
|
| 31 | ! |
d_ratio <- (P_dist - dist) / P_dist |
| 32 | ! |
xt <- (1 - d_ratio) * P1[1] + (d_ratio * P2[1]) |
| 33 | ! |
yt <- (1 - d_ratio) * P1[2] + (d_ratio * P2[2]) |
| 34 | ||
| 35 | ! |
P3 <- c(xt, yt) |
| 36 | ! |
names(P3) <- c("X", "Y")
|
| 37 | ||
| 38 | ! |
return(P3) |
| 39 |
} |
|
| 40 |
} |
|
| 41 |
MoveLineAlong <- function(x1, y1, m) {
|
|
| 42 | ! |
x <- 0 |
| 43 | ! |
y <- m * x - m * x1 + y1 |
| 44 | ||
| 45 | ! |
Line <- c(m, y) |
| 46 | ! |
names(Line) = c("slope", "intercept")
|
| 47 | ! |
class(Line) <- append(class(Line), "Line") |
| 48 | ! |
Line |
| 49 |
} |
|
| 50 |
CalculateSegmentHeight <- function(radius, chord_length) {
|
|
| 51 | ! |
(radius) - ( 0.5 * sqrt(4*(radius ^ 2) - (chord_length ^ 2)) ) |
| 52 |
} |
|
| 53 |
CalculateSegmentArea <- function(radius, height) {
|
|
| 54 | ! |
((radius ^ 2) * acos((radius - height) / radius)) - |
| 55 | ! |
((radius - height) * sqrt((2 * radius * height) - (height ^ 2))) |
| 56 |
} |
|
| 57 |
edge_fun <- function(x, fun, y = NULL) {
|
|
| 58 | ! |
if(!is.matrix(x)) {
|
| 59 | ! |
if (!is.vector(x)) {
|
| 60 | ! |
stop("x is required as matrix or vector. If it's a vector, y is required to be the same.")
|
| 61 |
} |
|
| 62 | ! |
else if (is.null(y)) {
|
| 63 | ! |
stop("If x is a vector, y is required to be a vector.")
|
| 64 |
} |
|
| 65 |
} |
|
| 66 |
else {
|
|
| 67 | ! |
y <- x[2,] |
| 68 | ! |
x <- x[1,] |
| 69 |
} |
|
| 70 | ||
| 71 | ! |
do.call(fun, list(x, y)) |
| 72 |
} |
|
| 73 |
edge_center <- function(x, y = NULL) {
|
|
| 74 | ! |
mid <- edge_fun(x = x, fun = LearnGeom::MidPoint, y = y); |
| 75 | ! |
names(mid) <- c("x", "y")
|
| 76 | ||
| 77 | ! |
mid |
| 78 |
} |
|
| 79 |
node_distance <- function(x, y = NULL) {
|
|
| 80 | ! |
dist <- edge_fun(x = x, fun = LearnGeom::DistancePoints, y = y); |
| 81 | ! |
names(dist) <- c("distance")
|
| 82 | ! |
dist |
| 83 |
} |
|
| 84 |
edge_center_weighted <- function(x, weight, toward = 1) {
|
|
| 85 | ! |
edge_line <- edge_fun(x = x, fun = LearnGeom::CreateLinePoints); |
| 86 | ! |
edge_mid <- edge_center(x) |
| 87 | ! |
edge_len <- node_distance(x) |
| 88 | ||
| 89 | ! |
pt_wh <- ifelse(weight > 0, 1, 2) |
| 90 | ! |
pt_ref <- x[toward, ] |
| 91 | ||
| 92 | ! |
v_dist <- edge_len * weight; |
| 93 | ! |
if(edge_line[1] == Inf) {
|
| 94 | ! |
int <- matrix(c( |
| 95 | ! |
rep(pt_ref[1], 2), |
| 96 | ! |
pt_ref[2] + v_dist, |
| 97 | ! |
pt_ref[2] - v_dist |
| 98 |
), |
|
| 99 | ! |
ncol = 2) |
| 100 |
} |
|
| 101 | ! |
else if (edge_line[1] == 0) {
|
| 102 |
# stop("No edge")
|
|
| 103 | ! |
int <- matrix(c( |
| 104 | ! |
pt_ref[1] + v_dist, |
| 105 | ! |
pt_ref[1] - v_dist, |
| 106 | ! |
rep(pt_ref[2], 2) |
| 107 |
), |
|
| 108 | ! |
ncol = 2) |
| 109 |
} |
|
| 110 |
else {
|
|
| 111 | ! |
if(all(abs(diff(x)) < (.Machine$double.eps ^ 0.5))) {
|
| 112 | ! |
int <- x; |
| 113 |
} |
|
| 114 |
else {
|
|
| 115 | ! |
int <- LearnGeom::IntersectLineCircle(edge_line, pt_ref, v_dist) |
| 116 |
} |
|
| 117 |
} |
|
| 118 | ! |
int_dists <- apply(int, 1, node_distance, x[-toward,]) |
| 119 | ||
| 120 | ! |
x_sorted <- sort(x[,1]) |
| 121 | ! |
y_sorted <- sort(x[,2]) |
| 122 | ! |
on_segment <- apply(int, 1, function(p) {
|
| 123 | ! |
p[1] >= x_sorted[1] && p[1] <= x_sorted[2] && |
| 124 | ! |
p[2] >= y_sorted[1] && p[2] <= y_sorted[2] |
| 125 |
}) |
|
| 126 | ! |
if(all(on_segment)) {
|
| 127 | ! |
int_closest <- which(int_dists == min(int_dists)) |
| 128 |
} |
|
| 129 |
else {
|
|
| 130 | ! |
int_closest <- which(on_segment) |
| 131 |
} |
|
| 132 | ! |
w_c <- int[int_closest, ] |
| 133 | ||
| 134 | ! |
w_c |
| 135 |
} |
|
| 136 | ||
| 137 |
create_edge_matrix <- function( |
|
| 138 |
set, dims = 1:2, |
|
| 139 |
weights = colMeans(as.matrix(set$line.weights)), |
|
| 140 |
nodes = set$rotation$nodes, |
|
| 141 |
direction = 1, |
|
| 142 |
node_position_multiplier = 1 |
|
| 143 |
) {
|
|
| 144 | ! |
raw_weights <- weights; |
| 145 | ! |
weights <- abs(weights); |
| 146 | ! |
weights_matrix <- to_square(weights); |
| 147 | ! |
raw_weights_matrix <- to_square(raw_weights); |
| 148 | ! |
rownames(weights_matrix) <- colnames(weights_matrix) <- nodes$code |
| 149 | ||
| 150 | ! |
nodes[, (seq(2, ncol(nodes))) := lapply(.SD, `*`, node_position_multiplier) , .SDcols = (seq(2, ncol(nodes)))]; |
| 151 | ! |
nodes_xy <- nodes[, c(1, dims+1), with = F] |
| 152 | ! |
colnames(nodes_xy) <- c("code", "x", "y")
|
| 153 | ! |
node_combinations <- combn(length(nodes_xy[[1]]), 2); |
| 154 | ||
| 155 | ! |
edge_names_matrix <- t(matrix(nodes$code[node_combinations], nrow = 2)) |
| 156 | ! |
edge_table <- data.table::data.table(node_1 = edge_names_matrix[, 1], node_2 = edge_names_matrix[, 2]) |
| 157 | ! |
edge_table[, label := paste(node_1, node_2, sep = "_")] |
| 158 | ! |
edge_table <- edge_table[, |
| 159 | ! |
c("slope","midpoint_x", "midpoint_y", "distance", "weight", "weight_1", "weight_2", "weighted_midpoint_x", "weighted_midpoint_y", "raw_weight_1", "raw_weight_2") := {
|
| 160 | ! |
node_indices <- node_combinations[,.I]; |
| 161 | ! |
node_1 <- .SD[["node_1"]]; |
| 162 | ! |
node_2 <- .SD[["node_2"]]; |
| 163 | ! |
points <- nodes_xy[code == node_1 | code == node_2, ]; |
| 164 | ! |
edge_line <- edge_fun(x = as.matrix(points), fun = LearnGeom::CreateLinePoints); |
| 165 | ! |
cent <- edge_center(as.matrix(points)); |
| 166 | ! |
distance <- node_distance(as.matrix(points)); |
| 167 | ||
| 168 |
# browser(); |
|
| 169 | ! |
if(direction == 1) {
|
| 170 | ! |
weight_2 <- weights_matrix[node_indices[1], node_indices[2]]; |
| 171 | ! |
weight_1 <- weights_matrix[node_indices[2], node_indices[1]]; |
| 172 | ! |
raw_weight_2 <- raw_weights_matrix[node_indices[1], node_indices[2]]; |
| 173 | ! |
raw_weight_1 <- raw_weights_matrix[node_indices[2], node_indices[1]]; |
| 174 |
} |
|
| 175 |
else {
|
|
| 176 | ! |
weight_1 <- weights_matrix[node_indices[1], node_indices[2]]; |
| 177 | ! |
weight_2 <- weights_matrix[node_indices[2], node_indices[1]]; |
| 178 | ! |
raw_weight_1 <- raw_weights_matrix[node_indices[1], node_indices[2]]; |
| 179 | ! |
raw_weight_2 <- raw_weights_matrix[node_indices[2], node_indices[1]]; |
| 180 |
} |
|
| 181 | ! |
weight_toward = ifelse(weight_2 > weight_1, 2, 1); |
| 182 | ||
| 183 |
# weight_diff = ifelse(weight_1 - weight_2 > 0, (weight_1 - weight_2) / (weight_1 + weight_2), 0) |
|
| 184 | ! |
weighted_center <- cent |
| 185 | ! |
weight_diff = max(weight_1, weight_2) / (weight_1 + weight_2) |
| 186 | ! |
if(!is.nan(weight_diff)) {
|
| 187 | ! |
if( weight_diff == 1 ) {
|
| 188 | ! |
if(direction == 1) {
|
| 189 | ! |
if(weight_toward == 1) {
|
| 190 | ! |
weighted_center <- as.matrix(points[2,]); |
| 191 |
} |
|
| 192 |
else {
|
|
| 193 | ! |
weighted_center <- as.matrix(points[1,]); |
| 194 |
} |
|
| 195 |
} |
|
| 196 |
else {
|
|
| 197 | ! |
if(weight_toward == 2) {
|
| 198 | ! |
weighted_center <- as.matrix(points[1,]); |
| 199 |
} |
|
| 200 |
else {
|
|
| 201 | ! |
weighted_center <- as.matrix(points[2,]); |
| 202 |
} |
|
| 203 |
} |
|
| 204 |
} |
|
| 205 | ! |
else if ( abs(weight_1 - weight_2) > 0.000000001 ) {
|
| 206 | ! |
weighted_center <- edge_center_weighted(as.matrix(points), weight_diff, toward = weight_toward) |
| 207 | ! |
if(weight_diff > 0) {
|
| 208 |
} |
|
| 209 |
} |
|
| 210 |
else {
|
|
| 211 |
# print("Why are we here?")
|
|
| 212 |
# we're here b/c equal weights, but are sure about self connections? |
|
| 213 |
} |
|
| 214 |
} |
|
| 215 |
else {
|
|
| 216 |
# Note: means there isn't a connection? |
|
| 217 |
# print("Why are we here too?")
|
|
| 218 |
} |
|
| 219 | ||
| 220 | ! |
list( |
| 221 | ! |
slope = ifelse(edge_line[1] == "Inf", Inf, edge_line[1]), |
| 222 | ! |
midpoint_x = cent[1], |
| 223 | ! |
midpoint_y = cent[2], |
| 224 | ! |
distance = distance, |
| 225 | ! |
weight = weight_1 + weight_2, |
| 226 | ! |
weight_1 = weight_1, |
| 227 | ! |
weight_2 = weight_2, |
| 228 | ! |
weighted_midpoint_x = weighted_center[1], |
| 229 | ! |
weighted_midpoint_y = weighted_center[2], |
| 230 | ! |
raw_weight_1 = raw_weight_1, |
| 231 | ! |
raw_weight_2 = raw_weight_2 |
| 232 |
) |
|
| 233 |
}, |
|
| 234 | ! |
by = seq(nrow(edge_table)) |
| 235 |
]; |
|
| 236 | ||
| 237 | ! |
attr(edge_table, "nodes_xy") <- nodes_xy |
| 238 | ! |
attr(edge_table, "node_combinations") <- node_combinations |
| 239 | ||
| 240 | ! |
edge_table |
| 241 |
} |
|
| 242 | ||
| 243 |
edge_paths <- function(x, |
|
| 244 |
edge_color = NULL, edge_end = "outward", |
|
| 245 |
edge_size_multiplier = 1, |
|
| 246 |
desaturate_edges_by = "weight", lighten_edges_by = desaturate_edges_by, |
|
| 247 |
fake_alpha = FALSE, |
|
| 248 |
scale_edges_to = c(0,1), scale_edges_from = c(0, max(x[, c("weight_1", "weight_2")])),
|
|
| 249 |
path_as = "svg", edge_arrow = TRUE, edge_arrow_offset = 0.5, edge_arrow_width = 0.05, |
|
| 250 |
edge_arrow_saturation_multiplier = 0.75, edge_halo = 0.5, edge_halo_multiplier = 1.04, |
|
| 251 |
edge_arrows_to_show = "both", arrow_halo = edge_halo, |
|
| 252 |
sender_direction = 1, edge_arrow_direction = 2 |
|
| 253 |
) {
|
|
| 254 | ! |
edge_arrows_to_show <- match.arg(edge_arrows_to_show, c("both", "min", "max"))
|
| 255 | ! |
edges <- data.table::copy(x); |
| 256 | ! |
edges_ <- data.table::melt(edges, measure.vars = c("weight_1", "weight_2"));
|
| 257 | ! |
edges_[variable == "weight_2", c("node_1", "node_2") := { list(node_2, node_1) }];
|
| 258 | ||
| 259 | ! |
data.table::setorder(edges, weight); |
| 260 | ! |
data.table::setorder(edges_, value); |
| 261 | ||
| 262 | ! |
nodes_xy <- attr(x, "nodes_xy"); |
| 263 | ! |
node_combinations <- attr(x, "node_combinations"); |
| 264 | ||
| 265 | ! |
if(is.null(edge_color)) {
|
| 266 | ! |
edge_color <- rep("#000000", nrow(edges_));
|
| 267 |
} |
|
| 268 | ! |
else if(length(edge_color) == 1) {
|
| 269 | ! |
edge_color <- rep(edge_color, nrow(edges_)); |
| 270 |
} |
|
| 271 | ! |
else if(length(edge_color) == 2) {
|
| 272 | ! |
edge_color <- edges_[, { ifelse(.SD[[paste0("raw_", variable)]] < 0, edge_color[2], edge_color[1]) }, by = 1:nrow(edges_)][[2]]
|
| 273 |
} |
|
| 274 | ||
| 275 | ! |
rgb_white <- grDevices::col2rgb("#FFFFFF", alpha = F)
|
| 276 | ! |
paths <- list(); |
| 277 |
# for(e_row in seq.int(nrow(edges_))) {
|
|
| 278 | ! |
for(e_row in seq.int(nrow(edges_))) {
|
| 279 | ! |
edge <- edges_[e_row,] |
| 280 | ! |
mid_point <- c(edge$weighted_midpoint_x, edge$weighted_midpoint_y); |
| 281 | ! |
node_col <- "node_1"; |
| 282 | ! |
weight_col <- "value"; #ifelse(e == 1, 2, 1)); |
| 283 | ||
| 284 | ! |
node <- nodes_xy[code == edge[[node_col]]]; |
| 285 | ! |
line_xy <- matrix(c(edge$weighted_midpoint_x, node$x, edge$weighted_midpoint_y, node$y), ncol = 2); |
| 286 | ! |
edge_line <- edge_fun(line_xy, fun = LearnGeom::CreateLinePoints); |
| 287 | ||
| 288 | ! |
rnd <- 40; |
| 289 | ! |
mp <- 1; |
| 290 | ! |
weight <- edge[[weight_col]] # * edge_size_multiplier; |
| 291 | ! |
if(weight > 0) { # && (mid_point != as.matrix(node))) {
|
| 292 | ! |
radius <- edge[[weight_col]] / 2; |
| 293 | ||
| 294 | ! |
path <- list(type = "path", weight = weight, line = list( width = edge_halo, color = edge_color[e_row] )) #"#FF0000" ) ) |
| 295 | ! |
if(!is.null(desaturate_edges_by)) {
|
| 296 | ! |
this_color_hsv <- as.list(t(grDevices::rgb2hsv(grDevices::col2rgb(edge_color[e_row])))); |
| 297 | ! |
names(this_color_hsv) <- c("h", "s", "v");
|
| 298 | ||
| 299 | ! |
if (is.function(desaturate_edges_by)) {
|
| 300 | ! |
this_color_hsv$s <- do.call(desaturate_edges_by, list(weight)) |
| 301 |
} |
|
| 302 | ! |
else if(desaturate_edges_by == "weight") {
|
| 303 | ! |
this_color_hsv$s <- scales::rescale(x = weight, to = scale_edges_to, from = scale_edges_from); |
| 304 |
} |
|
| 305 | ||
| 306 | ! |
if(!is.null(lighten_edges_by)) {
|
| 307 | ! |
if (is.function(lighten_edges_by)) {
|
| 308 | ! |
this_color_hsv$alpha <- do.call(lighten_edges_by, list(weight)) |
| 309 |
} |
|
| 310 | ! |
else if(lighten_edges_by == "weight") {
|
| 311 |
# this_color_hsv$alpha <- this_color_hsv$s; |
|
| 312 | ! |
this_color_hsv$alpha <- weight; |
| 313 |
} |
|
| 314 |
} |
|
| 315 | ||
| 316 | ! |
col_just_s <- grDevices::hsv(this_color_hsv$h, this_color_hsv$s, this_color_hsv$v) |
| 317 | ! |
rgb_just_s <- col2rgb(col_just_s) |
| 318 | ||
| 319 | ! |
path$opacity <- 1 |
| 320 | ! |
if(fake_alpha == TRUE) {
|
| 321 |
# browser() |
|
| 322 |
# rgb_s_and_a_equiv <- rgb_white + (rgb_just_s - rgb_white) * (this_color_hsv$alpha) |
|
| 323 | ! |
rgb_s_and_a_equiv <- lighten_color(rgb_just_s, alpha = this_color_hsv$alpha); |
| 324 | ! |
rgb_s_and_a_edge <- darken_color(rgb_just_s, alpha = this_color_hsv$alpha , amt = edge_halo_multiplier); |
| 325 | ||
| 326 | ! |
path$fillcolor <- grDevices::rgb(rgb_s_and_a_equiv[1,1], rgb_s_and_a_equiv[2,1], rgb_s_and_a_equiv[3,1], maxColorValue = 255) |
| 327 |
# browser(expr = { path$fillcolor == "#FFCFCF" })
|
|
| 328 | ! |
path$line$color <- grDevices::rgb(rgb_s_and_a_edge[1,1], rgb_s_and_a_edge[2,1], rgb_s_and_a_edge[3,1], maxColorValue = 255) |
| 329 |
} |
|
| 330 |
else {
|
|
| 331 |
# path$opacity <- this_color_hsv$alpha |
|
| 332 | ! |
path$fillcolor <- do.call(grDevices::hsv, this_color_hsv) |
| 333 |
} |
|
| 334 |
} |
|
| 335 |
else {
|
|
| 336 | ! |
path$fillcolor <- edge_color[e_row]; |
| 337 | ! |
rgb_just_s <- col2rgb(path$fillcolor) |
| 338 | ! |
this_color_hsv <- as.list(t(grDevices::rgb2hsv(grDevices::col2rgb(edge_color[e_row])))); |
| 339 | ! |
names(this_color_hsv) <- c("h", "s", "v");
|
| 340 | ! |
this_color_hsv$alpha <- weight; |
| 341 |
} |
|
| 342 | ||
| 343 | ! |
if(edge_end == "outward") {
|
| 344 | ! |
rotate_on <- c(x = node$x, y = node$y); |
| 345 | ! |
pinch_on <- c(edge$weighted_midpoint_x, edge$weighted_midpoint_y); |
| 346 | ! |
if (edge_line[1] == 0) {
|
| 347 | ! |
perp_line <- LearnGeom::CreateLinePoints(c(node$x, node$y), c(node$x+0.001, 0)); |
| 348 |
} |
|
| 349 | ! |
else if(is.finite(edge_line[1])){
|
| 350 | ! |
perp_line <- LearnGeom::Rotate(edge_line, as.matrix(node), 90); |
| 351 |
} |
|
| 352 |
else {
|
|
| 353 | ! |
perp_line <- LearnGeom::CreateLinePoints(c(node$x, node$y), c(0.001, node$y)); |
| 354 |
} |
|
| 355 | ! |
perp_base <- LearnGeom::IntersectLineCircle(perp_line, as.matrix(node), radius * edge_size_multiplier); |
| 356 |
# Find points of circle, with center at node, that intersect along the edge line. |
|
| 357 |
# The one that is furthest from the midpoint is used as the extension for the curve |
|
| 358 |
# edge_ext <- LearnGeom::IntersectLineCircle(edge_line, as.matrix(node), edge[[weight_col]] * edge_size_multiplier); |
|
| 359 |
# ext_dist <- apply(edge_ext, 1, LearnGeom::DistancePoints, c(edge$weighted_midpoint_x, edge$weighted_midpoint_y)); |
|
| 360 |
# ext_max <- which.max(ext_dist); |
|
| 361 |
# edge_ext_pt <- edge_ext[ext_max,]; |
|
| 362 | ||
| 363 | ! |
svg_curve_control_multiplier = 1.1; |
| 364 | ! |
if(!is.finite(perp_line[1]) || perp_line[1] == "Inf" || perp_line[1] == Inf) {
|
| 365 | ! |
browser() |
| 366 |
} |
|
| 367 | ! |
else if(perp_line[1] == 0) {
|
| 368 | ! |
perp_base_intercepts <- perp_base |
| 369 | ! |
perp_base_intercepts[, 2] <- 0 |
| 370 | ! |
perp_line_1 <- LearnGeom::CreateLinePoints(perp_base[1,], perp_base_intercepts[1,]); |
| 371 | ! |
perp_line_2 <- LearnGeom::CreateLinePoints(perp_base[2,], perp_base_intercepts[2,]); |
| 372 | ! |
perp_adj <- rep((radius * svg_curve_control_multiplier) * edge_size_multiplier, 2) * c(1,-1) |
| 373 | ! |
perp_line_1_ints <- matrix(perp_base[1,], nrow = 2, ncol = 2, byrow = TRUE) |
| 374 | ! |
perp_line_2_ints <- matrix(perp_base[2,], nrow = 2, ncol = 2, byrow = TRUE) |
| 375 | ||
| 376 | ! |
perp_line_1_ints[, 2] <- perp_line_1_ints[,2] + perp_adj |
| 377 | ! |
perp_line_2_ints[, 2] <- perp_line_2_ints[,2] + perp_adj |
| 378 |
} |
|
| 379 |
else {
|
|
| 380 | ! |
perp_line_1 <- LearnGeom::Rotate(perp_line, perp_base[1,], 90) |
| 381 | ! |
perp_line_2 <- LearnGeom::Rotate(perp_line, perp_base[2,], 90); |
| 382 | ||
| 383 | ! |
perp_line_1_ints <- LearnGeom::IntersectLineCircle(perp_line_1, perp_base[1,], (radius * svg_curve_control_multiplier) * edge_size_multiplier); |
| 384 | ! |
perp_line_2_ints <- LearnGeom::IntersectLineCircle(perp_line_2, perp_base[2,], (radius * svg_curve_control_multiplier) * edge_size_multiplier); |
| 385 |
} |
|
| 386 | ! |
perp_line_1_dists <- apply(perp_line_1_ints, 1, LearnGeom::DistancePoints, c(edge$weighted_midpoint_x, edge$weighted_midpoint_y)); |
| 387 | ! |
perp_line_1_dists_max <- which.max(perp_line_1_dists); |
| 388 | ! |
perp_line_1_pt <- perp_line_1_ints[perp_line_1_dists_max,]; |
| 389 | ||
| 390 | ! |
perp_line_2_dists <- apply(perp_line_2_ints, 1, LearnGeom::DistancePoints, c(edge$weighted_midpoint_x, edge$weighted_midpoint_y)); |
| 391 | ! |
perp_line_2_dists_max <- which.max(perp_line_2_dists); |
| 392 | ! |
perp_line_2_pt <- perp_line_2_ints[perp_line_2_dists_max,]; |
| 393 | ||
| 394 | ! |
new_path <- paste0( |
| 395 | ! |
"M", paste(mp * round(c(pinch_on[1], pinch_on[2]), rnd), collapse = " "), |
| 396 | ! |
" L", paste(mp * round(c(perp_base[1,1], perp_base[1,2]), rnd), collapse = " "), |
| 397 | ! |
" C", paste(mp * round(c(perp_line_1_pt[1], perp_line_1_pt[2]), rnd), collapse = " "), ", ", |
| 398 | ! |
paste(mp * round(c(perp_line_2_pt[1], perp_line_2_pt[2]), rnd), collapse = " "), ", ", |
| 399 | ! |
paste(mp * round(c(perp_base[2,1], perp_base[2,2]), rnd), collapse = " "), |
| 400 | ! |
" Z" |
| 401 |
) |
|
| 402 | ! |
path$path <- new_path; |
| 403 | ! |
paths <- c(paths, list(path)); |
| 404 |
} |
|
| 405 | ! |
else if (edge_end == "inward") {
|
| 406 | ! |
rotate_on <- c(x = edge$weighted_midpoint_x, y = edge$weighted_midpoint_y) |
| 407 | ! |
pinch_on <- c(x = node$x, y = node$y); |
| 408 | ! |
if(is.finite(edge_line[1])){
|
| 409 | ! |
perp_line <- LearnGeom::Rotate(edge_line, as.matrix(rotate_on), 90); |
| 410 |
} |
|
| 411 |
else {
|
|
| 412 | ! |
perp_line <- LearnGeom::CreateLinePoints(rotate_on, c(0, rotate_on[2])); |
| 413 |
} |
|
| 414 | ! |
perp_base <- LearnGeom::IntersectLineCircle(perp_line, as.matrix(rotate_on), radius * edge_size_multiplier); |
| 415 | ||
| 416 | ! |
svg_curve_control_multiplier = 1.1; |
| 417 | ! |
if(!is.finite(perp_line[1]) || perp_line[1] == "Inf" || perp_line[1] == Inf) {
|
| 418 | ! |
browser() |
| 419 |
} |
|
| 420 | ! |
else if(perp_line[1] == 0) {
|
| 421 | ! |
perp_base_intercepts <- perp_base |
| 422 | ! |
perp_base_intercepts[, 2] <- 0 |
| 423 | ! |
perp_line_1 <- LearnGeom::CreateLinePoints(perp_base[1,], perp_base_intercepts[1,]); |
| 424 | ! |
perp_line_2 <- LearnGeom::CreateLinePoints(perp_base[2,], perp_base_intercepts[2,]); |
| 425 | ! |
perp_adj <- rep((radius * svg_curve_control_multiplier) * edge_size_multiplier, 2) * c(1,-1) |
| 426 | ! |
perp_line_1_ints <- matrix(perp_base[1,], nrow = 2, ncol = 2, byrow = TRUE) |
| 427 | ! |
perp_line_2_ints <- matrix(perp_base[2,], nrow = 2, ncol = 2, byrow = TRUE) |
| 428 | ||
| 429 | ! |
perp_line_1_ints[, 2] <- perp_line_1_ints[,2] + perp_adj |
| 430 | ! |
perp_line_2_ints[, 2] <- perp_line_2_ints[,2] + perp_adj |
| 431 |
} |
|
| 432 |
else {
|
|
| 433 | ! |
perp_line_1 <- LearnGeom::Rotate(perp_line, perp_base[1,], 90) |
| 434 | ! |
perp_line_2 <- LearnGeom::Rotate(perp_line, perp_base[2,], 90); |
| 435 | ||
| 436 | ! |
perp_line_1_ints <- LearnGeom::IntersectLineCircle(perp_line_1, perp_base[1,], (radius * svg_curve_control_multiplier) * edge_size_multiplier); |
| 437 | ! |
perp_line_2_ints <- LearnGeom::IntersectLineCircle(perp_line_2, perp_base[2,], (radius * svg_curve_control_multiplier) * edge_size_multiplier); |
| 438 |
} |
|
| 439 | ! |
perp_line_1_dists <- apply(perp_line_1_ints, 1, LearnGeom::DistancePoints, c(edge$weighted_midpoint_x, edge$weighted_midpoint_y)); |
| 440 | ! |
perp_line_1_dists_max <- which.max(perp_line_1_dists); |
| 441 | ! |
perp_line_1_pt <- perp_line_1_ints[perp_line_1_dists_max,]; |
| 442 | ||
| 443 | ! |
perp_line_2_dists <- apply(perp_line_2_ints, 1, LearnGeom::DistancePoints, c(edge$weighted_midpoint_x, edge$weighted_midpoint_y)); |
| 444 | ! |
perp_line_2_dists_max <- which.max(perp_line_2_dists); |
| 445 | ! |
perp_line_2_pt <- perp_line_2_ints[perp_line_2_dists_max,]; |
| 446 | ||
| 447 | ! |
if(path_as == "svg") {
|
| 448 | ! |
new_path <- paste0( |
| 449 | ! |
"M ", paste(mp * round(c(pinch_on[1], pinch_on[2]), rnd), collapse = " "), |
| 450 | ! |
" L ", paste(mp * round(c(perp_base[1,1], perp_base[1,2]), rnd), collapse = " "), |
| 451 | ! |
" L ", paste(mp * round(c(perp_base[2,1], perp_base[2,2]), rnd), collapse = " "), |
| 452 | ! |
" Z " |
| 453 |
) |
|
| 454 | ! |
path$path <- new_path; |
| 455 | ! |
paths <- c(paths, list(path)); |
| 456 | ||
| 457 | ! |
paths <- c(paths, list(list( |
| 458 | ! |
type = "path", opacity = 0.25, |
| 459 | ! |
line = list( width = 1, color = "#000000", opacity = 0.5), |
| 460 | ! |
path = paste0("M", paste(mp * round(c(perp_base[1,1], perp_base[1,2]), rnd), collapse = " "),
|
| 461 | ! |
" L", paste(mp * round(c(perp_base[2,1], perp_base[2,2]), rnd), collapse = " ")) |
| 462 |
))) |
|
| 463 |
} |
|
| 464 |
else {
|
|
| 465 | ! |
new_path <- as.data.frame(matrix( |
| 466 | ! |
c(mp * round(c(pinch_on[1], pinch_on[2]), rnd), |
| 467 | ! |
mp * round(c(perp_base[1,1], perp_base[1,2]), rnd), |
| 468 | ! |
mp * round(c(perp_base[2,1], perp_base[2,2]), rnd), |
| 469 | ! |
mp * round(c(pinch_on[1], pinch_on[2]), rnd) |
| 470 |
), |
|
| 471 | ! |
ncol = 2, byrow = TRUE, dimnames = list(NULL, c("x", "y")))
|
| 472 |
) |
|
| 473 | ! |
path$path <- new_path; |
| 474 | ! |
paths <- c(paths, list(path)); |
| 475 |
} |
|
| 476 |
} |
|
| 477 |
else {
|
|
| 478 | ! |
stop("edge_end parameter unknown")
|
| 479 |
} |
|
| 480 | ||
| 481 | ! |
if(edge_arrow == TRUE && |
| 482 |
( |
|
| 483 | ! |
edge_arrows_to_show == "both" || |
| 484 |
# (do.call(paste0("which.", edge_arrows_to_show), list(edge[, c("weight_1", "weight_2")])) == e)
|
|
| 485 | ! |
edges_[label == edge$label, .SD[which.max(value)]]$node_1 == edge$node_1 |
| 486 |
) |
|
| 487 |
) {
|
|
| 488 | ! |
x_axis <- LearnGeom::CreateLinePoints(c(-10,0), c(10,0)) |
| 489 | ! |
perp_line_angle <- LearnGeom::LinesAngles(perp_line, x_axis) |
| 490 | ! |
if(perp_line_angle[1] == 0) {
|
| 491 | ! |
mid_point[1] <- mid_point[1] - 0.0001 |
| 492 |
} |
|
| 493 | ! |
arrow_offset <- LearnGeom::MidPoint(mid_point, as.matrix(node)) |
| 494 | ! |
arrow_offset_hgt <- CreatePointByDistance(as.matrix(node), arrow_offset, dist = weight * edge_arrow_width); |
| 495 | ! |
arrow_offset_hgt2 <- CreatePointByDistance(as.matrix(node), arrow_offset, dist = weight * (edge_arrow_width*2)); |
| 496 | ||
| 497 | ! |
arrow_offset_line <- MoveLineAlong(arrow_offset[1], arrow_offset[2], perp_line[1]) |
| 498 | ! |
arrow_offset_hgt_line <- MoveLineAlong(arrow_offset_hgt[1], arrow_offset_hgt[2], perp_line[1]) |
| 499 | ! |
arrow_offset_hgt2_line <- MoveLineAlong(arrow_offset_hgt2[1], arrow_offset_hgt2[2], perp_line[1]) |
| 500 | ! |
edge_line_1 <- LearnGeom::CreateLinePoints(perp_base[1,], mid_point); |
| 501 | ! |
edge_line_2 <- LearnGeom::CreateLinePoints(perp_base[2,], mid_point); |
| 502 | ||
| 503 |
# if(edge_line_1[1] == 0) {
|
|
| 504 |
# # add for offset |
|
| 505 |
# print("ER...Tell Cody you saw me.");
|
|
| 506 |
# # arrow_int_1 <- LearnGeom::IntersectLines(edge_line_1, arrow_offset_hgt_line); |
|
| 507 |
# # arrow_int_2 <- LearnGeom::IntersectLines(edge_line_2, arrow_offset_hgt_line); |
|
| 508 |
# # arrow_int2_1 <- LearnGeom::IntersectLines(edge_line_1, arrow_offset_hgt2_line); |
|
| 509 |
# # arrow_int2_2 <- LearnGeom::IntersectLines(edge_line_2, arrow_offset_hgt2_line); |
|
| 510 |
# } |
|
| 511 |
# else {
|
|
| 512 | ! |
offset_int_1 <- LearnGeom::IntersectLines(edge_line_1, arrow_offset_line); |
| 513 | ! |
offset_int_2 <- LearnGeom::IntersectLines(edge_line_2, arrow_offset_line); |
| 514 | ! |
arrow_int_1 <- LearnGeom::IntersectLines(edge_line_1, arrow_offset_hgt_line); |
| 515 | ! |
arrow_int_2 <- LearnGeom::IntersectLines(edge_line_2, arrow_offset_hgt_line); |
| 516 | ! |
arrow_int2_1 <- LearnGeom::IntersectLines(edge_line_1, arrow_offset_hgt2_line); |
| 517 | ! |
arrow_int2_2 <- LearnGeom::IntersectLines(edge_line_2, arrow_offset_hgt2_line); |
| 518 |
# } |
|
| 519 | ||
| 520 | ! |
arr_path <- list(line = list(width = 0)); |
| 521 | ! |
if ( edge_arrow_direction == 1 ) {
|
| 522 | ! |
new_path <- paste0( |
| 523 | ! |
"M", paste(mp * round(c(arrow_int_1), rnd), collapse = " "), |
| 524 | ! |
" L", paste(mp * round(c(arrow_offset), rnd), collapse = " "), |
| 525 | ! |
" L", paste(mp * round(c(arrow_int_2), rnd), collapse = " "), |
| 526 | ! |
" L", paste(mp * round(c(arrow_int2_2), rnd), collapse = " "), |
| 527 | ! |
" L", paste(mp * round(c(arrow_offset_hgt), rnd), collapse = " "), |
| 528 | ! |
" L", paste(mp * round(c(arrow_int2_1), rnd), collapse = " "), |
| 529 | ! |
" Z" |
| 530 |
) |
|
| 531 |
} |
|
| 532 |
else {
|
|
| 533 | ! |
new_path <- paste0( |
| 534 | ! |
"M", paste(mp * round(c(offset_int_1), rnd), collapse = " "), |
| 535 | ! |
" L", paste(mp * round(c(arrow_offset_hgt), rnd), collapse = " "), |
| 536 | ! |
" L", paste(mp * round(c(offset_int_2), rnd), collapse = " "), |
| 537 | ! |
" L", paste(mp * round(c(arrow_int_2), rnd), collapse = " "), |
| 538 | ! |
" L", paste(mp * round(c(arrow_offset_hgt2), rnd), collapse = " "), |
| 539 | ! |
" L", paste(mp * round(c(arrow_int_1), rnd), collapse = " "), |
| 540 | ! |
" Z" |
| 541 |
) |
|
| 542 |
} |
|
| 543 | ||
| 544 | ! |
arr_path$path <- new_path; |
| 545 | ! |
arr_path$fillcolor <- "#FFFFFF"; |
| 546 | ! |
arr_path$line$color <- "#FFFFFF"; |
| 547 | ! |
arr_path$line$width <- arrow_halo; |
| 548 | ! |
arr_path$opacity <- 1 |
| 549 | ! |
if(!is.null(this_color_hsv)) {
|
| 550 |
# add white |
|
| 551 | ! |
if(edge_arrow_saturation_multiplier < 1) {
|
| 552 |
# rgb_s_and_a_equiv_ext <- rgb_white + (rgb_just_s - rgb_white) * (this_color_hsv$alpha * edge_arrow_saturation_multiplier) |
|
| 553 | ! |
rgb_s_and_a_equiv_ext <- lighten_color(rgb_just_s, this_color_hsv$alpha, edge_arrow_saturation_multiplier); |
| 554 |
} |
|
| 555 | ||
| 556 |
# add shade |
|
| 557 |
else {
|
|
| 558 |
# rgb_s_and_a_equiv_ext <- (rgb_white + (rgb_just_s - rgb_white) * (this_color_hsv$alpha)) * (1 - -(1 - edge_arrow_saturation_multiplier)) |
|
| 559 | ! |
rgb_s_and_a_equiv_ext <- darken_color(rgb_just_s, edge_arrow_saturation_multiplier, this_color_hsv$alpha) |
| 560 |
} |
|
| 561 | ||
| 562 | ! |
col_s_and_a_equiv_ext <- grDevices::rgb(rgb_s_and_a_equiv_ext[1,1], rgb_s_and_a_equiv_ext[2,1], rgb_s_and_a_equiv_ext[3,1], maxColorValue = 255) |
| 563 | ! |
arr_path$fillcolor <- col_s_and_a_equiv_ext |
| 564 |
} |
|
| 565 | ||
| 566 | ! |
paths <- c(paths, list(arr_path)); |
| 567 |
} |
|
| 568 |
} |
|
| 569 | ||
| 570 |
else {
|
|
| 571 |
# cat("Zero edge: ", edge$node_1, ", ", edge$node_2, " - ", weight, "\n");
|
|
| 572 |
# print(edge); |
|
| 573 |
} |
|
| 574 |
} |
|
| 575 | ! |
paths |
| 576 |
} |
|
| 577 | ||
| 578 | ||
| 579 |
base_plot <- function( |
|
| 580 |
width = 600, height = width, |
|
| 581 |
autosize = (is.null(width) && is.null(height)), |
|
| 582 |
max_axis_marker = 3, |
|
| 583 |
title = "ENA Plot", ... |
|
| 584 |
) {
|
|
| 585 | ! |
p <- |
| 586 | ! |
plotly::plot_ly( |
| 587 | ! |
mode = "markers+lines", type = "scatter", |
| 588 | ! |
width = width, height = height |
| 589 |
) |
|
| 590 |
; |
|
| 591 | ||
| 592 | ! |
axis_list <- list( |
| 593 | ! |
type = "linear", |
| 594 | ! |
showgrid = F, |
| 595 | ! |
title = list(text = ""), |
| 596 | ! |
showticklabels = FALSE, |
| 597 | ! |
range = c(-max_axis_marker, max_axis_marker) |
| 598 |
); |
|
| 599 | ! |
x_axis <- axis_list; |
| 600 | ! |
x_axis$scaleanchor = "y"; |
| 601 | ! |
y_axis <- axis_list; |
| 602 | ||
| 603 | ! |
p <- plotly::layout( p = p, title = title, |
| 604 | ! |
autosize = autosize, |
| 605 | ! |
showlegend = FALSE, |
| 606 | ! |
xaxis = x_axis, |
| 607 | ! |
yaxis = y_axis |
| 608 |
); |
|
| 609 | ||
| 610 | ! |
class(p) <- c("enaplot", class(p));
|
| 611 | ||
| 612 | ! |
return(p); |
| 613 |
} |
|
| 614 | ||
| 615 |
#' Plot Function |
|
| 616 |
#' |
|
| 617 |
#' This function generates a plot based on the provided inputs. |
|
| 618 |
#' |
|
| 619 |
#' @param x A numeric vector or object to be plotted. |
|
| 620 |
#' @param ... Additional arguments passed to the plotting method. |
|
| 621 |
#' @param y An optional numeric vector for y-values. |
|
| 622 |
#' |
|
| 623 |
#' @return A plot object or visualization. |
|
| 624 |
#' @export |
|
| 625 |
'plot.ena.ordered.set' <- function(x, y, ...) {
|
|
| 626 | ! |
p <- base_plot(...) |
| 627 | ||
| 628 | ! |
attr(p, "model") <- x; |
| 629 | ||
| 630 | ! |
args <- list(...); |
| 631 | ! |
dimensions <- colnames(as.matrix(x$points))[1:2]; |
| 632 | ! |
if(!is.null(args$dimensions)) {
|
| 633 | ! |
dimensions <- args$dimensions; |
| 634 |
} |
|
| 635 | ! |
attr(p, "dimensions") <- dimensions; |
| 636 | ||
| 637 | ! |
p |
| 638 |
} |
|
| 639 | ||
| 640 |
#' Plot ENA nodes |
|
| 641 |
#' |
|
| 642 |
#' Plots the nodes of an ENA model using plotly, with options for node size, color, labels, and self-connections. |
|
| 643 |
#' |
|
| 644 |
#' @param x An ENA model object or plotly object with model attached. |
|
| 645 |
#' @param ... Additional arguments passed to plotting functions. |
|
| 646 |
#' @param weighted_nodes Logical; if TRUE, node sizes are weighted (default: TRUE). |
|
| 647 |
#' @param node_size_multiplier Numeric; scales node sizes (default: 1). |
|
| 648 |
#' @param node_color Character; color(s) for nodes (default: "#3E4750"). |
|
| 649 |
#' @param node_sizes Numeric; custom node sizes (default: 1). |
|
| 650 |
#' @param node_direction Integer; direction for node size calculation (default: 2). |
|
| 651 |
#' @param self_connections Logical; if TRUE, show self-connections (default: weighted_nodes). |
|
| 652 |
#' @param self_connection_color Character; color(s) for self-connections (default: "#000000"). |
|
| 653 |
#' @param nodes_include_self Logical; if TRUE, include self-connections in node size (default: TRUE). |
|
| 654 |
#' @param node_halo Numeric; width of node halo (default: 0). |
|
| 655 |
#' @param self_connection_halo Numeric; width of self-connection halo (default: 0). |
|
| 656 |
#' @param node_labels Logical; if TRUE, show node labels (default: TRUE). |
|
| 657 |
#' @param node_position_multiplier Numeric; scales node positions (default: 1). |
|
| 658 |
#' @param node_saturation_multiplier Numeric; controls node color saturation (default: 1). |
|
| 659 |
#' @param sender_direction Integer; direction for sender (default: 1). |
|
| 660 |
#' @param weights Optional; edge weights to use (default: from model). |
|
| 661 |
#' @param nodes Optional; node positions to use (default: from model). |
|
| 662 |
#' |
|
| 663 |
#' @return A plotly object with ENA nodes drawn. |
|
| 664 |
#' @export |
|
| 665 |
nodes <- function( |
|
| 666 |
x, ..., |
|
| 667 |
weighted_nodes = TRUE, node_size_multiplier = 1, |
|
| 668 |
node_color = "#3E4750", node_sizes = 1, node_direction = 2, |
|
| 669 |
self_connections = weighted_nodes, self_connection_color = "#000000", |
|
| 670 |
nodes_include_self = TRUE, node_halo = 0, self_connection_halo = 0, |
|
| 671 |
node_labels = TRUE, node_position_multiplier = 1, node_saturation_multiplier = 1, |
|
| 672 | ||
| 673 |
# |
|
| 674 |
sender_direction = 1, |
|
| 675 | ||
| 676 |
# parameters pulled from model `x` that can be overridden |
|
| 677 |
weights = NULL, nodes = NULL |
|
| 678 |
) {
|
|
| 679 | ! |
p <- NULL; |
| 680 | ! |
if(is(x, "plotly")) {
|
| 681 | ! |
p <- x; |
| 682 | ! |
x <- attr(x = p, which = "model"); |
| 683 | ! |
if(is.null(weights)) {
|
| 684 | ! |
weights <- attr(p, "edge_weights"); |
| 685 |
} |
|
| 686 |
} |
|
| 687 | ! |
if(is.null(weights)) {
|
| 688 | ! |
weights <- colMeans(as.matrix(x$line.weights$ENA_DIRECTION$response)); |
| 689 |
} |
|
| 690 | ! |
if(is.null(nodes)) {
|
| 691 | ! |
nodes <- data.table::copy(x$rotation$nodes); |
| 692 |
} |
|
| 693 |
else {
|
|
| 694 | ! |
nodes <- data.table::copy(nodes); |
| 695 |
} |
|
| 696 | ! |
raw_weights <- weights; |
| 697 | ! |
raw_sq_weights_raw <- to_square(raw_weights); |
| 698 | ! |
raw_sq_weights <- raw_weights * node_size_multiplier; |
| 699 | ||
| 700 | ! |
weights <- abs(weights); |
| 701 | ||
| 702 | ! |
dimensions <- attr(p, "dimensions"); |
| 703 | ||
| 704 |
# if(is.null(scale_edges_from)) {
|
|
| 705 |
# if(!is.null(model)) {
|
|
| 706 |
# scale_edges_from <- c(0, max(as.matrix(model$line.weights$ENA_DIRECTION$response))) |
|
| 707 |
# } |
|
| 708 |
# else {
|
|
| 709 |
# scale_edges_from <- c(0, max(raw_weights)) |
|
| 710 |
# } |
|
| 711 |
# } |
|
| 712 | ||
| 713 | ! |
sq_weights_raw <- to_square(weights); |
| 714 | ! |
sq_weights <- sq_weights_raw * node_size_multiplier; |
| 715 | ||
| 716 | ! |
if(nodes_include_self == TRUE) {
|
| 717 | ! |
node_sizes_raw <- (apply(sq_weights_raw, node_direction, sum)); |
| 718 | ! |
node_sizes <- (apply(sq_weights, node_direction, sum)); |
| 719 |
} |
|
| 720 |
else {
|
|
| 721 | ! |
node_sizes_raw <- (apply(sq_weights_raw, node_direction, sum) - diag(sq_weights_raw)); |
| 722 | ! |
node_sizes <- (apply(sq_weights, node_direction, sum) - diag(sq_weights)); |
| 723 |
} |
|
| 724 | ! |
node_sizes[node_sizes == 0] <- 0.001 |
| 725 | ||
| 726 | ! |
nodes[, (seq(2, ncol(nodes))) := lapply(.SD, `*`, node_position_multiplier) , .SDcols = (seq(2, ncol(nodes)))]; |
| 727 | ! |
dim_indices <- which(colnames(as.matrix(nodes)) %in% dimensions); |
| 728 | ! |
edge_table <- create_edge_matrix( |
| 729 | ! |
NULL, weights = raw_weights, nodes = nodes, direction = sender_direction, dims = dim_indices, |
| 730 | ! |
node_position_multiplier = 1 |
| 731 |
); |
|
| 732 | ! |
nodes_xy <- attr(edge_table, "nodes_xy"); |
| 733 | ||
| 734 | ! |
annotations <- list(); |
| 735 | ! |
node_traces <- list(); |
| 736 | ! |
if(weighted_nodes) {
|
| 737 |
# Node definition |
|
| 738 | ! |
shape = list( |
| 739 | ! |
type = "circle", |
| 740 | ! |
xanchor = "x", |
| 741 | ! |
yanchor = "y", |
| 742 | ! |
xref = "x", |
| 743 | ! |
yref = "y", |
| 744 | ! |
line = list (color = "#FFFFFF", width = node_halo) |
| 745 |
) |
|
| 746 | ||
| 747 |
# ___ Outer nodes ---- |
|
| 748 | ! |
if(length(node_color) == 1) {
|
| 749 | ! |
node_color <- rep(node_color, nrow(sq_weights)); |
| 750 |
} |
|
| 751 | ! |
if(self_connections == TRUE) {
|
| 752 | ! |
if(length(self_connection_color) == 1) {
|
| 753 | ! |
self_connection_color <- rep(self_connection_color, nrow(sq_weights)); |
| 754 |
} |
|
| 755 | ! |
else if(length(self_connection_color) == 2) {
|
| 756 | ! |
self_connection_color <- self_connection_color[((diag(raw_sq_weights_raw) < 0) * 1) + 1]; |
| 757 |
} |
|
| 758 |
} |
|
| 759 | ! |
for(i in seq(nrow(sq_weights))) {
|
| 760 | ! |
if(node_sizes[i] > 0) {
|
| 761 | ! |
shape$line$width = node_halo; |
| 762 | ! |
node <- nodes_xy[i,]; |
| 763 | ! |
node_radius <- node_sizes[i] / 2; |
| 764 | ! |
edge_line <- edge_fun(rbind(as.matrix(node),c(0,0)), fun = LearnGeom::CreateLinePoints); |
| 765 | ! |
node_pts <- LearnGeom::IntersectLineCircle(edge_line, as.matrix(node), node_radius); |
| 766 | ! |
shape$x0 <- node$x - (node_radius); |
| 767 | ! |
shape$y0 <- node$y - (node_radius); |
| 768 | ! |
shape$x1 <- node$x + (node_radius); |
| 769 | ! |
shape$y1 <- node$y + (node_radius); |
| 770 | ! |
shape$fillcolor <- paste0(node_color[i], alpha_to_hex(node_saturation_multiplier)); #hsv(0, 0, 0.1, 1); #edge_sizes[i]); |
| 771 | ||
| 772 | ! |
node_traces <- c(node_traces, list(shape)); |
| 773 | ||
| 774 | ! |
if(node_labels == TRUE) {
|
| 775 | ! |
annotations <- c(annotations, list(list( |
| 776 | ! |
x = shape$x1, |
| 777 | ! |
y = shape$y1, |
| 778 | ! |
text = node$code, |
| 779 | ! |
xref = "x", yref = "y", |
| 780 | ! |
showarrow = FALSE, arrowhead = 0, |
| 781 | ! |
ax = 0, ay = -60 |
| 782 |
))) |
|
| 783 |
} |
|
| 784 | ||
| 785 |
# ___ Self nodes ---- |
|
| 786 | ! |
if(self_connections) {
|
| 787 | ! |
shape$line$width = self_connection_halo; |
| 788 | ! |
shape$x0 <- node$x - (diag(sq_weights)[i] / 2); |
| 789 | ! |
shape$y0 <- node$y - (diag(sq_weights)[i] / 2); |
| 790 | ! |
shape$x1 <- node$x + (diag(sq_weights)[i] / 2); |
| 791 | ! |
shape$y1 <- node$y + (diag(sq_weights)[i] / 2); |
| 792 | ! |
shape$fillcolor <- hsv(0, 0, 1, 1); |
| 793 | ! |
node_traces <- c(node_traces, list(shape)); |
| 794 | ||
| 795 | ! |
shape$x0 <- node$x - (diag(sq_weights)[i] / 2); |
| 796 | ! |
shape$y0 <- node$y - (diag(sq_weights)[i] / 2); |
| 797 | ! |
shape$x1 <- node$x + (diag(sq_weights)[i] / 2); |
| 798 | ! |
shape$y1 <- node$y + (diag(sq_weights)[i] / 2); |
| 799 | ||
| 800 | ! |
this_color_hsv <- as.list(t(grDevices::rgb2hsv(grDevices::col2rgb(self_connection_color[i])))); |
| 801 | ! |
names(this_color_hsv) <- c("h", "s", "v");
|
| 802 | ! |
this_color_hsv$alpha <- diag(sq_weights_raw)[i]; |
| 803 | ! |
shape$fillcolor <- do.call(grDevices::hsv, this_color_hsv); #hsv(1, 1, 1, edge_sizes[i]); |
| 804 | ! |
node_traces <- c(node_traces, list(shape)); |
| 805 |
} |
|
| 806 |
} |
|
| 807 |
} |
|
| 808 | ||
| 809 | ! |
attr(x = p, which = "annotations") <- c(attr(x = p, which = "annotations"), annotations); |
| 810 | ! |
attr(x = p, which = "shapes") <- c(attr(x = p, which = "shapes"), node_traces); |
| 811 |
} |
|
| 812 | ||
| 813 |
# __ Non-weighted Nodes ---- |
|
| 814 |
else {
|
|
| 815 | ! |
nodes_xy$size <- 15; |
| 816 | ! |
p <- plotly::add_trace(p = p, data = nodes_xy, |
| 817 | ! |
x = ~x, y = ~y, |
| 818 | ! |
text = ~code, |
| 819 | ! |
type = "scatter", |
| 820 | ! |
mode = "markers+text", |
| 821 | ! |
textposition = "bottom center", |
| 822 | ! |
name = "Nodes", |
| 823 | ! |
marker = list( |
| 824 | ! |
sizemode = "diameter", |
| 825 | ! |
size = ~size, |
| 826 | ! |
color = "black", |
| 827 | ! |
line = list(width = 0) |
| 828 |
) |
|
| 829 |
); |
|
| 830 |
} |
|
| 831 | ||
| 832 | ! |
return(p); |
| 833 |
} |
|
| 834 | ||
| 835 |
#' Plot ENA edges |
|
| 836 |
#' |
|
| 837 |
#' Plots the edges (connections) between nodes in an ENA model using plotly, with options for color, width, direction, and arrowheads. |
|
| 838 |
#' |
|
| 839 |
#' @param x An ENA model object or plotly object with model attached. |
|
| 840 |
#' @param ... Additional arguments passed to plotting functions. |
|
| 841 |
#' @param show_edge_center Logical; if TRUE, show edge centers (default: FALSE). |
|
| 842 |
#' @param units Optional; units to include in the plot. |
|
| 843 |
#' @param edge_color Character vector of edge colors (default: c("#FF0000", "#0000FF")).
|
|
| 844 |
#' @param edge_end Character; "outward" or "inward" (default: "outward"). |
|
| 845 |
#' @param desaturate_edges_by Function or string; controls edge desaturation (default: sqrt). |
|
| 846 |
#' @param lighten_edges_by Function or string; controls edge lightening (default: same as desaturate_edges_by). |
|
| 847 |
#' @param multiplier Numeric; scales edge sizes (default: 1). |
|
| 848 |
#' @param edge_size_multiplier Numeric; scales edge width (default: multiplier). |
|
| 849 |
#' @param edges_behind_nodes Logical; if TRUE, draw edges behind nodes (default: TRUE). |
|
| 850 |
#' @param sender_direction Integer; direction for sender (default: 1). |
|
| 851 |
#' @param scale_edges_to Numeric vector; range to scale edge weights to (default: c(0,1)). |
|
| 852 |
#' @param scale_edges_from Numeric vector; range of edge weights to scale from (default: NULL). |
|
| 853 |
#' @param edge_arrow Logical; if TRUE, draw arrowheads (default: TRUE). |
|
| 854 |
#' @param edge_arrow_offset Numeric; offset for arrowhead placement (default: 2). |
|
| 855 |
#' @param edge_arrow_width Numeric; width of arrowhead (default: 0.1). |
|
| 856 |
#' @param edge_arrows_to_show Character; which arrows to show (default: "max"). |
|
| 857 |
#' @param edge_arrow_saturation_multiplier Numeric; controls arrowhead color saturation (default: 1.1). |
|
| 858 |
#' @param fake_alpha Logical; if TRUE, simulate alpha blending (default: TRUE). |
|
| 859 |
#' @param edge_halo Numeric; width of edge halo (default: 0.5). |
|
| 860 |
#' @param edge_halo_multiplier Numeric; multiplier for edge halo (default: 1.1). |
|
| 861 |
#' @param arrow_halo Numeric; width of arrow halo (default: 0). |
|
| 862 |
#' @param edge_arrow_direction Integer; direction for arrowhead (default: 2). |
|
| 863 |
#' @param weights Optional; edge weights to use (default: from model). |
|
| 864 |
#' @param nodes Optional; node positions to use (default: from model). |
|
| 865 |
#' @param node_position_multiplier Numeric; scales node positions (default: 1). |
|
| 866 |
#' |
|
| 867 |
#' @return A plotly object with ENA edges drawn. |
|
| 868 |
#' @export |
|
| 869 |
edges <- function( |
|
| 870 |
x, ..., |
|
| 871 |
show_edge_center = FALSE, units = NULL, |
|
| 872 |
edge_color = c("#FF0000","#0000FF"), edge_end = "outward",
|
|
| 873 |
desaturate_edges_by = sqrt, lighten_edges_by = desaturate_edges_by, |
|
| 874 |
multiplier = 1, |
|
| 875 |
edge_size_multiplier = multiplier, edges_behind_nodes = TRUE, sender_direction = 1, |
|
| 876 |
scale_edges_to = c(0,1), scale_edges_from = NULL, |
|
| 877 |
edge_arrow = TRUE, edge_arrow_offset = 2, edge_arrow_width = 0.1, edge_arrows_to_show = "max", |
|
| 878 |
edge_arrow_saturation_multiplier = 1.1, fake_alpha = TRUE, edge_halo = 0.5, edge_halo_multiplier = 1.1, |
|
| 879 |
arrow_halo = 0, edge_arrow_direction = 2, node_position_multiplier = 1, |
|
| 880 | ||
| 881 |
# parameters pulled from model `x` that can be overridden |
|
| 882 |
weights = NULL, nodes = NULL |
|
| 883 |
) {
|
|
| 884 | ! |
.SD <- NULL; |
| 885 | ||
| 886 | ! |
p <- NULL; |
| 887 | ! |
if(is(x, "plotly")) {
|
| 888 | ! |
p <- x; |
| 889 | ! |
x <- attr(x = p, which = "model"); |
| 890 |
} |
|
| 891 | ! |
if(is.null(weights)) {
|
| 892 | ! |
weights <- colMeans(as.matrix(x$line.weights$ENA_DIRECTION$response)); |
| 893 |
} |
|
| 894 | ! |
else if (!is.numeric(weights)) {
|
| 895 | ! |
weights <- colMeans(as.matrix(weights[ENA_DIRECTION == 'response',])); |
| 896 |
} |
|
| 897 | ! |
if(is.null(nodes)) {
|
| 898 | ! |
nodes <- data.table::copy(x$rotation$nodes); |
| 899 |
} |
|
| 900 |
else {
|
|
| 901 | ! |
nodes <- data.table::copy(nodes); |
| 902 |
} |
|
| 903 | ! |
nodes[, (seq(2, ncol(nodes))) := lapply(.SD, `*`, node_position_multiplier) , .SDcols = (seq(2, ncol(nodes)))]; |
| 904 | ! |
raw_weights <- weights; |
| 905 | ! |
raw_sq_weights_raw <- to_square(raw_weights); |
| 906 | ! |
raw_sq_weights <- raw_weights * multiplier; |
| 907 | ||
| 908 | ! |
weights <- abs(weights); |
| 909 | ||
| 910 | ! |
if(is.null(scale_edges_from)) {
|
| 911 | ! |
if(!is.null(model)) {
|
| 912 | ! |
scale_edges_from <- c(0, max(as.matrix(x$line.weights$ENA_DIRECTION$response))) |
| 913 |
} |
|
| 914 |
else {
|
|
| 915 | ! |
scale_edges_from <- c(0, max(raw_weights)) |
| 916 |
} |
|
| 917 |
} |
|
| 918 | ||
| 919 | ! |
sq_weights_raw <- to_square(weights); |
| 920 | ! |
sq_weights <- sq_weights_raw * multiplier; |
| 921 | ||
| 922 | ! |
edge_table <- create_edge_matrix(NULL, weights = raw_weights, nodes = nodes, direction = sender_direction); |
| 923 | ! |
nodes_xy <- attr(edge_table, "nodes_xy"); |
| 924 | ||
| 925 | ! |
edge_path_list <- list(); |
| 926 | ! |
nodes_xy <- attr(edge_table, "nodes_xy"); |
| 927 | ! |
node_combinations <- attr(edge_table, "node_combinations"); |
| 928 | ||
| 929 | ! |
edge_path_list <- edge_paths( |
| 930 | ! |
edge_table, edge_color = edge_color, edge_end = edge_end, |
| 931 | ! |
desaturate_edges_by = desaturate_edges_by, lighten_edges_by = lighten_edges_by, |
| 932 | ! |
edge_size_multiplier = edge_size_multiplier, |
| 933 | ! |
scale_edges_to = scale_edges_to, scale_edges_from = scale_edges_from, |
| 934 | ! |
edge_arrow = edge_arrow, edge_arrow_offset = edge_arrow_offset, |
| 935 | ! |
edge_arrow_width = edge_arrow_width, edge_arrow_saturation_multiplier = edge_arrow_saturation_multiplier, |
| 936 | ! |
fake_alpha = fake_alpha, edge_halo = edge_halo, edge_arrows_to_show = edge_arrows_to_show, |
| 937 | ! |
arrow_halo = arrow_halo, edge_halo_multiplier = edge_halo_multiplier, |
| 938 | ! |
sender_direction = sender_direction, |
| 939 | ! |
edge_arrow_direction = edge_arrow_direction |
| 940 |
); |
|
| 941 | ||
| 942 | ! |
if(show_edge_center) {
|
| 943 | ! |
p <- plotly::add_markers(p = p, data = edge_table, x = ~weighted_midpoint_x, y = ~weighted_midpoint_y, marker = list(color = "black"), name = ~label) |
| 944 | ! |
p <- plotly::add_markers(p = p, data = edge_table, x = ~midpoint_x, y = ~midpoint_y, marker = list(color = "black"), name = ~label) |
| 945 |
} |
|
| 946 | ||
| 947 |
# p <- plotly::layout(p = p, shapes = edge_path_list); |
|
| 948 | ! |
attr(x = p, which = "shapes") <- c(attr(x = p, which = "shapes"), edge_path_list); |
| 949 | ! |
attr(x = p, which = "edge_weights") <- raw_weights; |
| 950 | ||
| 951 | ! |
return (p); |
| 952 |
} |
|
| 953 | ||
| 954 |
unit_vectors <- function(points, dims = c(1,2)) {
|
|
| 955 | ! |
if(is(points, "list")) {
|
| 956 | ! |
meta_cols <- which(sapply(points[[1]], is, "ena.metadata")) |
| 957 | ! |
dim_cols <- which(sapply(points[[1]], is, "ena.dimension"))[dims] |
| 958 | ! |
dim_col_names <- colnames(points[[1]])[dim_cols] |
| 959 |
} |
|
| 960 |
else {
|
|
| 961 | ! |
meta_cols <- which(sapply(points, is, "ena.metadata")) |
| 962 | ! |
dim_cols <- which(sapply(points, is, "ena.dimension"))[dims] |
| 963 | ! |
dim_col_names <- colnames(points)[dim_cols] |
| 964 |
} |
|
| 965 | ||
| 966 | ! |
merge_by = c("ENA_UNIT")
|
| 967 | ! |
if("_GRP" %chin% colnames(points)) {
|
| 968 | ! |
dim_col_names <- c("_GRP", dim_col_names);
|
| 969 | ! |
merge_by = c(merge_by, "_GRP"); |
| 970 |
} |
|
| 971 | ||
| 972 | ! |
from_rows <- points[ENA_DIRECTION == "ground", c("ENA_UNIT", dim_col_names), with = FALSE]
|
| 973 | ! |
to_rows <- points[ENA_DIRECTION == "response", c("ENA_UNIT", dim_col_names), with = FALSE]
|
| 974 | ||
| 975 | ! |
sd_cols <- paste(rep(dim_col_names,2), c(rep("from",2), rep("to",2)), sep = ".");
|
| 976 | ! |
if(nrow(from_rows) > 0) {
|
| 977 | ! |
y <- merge(from_rows, to_rows, by = merge_by, suffixes = c(".from", ".to"));
|
| 978 | ! |
y[, distance := {
|
| 979 | ! |
LearnGeom::DistancePoints(c(.SD[[sd_cols[1]]], .SD[[sd_cols[2]]]), c(.SD[[sd_cols[3]]], .SD[[sd_cols[4]]])) |
| 980 | ! |
}, .SDcols = c(sd_cols), by = 1:nrow(y)]; |
| 981 | ! |
y |
| 982 |
} |
|
| 983 |
else {
|
|
| 984 | ! |
to_rows; |
| 985 |
} |
|
| 986 |
} |
|
| 987 | ||
| 988 |
#' Plot ENA units (points and vectors) |
|
| 989 |
#' |
|
| 990 |
#' Plots the units (points) and optionally vectors/arrows for each unit in an ENA model using plotly. |
|
| 991 |
#' |
|
| 992 |
#' @param x An ENA model object or plotly object with model attached. |
|
| 993 |
#' @param ... Additional arguments passed to plotting functions. |
|
| 994 |
#' @param units_as_vectors Logical; if TRUE, plot unit vectors/arrows (default: FALSE). |
|
| 995 |
#' @param unit_vectors_towards Character; "response" or "ground" (default: "response"). |
|
| 996 |
#' @param mean_vector_width Numeric; width of mean vector arrow (default: 5). |
|
| 997 |
#' @param mean_vector_arrow_size Numeric; size of mean vector arrowhead (default: 0.5). |
|
| 998 |
#' @param unit_vector_width Numeric; width of unit vector arrows (default: 3). |
|
| 999 |
#' @param unit_vector_arrow_size Numeric; size of unit vector arrowheads (default: 0.7). |
|
| 1000 |
#' @param show_points Logical; if TRUE, show points (default: TRUE). |
|
| 1001 |
#' @param point_shape Character; shape of points (default: "circle"). |
|
| 1002 |
#' @param dynamic_response_point_size Logical; if TRUE, scale response point size by distance (default: FALSE). |
|
| 1003 |
#' @param show_mean Logical; if TRUE, show mean vector/point (default: TRUE). |
|
| 1004 |
#' @param mean_value Optional; mean value to use (default: NULL). |
|
| 1005 |
#' @param points_color Character; color for points (default: "#FF0000"). |
|
| 1006 |
#' @param saturate_vectors_by Numeric or function; controls vector color saturation (default: 0.2). |
|
| 1007 |
#' @param point_position_multiplier Numeric; scales point positions (default: 1). |
|
| 1008 |
#' @param distance_scaled_by Function; rescales distances for arrow size (default: scales::rescale). |
|
| 1009 |
#' @param with_lines Logical; if TRUE, connect points with lines (default: FALSE). |
|
| 1010 |
#' @param with_ci Logical; if TRUE, show confidence intervals (default: TRUE). |
|
| 1011 |
#' @param points Optional; points to use (default: from model). |
|
| 1012 |
#' |
|
| 1013 |
#' @return A plotly object with ENA units (points and/or vectors) drawn. |
|
| 1014 |
#' @export |
|
| 1015 |
units <- function( |
|
| 1016 |
x, ..., |
|
| 1017 |
units_as_vectors = FALSE, unit_vectors_towards = "response", |
|
| 1018 |
mean_vector_width = 5, mean_vector_arrow_size = 0.5, |
|
| 1019 |
unit_vector_width = 3, unit_vector_arrow_size = 0.7, |
|
| 1020 |
show_points = TRUE, point_shape = "circle", |
|
| 1021 |
dynamic_response_point_size = FALSE, |
|
| 1022 |
show_mean = TRUE, |
|
| 1023 |
mean_value = NULL, |
|
| 1024 |
points_color = "#FF0000", |
|
| 1025 |
saturate_vectors_by = 0.2, |
|
| 1026 |
point_position_multiplier = 1, |
|
| 1027 | ! |
distance_scaled_by = function(x) { scales::rescale(x, to = c(0.3, 1.5), from = c(0, 2)) },
|
| 1028 |
with_lines = FALSE, |
|
| 1029 |
with_ci = TRUE, |
|
| 1030 | ||
| 1031 | ||
| 1032 |
# parameters pulled from model `x` that can be overridden |
|
| 1033 |
points = NULL |
|
| 1034 |
) {
|
|
| 1035 | ! |
p <- NULL; |
| 1036 | ! |
if(is(x, "plotly")) {
|
| 1037 | ! |
p <- x; |
| 1038 | ! |
x <- attr(x = p, which = "model"); |
| 1039 |
} |
|
| 1040 | ! |
if(is.null(points)) {
|
| 1041 | ! |
points <- x$points; |
| 1042 |
} |
|
| 1043 | ||
| 1044 | ! |
point_dim_cols <- which(rENA::find_dimension_cols(points)); |
| 1045 | ! |
points[,point_dim_cols] <- points[,c(point_dim_cols),with = FALSE] * point_position_multiplier; |
| 1046 | ||
| 1047 | ! |
dimensions <- attr(p, "dimensions"); |
| 1048 | ! |
dim_indices <- which(colnames(as.matrix(points)) %in% dimensions); |
| 1049 | ||
| 1050 | ||
| 1051 | ! |
unit_table <- unit_vectors(points, dims = dim_indices); # * scale_points_by; |
| 1052 | ! |
has_group <- "_GRP" %chin% colnames(unit_table); |
| 1053 | ||
| 1054 | ! |
if(length(unique(points$ENA_DIRECTION)) > 1) {
|
| 1055 | ! |
dim_cols <- paste(rep(dimensions,2), c(rep("from",2), rep("to",2)), sep = ".");
|
| 1056 |
} |
|
| 1057 |
else {
|
|
| 1058 | ! |
dim_cols <- dimensions; |
| 1059 |
} |
|
| 1060 | ! |
if(is.null(mean_value)) {
|
| 1061 |
# dim_cols <- c("SVD1.from", "SVD2.from", "SVD1.to", "SVD2.to");
|
|
| 1062 | ! |
mean_table <- if(has_group) {
|
| 1063 | ! |
unit_table[, lapply(.SD, mean), .SDcols = dim_cols, by = "_GRP"]; |
| 1064 |
} else {
|
|
| 1065 | ! |
unit_table[, lapply(.SD, mean), .SDcols = dim_cols]; |
| 1066 |
} |
|
| 1067 |
} |
|
| 1068 |
else {
|
|
| 1069 | ! |
browser() |
| 1070 | ! |
mean_table <- data.table::data.table( |
| 1071 | ! |
SVD1.from = mean_value[1], |
| 1072 | ! |
SVD2.from = mean_value[2], |
| 1073 | ! |
SVD1.to = mean_value[3], |
| 1074 | ! |
SVD2.to = mean_value[4] |
| 1075 |
) |
|
| 1076 |
} |
|
| 1077 | ||
| 1078 |
# browser() |
|
| 1079 | ||
| 1080 | ! |
if(length(unique(points$ENA_DIRECTION)) > 1) {
|
| 1081 | ! |
mean_table[ , c("slope", "intercept", "center.x", "center.y") := {
|
| 1082 | ! |
l = LearnGeom::CreateLinePoints( |
| 1083 | ! |
as.numeric(.SD[,c(dim_cols[1:2]), with = FALSE]), |
| 1084 | ! |
as.numeric(.SD[,c(dim_cols[3:4]), with = FALSE]) |
| 1085 |
); |
|
| 1086 | ! |
cen = LearnGeom::MidPoint( |
| 1087 | ! |
as.numeric(.SD[, c(dim_cols[1:2]), with = FALSE]), |
| 1088 | ! |
as.numeric(.SD[, c(dim_cols[3:4]), with = FALSE]) |
| 1089 |
); |
|
| 1090 | ! |
list(slope = l[1], intercept = l[2], center.x = cen[1], center.y = cen[2]) |
| 1091 | ! |
}, by = 1:nrow(mean_table)] |
| 1092 |
} |
|
| 1093 | ||
| 1094 | ! |
rgb_cols <- col2rgb(points_color); |
| 1095 | ! |
hsv_cols <- apply(rgb_cols, 2, function(rgb_col) rgb2hsv(rgb_col[1], rgb_col[2], rgb_col[3]) ); |
| 1096 | ||
| 1097 | ! |
if(show_points) {
|
| 1098 | ||
| 1099 | ! |
if(length(unique(points$ENA_DIRECTION)) > 1) {
|
| 1100 | ! |
units_by = if(has_group) c("ENA_UNIT", "_GRP") else c("ENA_UNIT")
|
| 1101 | ! |
if(has_group) {
|
| 1102 | ! |
unit_table[, c("ang_diff", "center.x", "center.y", "color") := {
|
| 1103 | ! |
mt <- mean_table[mean_table$`_GRP` == .BY$`_GRP`,] |
| 1104 | ! |
list( |
| 1105 | ! |
LearnGeom::Angle( |
| 1106 | ! |
as.numeric(mt[, c(dim_cols[3:4]), with = FALSE]), |
| 1107 | ! |
as.numeric(mt[, c(dim_cols[1:2]), with = FALSE]), |
| 1108 | ! |
as.numeric(.SD[1, c(dim_cols[3:4]), with = FALSE]) |
| 1109 |
), |
|
| 1110 | ! |
mt$center.x, |
| 1111 | ! |
mt$center.y, |
| 1112 | ! |
points_color[.BY$`_GRP`] |
| 1113 |
) |
|
| 1114 | ! |
}, by = units_by] |
| 1115 |
} |
|
| 1116 |
else {
|
|
| 1117 | ! |
unit_table[, c("ang_diff", "center.x", "center.y","color") := {
|
| 1118 | ! |
list( |
| 1119 | ! |
LearnGeom::Angle(as.numeric(mean_table[1,3:4, with = FALSE]), as.numeric(mean_table[1,1:2, with = FALSE]), as.numeric(.SD[1,3:4, with = FALSE])), |
| 1120 | ! |
mean_table$center.x, |
| 1121 | ! |
mean_table$center.y, |
| 1122 | ! |
points_color |
| 1123 |
) |
|
| 1124 | ! |
}, by = "ENA_UNIT"]; |
| 1125 |
} |
|
| 1126 | ||
| 1127 | ! |
mean_table[, c("length") := {
|
| 1128 | ! |
LearnGeom::DistancePoints( |
| 1129 | ! |
as.numeric(.SD[, c("center.x", "center.y"), with = FALSE]),
|
| 1130 | ! |
as.numeric(.SD[, c(dim_cols[3:4]), with = FALSE]) |
| 1131 |
) |
|
| 1132 | ! |
}, by = 1:nrow(mean_table)] |
| 1133 |
} |
|
| 1134 |
else {
|
|
| 1135 | ! |
if(has_group) {
|
| 1136 | ! |
warning("Colors should be updated.")
|
| 1137 |
} |
|
| 1138 |
else {
|
|
| 1139 | ! |
unit_table$color = points_color; |
| 1140 |
} |
|
| 1141 |
} |
|
| 1142 | ||
| 1143 | ! |
if(is.function(saturate_vectors_by)) {
|
| 1144 |
# saturate_vectors_by(unit_table$ang_diff, abs(unit_table$distance - mean_length)) |
|
| 1145 | ! |
browser() |
| 1146 | ! |
units_by = if(has_group) c("ENA_UNIT", "_GRP") else c("ENA_UNIT")
|
| 1147 | ! |
unit_table$ang_diff_scaled <- 1 |
| 1148 |
} |
|
| 1149 |
else {
|
|
| 1150 | ! |
unit_table$ang_diff_scaled <- saturate_vectors_by |
| 1151 |
} |
|
| 1152 | ||
| 1153 | ! |
unit_table[, color_adjusted := {
|
| 1154 | ! |
adjusted_color <- lighten_color(.SD$color, alpha = .SD$ang_diff_scaled) |
| 1155 | ! |
grDevices::rgb(adjusted_color[1], adjusted_color[2], adjusted_color[3], maxColorValue = 255) |
| 1156 | ! |
}, by = 1:nrow(unit_table)] |
| 1157 | ||
| 1158 | ! |
unit_points <- NULL; |
| 1159 | ! |
if(units_as_vectors == TRUE) {
|
| 1160 | ! |
data.table::setorder(unit_table, -"distance") |
| 1161 | ||
| 1162 | ! |
if(!is.null(point_shape)) {
|
| 1163 | ! |
p <- plotly::add_markers( |
| 1164 | ! |
p = p, |
| 1165 | ! |
data = unit_table, x = ~center.x, y = ~center.y, |
| 1166 | ! |
marker = list(color = ~color_adjusted, shape = point_shape) |
| 1167 |
); |
|
| 1168 |
} |
|
| 1169 | ||
| 1170 | ! |
arrow_size <- if(dynamic_response_point_size) {
|
| 1171 | ! |
unit_table$distance_scaled <- distance_scaled_by(unit_table$distance); |
| 1172 | ! |
unit_table$distance_scaled |
| 1173 |
} |
|
| 1174 |
else {
|
|
| 1175 | ! |
unit_vector_arrow_size |
| 1176 |
} |
|
| 1177 | ||
| 1178 | ! |
point_towards <- NULL |
| 1179 | ! |
if ( unit_vectors_towards == "ground" ) {
|
| 1180 | ! |
point_towards <- unit_table[, c(dim_cols[1:2]), with = FALSE] |
| 1181 |
} |
|
| 1182 |
else {
|
|
| 1183 | ! |
point_towards <- unit_table[, c(dim_cols[3:4]), with = FALSE] |
| 1184 |
} |
|
| 1185 | ! |
p <- plotly::add_annotations( |
| 1186 | ! |
p = p, |
| 1187 | ! |
data = unit_table, |
| 1188 |
# x = ~SVD1.to, y = ~SVD2.to, |
|
| 1189 | ! |
x = point_towards[[1]], y = point_towards[[2]], |
| 1190 | ! |
arrowsize = arrow_size, |
| 1191 | ! |
arrowwidth = unit_vector_width, |
| 1192 | ! |
xref = "x", yref = "y", |
| 1193 | ! |
axref = "x", ayref = "y", |
| 1194 | ! |
text = "", showarrow = TRUE, |
| 1195 | ! |
ax = ~center.x, ay = ~center.y, |
| 1196 | ! |
arrowcolor = ~color_adjusted |
| 1197 |
); |
|
| 1198 |
} |
|
| 1199 | ||
| 1200 |
# Not arrows |
|
| 1201 |
else {
|
|
| 1202 | ! |
if ( unit_vectors_towards == "ground" ) {
|
| 1203 | ! |
unit_points <- unit_table[, c(dim_cols[1:2]), with = FALSE] |
| 1204 |
} |
|
| 1205 |
else {
|
|
| 1206 | ! |
unit_points <- unit_table[, c(which(colnames(unit_table) %in% dim_cols)), with = FALSE] |
| 1207 |
} |
|
| 1208 | ! |
p <- plotly::add_markers( |
| 1209 | ! |
p = p, |
| 1210 |
# data = unit_table, x = ~SVD1.to, y = ~SVD2.to, |
|
| 1211 | ! |
data = unit_table, x = unit_points[[1]], y = unit_points[[2]], |
| 1212 | ! |
marker = list(color = ~color, shape = point_shape), |
| 1213 | ! |
text = ~ENA_UNIT, |
| 1214 | ! |
hovertemplate = paste('(%{x},%{y})', '<b>%{text}</b>')
|
| 1215 |
) |
|
| 1216 | ! |
if(with_lines == TRUE) {
|
| 1217 | ! |
if ( unit_vectors_towards == "ground" ) {
|
| 1218 | ! |
point_towards_x <- c("center.x", dim_cols[1])
|
| 1219 | ! |
point_towards_y <- c("center.y", dim_cols[2])
|
| 1220 |
} |
|
| 1221 |
else {
|
|
| 1222 | ! |
point_towards_x <- c("center.x", dim_cols[3])
|
| 1223 | ! |
point_towards_y <- c("center.y", dim_cols[4])
|
| 1224 |
} |
|
| 1225 | ! |
for( i in 1:nrow(unit_table) ) {
|
| 1226 | ! |
p <- plotly::add_trace( |
| 1227 | ! |
p = p, |
| 1228 | ! |
type = "scatter", |
| 1229 | ! |
mode = "lines", |
| 1230 | ! |
data = data.frame( |
| 1231 | ! |
X1 = unlist(unit_table[i, c(point_towards_x), with = FALSE]), |
| 1232 | ! |
X2 = unlist(unit_table[i, c(point_towards_y), with = FALSE]), |
| 1233 | ! |
row.names = NULL |
| 1234 |
), |
|
| 1235 | ! |
x = ~X1, y = ~X2, |
| 1236 | ! |
line = list( |
| 1237 | ! |
color = unit_table[i,]$color_adjusted, |
| 1238 | ! |
width = unit_vector_width |
| 1239 |
) |
|
| 1240 |
) |
|
| 1241 |
} |
|
| 1242 |
} |
|
| 1243 |
} |
|
| 1244 |
} |
|
| 1245 | ! |
if(show_mean){
|
| 1246 | ! |
mean_table$color <- points_color; |
| 1247 | ! |
error = list( |
| 1248 | ! |
x = list(color = points_color[1], visible=T, type="data"), |
| 1249 | ! |
y = list(color = points_color[1], visible=T, type="data") |
| 1250 |
); |
|
| 1251 | ! |
int.values = NULL; |
| 1252 | ! |
if(with_ci == TRUE) {
|
| 1253 | ! |
if(has_group) {
|
| 1254 | ! |
int.values <- unit_table[, lapply(.SD, function(x) { t.test(x, conf.level = 0.95)$conf.int }), .SDcols = dim_cols, by = "_GRP"];
|
| 1255 | ||
| 1256 | ! |
error$x$array = unlist(int.values[c(1,3), c(4)]); |
| 1257 | ! |
error$y$array = unlist(int.values[c(2,4), c(5)]); |
| 1258 | ! |
error$x$color = "black"; #points_color; |
| 1259 | ! |
error$y$color = "black"; #points_color; |
| 1260 |
} else {
|
|
| 1261 | ! |
int.values <- matrix( |
| 1262 | ! |
c( |
| 1263 | ! |
as.vector(stats::t.test(points[,point_dim_cols[1],with=FALSE], conf.level = 0.95)$conf.int), |
| 1264 | ! |
as.vector(stats::t.test(points[,point_dim_cols[2],with=FALSE], conf.level = 0.95)$conf.int) |
| 1265 |
), |
|
| 1266 | ! |
ncol=2, byrow = TRUE |
| 1267 |
); |
|
| 1268 |
#error$x$array = int.values[,1] Carl thinks these two lines are not right |
|
| 1269 |
#error$y$array = int.values[,2] |
|
| 1270 | ! |
error$x$array = (int.values[1, 2]-int.values[1, 1])/2 # have to compute radius |
| 1271 | ! |
error$y$array = (int.values[2, 2]-int.values[2, 1])/2 # if you use two numbers, it may just use the first number. |
| 1272 | ||
| 1273 |
} |
|
| 1274 |
} |
|
| 1275 | ||
| 1276 | ! |
if(units_as_vectors == TRUE) {
|
| 1277 | ! |
p <- plotly::add_markers( |
| 1278 | ! |
p = p, |
| 1279 | ! |
data = mean_table, |
| 1280 | ! |
x = mean_table$center.x, |
| 1281 | ! |
y = mean_table$center.y, |
| 1282 | ! |
error_x = error$x, error_y = error$y, |
| 1283 | ! |
marker = list(color = ~color, symbol = "square", size = 10) |
| 1284 |
); |
|
| 1285 |
} |
|
| 1286 |
else {
|
|
| 1287 |
# mean_cols <- dim_cols[seq.int(ifelse(unit_vectors_towards == "ground", 1, 3), length.out = 2)]; |
|
| 1288 | ! |
mean_cols <- colnames(mean_table)[1:2]; #colnames(unit_points); |
| 1289 | ! |
p <- plotly::add_markers( |
| 1290 | ! |
p = p, |
| 1291 | ! |
data = mean_table, |
| 1292 |
# x = mean_table$center.x, |
|
| 1293 |
# y = mean_table$center.y, |
|
| 1294 | ! |
x = mean_table[[mean_cols[1]]], |
| 1295 | ! |
y = mean_table[[mean_cols[2]]], |
| 1296 | ! |
error_x = error$x, error_y = error$y, |
| 1297 | ! |
marker = list(color = ~color, symbol = "square", size = 10) |
| 1298 |
); |
|
| 1299 |
} |
|
| 1300 |
} |
|
| 1301 | ||
| 1302 | ! |
return(p); |
| 1303 |
} |
|
| 1304 | ||
| 1305 |
#' Print ENA plot |
|
| 1306 |
#' |
|
| 1307 |
#' Prints an ENA plotly object, applying any stored shapes and annotations. |
|
| 1308 |
#' |
|
| 1309 |
#' @param x An ENA plot object (class "enaplot"). |
|
| 1310 |
#' @param ... Additional arguments (currently ignored). |
|
| 1311 |
#' |
|
| 1312 |
#' @return Invisibly returns the plotly object after printing. |
|
| 1313 |
#' @export |
|
| 1314 |
'print.enaplot' <- function(x, ...) {
|
|
| 1315 | ! |
class(x) <- c("plotly", "htmlwidget");
|
| 1316 | ||
| 1317 | ! |
shapes <- attr(x = x, which = "shapes"); |
| 1318 | ! |
annotations <- attr(x = x, which = "annotations"); |
| 1319 | ! |
x <- plotly::layout(p = x, shapes = shapes, annotations = annotations); |
| 1320 | ||
| 1321 | ! |
print(x); |
| 1322 |
} |
| 1 |
##' Calculate correlations between SVD and centroid differences in ONA model |
|
| 2 |
##' |
|
| 3 |
##' Computes Pearson and Spearman correlations between pairwise differences of points and centroids along specified dimensions in an Epistemic Network Analysis (ENA) model. |
|
| 4 |
##' |
|
| 5 |
##' @param enaset An ENA set object containing points and model centroids (typically output from ENA model fitting). |
|
| 6 |
##' @param pts Optional data frame of points to use. If NULL, points are selected from `enaset$points` matching the specified direction. |
|
| 7 |
##' @param cts Optional data frame or matrix of centroids to use. If NULL, centroids are taken from `enaset$model$centroids`. |
|
| 8 |
##' @param dims Integer vector specifying which dimensions to use for the correlation (default: c(1,2)). |
|
| 9 |
##' @param direction Character string specifying which direction(s) to include from `enaset$points$ENA_DIRECTION` (default: "response"). |
|
| 10 |
##' |
|
| 11 |
##' @return A data frame with Pearson and Spearman correlations for each specified dimension. |
|
| 12 |
##' @export |
|
| 13 |
correlations <- function(enaset, pts = NULL, cts = NULL, dims = c(1:2), direction = "response") {
|
|
| 14 | ! |
if(is.null(pts) || is.null(cts)) {
|
| 15 |
# Not every ordered set carries an ENA_DIRECTION column -- a model with one |
|
| 16 |
# row per unit has no directions to separate. Check for the column by name |
|
| 17 |
# rather than reading it: filtering on an absent column would drop every |
|
| 18 |
# row, and rENA's `$.ena.points` raises an error rather than returning NULL. |
|
| 19 | ! |
if("ENA_DIRECTION" %in% colnames(enaset$points)) {
|
| 20 | ! |
rows <- enaset$points$ENA_DIRECTION %in% direction |
| 21 |
} else {
|
|
| 22 | ! |
rows <- rep(TRUE, nrow(enaset$points)) |
| 23 |
} |
|
| 24 | ! |
pts <- enaset$points[rows, ] |
| 25 | ! |
cts <- enaset$model$centroids[, ] |
| 26 |
} |
|
| 27 | ||
| 28 | ! |
pComb = combn(nrow(pts), 2) |
| 29 | ! |
point1 = pComb[1,] |
| 30 | ! |
point2 = pComb[2,] |
| 31 | ||
| 32 | ! |
points = as.matrix(pts) |
| 33 | ! |
centroids = as.matrix(cts) |
| 34 | ! |
svdDiff = matrix(points[point1, dims] - points[point2, dims], ncol=length(dims), nrow=length(point1)) |
| 35 | ! |
optDiff = matrix(centroids[point1, dims] - centroids[point2, dims], ncol=length(dims), nrow=length(point1)) |
| 36 | ||
| 37 |
# svdDiff/optDiff have one column per requested dimension, so index them by |
|
| 38 |
# position rather than by the caller's dimension number. Indexing by `dims` |
|
| 39 |
# only works for the default c(1,2); any other pair reads past the end. |
|
| 40 | ! |
corrs = as.data.frame(mapply(function(method) {
|
| 41 | ! |
sapply(seq_along(dims), function(dim) {
|
| 42 | ! |
cor(as.numeric(svdDiff[,dim]), as.numeric(optDiff[,dim]), method=method) |
| 43 |
}); |
|
| 44 | ! |
}, c("pearson","spearman")))
|
| 45 | ||
| 46 | ! |
return(corrs); |
| 47 |
} |
| 1 |
### |
|
| 2 |
#' ona writeup |
|
| 3 |
#' |
|
| 4 |
#' @description provide writeup of the provided model |
|
| 5 |
#' |
|
| 6 |
#' @param enaset ENAset to view methods of |
|
| 7 |
#' @param tool c("rENA","webENA")
|
|
| 8 |
#' @param tool.version as.character(packageVersion(tool)) |
|
| 9 |
#' @param comparison character string representing the comparison used, c(NULL, "parametric", "non-parametric"). Default NULL |
|
| 10 |
#' @param comparison.groups Groups that were used for the comparison |
|
| 11 |
#' @param sig.dig Integer for the number of digits to round to |
|
| 12 |
#' @param output_dir Where to save the output file |
|
| 13 |
#' @param type c("file","stream") File will save to a file in output_dir, Stream returns the contents directly
|
|
| 14 |
#' @param theory Logical indicating whether to include theory in the writeup |
|
| 15 |
#' @param methods Logical indicating whether to include methods in the writeup |
|
| 16 |
#' @param params additional parameters for rmarkdown::render |
|
| 17 |
#' @param output_file character |
|
| 18 |
#' @param output_format character |
|
| 19 |
#' |
|
| 20 |
#' @importFrom utils packageVersion |
|
| 21 |
#' |
|
| 22 |
#' @export |
|
| 23 |
#' |
|
| 24 |
#' @return String representing the methods used to generate the model |
|
| 25 |
ona.writeup <- function( |
|
| 26 |
enaset, |
|
| 27 |
tool = "ona", tool.version = as.character(packageVersion(tool)), |
|
| 28 |
comparison = NULL, comparison.groups = NULL, sig.dig = 2, |
|
| 29 |
output_dir = getwd(), type = c("file","stream"), theory = T, methods = T,
|
|
| 30 |
params = NULL, output_file = NULL, output_format = NULL |
|
| 31 |
) {
|
|
| 32 | ! |
if(is.null(enaset$`_function.params`$weight.by)) |
| 33 | ! |
enaset$`_function.params`$weight.by <- enaset$`_function.params`$args$weight.by |
| 34 | ||
| 35 | ! |
type = match.arg(type, choices = c("file","stream"), several.ok = FALSE)
|
| 36 | ||
| 37 | ! |
if(type == "file") {
|
| 38 | ! |
output_format = "word_document" |
| 39 |
} |
|
| 40 | ||
| 41 | ! |
file = rmarkdown::render(system.file("rmd","methods_ona.rmd", package="ona"), output_dir = output_dir,
|
| 42 | ! |
knit_root_dir = output_dir, intermediates_dir = output_dir, quiet = TRUE, |
| 43 | ! |
params = params, output_file = output_file |
| 44 | ! |
,output_format = output_format |
| 45 |
# ,output_format = ifelse(type == "file", rENA::methods_report, rENA::methods_report_stream) |
|
| 46 |
) |
|
| 47 | ||
| 48 | ! |
if(type == "file") |
| 49 | ! |
file |
| 50 | ! |
else if (type == "stream" && endsWith(file, ".plain")) |
| 51 | ! |
readChar(file, file.info(file)$size) |
| 52 |
} |
|
| 53 | ||
| 54 |
#' @title methods_report |
|
| 55 |
#' @description Output format for methods report in R Markdown (Word/docx) |
|
| 56 |
#' @param toc Logical; include a table of contents (default: FALSE). |
|
| 57 |
#' @param toc_depth Integer; depth of table of contents (default: 3). |
|
| 58 |
#' @param fig_width Numeric; width (in inches) of figures (default: 5). |
|
| 59 |
#' @param fig_height Numeric; height (in inches) of figures (default: 4). |
|
| 60 |
#' @param keep_md Logical; keep the intermediate markdown file (default: FALSE). |
|
| 61 |
#' @param md_extensions Character vector of additional markdown extensions to use (default: NULL). |
|
| 62 |
#' @param pandoc_args Character vector of additional Pandoc command line arguments (default: NULL). |
|
| 63 |
#' |
|
| 64 |
#' @return An R Markdown output format object for use with `rmarkdown::render` (Word/docx output). |
|
| 65 |
#' @export |
|
| 66 |
methods_report <- function(toc = FALSE, |
|
| 67 |
toc_depth = 3, |
|
| 68 |
fig_width = 5, |
|
| 69 |
fig_height = 4, |
|
| 70 |
keep_md = FALSE, |
|
| 71 |
md_extensions = NULL, |
|
| 72 |
pandoc_args = NULL) {
|
|
| 73 | ||
| 74 |
# knitr options and hooks |
|
| 75 | ! |
knitr <- rmarkdown::knitr_options( |
| 76 | ! |
opts_chunk = list(dev = 'png', |
| 77 | ! |
dpi = 96, |
| 78 | ! |
fig.width = fig_width, |
| 79 | ! |
fig.height = fig_height) |
| 80 |
) |
|
| 81 | ||
| 82 |
# build pandoc args |
|
| 83 | ! |
args <- c("--standalone")
|
| 84 | ||
| 85 |
# table of contents |
|
| 86 | ! |
args <- c(args, rmarkdown::pandoc_toc_args(toc, toc_depth)) |
| 87 | ||
| 88 |
# pandoc args |
|
| 89 | ! |
args <- c(args, pandoc_args) |
| 90 | ||
| 91 | ! |
preserved_chunks <- character() |
| 92 | ||
| 93 |
# pre_processor <- function(metadata, input_file, runtime, knit_meta, |
|
| 94 |
# files_dir, output_dir) {
|
|
| 95 |
# preserved_chunks <<- extract_preserve_chunks(input_file, knitr::extract_raw_output) |
|
| 96 |
# NULL |
|
| 97 |
# } |
|
| 98 | ||
| 99 |
# post_processor <- function(metadata, input_file, output_file, clean, verbose) {
|
|
| 100 |
# output_str <- readLines(output_file, encoding = 'UTF-8') |
|
| 101 |
# output_res <- knitr::restore_raw_output(output_str, preserved_chunks) |
|
| 102 |
# if (!identical(output_str, output_res)) |
|
| 103 |
# writeLines(enc2utf8(output_res), output_file, useBytes = TRUE) |
|
| 104 |
# output_file |
|
| 105 |
# } |
|
| 106 | ||
| 107 |
# return output format |
|
| 108 | ! |
rmarkdown::output_format( |
| 109 | ! |
knitr = knitr, |
| 110 | ! |
pandoc = rmarkdown::pandoc_options(to = "docx", |
| 111 | ! |
from = rmarkdown::from_rmarkdown(extensions = md_extensions), |
| 112 | ! |
args = args), |
| 113 | ! |
keep_md = keep_md |
| 114 |
# ,pre_processor = pre_processor, |
|
| 115 |
# post_processor = post_processor |
|
| 116 |
) |
|
| 117 |
} |
|
| 118 | ||
| 119 |
#' @title methods_report_stream |
|
| 120 |
#' @description Output format for methods report in R Markdown (plain text stream) |
|
| 121 |
#' @param toc Logical; include a table of contents (default: FALSE). |
|
| 122 |
#' @param toc_depth Integer; depth of table of contents (default: 3). |
|
| 123 |
#' @param fig_width Numeric; width (in inches) of figures (default: 5). |
|
| 124 |
#' @param fig_height Numeric; height (in inches) of figures (default: 4). |
|
| 125 |
#' @param keep_md Logical; keep the intermediate markdown file (default: FALSE). |
|
| 126 |
#' @param md_extensions Character vector of additional markdown extensions to use (default: NULL). |
|
| 127 |
#' @param pandoc_args Character vector of additional Pandoc command line arguments (default: NULL). |
|
| 128 |
#' |
|
| 129 |
#' @return An R Markdown output format object for use with `rmarkdown::render` (plain text output). |
|
| 130 |
#' @export |
|
| 131 |
methods_report_stream <- function(toc = FALSE, |
|
| 132 |
toc_depth = 3, |
|
| 133 |
fig_width = 5, |
|
| 134 |
fig_height = 4, |
|
| 135 |
keep_md = FALSE, |
|
| 136 |
md_extensions = NULL, |
|
| 137 |
pandoc_args = NULL) {
|
|
| 138 | ||
| 139 |
# knitr options and hooks |
|
| 140 | ! |
knitr <- rmarkdown::knitr_options( |
| 141 | ! |
opts_chunk = list(dev = 'png', |
| 142 | ! |
dpi = 96, |
| 143 | ! |
fig.width = fig_width, |
| 144 | ! |
fig.height = fig_height) |
| 145 |
) |
|
| 146 | ||
| 147 |
# build pandoc args |
|
| 148 | ! |
args <- c("--standalone")
|
| 149 | ||
| 150 |
# table of contents |
|
| 151 | ! |
args <- c(args, rmarkdown::pandoc_toc_args(toc, toc_depth)) |
| 152 | ||
| 153 |
# pandoc args |
|
| 154 | ! |
args <- c(args, pandoc_args) |
| 155 | ||
| 156 | ! |
preserved_chunks <- character() |
| 157 | ||
| 158 |
# return output format |
|
| 159 | ! |
rmarkdown::output_format( |
| 160 | ! |
knitr = knitr, |
| 161 | ! |
pandoc = rmarkdown::pandoc_options(to = "plain", |
| 162 | ! |
from = rmarkdown::from_rmarkdown(extensions = md_extensions), |
| 163 | ! |
args = args), |
| 164 | ! |
keep_md = keep_md |
| 165 |
) |
|
| 166 |
} |
| 1 |
.onLoad <- function(libname, pkgname) {
|
|
| 2 | ! |
utils::globalVariables(c( |
| 3 | ! |
"%chin%",".BY",".I",".SD",":=","ENA_DIRECTION","as.data.table","code","col2rgb", |
| 4 | ! |
"color_adjusted","combn","data.table","distance","hsv","is","label","node_1","node_2", |
| 5 | ! |
"prcomp","rgb2hsv","set","t.test","value","var","variable" |
| 6 |
)) |
|
| 7 |
} |
|
| 8 | ||
| 9 |
.onAttach <- function(libname, pkgname) {
|
|
| 10 | 2x |
packageStartupMessage("For the latest features and updates, install from https://cran.qe-libs.org");
|
| 11 | 2x |
invisible(); |
| 12 |
} |
| 1 |
# R-level wrappers replacing the former C++ exports in src/optim.cpp. |
|
| 2 |
# These preserve backward compatibility for any code calling these functions |
|
| 3 |
# directly as ona::accum_stanza_window(), ona::vector_to_ut(), etc. |
|
| 4 | ||
| 5 |
#' Accumulate Stanza Window (directed, full-square output) |
|
| 6 |
#' |
|
| 7 |
#' For each row, accumulates co-occurrences over a backward stanza window. |
|
| 8 |
#' Preserves directionality: output column (i*n_codes + j) represents |
|
| 9 |
#' code i (context/ground) co-occurring with code j (current row/response). |
|
| 10 |
#' Returns a matrix with \code{n_codes²} columns (full square adjacency).
|
|
| 11 |
#' |
|
| 12 |
#' Delegates to \code{\link[libqe]{accumulate_stanza}(ordered = TRUE)}.
|
|
| 13 |
#' |
|
| 14 |
#' @param df A data frame of code columns (one row per utterance) |
|
| 15 |
#' @param windowSize Number of prior rows in the window (default 1; use |
|
| 16 |
#' \code{Inf} for all prior rows in the stanza)
|
|
| 17 |
#' @param binary Logical; binarise non-zero co-occurrences (default TRUE) |
|
| 18 |
#' @return Numeric matrix with \code{nrow(df)} rows and \code{ncol(df)²} columns
|
|
| 19 |
#' @importFrom libqe accumulate_stanza |
|
| 20 |
#' @export |
|
| 21 |
accum_stanza_window <- function(df, windowSize = 1, binary = TRUE) {
|
|
| 22 | ! |
INT_MAX <- .Machine$integer.max |
| 23 | ! |
wb <- if (is.infinite(windowSize) || windowSize >= INT_MAX) INT_MAX |
| 24 | ! |
else as.integer(windowSize) |
| 25 | ! |
as.data.frame( |
| 26 | ! |
libqe::accumulate_stanza(as.matrix(df), window_back = wb, |
| 27 | ! |
window_forward = 0L, binary = binary, |
| 28 | ! |
ordered = TRUE) |
| 29 |
) |
|
| 30 |
} |
|
| 31 | ||
| 32 |
#' Upper Triangle from Vector (numeric) |
|
| 33 |
#' |
|
| 34 |
#' Compute pairwise products v[i] * v[j] for all i < j. |
|
| 35 |
#' Thin wrapper around \code{\link[rENA]{vector_to_ut}}.
|
|
| 36 |
#' |
|
| 37 |
#' @param v Numeric vector or single-row matrix of code values |
|
| 38 |
#' @return Numeric row vector of pairwise products (length choose_two(length(v))) |
|
| 39 |
#' @export |
|
| 40 |
vector_to_ut <- function(v) {
|
|
| 41 | ! |
rENA::vector_to_ut(v) |
| 42 |
} |
|
| 43 | ||
| 44 |
#' Least-squares node positions for directed ENA |
|
| 45 |
#' |
|
| 46 |
#' Thin wrapper around \code{\link[rENA]{directed_node_positions}}.
|
|
| 47 |
#' |
|
| 48 |
#' @param line_weights Numeric matrix (units x connections) |
|
| 49 |
#' @param points Numeric matrix of rotated points (units x dims) |
|
| 50 |
#' @param numDims Number of dimensions |
|
| 51 |
#' @return List with nodes, centroids, weights, points |
|
| 52 |
#' @export |
|
| 53 |
directed_node_positions <- function(line_weights, points, numDims) {
|
|
| 54 | ! |
rENA::directed_node_positions(line_weights, points, numDims) |
| 55 |
} |
|
| 56 | ||
| 57 |
#' Directed node positions with ground+response rows combined |
|
| 58 |
#' |
|
| 59 |
#' Thin wrapper around |
|
| 60 |
#' \code{\link[rENA]{directed_node_positions_with_ground_response_added}}.
|
|
| 61 |
#' |
|
| 62 |
#' @param line_weights Numeric matrix (units x connections) |
|
| 63 |
#' @param points Numeric matrix of rotated points (units x dims) |
|
| 64 |
#' @param numDims Number of dimensions |
|
| 65 |
#' @return List with nodes, centroids, weights, points |
|
| 66 |
#' @export |
|
| 67 |
directed_node_positions_with_ground_response_added <- function(line_weights, |
|
| 68 |
points, |
|
| 69 |
numDims) {
|
|
| 70 | ! |
rENA::directed_node_positions_with_ground_response_added(line_weights, |
| 71 | ! |
points, numDims) |
| 72 |
} |
| 1 |
to_square <- function(x) {
|
|
| 2 | ! |
n <- sqrt(length(x)) |
| 3 | ||
| 4 | ! |
dim(x) <- c(n, n); |
| 5 | ! |
x |
| 6 |
} |
|
| 7 | ||
| 8 |
#' Re-class vector as ena.co.occurrence |
|
| 9 |
#' |
|
| 10 |
#' @param x Vector to re-class |
|
| 11 |
#' |
|
| 12 |
#' @return re-classed vector |
|
| 13 |
#' @export |
|
| 14 |
as.ena.co.occurrence <- function(x) {
|
|
| 15 | ! |
if(is.factor(x)) {
|
| 16 | ! |
x = as.character(x) |
| 17 |
} |
|
| 18 | ! |
class(x) = c("ena.co.occurrence", class(x))
|
| 19 | ! |
x |
| 20 |
} |
| 1 |
#' Normalize and optimize a directed (ordered) network accumulation |
|
| 2 |
#' |
|
| 3 |
#' Thin wrapper around \code{\link[rENA]{model}} that applies the ONA-specific
|
|
| 4 |
#' defaults: SVD rotation, zero-network exclusion from centering, and |
|
| 5 |
#' center-to-origin post-processing. |
|
| 6 |
#' |
|
| 7 |
#' @param x An \code{ena.ordered.set} produced by
|
|
| 8 |
#' \code{\link[rENA]{accumulate}(ordered = TRUE)} or
|
|
| 9 |
#' \code{tma::accumulate_contexts}.
|
|
| 10 |
#' @param ... Additional arguments forwarded to \code{rENA::model}.
|
|
| 11 |
#' @param rotate.using Character. \code{"svd"} (default) for standard principal
|
|
| 12 |
#' components rotation; \code{"mean"} for means rotation.
|
|
| 13 |
#' @param rotation.params Additional parameters for the rotation function |
|
| 14 |
#' (passed as \code{rotate_params} to \code{rENA::model}).
|
|
| 15 |
#' @param rotation.set Optional pre-computed \code{ENARotationSet}. When
|
|
| 16 |
#' supplied the rotation step is skipped and this set is used directly. |
|
| 17 |
#' @param center_to_origin Logical. When \code{TRUE} (default) the projected
|
|
| 18 |
#' space is translated so the mean of all points is at the origin. |
|
| 19 |
#' |
|
| 20 |
#' @return An \code{ena.ordered.set} with calculated points and node positions.
|
|
| 21 |
#' @export |
|
| 22 |
model <- function( |
|
| 23 |
x, ..., |
|
| 24 |
rotate.using = "svd", |
|
| 25 |
rotation.params = NULL, |
|
| 26 |
rotation.set = NULL, |
|
| 27 |
center_to_origin = TRUE |
|
| 28 |
) {
|
|
| 29 | 1x |
rotate_fun <- if (rotate.using == "mean") {
|
| 30 | ! |
rENA::ena.rotate.by.mean |
| 31 |
} else {
|
|
| 32 | 1x |
rENA::ena.rotate.by.svd |
| 33 |
} |
|
| 34 | ||
| 35 | 1x |
rotate_params <- if (!is.null(rotation.params)) rotation.params else list() |
| 36 | ||
| 37 | 1x |
if (!is.null(rotation.set)) {
|
| 38 |
# Custom rotation: normalise + centre, then apply the supplied rotation set |
|
| 39 |
# directly (skipping the rotation step) before projecting and optimising. |
|
| 40 | ! |
x <- rENA::sphere_norm(x) |
| 41 | ! |
x <- rENA::center(x, exclude_zero_networks = TRUE) |
| 42 | ||
| 43 | ! |
if (!is(rotation.set, "ena.rotation.set")) {
|
| 44 | ! |
stop("Supplied rotation.set is not an instance of ENARotationSet")
|
| 45 |
} |
|
| 46 | ! |
x$rotation.matrix <- rotation.set$rotation.matrix |
| 47 | ! |
x$rotation$rotation.matrix <- rotation.set$rotation.matrix |
| 48 | ! |
x$rotation$nodes <- rotation.set$nodes |
| 49 | ! |
x$rotation$eigenvalues <- rotation.set$eigenvalues |
| 50 | ||
| 51 | ! |
x <- rENA::project(x) |
| 52 | ! |
x <- rENA::optimize(x) |
| 53 |
} else {
|
|
| 54 | 1x |
x <- rENA::model( |
| 55 | 1x |
x, ..., |
| 56 | 1x |
rotate_fun = rotate_fun, |
| 57 | 1x |
rotate_params = rotate_params, |
| 58 | 1x |
exclude_zero_networks = TRUE, |
| 59 | 1x |
center_to_origin = center_to_origin |
| 60 |
) |
|
| 61 |
} |
|
| 62 | ||
| 63 | 1x |
return(x) |
| 64 |
} |
| 1 |
#' Calculate node positions for a directed ena model |
|
| 2 |
#' |
|
| 3 |
#' @param set ena model |
|
| 4 |
#' @param filter_rows logical indicating rows from model points to use |
|
| 5 |
#' |
|
| 6 |
#' @return list with matrix of node.positions and centroids |
|
| 7 |
#' |
|
| 8 |
#' @export |
|
| 9 |
directed_node_optimization <- function(set, filter_rows = rep(TRUE, nrow(set$model$points.for.projection))) {
|
|
| 10 |
# stop("Node optimization isn't implemented yet.")
|
|
| 11 | ||
| 12 | ! |
points = as.matrix(set$points)[filter_rows, ]; |
| 13 | ! |
weights = as.matrix(set$line.weights)[filter_rows, ]; |
| 14 |
# positions = directed_node_positions(weights, points, ncol(points)); |
|
| 15 |
# positions = directed_node_positions_with_ground_response_added(weights, points, ncol(points)); |
|
| 16 | ! |
if (length(unique(set$points[filter_rows,]$ENA_DIRECTION)) == 2) {
|
| 17 | ! |
positions = directed_node_positions_with_ground_response_added(weights, points, ncol(points)); |
| 18 |
} |
|
| 19 |
else {
|
|
| 20 | ! |
positions = directed_node_positions(weights, points, ncol(points)); |
| 21 |
} |
|
| 22 | ||
| 23 | ! |
node.positions = positions$nodes; |
| 24 | ! |
rownames(node.positions) = set$enadata$codes; |
| 25 | ||
| 26 | ! |
return(list("node.positions" = node.positions, "centroids" = positions$centroids))
|
| 27 |
} |
| 1 |
### |
|
| 2 |
#' ONA rotation by mean difference |
|
| 3 |
#' |
|
| 4 |
#' Computes a dimensional reduction (rotation) such that the first dimension |
|
| 5 |
#' passes through the means of two groups. Subsequent dimensions use SVD on |
|
| 6 |
#' the deflated data. Thin wrapper around \code{\link[rENA]{ena.rotate.by.mean}};
|
|
| 7 |
#' kept for backward compatibility with existing ONA scripts. |
|
| 8 |
#' |
|
| 9 |
#' @param x A matrix or \code{ena.points} data table of ENA points
|
|
| 10 |
#' (typically centered and normalized). Metadata columns are stripped |
|
| 11 |
#' automatically via \code{as.matrix}.
|
|
| 12 |
#' @param groups A list of length 2 (or more), each element being a length-2 |
|
| 13 |
#' list \code{list(a, b)} where \code{a} and \code{b} are logical vectors or
|
|
| 14 |
#' character unit IDs identifying the two groups. |
|
| 15 |
#' @param codes Character vector of code names corresponding to columns of |
|
| 16 |
#' \code{x}; used to label the rows of the returned rotation matrix.
|
|
| 17 |
#' |
|
| 18 |
#' @return A list with \code{rotation}, \code{codes}, \code{eigenvalues}, and
|
|
| 19 |
#' \code{node.positions = NULL}.
|
|
| 20 |
#' @export |
|
| 21 |
### |
|
| 22 |
ona.rotate.by.mean <- function(x, groups, codes) {
|
|
| 23 |
# Construct a minimal enaset-compatible list so we can delegate to |
|
| 24 |
# rENA::ena.rotate.by.mean which now calls libqe::means_rotation internally. |
|
| 25 | ! |
data_matrix <- as.matrix(x) # as.matrix.ena.matrix strips metadata columns |
| 26 | ! |
enaset <- list( |
| 27 | ! |
model = list(points.for.projection = data_matrix), |
| 28 | ! |
points.normed.centered = NULL, |
| 29 | ! |
connection.counts = list(ENA_UNIT = x$ENA_UNIT), |
| 30 | ! |
line.weights = data_matrix, |
| 31 | ! |
rotation = list(codes = codes) |
| 32 |
) |
|
| 33 | ! |
rENA::ena.rotate.by.mean(enaset, groups = groups) |
| 34 |
} |