content
stringlengths
0
14.9M
filename
stringlengths
44
136
condorcet <- function(votes, runoff = FALSE, fsep = '\t', quiet = FALSE, ...) { compare.two.candidates <- function(v1, v2) { i.wins <- sum(v1 < v2) j.wins <- sum(v1 > v2) c(i.wins > j.wins, i.wins < j.wins) } compute.wins <- function(dat, ncan, cnam){ p <- matrix(0, ncan, ncan, dimnames = list(cnam, cnam)) for(i in 1:(ncan-1)){ for(j in ((i+1):ncan)){ pair.run <- compare.two.candidates(dat[,i], dat[,j]) p[i,j] <- pair.run[1] p[j,i] <- pair.run[2] } } p } votes <- prepare.votes(votes, fsep=fsep) nc <- ncol(votes) cnames <- colnames(votes) corvotes <- correct.ranking(votes, quiet = quiet) x <- check.votes(corvotes, "condorcet", quiet = quiet) corrected <- which(rowSums(corvotes != votes) > 0 & rownames(votes) %in% rownames(x)) corrected.votes <- NULL if(length(corrected) > 0) corrected.votes <- list(original = votes[corrected,], new = corvotes[corrected, ], index = as.numeric(corrected)) check.nseats(1, ncol(x)) x2 <- x x2[x2 == 0] <- max(x2) + 1 # give not-ranked candidates the worst ranking points <- compute.wins(x2, nc, cnames) cdc.winner <- apply(points, 1, function(p) sum(p) == nc-1) cdc.loser <- apply(points, 2, function(p) sum(p) == nc-1) runoff.winner <- ro.part <- ro.part.first <- NULL if(sum(cdc.winner) == 0 && runoff) { # run-off nwins <- rowSums(points) winner.exists <- FALSE cand.names <- cnames ncro <- nc while(!winner.exists) { most.wins <- nwins == max(nwins) if(sum(most.wins) < 2) # second most wins most.wins <- (most.wins | nwins == max(nwins[nwins < max(nwins)])) & nwins > 0 ro.part <- cand.names[most.wins] if(is.null(ro.part.first)) ro.part.first <- ro.part # keep the list of the original run-off participants if(length(ro.part) == ncro || length(ro.part) <= 1) { # run-off must have less candidates than the original set if(length(ro.part) == 1) runoff.winner <- ro.part # only one run-off participant break } if(sum(most.wins) == 2) { # run-off between two candidates pair.run <- compare.two.candidates(x2[,which(most.wins)[1]], x2[,which(most.wins)[2]]) runoff.winner <- cand.names[which(most.wins)[which(pair.run == TRUE)]] } else { # run-off between more than two candidates x3 <- x2[, most.wins] p.runoff <- compute.wins(x3, ncol(x3), colnames(x3)) runoff.winner <- colnames(x3)[apply(p.runoff, 1, function(p) sum(p) == ncol(x3)-1)] } if(length(runoff.winner) > 0) { winner.exists <- TRUE break } if(sum(most.wins) == 2) break nwins <- rowSums(p.runoff) x2 <- x3 cand.names <- colnames(x2) ncro <- ncol(x2) } } result <- structure(list(elected = if(sum(cdc.winner) > 0) cnames[which(cdc.winner)] else NULL, totals = points, data = x, invalid.votes = votes[setdiff(rownames(votes), rownames(x)),, drop = FALSE], corrected.votes = corrected.votes, loser = if(sum(cdc.loser) > 0) cnames[which(cdc.loser)] else NULL, runoff.winner = if(length(runoff.winner) > 0) runoff.winner else NULL, runoff.participants = ro.part.first), class="vote.condorcet") if(!quiet) print(summary(result)) invisible(result) } summary.vote.condorcet <- function(object, ...) { df <- data.frame(object$totals, stringsAsFactors=FALSE) df$Total <- rowSums(object$totals) attr(df, "align") <- rep("r", ncol(df)) if(!is.null(object$elected)) { df$Winner <- rep("", nrow(df)) df[object$elected, "Winner"] <- "x" attr(df, "align") <- c(attr(df, "align"), "c") } if(!is.null(object$loser)) { df$Loser <- rep("", nrow(df)) df[object$loser, "Loser"] <- "x" attr(df, "align") <- c(attr(df, "align"), "c") } if(!is.null(object$runoff.participants)) { df$Runoff <- rep("", nrow(df)) df[setdiff(object$runoff.participants, object$runoff.winner), "Runoff"] <- "o" if(!is.null(object$runoff.winner)) df[object$runoff.winner, "Runoff"] <- "x" attr(df, "align") <- c(attr(df, "align"), "c") } attr(df, "number.of.votes") <- nrow(object$data) attr(df, "number.of.invalid.votes") <- nrow(object$invalid.votes) attr(df, "number.of.candidates") <- nrow(object$totals) attr(df, "number.of.seats") <- length(object$elected) attr(df, "condorcet.winner") <- object$elected attr(df, "condorcet.loser") <- object$loser attr(df, "runoff.winner") <- object$runoff.winner attr(df, "runoff.participants") <- object$runoff.participants class(df) <- c('summary.vote.condorcet', class(df)) return(df) } print.summary.vote.condorcet <- function(x, ...) { cat("\nResults of Condorcet voting") cat("\n===========================") election.info(x) print(kable(x, align = attr(x, "align"), ...)) if(is.null(attr(x, "condorcet.winner"))) cat("\nThere is no condorcet winner (no candidate won over all other candidates).") else cat("\nCondorcet winner:", attr(x, "condorcet.winner")) if(is.null(attr(x, "condorcet.loser"))) cat("\nThere is no condorcet loser (no candidate lost to all other candidates).") else cat("\nCondorcet loser:", attr(x, "condorcet.loser")) if(!is.null(attr(x, "runoff.winner"))) cat("\nRun-off winner:", attr(x, "runoff.winner")) cat("\n\n") } view.vote.condorcet <- function(object, ...) view.vote.approval(object, ...) image.vote.condorcet <- function(x, ...) image.vote.stv(x, ...)
/scratch/gouwar.j/cran-all/cranData/vote/R/condorcet.R
count.votes <- function(votes, method=c("auto", "plurality", "approval", "stv", "score", "condorcet", "tworound.runoff"), fsep='\t', ...) { # Main function for counting votes. # If method is "auto" it determines the right method depending on the # number of valid records. x <- prepare.votes(votes, fsep=fsep) method <- match.arg(method) if(method == "auto") { # extract method names from the method argument all.methods <- eval(formals()[["method"]])[-1] # count valid records for all methods valid <- rep(0, length(all.methods)) names(valid) <- all.methods for (meth in all.methods) { assembly.fun <- paste0("assemble.args.for.check.", meth) args <- if(exists(assembly.fun)) do.call(assembly.fun, list(x, ...)) else list() valid[meth] <- sum(do.call(is.valid.vote, c(list(x, method=meth), args))) } method <- names(valid)[which.max(valid)] } return(do.call(method, list(x, ...))) } invalid.votes <- function(object) { return(object$invalid.votes) } valid.votes <- function(object) { return(object$data) } corrected.votes <- function(object) { return(object$corrected.votes) }
/scratch/gouwar.j/cran-all/cranData/vote/R/count_votes.R
stv <- function(votes, nseats = NULL, eps = 0.001, equal.ranking = FALSE, fsep = '\t', ties = c("f", "b"), constant.quota = FALSE, quota.hare = FALSE, group.nseats = NULL, group.members = NULL, complete.ranking = FALSE, invalid.partial = FALSE, impute.missing = FALSE, verbose = FALSE, seed = 1234, quiet = FALSE, digits = 3, ...) { ################################### # Single transferable vote. # Adopted from Bernard Silverman's code. # The argument votes (matrix or data frame) contains the votes themselves. # Row i of the matrix contains the preferences of voter i # numbered 1, 2, .., r, 0,0,0,0, in some order # The columns of the matrix correspond to the candidates. # The dimnames of the columns are the names of the candidates; if these # are not supplied then the candidates are lettered A, B, C, ... # # If votes is a character string it is interpreted as a file name from which the # votes are to be read. A tab delimited file produced by excel # will be in the right format, with the candidate names in the first row. # # The argument nseats is number of candidates to be elected. # # If nseats is not supplied it will be assumed that the number of candidates # to be elected is half the number of candidates standing. # # If verbose=T, the progress of the count will be printed # The quiet argument if set to TRUE, it shuts all outputs off. # # The program was written by Bernard Silverman for the IMS in August 2002 # # Equal ranking added November 2020. ################################## if(verbose && !quiet) { cat("\nSingle transferable vote count") if(equal.ranking) cat(" with equal preferences") cat("\n===================================") if(equal.ranking) cat("==================") cat("\n") } # Prepare by finding names of candidates and setting up # vector w of vote weights and list of elected candidates votes <- prepare.votes(votes, fsep=fsep) nc <- ncol(votes) cnames <- colnames(votes) nseats <- check.nseats(nseats, nc, default=floor(nc/2), ...) # check groups (if used) use.marking <- FALSE if(!is.null(group.nseats)) { # number of candidates to be elected from a group if(is.null(group.members)) stop("If group.nseats is given, argument group.members must be used to mark members of the group.") if(group.nseats > nseats) { warning("group.nseats must be <= nseats. Adjusting group.nseats to ", nseats, ".") group.nseats <- nseats } if(length(group.members) < group.nseats) { warning("There are less group members than group.nseats. Adjusting group.nseats to ", length(group.members), ".") group.nseats <- length(group.members) } if(!is.numeric(group.members)) { # convert names to indices gind <- match(group.members, cnames) if(any(is.na(gind))) { warning("Group member(s) ", paste(group.members[is.na(gind)], collapse = ", "), " not found in the set of candidates, therefore removed from the group.") gind <- gind[!is.na(gind)] } group.members <- gind } # now group memebers are given as indices group.members <- unique(group.members[group.members <= nc & group.members > 0]) use.marking <- TRUE } else{ group.nseats <- 0 group.members <- c() } elected <- NULL # # The next step is to remove invalid votes. A vote is invalid if # the preferences are not numbered in consecutively increasing order. # A warning is printed out for each invalid vote, but the votes are # not counted. If necessary, it is possible to correct errors in the # original x matrix. # If x is generated from an excel spreadsheet, then the jth vote will # be in row (j-1) of the spreadsheet. # if(verbose && !quiet) cat("Number of votes cast is", nrow(votes), "\n") corvotes <- votes corrected.votes <- NULL if(impute.missing){ to.impute <- votes == -1 corvotes[to.impute] <- 0 } if(equal.ranking) corvotes <- correct.ranking(corvotes, partial = FALSE, quiet = quiet) else { if(invalid.partial) corvotes <- correct.ranking(corvotes, partial = TRUE, quiet = quiet) } if(impute.missing && any(to.impute)){ corvotes[to.impute] <- -1 corvotes <- impute.ranking(corvotes, equal.ranking = equal.ranking, quiet = quiet) imputed <- votes imputed[] <- NA imputed[to.impute] <- corvotes[to.impute] if(equal.ranking) # rerun the correction in case something got shifted out of range corvotes <- correct.ranking(corvotes, partial = FALSE, quiet = TRUE) } x <- check.votes(corvotes, "stv", equal.ranking = equal.ranking, quiet = quiet) corrected <- which(rowSums(corvotes != votes) > 0 & rownames(votes) %in% rownames(x)) if(length(corrected) > 0) { corrected.votes <- list(original = votes[corrected,]) if(impute.missing && any(to.impute)) corrected.votes$imputed <- imputed[corrected,] corrected.votes <- c(corrected.votes, list(new = corvotes[corrected, ], index = as.numeric(corrected))) } nvotes <- nrow(x) if(is.null(nvotes) || nvotes == 0) stop("There must be more than one valid ballot to run STV.") w <- rep(1, nvotes) # Create elimination ranking tie.method <- match.arg(ties) tie.method.name <- c(f = "forwards", b = "backwards") otb <- ordered.tiebreak(x, seed) if(use.marking) { if(verbose && !quiet) { cat("Number of reserved seats is", group.nseats, "\n") cat("Eligible for reserved seats:", paste(cnames[group.members], collapse = ", "), "\n") } group.nseats.orig <- group.nseats } # initialize results result.pref <- result.elect <- matrix(NA, ncol=nc, nrow=0, dimnames=list(NULL, cnames)) result.quota <- result.ties <- c() orig.x <- x # # the main loop # if(verbose && !quiet) cat("\nList of 1st preferences in STV counts: \n") count <- 0 while(nseats > 0) { # # calculate quota and total first preference votes # count <- count + 1 A <- (x == 1)/rowSums(x == 1) # splits 1st votes if there are more than one first ranking per vote A[is.na(A)] <- 0 uij <- w * A vcast <- apply(uij, 2, sum) names(vcast) <- cnames if(!constant.quota || count == 1) # Quota calculation via either Hare (quota.hare is TRUE) or Droop (FALSE) method quota <- if(quota.hare) sum(vcast)/nseats + eps else sum(vcast)/(nseats + 1) + eps result.quota <- c(result.quota, quota) result.pref <- rbind(result.pref, vcast) result.elect <- rbind(result.elect, rep(0,nc)) tie <- 0 if(verbose && !quiet) { cat("\nCount:" , count, "\n") df <- data.frame(QUOTA=round(quota, 3), t(round(vcast[vcast != 0], 3))) rownames(df) <- count print(df) } # if leading candidate exceeds quota, declare elected and adjust weights # mark candidate for elimination in subsequent counting # # if the number of remaining candidates is smaller equal the number of seats, # then select the one with the largest vcast, no matter if quota is exceeded # vmax <- max(vcast) ic <- (1:nc)[vcast == vmax] D <- colSums(abs(result.elect)) == 0 # set of hopeful candidates if(use.marking){ Dm <- D Dm[-group.members] <- FALSE # set of hopeful marked candidates } if((vmax >= quota && !(! any(ic %in% group.members) && nseats == group.nseats) || (constant.quota && sum(D) <= nseats)) || # with constant.quota elected candidates may not need to reach quota (use.marking && any(ic %in% group.members) && (sum(Dm) <= group.nseats || sum(D) - sum(Dm) == 0))) { if(use.marking && length(ic) > 1 && sum(Dm) <= group.nseats) # if a tiebreak, choose marked candidates if needed ic <- ic[ic %in% group.members] if(length(ic) > 1) {# tie ic <- solve.tiebreak(tie.method, result.pref, ic, otb, elim = FALSE) tie <- 1 tie <- tie + (attr(ic, "ordered") == TRUE) tie <- tie + (attr(ic, "sampled") == TRUE) } surplus <- if(vmax > quota) (vmax - quota)/vmax else 0 index <- (x[, ic] == 1) # ballots where ic has the first preference w[index] <- uij[index, ic] * surplus # update weights if(equal.ranking) w[index] <- w[index] + rowSums(uij[index, , drop = FALSE]) - uij[index, ic] # reduce number of seats available nseats <- nseats - 1 if(use.marking && ic %in% group.members) group.nseats <- group.nseats - 1 elected <- c(elected, cnames[ic]) result.elect[count,ic] <- 1 if(verbose && !quiet) { cat("Candidate", cnames[ic], "elected ") if(tie > 0) { cat("using", tie.method.name[tie.method]) if(tie == 2) cat(" & ordered") cat(" tie-breaking method ") if(tie > 2) cat("(sampled)") } cat("\n") } } else { # if no candidate reaches quota, mark lowest candidate for elimination elim.select <- D if(use.marking && (nseats == group.nseats || sum(Dm) <= group.nseats)) elim.select <- elim.select & !Dm vmin <- min(vcast[elim.select]) ic <- (1:nc)[vcast == vmin & elim.select] if(length(ic) > 1) {# tie ic <- solve.tiebreak(tie.method, result.pref, ic, otb, elim = TRUE) tie <- 1 tie <- tie + (attr(ic, "ordered") == TRUE) tie <- tie + (attr(ic, "sampled") == TRUE) } result.elect[count,ic] <- -1 if(verbose && !quiet) { cat("Candidate", cnames[ic], "eliminated ") if(tie > 0) { cat("using", tie.method.name[tie.method]) if(tie == 2) cat(" & ordered") cat(" tie-breaking method ") if(tie > 2) cat("(sampled)") } cat("\n") } } result.ties <- c(result.ties, tie) # shift votes for voters who voted for ic jp <- x[, ic] for(i in which(jp > 0)) { index <- x[i, ] > jp[i] x[i, index] <- x[i, index] - 1 } x[, ic] <- 0 } rownames(result.pref) <- 1:count result <- structure(list(elected = elected, preferences = result.pref, quotas = result.quota, elect.elim = result.elect, equal.pref.allowed = equal.ranking, ties = translate.ties(result.ties, tie.method), data = orig.x, invalid.votes = votes[setdiff(rownames(votes), rownames(x)),,drop = FALSE], corrected.votes = corrected.votes, reserved.seats = if(use.marking) group.nseats.orig else NULL, group.members = if(use.marking) group.members else NULL), class = "vote.stv") if(!quiet) print(summary(result, complete.ranking = complete.ranking, digits = digits)) invisible(result) } translate.ties <- function(ties, method){ ties.char <- ifelse(ties == 0, "", method) ties.char <- ifelse(ties > 1, paste0(ties.char, "o"), ties.char) ties.char <- ifelse(ties > 2, paste0(ties.char, "s"), ties.char) names(ties.char) <- 1:length(ties) return(ties.char) } solve.tiebreak <- function(method, prefs, icans, ordered.ranking = NULL, elim = TRUE){ if(method == "f") # forwards ic <- forwards.tiebreak(prefs, icans, elim = elim) else { # backwards ic <- backwards.tiebreak(prefs, icans, elim = elim) } # solve remaining ties by ordered ranking sampled <- FALSE ordered <- FALSE if(length(ic) > 1) { ic <- ic[if(elim) which.min(ordered.ranking[ic]) else which.max(ordered.ranking[ic])] sampled <- attr(ordered.ranking, "sampled")[ic] ordered <- TRUE } attr(ic, "sampled") <- sampled attr(ic, "ordered") <- ordered return(ic) } ordered.preferences <- function(vmat) { sapply(1:ncol(vmat), function(pref) apply(vmat, 2, function(f) sum(f == pref))) } ordered.tiebreak <- function(vmat, seed = NULL) { # Create elimination ranking using ordered tie-breaking # element ij in matrix nij is the number of j-th preferences # for candidate i nij <- ordered.preferences(vmat) # ranking for each preference nij.ranking <- apply(nij, 2, rank, ties.method="min") rnk <- nij.ranking[,1] dpl <- duplicated(rnk) | duplicated(rnk, fromLast = TRUE) sampled <- rep(FALSE, length(rnk)) # resolve ranking duplicates by moving to the next column if(any(dpl)) { if(!is.null(seed)) set.seed(seed) for(pref in 1:ncol(vmat)) { if(! pref %in% rnk[dpl]) next j <- 2 rnk[rnk == pref] <- NA while(any(is.na(rnk))) { # which candidates to resolve in.game <- is.na(rnk) # if we moved across all columns and there are # still duplicates, determine the rank randomly if(j > ncol(nij)) { rnk[in.game] <- sample(sum(in.game)) + pref - 1 sampled <- sampled | in.game break } rnk[in.game] <- rank(nij.ranking[in.game, j], ties.method="min") + pref - 1 dplj <- rnk == pref & (duplicated(rnk) | duplicated(rnk, fromLast = TRUE)) rnk[dplj] <- NA j <- j + 1 } } } attr(rnk, "sampled") <- sampled return(rnk) } forwards.tiebreak <- function(prefs, icans, elim = TRUE) { if(!elim) prefs <- -prefs if(is.null(dim(prefs))) dim(prefs) <- c(1, length(prefs)) rnk <- t(apply(prefs, 1, rank, ties.method="min")) if(is.null(dim(rnk))) dim(rnk) <- c(1, length(rnk)) i <- 0 icv <- rep(FALSE, ncol(prefs)) icv[icans] <- TRUE while(i < nrow(rnk) && length(icans) > 1){ i <- i + 1 ic.rnk <- rnk[i, icans] icans <- which(icv & (rnk[i, ] == min(ic.rnk))) } return(icans) } backwards.tiebreak <- function(prefs, icans, elim = TRUE) { if(!elim) prefs <- -prefs if(is.null(dim(prefs))) dim(prefs) <- c(1, length(prefs)) rnk <- t(apply(prefs, 1, rank, ties.method="min")) if(is.null(dim(rnk))) dim(rnk) <- c(1, length(rnk)) i <- nrow(rnk) icv <- rep(FALSE, ncol(prefs)) icv[icans] <- TRUE while(i > 1 && length(icans) > 1){ i <- i - 1 ic.rnk <- rnk[i, icans] icans <- which(icv & (rnk[i, ] == min(ic.rnk))) } return(icans) } summary.vote.stv <- function(object, ..., complete.ranking = FALSE, digits = 3) { decimalplaces <- function(x) { ifelse(abs(x - round(x)) > .Machine$double.eps^0.5, nchar(sub('^\\d+\\.', '', sub('0+$', '', as.character(x)))), 0) } ncounts <- nrow(object$preferences) df <- data.frame(matrix(NA, nrow=ncol(object$preferences)+4, ncol=2*ncounts-1), stringsAsFactors = FALSE) rownames(df) <- c("Quota", colnames(object$preferences), "Tie-breaks", "Elected", "Eliminated") colnames(df)[1] <- 1 idxcols <- 1 if(ncounts > 1) { colnames(df)[2:ncol(df)] <- paste0(rep(2:ncounts, each=2), c("-trans", "")) idxcols <- c(idxcols, seq(3,ncol(df), by=2)) } df["Quota", idxcols] <- object$quotas df[2:(nrow(df)-3), idxcols] <- t(object$preferences) # calculate transfers pref <- object$preferences # remove quotas for winners and compute difference where.winner <- which(rowSums(object$elect.elim==1)==1) pref[where.winner,] <- pref[where.winner,] - object$elect.elim[where.winner,]*object$quotas[where.winner] if(ncounts > 1) { tmp <- t(object$preferences[2:nrow(object$preferences),] - pref[1:(nrow(pref)-1),]) if(nrow(tmp) == 1) tmp <- as.numeric(tmp) # because of R weirdness with vectors and matrices (when there are just two counts) df[2:(nrow(df)-3), seq(2,ncol(df), by=2)] <- tmp } # format the right number of digits df[1:(nrow(df)-3),] <- apply(df[1:(nrow(df)-3),, drop = FALSE], 2, function(d) ifelse(!is.na(d), format(round(d, digits), nsmall = min(digits, max(decimalplaces(round(d[!is.na(d)], digits))))), "")) where.elim <- which(rowSums(object$elect.elim==-1)==1) cnames <- colnames(object$elect.elim) for(i in 1:ncounts) { if (i %in% where.winner) { elected <- cnames[which(object$elect.elim[i,]==1)] df["Elected", idxcols[i]] <- paste(elected, collapse=", ") for(can in elected) { if(idxcols[i]+2 <= ncol(df)) df[can, (idxcols[i]+2):ncol(df)] <- NA } } if (i %in% where.elim) { eliminated <-cnames[which(object$elect.elim[i,]==-1)] df["Eliminated", idxcols[i]] <- paste(eliminated, collapse=", ") for(can in eliminated) { if(idxcols[i]+2 <= ncol(df)) df[can, (idxcols[i]+2):ncol(df)] <- NA } } } if(any(object$ties != "")) df["Tie-breaks", seq(1, ncol(df), by = 2)] <- object$ties else df <- df[-which(rownames(df) == "Tie-breaks"),, drop = FALSE] if(!is.null(object$reserved.seats)) rownames(df)[object$group.members + 1] <- paste0(rownames(df)[object$group.members + 1], "*") df[is.na(df)] <- "" class(df) <- c('summary.vote.stv', class(df)) attr(df, "number.of.votes") <- nrow(object$data) attr(df, "number.of.invalid.votes") <- nrow(object$invalid.votes) attr(df, "number.of.candidates") <- ncol(object$preferences) attr(df, "number.of.seats") <- length(object$elected) if(!is.null(object$reserved.seats)) { attr(df, "reserved.seats") <- object$reserved.seats attr(df, "reservation.eligible") <- object$group.members } attr(df, "equal.pref.allowed") <- object$equal.pref.allowed if(complete.ranking) attr(df, "complete.ranking") <- complete.ranking(object) return(df) } print.summary.vote.stv <- function(x, ...) { cat("\nResults of Single transferable vote") if(attr(x, "equal.pref.allowed")) cat(" with equal preferences") cat("\n===================================") if(attr(x, "equal.pref.allowed")) cat("=======================") election.info(x) if(!is.null(attr(x, "reserved.seats"))){ cat("Number of reserved seats:\t", attr(x, "reserved.seats"), "\n") cat("Eligible for reserved seats:\t", length(attr(x, "reservation.eligible")), "\n") } print(kable(x, align='r', ...)) if(!is.null(attr(x, "complete.ranking"))) { cat("\nComplete Ranking") cat("\n================") print(kable(attr(x, "complete.ranking"), align = c("r", "l", "c"))) } cat("\nElected:", paste(x['Elected', x['Elected',] != ""], collapse=", "), "\n\n") } "view" <- function(object, ...) UseMethod("view") view.vote.stv <- function(object, ...) { s <- summary(object) formatter <- list(area(row=2:(nrow(s)-2), col=seq(1,ncol(s), by=2)) ~ color_text("red", "red"), area(row=1, col=seq(1,ncol(s), by=2)) ~ color_text("blue", "blue") #Quota=color_text("blue", "blue") ) formattable(s, formatter, ...) } image.vote.stv <- function(x, xpref = 2, ypref = 1, all.pref = FALSE, proportion = TRUE, ...) { voter <- rank <- NULL # to avoid warnings of the CRAN check xd <- x$data nc <- ncol(xd) if(all.pref) { nij <- ordered.preferences(xd)[nc:1,] image.plot(x = 1:nc, y = 1:nc, t(nij), axes = FALSE, xlab = "", ylab = "", col = hcl.colors(12, "YlOrRd", rev = TRUE), ...) axis(3, at = 1:nc, labels = 1:nc) axis(2, at = 1:nc, labels = rev(colnames(xd)), tick = FALSE, las = 2) mtext("Ranking", side = 1, line = 0.5) } else { xdt <- data.table(xd) xdt[, voter := 1:nrow(xd)] xdtl <- melt(xdt, id.vars = "voter", variable.name = "candidate", value.name = "rank") xdtl <- xdtl[rank %in% c(xpref, ypref)] if(sum(duplicated(xdtl[, c("voter", "rank"), with = FALSE])) > 0) stop("Sorry, the image function is not available for ballots with equal preferences.") xdtw <- dcast(xdtl, voter ~ rank, value.var = "candidate") setnames(xdtw, as.character(xpref), "xpref") setnames(xdtw, as.character(ypref), "ypref") ctbl <- table(xdtw[, ypref], xdtw[, xpref]) if(proportion) { ctbl <- ctbl/rowSums(ctbl) ctbl[is.na(ctbl)] <- 0 } image.plot(x = 1:nc, y = 1:nc, t(ctbl[nc:1,]), axes = FALSE, xlab = "", ylab = "", col = hcl.colors(12, "YlOrRd", rev = TRUE), ...) axis(2, at = nc:1, labels = rownames(ctbl), tick = FALSE, las = 1) text(1:nc, y = par("usr")[4], labels = colnames(ctbl), xpd = NA, srt = 45, adj = 0) mtext(paste("Preference", ypref), side = 4, line = 0.1) mtext(paste("Preference", xpref), side = 1, line = 0.5) } } plot.vote.stv <- function(x, xlab = "Count", ylab = "Preferences", point.size = 2, ...) { stopifnot(requireNamespace("ggplot2", quietly = TRUE)) Count <- value <- selection <- i.value <- count.select <- Candidate <- i.Count <- NULL # to avoid warnings of the CRAN check # Plot evolution of the preferences # prepare data in the long format df <- data.table(x$preferences) df[, Count := 1:nrow(df)] dfl <- melt(df, id.vars = "Count", variable.name = "Candidate") dfl <- rbind(dfl, dfl[Count == 1][, Count := 0]) # add Count 0 with initial values # dataset for plotting the quota dfq <- data.table(Count = 1:length(x$quotas), value = x$quotas, Candidate = "Quota") # dataset for plotting points of elected and eliminated candidates dfe <- melt(data.table(Count = 1:nrow(x$elect.elim), x$elect.elim), id.vars = "Count", variable.name = "Candidate") dfe <- dfe[value != 0] dfe[, selection := ifelse(value > 0, "elected", "eliminated")] dfe <- dfe[dfl, value := i.value, on = c("Count", "Candidate")] # remove data after candidates are selected dfl[dfe, count.select := i.Count, on = "Candidate"] dfl <- dfl[is.na(count.select) | Count <= count.select] # create plots g <- ggplot2::ggplot(dfl, ggplot2::aes(x = as.factor(Count), y = value, color = Candidate, group = Candidate)) + ggplot2::geom_line() g <- g + ggplot2::geom_line(data = dfq, ggplot2::aes(x = as.factor(Count)), color = "black") + ggplot2::xlab(xlab) + ggplot2::ylab(ylab) g <- g + ggplot2::geom_point(data = dfe, ggplot2::aes(shape = selection), size = point.size) + ggplot2::ylim(range(0, max(dfl$value, dfq$value))) g <- g + ggplot2::annotate(geom="text", x=as.factor(1), y=dfq[Count == 1, value], label="Quota", hjust = "right") g } "complete.ranking" <- function(object, ...) UseMethod("complete.ranking") complete.ranking.vote.stv <- function(object, ...){ result <- data.frame(Rank = 1:length(object$elected), Candidate = object$elected, Elected = "x") cand.in.play <- colSums(abs(object$elect.elim)) == 0 if(any(cand.in.play)){ # for neither elected not eliminated candidates look at the position in the last round rnk <- rank(- object$preferences[nrow(object$preferences), cand.in.play], ties.method = "random") result <- rbind(result, data.frame(Rank = seq(max(result$Rank) + 1, length = length(rnk)), Candidate = colnames(object$preferences)[cand.in.play][order(rnk)], Elected = "")) } if(any(object$elect.elim < 0)) { # eliminated candidates elims <- c() for(i in rev(which(apply(object$elect.elim, 1, function(x) any(x < 0))))) { # iterate over counts backwards elims <- c(elims, colnames(object$elect.elim)[object$elect.elim[i,] < 0]) } result <- rbind(result, data.frame(Rank = seq(max(result$Rank) + 1, length = length(elims)), Candidate = elims, Elected = "")) } return(result) }
/scratch/gouwar.j/cran-all/cranData/vote/R/stv.R
tworound.runoff <- function(votes, fsep = '\t', seed = NULL, quiet = FALSE, ...) { do.rank <- function(x){ res <- rep(0, length(x)) res[x > 0] <- rank(x[x > 0], ties.method = "min") res } votes <- prepare.votes(votes, fsep=fsep) nc <- ncol(votes) cnames <- colnames(votes) x <- check.votes(votes, "tworound.runoff", quiet = quiet) check.nseats(1, ncol(x)) nvotes <- nrow(x) # first round res <- .sum.votes(x == 1) winners <- res/nvotes > 0.5 resoff <- NULL coin.toss.winner <- coin.toss.runoff <- seed.set <- FALSE if(sum(winners) > 1 || !any(winners)) { # second round best <- res == max(res) if(sum(best) > 2) { # more than 2 candidates have the best score - sample two of them if(!is.null(seed)) set.seed(seed) idx <- sample(which(best), 2) best[] <- FALSE best[idx] <- TRUE coin.toss.runoff <- TRUE seed.set <- TRUE } if(sum(best) < 2) { second.best <- which(res == max(res[res < max(res)])) # second best results if(length(second.best) > 1) { # more than 1 candidate has the second best score - sample one of them if(!is.null(seed) && !seed.set) set.seed(seed) second.best <- sample(second.best, 1) coin.toss.runoff <- TRUE seed.set <- TRUE } best[second.best] <- TRUE } xroff <- x[,cnames[best]] xroff <- t(apply(xroff, 1, do.rank)) # shift ranking colnames(xroff) <- cnames[best] rownames(xroff) <- rownames(x) resoff <- .sum.votes(xroff == 1) res.elect <- resoff } else { res.elect <- res } winner.index <- which(res.elect == max(res.elect)) if(length(winner.index) > 1) {# tie if(!is.null(seed) && !seed.set) set.seed(seed) winner.index <- sample(winner.index, 1) coin.toss.winner <- TRUE } result <- structure(list(elected = names(res.elect)[winner.index], totals = res, totals2r = resoff, data = x, coin.toss.winner = coin.toss.winner, coin.toss.runoff = coin.toss.runoff, invalid.votes = votes[setdiff(rownames(votes), rownames(x)),, drop = FALSE]), class="vote.tworound.runoff") if(!quiet) print(summary(result)) invisible(result) } summary.vote.tworound.runoff <- function(object, ...) { df <- .summary.vote(object, reorder = FALSE) df[, "Percent"] <- c(round(object$totals/sum(object$totals)*100, 1), 100) attr(df, "align") <- c(attr(df, "align"), "r") if(!is.null(object$totals2r)) { df$ROffTotal <- rep(0, nrow(df)) df$ROffPercent <- rep(0, nrow(df)) idx <- match(names(object$totals2r), df$Candidate) df[idx, "ROffTotal"] <- object$totals2r df[nrow(df), "ROffTotal"] <- sum(object$totals2r) df[idx, "ROffPercent"] <- round(object$totals2r/sum(object$totals2r)*100, 1) df[nrow(df), "ROffPercent"] <- 100 attr(df, "align") <- c(attr(df, "align"), "r", "r") } df2 <- df[, c(setdiff(colnames(df), "Elected"), "Elected")] # reshuffle the order of columns # the above deleted the varios attributes, so re-attached for(att in setdiff(names(attributes(df)), c("names", "row.names", "class"))) attr(df2, att) <- attr(df, att) attr(df2, "align") <- c(attr(df, "align")[-which(colnames(df) == "Elected")], "c") attr(df2, "coin.toss") <- c(winner = object$coin.toss.winner, runoff = object$coin.toss.runoff) class(df2) <- c('summary.vote.tworound.runoff', class(df)) return(df2) } print.summary.vote.tworound.runoff <- function(x, ...) { cat("\nResults of two-round-runoff voting") cat("\n==================================") .print.summary.vote(x, ...) if(attr(x, "coin.toss")["winner"]) cat("Winner chosen by a coin toss.\n") if(attr(x, "coin.toss")["runoff"]) cat("Runoff candidates chosen by a coin toss.\n") } view.vote.tworound.runoff <- function(object, ...) view.vote.approval(object, ...) image.vote.tworound.runoff <- function(x, ...) image.vote.stv(x, ...)
/scratch/gouwar.j/cran-all/cranData/vote/R/two_round_runoff.R
approval <- function(votes, nseats = 1, fsep='\t', quiet = FALSE, ...) { votes <- prepare.votes(votes, fsep=fsep) x <- check.votes(votes, "approval", quiet = quiet) nseats <- check.nseats(nseats, ncol(x), ...) res <- .sum.votes(x) elected <- names(rev(sort(res))[1:nseats]) result <- structure(list(elected=elected, totals=res, data=x, invalid.votes=votes[setdiff(rownames(votes), rownames(x)),, drop = FALSE]), class="vote.approval") if(!quiet) print(summary(result)) invisible(result) } plurality <- function(votes, nseats=1, fsep='\t', quiet = FALSE, ...) { votes <- prepare.votes(votes, fsep=fsep) x <- check.votes(votes, "plurality", quiet = quiet) nseats <- check.nseats(nseats, ncol(x), ...) res <- .sum.votes(x) elected <- names(rev(sort(res))[1:nseats]) result <- structure(list(elected=elected, totals=res, data=x, invalid.votes=votes[setdiff(rownames(votes), rownames(x)),, drop = FALSE]), class="vote.plurality") if(!quiet) print(summary(result)) invisible(result) } score <- function(votes, nseats=1, max.score=NULL, larger.wins=TRUE, fsep='\t', quiet = FALSE, ...) { votes <- prepare.votes(votes, fsep=fsep) if(is.null(max.score) || max.score < 1) { max.score <- max(votes) warning("Invalid max.score. Set to observed maximum: ", max.score) } x <- check.votes(votes, "score", max.score, quiet = quiet) nseats <- check.nseats(nseats, ncol(x), ...) res <- .sum.votes(x) elected <- names(sort(res, decreasing=larger.wins)[1:nseats]) result <- structure(list(elected=elected, totals=res, larger.wins=larger.wins, data=x, invalid.votes=votes[setdiff(rownames(votes), rownames(x)),, drop = FALSE]), class="vote.score") if(!quiet) print(summary(result)) invisible(result) } .sum.votes <- function(votes) { vtot <- apply(votes, 2, sum) return (vtot) } .summary.vote <- function(object, larger.wins=TRUE, reorder = TRUE) { df <- data.frame(Candidate=names(object$totals), Total=object$totals, Elected="", stringsAsFactors=FALSE) if(reorder) df <- df[order(df$Total, decreasing=larger.wins),] df[object$elected, "Elected"] <- "x" rownames(df) <- NULL df <- rbind(df, c('', sum(df$Total), '')) rownames(df)[nrow(df)] <- "Sum" attr(df, "align") <- c("l", "r", "c") attr(df, "number.of.votes") <- nrow(object$data) attr(df, "number.of.invalid.votes") <- nrow(object$invalid.votes) attr(df, "number.of.candidates") <- length(object$totals) attr(df, "number.of.seats") <- length(object$elected) return(df) } summary.vote.approval <- function(object, ...) { df <- .summary.vote(object) class(df) <- c('summary.vote.approval', class(df)) return(df) } election.info <- function(x) { df <- data.frame(sapply(c("number.of.votes", "number.of.invalid.votes", "number.of.candidates", "number.of.seats"), function(a) attr(x, a))) rownames(df) <- c("Number of valid votes:", "Number of invalid votes:", "Number of candidates:", "Number of seats:") colnames(df) <- NULL print(df) } .print.summary.vote <- function(x, ...) { election.info(x) print(kable(x, align = attr(x, "align"), ...)) cat("\nElected:", paste(x$Candidate[trimws(x$Elected) == "x"], collapse=", "), "\n\n") } print.summary.vote.approval <- function(x, ...) { cat("\nResults of Approval voting") cat("\n==========================") .print.summary.vote(x, ...) } view.vote.approval <- function(object, ...) { s <- summary(object) col_formatter <- formatter("span", style = x ~ style(background = ifelse(x %in% s$Candidate[trimws(s$Elected)=="x"], "lightgreen", "transparent") #width = "20px" # doesn't work )) formattable(s, list(Candidate=col_formatter), ...) } summary.vote.plurality <- function(object, ...) { df <- .summary.vote(object) class(df) <- c('summary.vote.plurality', class(df)) return(df) } print.summary.vote.plurality <- function(x, ...) { cat("\nResults of Plurality voting") cat("\n===========================") .print.summary.vote(x, ...) } view.vote.plurality <- function(object, ...) view.vote.approval(object, ...) summary.vote.score <- function(object, ...) { df <- .summary.vote(object, larger.wins=object$larger.wins) class(df) <- c('summary.vote.score', class(df)) return(df) } print.summary.vote.score <- function(x, ...) { cat("\nResults of Score voting") cat("\n=======================") .print.summary.vote(x, ...) } view.vote.score <- function(object, ...) view.vote.approval(object, ...)
/scratch/gouwar.j/cran-all/cranData/vote/R/vote_by_sum.R
###################################### # générateur de données suivant # une loi de distribution empirique # et avec copule ###################################### ## Function: fpx ## Description : Obtain the ranks of a vector (A factor of ## 0.5 is used to avoid extremes values of ranks). fpx <- function(x) (rank(x, ties.method = "max") - 0.5) / length(x) #' Rename_rows #' @param preferences voters preferences #' @returns preferences rename_rows <- function(preferences) { n_candidates <- nrow(preferences) n_voters <- ncol(preferences) rownames(preferences) <- paste0("Candidate ", seq_len(n_candidates)) return(preferences) } #' Generalized inverse of the empirical cumulative function. #' #' @param u a numeric vector of quantiles to be transformed. #' @param x a numeric vector of data values. #' @param n a positive integer specifying the length of the output vector. #' #' @return a numeric vector of transformed quantiles. #' @details Computes the generalized inverse of the empirical cumulative function, #' which transforms quantiles \code{u} to the corresponding values of \code{x} based on #' the frequency distribution of \code{x}. #' #' @importFrom stats splinefun #' @importFrom stats uniroot #' icdf <- function(u, x, n) { freq <- fpx(x) Fn <- splinefun(x, freq, method = "monoH.FC") xstar <- numeric(n) for(i in seq_along(xstar)){ xstar[i] <- uniroot(function(x) Fn(x) - u[i], range(x), extendInt = "upX", f.lower = - u[i], f.upper = 1 - u[i])$root } return(xstar) } #' Distance formula #' @param votant array #' @param candidats array #' @returns distance distance<-function(votant, candidats){apply(candidats, 1, function(x) sqrt(sum((votant-x)^2)))} #' Score to distance #' @param x score #' @param dim dimension int #' @param method method string #' @returns distance ScoresToDist<-function(x, dim=2, method="linear") { if (method=="linear") {T<-dim*(1-x) }else{#transformation sigmoïde lambda<-5 x_min<-1/(1+exp(lambda*(2*sqrt(dim)-1))) x_max<-1/(1+exp(-lambda)) x[x<x_min]<-x_min x[x>x_max]<-x_max T<-((log(1/x-1))/lambda+1)/2 T[T<0]<-0 } return(as.data.frame(T)) } #' Distance to score #' @param dist int #' @param dim dimension int #' @param method method string #' @param lambda lambdad int #' @returns score DistToScores <- function(dist, dim=2, method="linear", lambda=5) { if (method=="linear"){ x <- 1-2*dist x[x<0]<-0 }else{#transformation sigmoide x <- 1/(1+exp(lambda*(4*dist-1))) } return(as.data.frame(x)) } ###################################### #Metric Unfolding Using the MLSMU6 Procedure ###################################### doubleCenterRect <- function(T){ # version score d'appétence n <- nrow(T) q <- ncol(T) (T-matrix(apply(T,1,mean), nrow=n, ncol=q) - t(matrix(apply(T,2,mean), nrow=q, ncol=n)) + mean(T))/2 } MLSMU6 <- function(df, ndim=2){ T <- as.matrix(df) n <- nrow(T) T <- (1-T)*2 TTSQ <- T*T TTSQ[is.na(T)] <- (mean(T,na.rm=TRUE))^2 TTSQDC <- doubleCenterRect(TTSQ) xsvd <- svd(TTSQDC) zz <- xsvd$v[,1:ndim] xx <- matrix(0, nrow=n, ncol=ndim) for (i in 1:ndim){ zz[,i] <- zz[,i] * sqrt(xsvd$d[i]) xx[,i] <- xsvd$u[,i] * sqrt(xsvd$d[i]) } MLSMU6<-list(X=xx, Z=zz) } #' Preferences_to_ranks #' @param preferences voters preferences #' @returns ranks preferences_to_ranks <- function(preferences) { # Calculer les rangs de chaque élément sur chaque colonne ranks <- apply(preferences, 2, rank) # Inverser les rangs pour que le candidat le plus préféré soit le numéro 1 ranks <- nrow(ranks) + 1 - ranks # Retourner les rangs return(ranks) } #' Distance formula #' @param distance_matrix distance_matrix #' @returns mat_inverse distance_to_pref<- function(distance_matrix){ #mat_inverse <- apply(distance_matrix, 2, rev) #mat_inverse <- apply(distance_matrix, 2, function(x) x[order(x, decreasing = TRUE)]) mat_inverse_rangs <- apply(distance_matrix, 2, order, decreasing = TRUE) # Réarrangement des valeurs en utilisant les rangs inversés #mat_inversee <- apply(mat_inverse_rangs, 2, function(x) mat[x]) return(mat_inverse_rangs) }
/scratch/gouwar.j/cran-all/cranData/voteSim/R/fonctions_utiles.R
# You can learn more about package authoring with RStudio at: # # http://r-pkgs.had.co.nz/ # # Some useful keyboard shortcuts for package authoring: # library(devtools) # library(roxygen2) # Check Package: 'Ctrl + Shift + E' # Buid package # Test Package: 'Ctrl + Shift + T' # Install Package: 'Ctrl + Shift + B' #' Generates a simulation of voting according to a beta law, returns voters preferences #' @export #' @param n_voters integer, represents the number of voters in the election #' @param n_candidates integer, represents the number of candidates in the election #' @param beta_a double, parameter of the Beta law (by default 0.5) #' @param beta_b double, parameter of the Beta law (by default 0.5) #' @param lambda double, alternative parameter of the Beta law #' @param min int, the minimum value of the range of possible scores (by default 0) #' @param max int, the maximum value of the range of possible scores (by default 1) #' @importFrom stats rbeta #' @returns scores #' @examples #' voting_situation<- generate_beta(n_voters=10, n_candidates=3, beta_a=1, beta_b=5) #' generate_beta <- function(n_voters,n_candidates,beta_a = 0.5,beta_b = 0.5, lambda = 0,min = 0,max = 1) { #set.seed(2023) scores<-matrix(stats::rbeta(n_candidates*n_voters, shape1 = beta_a, shape2 = beta_b, ncp=lambda),c(n_candidates,n_voters)) scores<-scores*(max-min)+min # on borne les prefs entre min et max scores <- rename_rows(scores) return(scores) } #' Generates a simulation of voting according to a uniform law, returns voters preferences #' @export #' @param n_voters integer, represents the number of voters in the election #' @param n_candidates integer, represents the number of candidates in the election #' @param min int, the minimum value of the range of possible scores (by default 0) #' @param max int, the maximum value of the range of possible scores (by default 1) #' @importFrom stats runif #' @returns scores #' @examples #' voting_situation<- generate_unif_continuous(n_voters=10, n_candidates=3, min=0, max=10) generate_unif_continuous <-function(n_voters, n_candidates, min=0, max=1){ #set.seed(2023) scores <- matrix(runif(n_candidates*n_voters, min=min, max=max),c(n_candidates,n_voters)) scores <- rename_rows(scores) return(scores) } library(truncnorm) #' Generate truncated normal scores #' #' This function generates truncated normal scores using the 'rtruncnorm' function from the 'truncnorm' package. #' #' @param n_candidates The number of candidates to generate scores for. #' @param n_voters The number of voters to generate scores for. #' @param min The minimum value of the truncated normal distribution. #' @param max The maximum value of the truncated normal distribution. #' @param mean The mean of the truncated normal distribution. #' @param sd The standard deviation of the truncated normal distribution. #' #' @return A matrix of scores with 'n_candidates' rows and 'n_voters' columns. #' @import truncnorm #' #' @export #' @examples #' voting_situation<- generate_norm(n_voters=10, n_candidates=3, min=0, max=10, mean=0.7) generate_norm<-function(n_voters, n_candidates, min=0, max=1, mean=0.5, sd=0.25){ #set.seed(2023) scores<-matrix(truncnorm::rtruncnorm(n_candidates*n_voters, a=min, b=max, mean = mean, sd = sd),c(n_candidates,n_voters)) scores <- rename_rows(scores) return(scores) } ######################## # DISCRETE SIMULATIONS # ######################## #' Generate uniform discrete scores #' #' This function generates uniform discrete scores on a given scale #' #' @param n_candidates integer, The number of candidates to generate scores for. #' @param n_voters integer, the number of voters to generate scores for. #' @param min The minimum value of the distribution, by default 0 #' @param max The maximum value of the distribution, by default 10 #' @return A matrix of scores with 'n_candidates' rows and 'n_voters' columns. #' @export #' @examples #' voting_situation <- generate_unif_disc(n_voters=10, n_candidates=3, min=0, max=5) generate_unif_disc<-function(n_voters, n_candidates, min=0, max=10){ #set.seed(2023) scores <- matrix(rep(sample(seq(from=min,to=max), n_voters, replace = TRUE), n_candidates), c(n_candidates,n_voters)) scores <- rename_rows(t(scores)) return(scores) } #' Generate binomial scores #' #' This function generates discrete scores following a binomial distribution on a given scale #' #' @param n_candidates integer, The number of candidates to generate scores for. #' @param n_voters integer, the number of voters to generate scores for. #' @param min The minimum value of the distribution, by default 0 #' @param max The maximum value of the distribution, by default 10 #' @param mean The mean value of the distribution, by default 5 #' @return A matrix of scores with 'n_candidates' rows and 'n_voters' columns. #' @importFrom stats rbinom #' @export #' @examples #' voting_situation <- generate_binomial(n_voters=10, n_candidates=3, min=0, max=7, mean=5) generate_binomial<-function(n_voters, n_candidates, min=0, max=10, mean=5){ #set.seed(2023) scores <- matrix(stats::rbinom(n_candidates*n_voters, size= max-min, prob=((mean-min)/(max-min))),c(n_candidates,n_voters)) scores<-scores+min scores <- rename_rows(t(scores)) return(scores) } #' Generate beta-binomial scores #' #' This function generates discrete scores following a beta-binomial distribution on a given scale #' #' @param n_candidates integer, The number of candidates to generate scores for. #' @param n_voters integer, the number of voters to generate scores for. #' @param min The minimum value of the distribution, by default 0 #' @param max The maximum value of the distribution, by default 10 #' @param alpha The first parameter of the beta-binomial distribution, by default 0.5 #' @param beta The second parameter of the beta-binomial distribution, by default 0.5 #' @return A matrix of scores with 'n_candidates' rows and 'n_voters' columns. #' @import extraDistr #' @export #' @examples #' voting_situation <- generate_beta_binomial(n_voters=10, n_candidates=3, max=7) generate_beta_binomial<-function(n_voters, n_candidates, min=0, max=10, alpha=0.5, beta=0.5){ #set.seed(2023) scores <- matrix(extraDistr::rbbinom(n_candidates*n_voters, size=(max-min), alpha=alpha, beta=beta),c(n_candidates,n_voters)) scores<-scores+min scores <- rename_rows(t(scores)) return(scores) } ############################# # MULTINOMIAL AND DIRICHEL # # SIMULATIONS # ############################# #' Generate multinomial scores #' #' This function generates discrete scores following a multinomial distribution on a given scale #' #' @param n_candidates integer, The number of candidates to generate scores for. #' @param n_voters integer, the number of voters to generate scores for. #' @param max The maximum value of the distribution, by default 10. It also corresponds to the sum of scores on all the candidates #' @param probs A vector of size n_candidates corresponding to the parameters of the multinomial distribution. By default all values are equal to 1/n_candidates #' @return A matrix of scores with 'n_candidates' rows and 'n_voters' columns. #' @import stats #' @export #' @examples #' voting_situation <- generate_multinom(n_voters=10, n_candidates=3, max=100, probs=c(0.5, 0.3, 0.2)) generate_multinom<-function(n_voters, n_candidates, max=10, probs=0) { if (length(probs)!=n_candidates){probs<-rep(1/n_candidates, n_candidates)} probs<-probs/(sum(probs)) scores<-stats::rmultinom(n_voters, size= max, prob=probs) scores <- rename_rows(t(scores)) return(scores) } #' Generate multinomial scores #' #' This function generates scores following a Dirichlet distribution #' #' @param n_candidates integer, The number of candidates to generate scores for. #' @param n_voters integer, the number of voters to generate scores for. #' @param probs A vector of size n_candidates corresponding to the parameters of the Dirichlet distribution. By default all values are equal to 1. #' @return A matrix of scores with 'n_candidates' rows and 'n_voters' columns. #' @import extraDistr #' @export #' @examples #' voting_situation <- generate_dirichlet(n_voters=10, n_candidates=3, probs=c(0.5, 0.3, 0.2)) generate_dirichlet<-function( n_voters, n_candidates, probs=0) { if (length(probs)!=n_candidates){probs<-rep(1/n_candidates, n_candidates)} scores<-extraDistr::rdirichlet(n_voters, probs) scores <- rename_rows(t(scores)) return(scores) } ############################# # COPULA BASED # # SIMULATIONS # ############################# #' Discrete Copula based scores #' #' This function generates discrete scores following marginals distributions linked by a copula #' #' #' @param n_candidates integer, The number of candidates to generate scores for. #' @param n_voters integer, the number of voters to generate scores for. #' @param min The minimum value of the distribution, by default 0 #' @param max The maximum value of the distribution, by default 10 #' @param margins A list of n_candidates cumulative distribution vectors of length (max-min-1) : the last value of the cumulative distribution, 1, should be omitted. By default margin distribution are uniform distributions. #' @param cor_mat A matrix of correlation coefficients between the n_candidates distributions. By default all correlation coefficients are set up alternatively to 0.5 or -0.5. #' @return A matrix of scores with 'n_candidates' rows and 'n_voters' columns. #' @import GenOrd #' @export #' @examples #' # Example for 3 candidates, binomial distributions #' min=0 #' max=7 #' n_candidates<-3 #' distribution<-dbinom(x=(min:max), size=max, prob=0.7) #' distribution_cumul<-cumsum(distribution) #' distribution_cumul<-distribution_cumul[-length(distribution_cumul)] #' margins <- matrix(rep(distribution_cumul, n_candidates), ncol=n_candidates) #' margins <-as.list(as.data.frame(margins)) #' cor_mat<-matrix(c(1,0.8,0,0.8,1,0, 0,0,1), ncol=n_candidates) #' voting_situation <- generate_discrete_copula_based(10, 3, max=max, margins=margins, cor_mat=cor_mat) generate_discrete_copula_based<-function(n_voters, n_candidates, min=0, max=10, margins=list("default"), cor_mat=0) { score_levels<-min:max n_levels<-length(score_levels) if(identical(margins,list("default"))){ distrib<-rep(1/n_levels, nlevels) distrib_cumul<-cumsum(distrib) distrib_cumul<-distrib_cumul[-length(distrib_cumul)] marginales <- matrix(rep(distrib_cumul, n_candidates), ncol=n_candidates) margins<- as.list(as.data.frame(marginales)) } test_distrib<-is.list(margins)&(length(margins)==n_candidates)&all(lengths(margins)==(n_levels-1)) if (test_distrib==FALSE){stop("margin distributions are not consistant")} if (identical(cor_mat,0)){ cor_mat<-matrix(nrow=n_candidates, ncol=n_candidates) for (i in 1:n_candidates) {for(j in 1:n_candidates) {if (i==j){ cor_mat[i,j]<-1 }else{ cor_mat[i,j]<-0.5*(-1)^(i+j) } } } } support<-list() for (i in 1:n_candidates){support[[i]]<-score_levels} scores<-GenOrd::ordsample(n_voters, margins, cor_mat, support = support, Spearman = FALSE, cormat = "discrete") scores <-scores +min scores <- rename_rows(t(scores)) return(scores) } ############################# # SPATIAL # # SIMULATIONS # ############################# #' Generate spatial simulation #' #' This function generates spatial data consisting of \code{n_voters} voters and \code{n_candidates} candidates. The spatial model is created by placing the candidates on a 2-dimensional plane according to the \code{placement} parameter, and then computing a distance matrix between voters and candidates. The distances are then transformed into scores using the \code{score_method} parameter. Finally, a plot of the candidates and voters is produced. #' #' @param n_voters The number of voters. #' @param n_candidates The number of candidates. #' @param placement The method used to place the candidates on the 2-dimensional plane. Must be either "uniform" or "beta". Default is "uniform". #' @param score_method The method used to transform distances into scores. Must be either "linear" or "sigmoide". Default is "linear". #' @param dim The dimension of the latent space (by default dim =2) #' @return A matrix of scores. #' @export #' @importFrom graphics text #' @importFrom graphics points #' @importFrom stats rbeta #' @importFrom stats runif #' @examples #' generate_spatial(n_candidates = 5,n_voters = 100, placement = "uniform", score_method = "linear") generate_spatial <- function(n_voters,n_candidates,placement = "uniform",score_method = "linear", dim=2){ #set.seed(2023) if (dim<1){ warning("dim must be at least 1 - dim has been set up to 2") dim <- 2} # constante # === placement === # if (placement == "uniform"){ candidates<-matrix(stats::runif(n_candidates*dim), nrow = n_candidates, ncol=dim) voters<-matrix(stats::runif(n_voters*dim), nrow = n_voters, ncol=dim) }else if(placement == "beta"){ beta_a= 1.2 # 2 = points centrés beta_b= 1.2 candidates <- matrix(stats::rbeta(n_candidates*dim, shape1 = beta_a, shape2 = beta_b),nrow = n_candidates,ncol = dim) voters <- matrix(stats::rbeta(n_voters*dim, shape1 = beta_a, shape2 = beta_b), nrow = n_voters, ncol = dim) }else{ stop("placement must be 'uniform' or 'beta'") } # === distance between voters / candidates} === # matrix_distances<-apply(voters,1, function(x) distance(x,candidates)) # === distance to score === # (linear / sigmoide) matrix_scores<-DistToScores(matrix_distances,method = score_method) #View(matrix_distances) # test #View(matrix_scores) # test # === plots === # plot(candidates, xlab="dim. 1", ylab="dim. 2", xlim=c(0,1), ylim=c(0,1), col="red", pch=c(17), cex=1.5, main="Spatial model") text(candidates[,1]+0.001, candidates[,2]+0.001, labels=1:n_candidates, pos=4, col="red") if(n_voters <= 200){ points(voters) }else{ points(voters[sample(n_voters,200),]) } #pref_rank <- preferences_to_ranks(matrix_scores) #View(pref_rank) #View(distance_to_pref(pref_rank)) return(rename_rows(matrix_scores)) }
/scratch/gouwar.j/cran-all/cranData/voteSim/R/main.R
#' @keywords internal "_PACKAGE" ## usethis namespace: start ## usethis namespace: end NULL
/scratch/gouwar.j/cran-all/cranData/voteSim/R/voteSim-package.R
#' voteogram manual scale colors #' #' Manual color scales fill and color scale values (in the event you need to use them) #' outisde the main plotting functions. #' #' @name voteogram-colors NULL #' @name vote_carto_fill #' @rdname voteogram-colors vote_carto_fill <- c( `D-yes`="#003366", `D-no`="#869fc4", `D-not voting`="#e1ecf8", `D-present`="#000055", `ID-yes`="#e59b16", `ID-no`="#eeba58", `ID-not voting`="#f9f2df", `ID-present`="#335500", `R-yes`="#aa0000", `R-no`="#d68585", `R-not voting`="#f8e9e9", `R-present`="#550000", `Vacant`="#2b2b2b" ) #' @name vote_carto_color #' @rdname voteogram-colors vote_carto_color <- c( `D-yes`="#003366", `D-no`="#869fc4", `D-not voting`="#e1ecf8", `D-present`="#000055", `ID-yes`="#e59b16", `ID-no`="#eeba58", `ID-not voting`="#f9f2df", `ID-present`="#335500", `R-yes`="#aa0000", `R-no`="#d68585", `R-not voting`="#f8e9e9", `R-present`="#550000", `Vacant`="#2b2b2b" )
/scratch/gouwar.j/cran-all/cranData/voteogram/R/aaa-colors.r
structure(list(x = c(0, 10, 20, 20, 10, 0, 0, 300, 310, 320, 320, 310, 300, 300, 310, 320, 330, 330, 320, 310, 310, 320, 330, 340, 340, 330, 320, 320, 290, 300, 310, 310, 300, 290, 290, 310, 320, 330, 330, 320, 310, 310, 300, 310, 320, 320, 310, 300, 300, 290, 300, 310, 310, 300, 290, 290, 260, 270, 280, 280, 270, 260, 260, 260, 270, 280, 280, 270, 260, 260, 250, 260, 270, 270, 260, 250, 250, 240, 250, 260, 260, 250, 240, 240, 100, 110, 120, 120, 110, 100, 100, 140, 150, 160, 160, 150, 140, 140, 150, 160, 170, 170, 160, 150, 150, 130, 140, 150, 150, 140, 130, 130, 120, 130, 140, 140, 130, 120, 120, 140, 150, 160, 160, 150, 140, 140, 150, 160, 170, 170, 160, 150, 150, 110, 120, 130, 130, 120, 110, 110, 130, 140, 150, 150, 140, 130, 130, 120, 130, 140, 140, 130, 120, 120, 100, 110, 120, 120, 110, 100, 100, 80, 90, 100, 100, 90, 80, 80, 90, 100, 110, 110, 100, 90, 90, 120, 130, 140, 140, 130, 120, 120, 70, 80, 90, 90, 80, 70, 70, 80, 90, 100, 100, 90, 80, 80, 100, 110, 120, 120, 110, 100, 100, 110, 120, 130, 130, 120, 110, 110, 100, 110, 120, 120, 110, 100, 100, 110, 120, 130, 130, 120, 110, 110, 90, 100, 110, 110, 100, 90, 90, 50, 60, 70, 70, 60, 50, 50, 70, 80, 90, 90, 80, 70, 70, 40, 50, 60, 60, 50, 40, 40, 60, 70, 80, 80, 70, 60, 60, 50, 60, 70, 70, 60, 50, 50, 40, 50, 60, 60, 50, 40, 40, 30, 40, 50, 50, 40, 30, 30, 30, 40, 50, 50, 40, 30, 30, 20, 30, 40, 40, 30, 20, 20, 70, 80, 90, 90, 80, 70, 70, 80, 90, 100, 100, 90, 80, 80, 10, 20, 30, 30, 20, 10, 10, 40, 50, 60, 60, 50, 40, 40, 20, 30, 40, 40, 30, 20, 20, 60, 70, 80, 80, 70, 60, 60, 70, 80, 90, 90, 80, 70, 70, 50, 60, 70, 70, 60, 50, 50, 30, 40, 50, 50, 40, 30, 30, 80, 90, 100, 100, 90, 80, 80, 40, 50, 60, 60, 50, 40, 40, 10, 20, 30, 30, 20, 10, 10, 20, 30, 40, 40, 30, 20, 20, 60, 70, 80, 80, 70, 60, 60, 80, 90, 100, 100, 90, 80, 80, 0, 10, 20, 20, 10, 0, 0, 50, 60, 70, 70, 60, 50, 50, 70, 80, 90, 90, 80, 70, 70, 30, 40, 50, 50, 40, 30, 30, 90, 100, 110, 110, 100, 90, 90, 100, 110, 120, 120, 110, 100, 100, 10, 20, 30, 30, 20, 10, 10, 20, 30, 40, 40, 30, 20, 20, 80, 90, 100, 100, 90, 80, 80, 60, 70, 80, 80, 70, 60, 60, 40, 50, 60, 60, 50, 40, 40, 50, 60, 70, 70, 60, 50, 50, 70, 80, 90, 90, 80, 70, 70, 100, 110, 120, 120, 110, 100, 100, 90, 100, 110, 110, 100, 90, 90, 90, 100, 110, 110, 100, 90, 90, 110, 120, 130, 130, 120, 110, 110, 190, 200, 210, 210, 200, 190, 190, 180, 190, 200, 200, 190, 180, 180, 180, 190, 200, 200, 190, 180, 180, 220, 230, 240, 240, 230, 220, 220, 200, 210, 220, 220, 210, 200, 200, 210, 220, 230, 230, 220, 210, 210, 200, 210, 220, 220, 210, 200, 200, 570, 580, 590, 590, 580, 570, 570, 590, 600, 610, 610, 600, 590, 590, 580, 590, 600, 600, 590, 580, 580, 560, 570, 580, 580, 570, 560, 560, 550, 560, 570, 570, 560, 550, 550, 440, 450, 460, 460, 450, 440, 440, 490, 500, 510, 510, 500, 490, 490, 310, 320, 330, 330, 320, 310, 310, 330, 340, 350, 350, 340, 330, 330, 350, 360, 370, 370, 360, 350, 350, 370, 380, 390, 390, 380, 370, 370, 380, 390, 400, 400, 390, 380, 380, 390, 400, 410, 410, 400, 390, 390, 400, 410, 420, 420, 410, 400, 400, 420, 430, 440, 440, 430, 420, 420, 430, 440, 450, 450, 440, 430, 430, 410, 420, 430, 430, 420, 410, 410, 360, 370, 380, 380, 370, 360, 360, 340, 350, 360, 360, 350, 340, 340, 350, 360, 370, 370, 360, 350, 350, 370, 380, 390, 390, 380, 370, 370, 390, 400, 410, 410, 400, 390, 390, 380, 390, 400, 400, 390, 380, 380, 400, 410, 420, 420, 410, 400, 400, 440, 450, 460, 460, 450, 440, 440, 390, 400, 410, 410, 400, 390, 390, 430, 440, 450, 450, 440, 430, 430, 460, 470, 480, 480, 470, 460, 460, 450, 460, 470, 470, 460, 450, 450, 470, 480, 490, 490, 480, 470, 470, 440, 450, 460, 460, 450, 440, 440, 410, 420, 430, 430, 420, 410, 410, 430, 440, 450, 450, 440, 430, 430, 450, 460, 470, 470, 460, 450, 450, 380, 390, 400, 400, 390, 380, 380, 340, 350, 360, 360, 350, 340, 340, 320, 330, 340, 340, 330, 320, 320, 370, 380, 390, 390, 380, 370, 370, 350, 360, 370, 370, 360, 350, 350, 360, 370, 380, 380, 370, 360, 360, 380, 390, 400, 400, 390, 380, 380, 360, 370, 380, 380, 370, 360, 360, 350, 360, 370, 370, 360, 350, 350, 370, 380, 390, 390, 380, 370, 370, 340, 350, 360, 360, 350, 340, 340, 390, 400, 410, 410, 400, 390, 390, 330, 340, 350, 350, 340, 330, 330, 330, 340, 350, 350, 340, 330, 330, 60, 70, 80, 80, 70, 60, 60, 0, 10, 20, 20, 10, 0, 0, 10, 20, 30, 30, 20, 10, 10, 240, 250, 260, 260, 250, 240, 240, 250, 260, 270, 270, 260, 250, 250, 230, 240, 250, 250, 240, 230, 230, 220, 230, 240, 240, 230, 220, 220, 160, 170, 180, 180, 170, 160, 160, 170, 180, 190, 190, 180, 170, 170, 280, 290, 300, 300, 290, 280, 280, 270, 280, 290, 290, 280, 270, 270, 250, 260, 270, 270, 260, 250, 250, 260, 270, 280, 280, 270, 260, 260, 280, 290, 300, 300, 290, 280, 280, 230, 240, 250, 250, 240, 230, 230, 270, 280, 290, 290, 280, 270, 270, 240, 250, 260, 260, 250, 240, 240, 270, 280, 290, 290, 280, 270, 270, 250, 260, 270, 270, 260, 250, 250, 260, 270, 280, 280, 270, 260, 260, 280, 290, 300, 300, 290, 280, 280, 270, 280, 290, 290, 280, 270, 270, 240, 250, 260, 260, 250, 240, 240, 290, 300, 310, 310, 300, 290, 290, 280, 290, 300, 300, 290, 280, 280, 250, 260, 270, 270, 260, 250, 250, 260, 270, 280, 280, 270, 260, 260, 290, 300, 310, 310, 300, 290, 290, 300, 310, 320, 320, 310, 300, 300, 310, 320, 330, 330, 320, 310, 310, 290, 300, 310, 310, 300, 290, 290, 300, 310, 320, 320, 310, 300, 300, 310, 320, 330, 330, 320, 310, 310, 300, 310, 320, 320, 310, 300, 300, 310, 320, 330, 330, 320, 310, 310, 320, 330, 340, 340, 330, 320, 320, 230, 240, 250, 250, 240, 230, 230, 240, 250, 260, 260, 250, 240, 240, 250, 260, 270, 270, 260, 250, 250, 240, 250, 260, 260, 250, 240, 240, 300, 310, 320, 320, 310, 300, 300, 320, 330, 340, 340, 330, 320, 320, 330, 340, 350, 350, 340, 330, 330, 350, 360, 370, 370, 360, 350, 350, 360, 370, 380, 380, 370, 360, 360, 340, 350, 360, 360, 350, 340, 340, 270, 280, 290, 290, 280, 270, 270, 250, 260, 270, 270, 260, 250, 250, 230, 240, 250, 250, 240, 230, 230, 240, 250, 260, 260, 250, 240, 240, 250, 260, 270, 270, 260, 250, 250, 260, 270, 280, 280, 270, 260, 260, 540, 550, 560, 560, 550, 540, 540, 560, 570, 580, 580, 570, 560, 560, 580, 590, 600, 600, 590, 580, 580, 600, 610, 620, 620, 610, 600, 600, 570, 580, 590, 590, 580, 570, 570, 600, 610, 620, 620, 610, 600, 600, 590, 600, 610, 610, 600, 590, 590, 610, 620, 630, 630, 620, 610, 610, 620, 630, 640, 640, 630, 620, 620, 490, 500, 510, 510, 500, 490, 490, 470, 480, 490, 490, 480, 470, 470, 480, 490, 500, 500, 490, 480, 480, 460, 470, 480, 480, 470, 460, 460, 470, 480, 490, 490, 480, 470, 470, 410, 420, 430, 430, 420, 410, 410, 450, 460, 470, 470, 460, 450, 450, 430, 440, 450, 450, 440, 430, 430, 560, 570, 580, 580, 570, 560, 560, 550, 560, 570, 570, 560, 550, 550, 290, 300, 310, 310, 300, 290, 290, 320, 330, 340, 340, 330, 320, 320, 310, 320, 330, 330, 320, 310, 310, 340, 350, 360, 360, 350, 340, 340, 360, 370, 380, 380, 370, 360, 360, 310, 320, 330, 330, 320, 310, 310, 330, 340, 350, 350, 340, 330, 330, 320, 330, 340, 340, 330, 320, 320, 350, 360, 370, 370, 360, 350, 350, 370, 380, 390, 390, 380, 370, 370, 330, 340, 350, 350, 340, 330, 330, 350, 360, 370, 370, 360, 350, 350, 340, 350, 360, 360, 350, 340, 340, 360, 370, 380, 380, 370, 360, 360, 210, 220, 230, 230, 220, 210, 210, 230, 240, 250, 250, 240, 230, 230, 190, 200, 210, 210, 200, 190, 190, 220, 230, 240, 240, 230, 220, 220, 200, 210, 220, 220, 210, 200, 200, 210, 220, 230, 230, 220, 210, 210, 180, 190, 200, 200, 190, 180, 180, 200, 210, 220, 220, 210, 200, 200, 270, 280, 290, 290, 280, 270, 270, 280, 290, 300, 300, 290, 280, 280, 260, 270, 280, 280, 270, 260, 260, 260, 270, 280, 280, 270, 260, 260, 250, 260, 270, 270, 260, 250, 250, 240, 250, 260, 260, 250, 240, 240, 270, 280, 290, 290, 280, 270, 270, 290, 300, 310, 310, 300, 290, 290, 20, 30, 40, 40, 30, 20, 20, 270, 280, 290, 290, 280, 270, 270, 280, 290, 300, 300, 290, 280, 280, 270, 280, 290, 290, 280, 270, 270, 280, 290, 300, 300, 290, 280, 280, 180, 190, 200, 200, 190, 180, 180, 470, 480, 490, 490, 480, 470, 470, 440, 450, 460, 460, 450, 440, 440, 480, 490, 500, 500, 490, 480, 480, 450, 460, 470, 470, 460, 450, 450, 390, 400, 410, 410, 400, 390, 390, 430, 440, 450, 450, 440, 430, 430, 450, 460, 470, 470, 460, 450, 450, 430, 440, 450, 450, 440, 430, 430, 420, 430, 440, 440, 430, 420, 420, 400, 410, 420, 420, 410, 400, 400, 380, 390, 400, 400, 390, 380, 380, 410, 420, 430, 430, 420, 410, 410, 460, 470, 480, 480, 470, 460, 460, 190, 200, 210, 210, 200, 190, 190, 220, 230, 240, 240, 230, 220, 220, 230, 240, 250, 250, 240, 230, 230, 210, 220, 230, 230, 220, 210, 210, 550, 560, 570, 570, 560, 550, 550, 540, 550, 560, 560, 550, 540, 540, 510, 520, 530, 530, 520, 510, 510, 520, 530, 540, 540, 530, 520, 520, 530, 540, 550, 550, 540, 530, 530, 520, 530, 540, 540, 530, 520, 520, 510, 520, 530, 530, 520, 510, 510, 540, 550, 560, 560, 550, 540, 540, 510, 520, 530, 530, 520, 510, 510, 540, 550, 560, 560, 550, 540, 540, 530, 540, 550, 550, 540, 530, 530, 530, 540, 550, 550, 540, 530, 530, 520, 530, 540, 540, 530, 520, 520, 500, 510, 520, 520, 510, 500, 500, 170, 180, 190, 190, 180, 170, 170, 160, 170, 180, 180, 170, 160, 160, 190, 200, 210, 210, 200, 190, 190, 140, 150, 160, 160, 150, 140, 140, 130, 140, 150, 150, 140, 130, 130, 130, 140, 150, 150, 140, 130, 130, 150, 160, 170, 170, 160, 150, 150, 640, 650, 660, 660, 650, 640, 640, 630, 640, 650, 650, 640, 630, 630, 620, 630, 640, 640, 630, 620, 620, 610, 620, 630, 630, 620, 610, 610, 590, 600, 610, 610, 600, 590, 590, 580, 590, 600, 600, 590, 580, 580, 570, 580, 590, 590, 580, 570, 570, 600, 610, 620, 620, 610, 600, 600, 580, 590, 600, 600, 590, 580, 580, 550, 560, 570, 570, 560, 550, 550, 560, 570, 580, 580, 570, 560, 560, 560, 570, 580, 580, 570, 560, 560, 550, 560, 570, 570, 560, 550, 550, 590, 600, 610, 610, 600, 590, 590, 570, 580, 590, 590, 580, 570, 570, 530, 540, 550, 550, 540, 530, 530, 540, 550, 560, 560, 550, 540, 540, 520, 530, 540, 540, 530, 520, 520, 500, 510, 520, 520, 510, 500, 500, 510, 520, 530, 530, 520, 510, 510, 510, 520, 530, 530, 520, 510, 510, 490, 500, 510, 510, 500, 490, 490, 470, 480, 490, 490, 480, 470, 470, 520, 530, 540, 540, 530, 520, 520, 500, 510, 520, 520, 510, 500, 500, 460, 470, 480, 480, 470, 460, 460, 480, 490, 500, 500, 490, 480, 480, 340, 350, 360, 360, 350, 340, 340, 360, 370, 380, 380, 370, 360, 360, 340, 350, 360, 360, 350, 340, 340, 330, 340, 350, 350, 340, 330, 330, 320, 330, 340, 340, 330, 320, 320, 370, 380, 390, 390, 380, 370, 370, 360, 370, 380, 380, 370, 360, 360, 320, 330, 340, 340, 330, 320, 320, 340, 350, 360, 360, 350, 340, 340, 330, 340, 350, 350, 340, 330, 330, 380, 390, 400, 400, 390, 380, 380, 350, 360, 370, 370, 360, 350, 350, 380, 390, 400, 400, 390, 380, 380, 370, 380, 390, 390, 380, 370, 370, 350, 360, 370, 370, 360, 350, 350, 360, 370, 380, 380, 370, 360, 360, 220, 230, 240, 240, 230, 220, 220, 230, 240, 250, 250, 240, 230, 230, 200, 210, 220, 220, 210, 200, 200, 210, 220, 230, 230, 220, 210, 210, 210, 220, 230, 230, 220, 210, 210, 100, 110, 120, 120, 110, 100, 100, 140, 150, 160, 160, 150, 140, 140, 120, 130, 140, 140, 130, 120, 120, 110, 120, 130, 130, 120, 110, 110, 90, 100, 110, 110, 100, 90, 90, 500, 510, 520, 520, 510, 500, 500, 490, 500, 510, 510, 500, 490, 490, 390, 400, 410, 410, 400, 390, 390, 440, 450, 460, 460, 450, 440, 440, 400, 410, 420, 420, 410, 400, 400, 450, 460, 470, 470, 460, 450, 450, 480, 490, 500, 500, 490, 480, 480, 470, 480, 490, 490, 480, 470, 470, 420, 430, 440, 440, 430, 420, 420, 420, 430, 440, 440, 430, 420, 420, 430, 440, 450, 450, 440, 430, 430, 400, 410, 420, 420, 410, 400, 400, 480, 490, 500, 500, 490, 480, 480, 410, 420, 430, 430, 420, 410, 410, 460, 470, 480, 480, 470, 460, 460, 460, 470, 480, 480, 470, 460, 460, 440, 450, 460, 460, 450, 440, 440, 390, 400, 410, 410, 400, 390, 390, 530, 540, 550, 550, 540, 530, 530, 610, 620, 630, 630, 620, 610, 610, 600, 610, 620, 620, 610, 600, 600, 430, 440, 450, 450, 440, 430, 430, 400, 410, 420, 420, 410, 400, 400, 390, 400, 410, 410, 400, 390, 390, 410, 420, 430, 430, 420, 410, 410, 420, 430, 440, 440, 430, 420, 420, 410, 420, 430, 430, 420, 410, 410, 440, 450, 460, 460, 450, 440, 440, 200, 210, 220, 220, 210, 200, 200, 370, 380, 390, 390, 380, 370, 370, 360, 370, 380, 380, 370, 360, 360, 340, 350, 360, 360, 350, 340, 340, 320, 330, 340, 340, 330, 320, 320, 330, 340, 350, 350, 340, 330, 330, 350, 360, 370, 370, 360, 350, 350, 300, 310, 320, 320, 310, 300, 300, 310, 320, 330, 330, 320, 310, 310, 280, 290, 300, 300, 290, 280, 280, 230, 240, 250, 250, 240, 230, 230, 200, 210, 220, 220, 210, 200, 200, 200, 210, 220, 220, 210, 200, 200, 220, 230, 240, 240, 230, 220, 220, 200, 210, 220, 220, 210, 200, 200, 190, 200, 210, 210, 200, 190, 190, 170, 180, 190, 190, 180, 170, 170, 210, 220, 230, 230, 220, 210, 210, 190, 200, 210, 210, 200, 190, 190, 160, 170, 180, 180, 170, 160, 160, 170, 180, 190, 190, 180, 170, 170, 160, 170, 180, 180, 170, 160, 160, 180, 190, 200, 200, 190, 180, 180, 220, 230, 240, 240, 230, 220, 220, 170, 180, 190, 190, 180, 170, 170, 150, 160, 170, 170, 160, 150, 150, 170, 180, 190, 190, 180, 170, 170, 180, 190, 200, 200, 190, 180, 180, 170, 180, 190, 190, 180, 170, 170, 160, 170, 180, 180, 170, 160, 160, 140, 150, 160, 160, 150, 140, 140, 200, 210, 220, 220, 210, 200, 200, 140, 150, 160, 160, 150, 140, 140, 190, 200, 210, 210, 200, 190, 190, 160, 170, 180, 180, 170, 160, 160, 190, 200, 210, 210, 200, 190, 190, 190, 200, 210, 210, 200, 190, 190, 180, 190, 200, 200, 190, 180, 180, 210, 220, 230, 230, 220, 210, 210, 180, 190, 200, 200, 190, 180, 180, 150, 160, 170, 170, 160, 150, 150, 210, 220, 230, 230, 220, 210, 210, 180, 190, 200, 200, 190, 180, 180, 180, 190, 200, 200, 190, 180, 180, 150, 160, 170, 170, 160, 150, 150, 220, 230, 240, 240, 230, 220, 220, 160, 170, 180, 180, 170, 160, 160, 160, 170, 180, 180, 170, 160, 160, 170, 180, 190, 190, 180, 170, 170, 150, 160, 170, 170, 160, 150, 150, 440, 450, 460, 460, 450, 440, 440, 480, 490, 500, 500, 490, 480, 480, 420, 430, 440, 440, 430, 420, 420, 460, 470, 480, 480, 470, 460, 460, 400, 410, 420, 420, 410, 400, 400, 390, 400, 410, 410, 400, 390, 390, 410, 420, 430, 430, 420, 410, 410, 450, 460, 470, 470, 460, 450, 450, 380, 390, 400, 400, 390, 380, 380, 420, 430, 440, 440, 430, 420, 420, 430, 440, 450, 450, 440, 430, 430, 590, 600, 610, 610, 600, 590, 590, 530, 540, 550, 550, 540, 530, 530, 120, 130, 140, 140, 130, 120, 120, 100, 110, 120, 120, 110, 100, 100, 80, 90, 100, 100, 90, 80, 80, 140, 150, 160, 160, 150, 140, 140, 150, 160, 170, 170, 160, 150, 150, 80, 90, 100, 100, 90, 80, 80, 90, 100, 110, 110, 100, 90, 90, 130, 140, 150, 150, 140, 130, 130, 110, 120, 130, 130, 120, 110, 110, 70, 80, 90, 90, 80, 70, 70, 220, 230, 240, 240, 230, 220, 220, 210, 220, 230, 230, 220, 210, 210, 220, 230, 240, 240, 230, 220, 220, 280, 290, 300, 300, 290, 280, 280, 230, 240, 250, 250, 240, 230, 230, 260, 270, 280, 280, 270, 260, 260, 230, 240, 250, 250, 240, 230, 230, 240, 250, 260, 260, 250, 240, 240, 400, 410, 420, 420, 410, 400, 400, 380, 390, 400, 400, 390, 380, 380, 370, 380, 390, 390, 380, 370, 370, 190, 200, 210, 210, 200, 190, 190), y = c(27, 31.5, 27, 18, 13.5, 18, 27, 243, 247.5, 243, 234, 229.5, 234, 243, 229.5, 234, 229.5, 220.5, 216, 220.5, 229.5, 216, 220.5, 216, 207, 202.5, 207, 216, 202.5, 207, 202.5, 193.5, 189, 193.5, 202.5, 202.5, 207, 202.5, 193.5, 189, 193.5, 202.5, 216, 220.5, 216, 207, 202.5, 207, 216, 229.5, 234, 229.5, 220.5, 216, 220.5, 229.5, 189, 193.5, 189, 180, 175.5, 180, 189, 216, 220.5, 216, 207, 202.5, 207, 216, 202.5, 207, 202.5, 193.5, 189, 193.5, 202.5, 216, 220.5, 216, 207, 202.5, 207, 216, 324, 328.5, 324, 315, 310.5, 315, 324, 162, 166.5, 162, 153, 148.5, 153, 162, 202.5, 207, 202.5, 193.5, 189, 193.5, 202.5, 202.5, 207, 202.5, 193.5, 189, 193.5, 202.5, 162, 166.5, 162, 153, 148.5, 153, 162, 189, 193.5, 189, 180, 175.5, 180, 189, 175.5, 180, 175.5, 166.5, 162, 166.5, 175.5, 202.5, 207, 202.5, 193.5, 189, 193.5, 202.5, 175.5, 180, 175.5, 166.5, 162, 166.5, 175.5, 189, 193.5, 189, 180, 175.5, 180, 189, 135, 139.5, 135, 126, 121.5, 126, 135, 135, 139.5, 135, 126, 121.5, 126, 135, 148.5, 153, 148.5, 139.5, 135, 139.5, 148.5, 135, 139.5, 135, 126, 121.5, 126, 135, 148.5, 153, 148.5, 139.5, 135, 139.5, 148.5, 162, 166.5, 162, 153, 148.5, 153, 162, 162, 166.5, 162, 153, 148.5, 153, 162, 148.5, 153, 148.5, 139.5, 135, 139.5, 148.5, 189, 193.5, 189, 180, 175.5, 180, 189, 175.5, 180, 175.5, 166.5, 162, 166.5, 175.5, 175.5, 180, 175.5, 166.5, 162, 166.5, 175.5, 148.5, 153, 148.5, 139.5, 135, 139.5, 148.5, 175.5, 180, 175.5, 166.5, 162, 166.5, 175.5, 162, 166.5, 162, 153, 148.5, 153, 162, 189, 193.5, 189, 180, 175.5, 180, 189, 202.5, 207, 202.5, 193.5, 189, 193.5, 202.5, 189, 193.5, 189, 180, 175.5, 180, 189, 175.5, 180, 175.5, 166.5, 162, 166.5, 175.5, 202.5, 207, 202.5, 193.5, 189, 193.5, 202.5, 189, 193.5, 189, 180, 175.5, 180, 189, 202.5, 207, 202.5, 193.5, 189, 193.5, 202.5, 216, 220.5, 216, 207, 202.5, 207, 216, 202.5, 207, 202.5, 193.5, 189, 193.5, 202.5, 216, 220.5, 216, 207, 202.5, 207, 216, 216, 220.5, 216, 207, 202.5, 207, 216, 216, 220.5, 216, 207, 202.5, 207, 216, 229.5, 234, 229.5, 220.5, 216, 220.5, 229.5, 229.5, 234, 229.5, 220.5, 216, 220.5, 229.5, 229.5, 234, 229.5, 220.5, 216, 220.5, 229.5, 243, 247.5, 243, 234, 229.5, 234, 243, 243, 247.5, 243, 234, 229.5, 234, 243, 229.5, 234, 229.5, 220.5, 216, 220.5, 229.5, 243, 247.5, 243, 234, 229.5, 234, 243, 243, 247.5, 243, 234, 229.5, 234, 243, 189, 193.5, 189, 180, 175.5, 180, 189, 243, 247.5, 243, 234, 229.5, 234, 243, 256.5, 261, 256.5, 247.5, 243, 247.5, 256.5, 256.5, 261, 256.5, 247.5, 243, 247.5, 256.5, 256.5, 261, 256.5, 247.5, 243, 247.5, 256.5, 256.5, 261, 256.5, 247.5, 243, 247.5, 256.5, 270, 274.5, 270, 261, 256.5, 261, 270, 256.5, 261, 256.5, 247.5, 243, 247.5, 256.5, 270, 274.5, 270, 261, 256.5, 261, 270, 270, 274.5, 270, 261, 256.5, 261, 270, 270, 274.5, 270, 261, 256.5, 261, 270, 270, 274.5, 270, 261, 256.5, 261, 270, 283.5, 288, 283.5, 274.5, 270, 274.5, 283.5, 283.5, 288, 283.5, 274.5, 270, 274.5, 283.5, 216, 220.5, 216, 207, 202.5, 207, 216, 202.5, 207, 202.5, 193.5, 189, 193.5, 202.5, 283.5, 288, 283.5, 274.5, 270, 274.5, 283.5, 283.5, 288, 283.5, 274.5, 270, 274.5, 283.5, 148.5, 153, 148.5, 139.5, 135, 139.5, 148.5, 135, 139.5, 135, 126, 121.5, 126, 135, 162, 166.5, 162, 153, 148.5, 153, 162, 162, 166.5, 162, 153, 148.5, 153, 162, 162, 166.5, 162, 153, 148.5, 153, 162, 148.5, 153, 148.5, 139.5, 135, 139.5, 148.5, 135, 139.5, 135, 126, 121.5, 126, 135, 67.5, 72, 67.5, 58.5, 54, 58.5, 67.5, 67.5, 72, 67.5, 58.5, 54, 58.5, 67.5, 81, 85.5, 81, 72, 67.5, 72, 81, 81, 85.5, 81, 72, 67.5, 72, 81, 67.5, 72, 67.5, 58.5, 54, 58.5, 67.5, 135, 139.5, 135, 126, 121.5, 126, 135, 121.5, 126, 121.5, 112.5, 108, 112.5, 121.5, 256.5, 261, 256.5, 247.5, 243, 247.5, 256.5, 256.5, 261, 256.5, 247.5, 243, 247.5, 256.5, 256.5, 261, 256.5, 247.5, 243, 247.5, 256.5, 256.5, 261, 256.5, 247.5, 243, 247.5, 256.5, 270, 274.5, 270, 261, 256.5, 261, 270, 256.5, 261, 256.5, 247.5, 243, 247.5, 256.5, 270, 274.5, 270, 261, 256.5, 261, 270, 270, 274.5, 270, 261, 256.5, 261, 270, 283.5, 288, 283.5, 274.5, 270, 274.5, 283.5, 283.5, 288, 283.5, 274.5, 270, 274.5, 283.5, 270, 274.5, 270, 261, 256.5, 261, 270, 270, 274.5, 270, 261, 256.5, 261, 270, 283.5, 288, 283.5, 274.5, 270, 274.5, 283.5, 283.5, 288, 283.5, 274.5, 270, 274.5, 283.5, 283.5, 288, 283.5, 274.5, 270, 274.5, 283.5, 297, 301.5, 297, 288, 283.5, 288, 297, 297, 301.5, 297, 288, 283.5, 288, 297, 297, 301.5, 297, 288, 283.5, 288, 297, 310.5, 315, 310.5, 301.5, 297, 301.5, 310.5, 310.5, 315, 310.5, 301.5, 297, 301.5, 310.5, 324, 328.5, 324, 315, 310.5, 315, 324, 310.5, 315, 310.5, 301.5, 297, 301.5, 310.5, 337.5, 342, 337.5, 328.5, 324, 328.5, 337.5, 324, 328.5, 324, 315, 310.5, 315, 324, 310.5, 315, 310.5, 301.5, 297, 301.5, 310.5, 337.5, 342, 337.5, 328.5, 324, 328.5, 337.5, 337.5, 342, 337.5, 328.5, 324, 328.5, 337.5, 243, 247.5, 243, 234, 229.5, 234, 243, 243, 247.5, 243, 234, 229.5, 234, 243, 243, 247.5, 243, 234, 229.5, 234, 243, 229.5, 234, 229.5, 220.5, 216, 220.5, 229.5, 229.5, 234, 229.5, 220.5, 216, 220.5, 229.5, 216, 220.5, 216, 207, 202.5, 207, 216, 216, 220.5, 216, 207, 202.5, 207, 216, 243, 247.5, 243, 234, 229.5, 234, 243, 202.5, 207, 202.5, 193.5, 189, 193.5, 202.5, 202.5, 207, 202.5, 193.5, 189, 193.5, 202.5, 216, 220.5, 216, 207, 202.5, 207, 216, 229.5, 234, 229.5, 220.5, 216, 220.5, 229.5, 229.5, 234, 229.5, 220.5, 216, 220.5, 229.5, 202.5, 207, 202.5, 193.5, 189, 193.5, 202.5, 324, 328.5, 324, 315, 310.5, 315, 324, 81, 85.5, 81, 72, 67.5, 72, 81, 94.5, 99, 94.5, 85.5, 81, 85.5, 94.5, 108, 112.5, 108, 99, 94.5, 99, 108, 121.5, 126, 121.5, 112.5, 108, 112.5, 121.5, 121.5, 126, 121.5, 112.5, 108, 112.5, 121.5, 108, 112.5, 108, 99, 94.5, 99, 108, 108, 112.5, 108, 99, 94.5, 99, 108, 121.5, 126, 121.5, 112.5, 108, 112.5, 121.5, 81, 85.5, 81, 72, 67.5, 72, 81, 94.5, 99, 94.5, 85.5, 81, 85.5, 94.5, 67.5, 72, 67.5, 58.5, 54, 58.5, 67.5, 54, 58.5, 54, 45, 40.5, 45, 54, 54, 58.5, 54, 45, 40.5, 45, 54, 67.5, 72, 67.5, 58.5, 54, 58.5, 67.5, 67.5, 72, 67.5, 58.5, 54, 58.5, 67.5, 54, 58.5, 54, 45, 40.5, 45, 54, 40.5, 45, 40.5, 31.5, 27, 31.5, 40.5, 40.5, 45, 40.5, 31.5, 27, 31.5, 40.5, 81, 85.5, 81, 72, 67.5, 72, 81, 135, 139.5, 135, 126, 121.5, 126, 135, 121.5, 126, 121.5, 112.5, 108, 112.5, 121.5, 81, 85.5, 81, 72, 67.5, 72, 81, 148.5, 153, 148.5, 139.5, 135, 139.5, 148.5, 108, 112.5, 108, 99, 94.5, 99, 108, 94.5, 99, 94.5, 85.5, 81, 85.5, 94.5, 108, 112.5, 108, 99, 94.5, 99, 108, 94.5, 99, 94.5, 85.5, 81, 85.5, 94.5, 81, 85.5, 81, 72, 67.5, 72, 81, 94.5, 99, 94.5, 85.5, 81, 85.5, 94.5, 121.5, 126, 121.5, 112.5, 108, 112.5, 121.5, 108, 112.5, 108, 99, 94.5, 99, 108, 121.5, 126, 121.5, 112.5, 108, 112.5, 121.5, 135, 139.5, 135, 126, 121.5, 126, 135, 148.5, 153, 148.5, 139.5, 135, 139.5, 148.5, 135, 139.5, 135, 126, 121.5, 126, 135, 175.5, 180, 175.5, 166.5, 162, 166.5, 175.5, 162, 166.5, 162, 153, 148.5, 153, 162, 175.5, 180, 175.5, 166.5, 162, 166.5, 175.5, 189, 193.5, 189, 180, 175.5, 180, 189, 162, 166.5, 162, 153, 148.5, 153, 162, 162, 166.5, 162, 153, 148.5, 153, 162, 148.5, 153, 148.5, 139.5, 135, 139.5, 148.5, 148.5, 153, 148.5, 139.5, 135, 139.5, 148.5, 162, 166.5, 162, 153, 148.5, 153, 162, 162, 166.5, 162, 153, 148.5, 153, 162, 256.5, 261, 256.5, 247.5, 243, 247.5, 256.5, 256.5, 261, 256.5, 247.5, 243, 247.5, 256.5, 256.5, 261, 256.5, 247.5, 243, 247.5, 256.5, 243, 247.5, 243, 234, 229.5, 234, 243, 229.5, 234, 229.5, 220.5, 216, 220.5, 229.5, 243, 247.5, 243, 234, 229.5, 234, 243, 54, 58.5, 54, 45, 40.5, 45, 54, 54, 58.5, 54, 45, 40.5, 45, 54, 54, 58.5, 54, 45, 40.5, 45, 54, 54, 58.5, 54, 45, 40.5, 45, 54, 40.5, 45, 40.5, 31.5, 27, 31.5, 40.5, 27, 31.5, 27, 18, 13.5, 18, 27, 40.5, 45, 40.5, 31.5, 27, 31.5, 40.5, 40.5, 45, 40.5, 31.5, 27, 31.5, 40.5, 54, 58.5, 54, 45, 40.5, 45, 54, 148.5, 153, 148.5, 139.5, 135, 139.5, 148.5, 121.5, 126, 121.5, 112.5, 108, 112.5, 121.5, 135, 139.5, 135, 126, 121.5, 126, 135, 135, 139.5, 135, 126, 121.5, 126, 135, 148.5, 153, 148.5, 139.5, 135, 139.5, 148.5, 121.5, 126, 121.5, 112.5, 108, 112.5, 121.5, 121.5, 126, 121.5, 112.5, 108, 112.5, 121.5, 121.5, 126, 121.5, 112.5, 108, 112.5, 121.5, 27, 31.5, 27, 18, 13.5, 18, 27, 13.5, 18, 13.5, 4.5, 0, 4.5, 13.5, 13.5, 18, 13.5, 4.5, 0, 4.5, 13.5, 27, 31.5, 27, 18, 13.5, 18, 27, 40.5, 45, 40.5, 31.5, 27, 31.5, 40.5, 27, 31.5, 27, 18, 13.5, 18, 27, 27, 31.5, 27, 18, 13.5, 18, 27, 67.5, 72, 67.5, 58.5, 54, 58.5, 67.5, 67.5, 72, 67.5, 58.5, 54, 58.5, 67.5, 54, 58.5, 54, 45, 40.5, 45, 54, 40.5, 45, 40.5, 31.5, 27, 31.5, 40.5, 40.5, 45, 40.5, 31.5, 27, 31.5, 40.5, 40.5, 45, 40.5, 31.5, 27, 31.5, 40.5, 67.5, 72, 67.5, 58.5, 54, 58.5, 67.5, 54, 58.5, 54, 45, 40.5, 45, 54, 54, 58.5, 54, 45, 40.5, 45, 54, 94.5, 99, 94.5, 85.5, 81, 85.5, 94.5, 94.5, 99, 94.5, 85.5, 81, 85.5, 94.5, 67.5, 72, 67.5, 58.5, 54, 58.5, 67.5, 81, 85.5, 81, 72, 67.5, 72, 81, 81, 85.5, 81, 72, 67.5, 72, 81, 67.5, 72, 67.5, 58.5, 54, 58.5, 67.5, 54, 58.5, 54, 45, 40.5, 45, 54, 54, 58.5, 54, 45, 40.5, 45, 54, 148.5, 153, 148.5, 139.5, 135, 139.5, 148.5, 162, 166.5, 162, 153, 148.5, 153, 162, 135, 139.5, 135, 126, 121.5, 126, 135, 162, 166.5, 162, 153, 148.5, 153, 162, 148.5, 153, 148.5, 139.5, 135, 139.5, 148.5, 135, 139.5, 135, 126, 121.5, 126, 135, 175.5, 180, 175.5, 166.5, 162, 166.5, 175.5, 175.5, 180, 175.5, 166.5, 162, 166.5, 175.5, 324, 328.5, 324, 315, 310.5, 315, 324, 202.5, 207, 202.5, 193.5, 189, 193.5, 202.5, 216, 220.5, 216, 207, 202.5, 207, 216, 229.5, 234, 229.5, 220.5, 216, 220.5, 229.5, 243, 247.5, 243, 234, 229.5, 234, 243, 108, 112.5, 108, 99, 94.5, 99, 108, 175.5, 180, 175.5, 166.5, 162, 166.5, 175.5, 189, 193.5, 189, 180, 175.5, 180, 189, 189, 193.5, 189, 180, 175.5, 180, 189, 175.5, 180, 175.5, 166.5, 162, 166.5, 175.5, 175.5, 180, 175.5, 166.5, 162, 166.5, 175.5, 175.5, 180, 175.5, 166.5, 162, 166.5, 175.5, 202.5, 207, 202.5, 193.5, 189, 193.5, 202.5, 202.5, 207, 202.5, 193.5, 189, 193.5, 202.5, 189, 193.5, 189, 180, 175.5, 180, 189, 189, 193.5, 189, 180, 175.5, 180, 189, 189, 193.5, 189, 180, 175.5, 180, 189, 175.5, 180, 175.5, 166.5, 162, 166.5, 175.5, 189, 193.5, 189, 180, 175.5, 180, 189, 94.5, 99, 94.5, 85.5, 81, 85.5, 94.5, 135, 139.5, 135, 126, 121.5, 126, 135, 148.5, 153, 148.5, 139.5, 135, 139.5, 148.5, 121.5, 126, 121.5, 112.5, 108, 112.5, 121.5, 40.5, 45, 40.5, 31.5, 27, 31.5, 40.5, 27, 31.5, 27, 18, 13.5, 18, 27, 148.5, 153, 148.5, 139.5, 135, 139.5, 148.5, 162, 166.5, 162, 153, 148.5, 153, 162, 148.5, 153, 148.5, 139.5, 135, 139.5, 148.5, 135, 139.5, 135, 126, 121.5, 126, 135, 94.5, 99, 94.5, 85.5, 81, 85.5, 94.5, 135, 139.5, 135, 126, 121.5, 126, 135, 121.5, 126, 121.5, 112.5, 108, 112.5, 121.5, 108, 112.5, 108, 99, 94.5, 99, 108, 94.5, 99, 94.5, 85.5, 81, 85.5, 94.5, 121.5, 126, 121.5, 112.5, 108, 112.5, 121.5, 108, 112.5, 108, 99, 94.5, 99, 108, 135, 139.5, 135, 126, 121.5, 126, 135, 175.5, 180, 175.5, 166.5, 162, 166.5, 175.5, 189, 193.5, 189, 180, 175.5, 180, 189, 175.5, 180, 175.5, 166.5, 162, 166.5, 175.5, 135, 139.5, 135, 126, 121.5, 126, 135, 121.5, 126, 121.5, 112.5, 108, 112.5, 121.5, 148.5, 153, 148.5, 139.5, 135, 139.5, 148.5, 121.5, 126, 121.5, 112.5, 108, 112.5, 121.5, 108, 112.5, 108, 99, 94.5, 99, 108, 121.5, 126, 121.5, 112.5, 108, 112.5, 121.5, 108, 112.5, 108, 99, 94.5, 99, 108, 121.5, 126, 121.5, 112.5, 108, 112.5, 121.5, 121.5, 126, 121.5, 112.5, 108, 112.5, 121.5, 108, 112.5, 108, 99, 94.5, 99, 108, 121.5, 126, 121.5, 112.5, 108, 112.5, 121.5, 135, 139.5, 135, 126, 121.5, 126, 135, 135, 139.5, 135, 126, 121.5, 126, 135, 121.5, 126, 121.5, 112.5, 108, 112.5, 121.5, 135, 139.5, 135, 126, 121.5, 126, 135, 108, 112.5, 108, 99, 94.5, 99, 108, 94.5, 99, 94.5, 85.5, 81, 85.5, 94.5, 94.5, 99, 94.5, 85.5, 81, 85.5, 94.5, 94.5, 99, 94.5, 85.5, 81, 85.5, 94.5, 67.5, 72, 67.5, 58.5, 54, 58.5, 67.5, 81, 85.5, 81, 72, 67.5, 72, 81, 81, 85.5, 81, 72, 67.5, 72, 81, 81, 85.5, 81, 72, 67.5, 72, 81, 67.5, 72, 67.5, 58.5, 54, 58.5, 67.5, 40.5, 45, 40.5, 31.5, 27, 31.5, 40.5, 67.5, 72, 67.5, 58.5, 54, 58.5, 67.5, 67.5, 72, 67.5, 58.5, 54, 58.5, 67.5, 54, 58.5, 54, 45, 40.5, 45, 54, 54, 58.5, 54, 45, 40.5, 45, 54, 54, 58.5, 54, 45, 40.5, 45, 54, 54, 58.5, 54, 45, 40.5, 45, 54, 135, 139.5, 135, 126, 121.5, 126, 135, 135, 139.5, 135, 126, 121.5, 126, 135, 108, 112.5, 108, 99, 94.5, 99, 108, 94.5, 99, 94.5, 85.5, 81, 85.5, 94.5, 81, 85.5, 81, 72, 67.5, 72, 81, 121.5, 126, 121.5, 112.5, 108, 112.5, 121.5, 81, 85.5, 81, 72, 67.5, 72, 81, 108, 112.5, 108, 99, 94.5, 99, 108, 81, 85.5, 81, 72, 67.5, 72, 81, 121.5, 126, 121.5, 112.5, 108, 112.5, 121.5, 81, 85.5, 81, 72, 67.5, 72, 81, 94.5, 99, 94.5, 85.5, 81, 85.5, 94.5, 108, 112.5, 108, 99, 94.5, 99, 108, 94.5, 99, 94.5, 85.5, 81, 85.5, 94.5, 121.5, 126, 121.5, 112.5, 108, 112.5, 121.5, 108, 112.5, 108, 99, 94.5, 99, 108, 189, 193.5, 189, 180, 175.5, 180, 189, 202.5, 207, 202.5, 193.5, 189, 193.5, 202.5, 189, 193.5, 189, 180, 175.5, 180, 189, 202.5, 207, 202.5, 193.5, 189, 193.5, 202.5, 175.5, 180, 175.5, 166.5, 162, 166.5, 175.5, 108, 112.5, 108, 99, 94.5, 99, 108, 108, 112.5, 108, 99, 94.5, 99, 108, 108, 112.5, 108, 99, 94.5, 99, 108, 121.5, 126, 121.5, 112.5, 108, 112.5, 121.5, 121.5, 126, 121.5, 112.5, 108, 112.5, 121.5, 108, 112.5, 108, 99, 94.5, 99, 108, 94.5, 99, 94.5, 85.5, 81, 85.5, 94.5, 94.5, 99, 94.5, 85.5, 81, 85.5, 94.5, 108, 112.5, 108, 99, 94.5, 99, 108, 81, 85.5, 81, 72, 67.5, 72, 81, 94.5, 99, 94.5, 85.5, 81, 85.5, 94.5, 108, 112.5, 108, 99, 94.5, 99, 108, 94.5, 99, 94.5, 85.5, 81, 85.5, 94.5, 108, 112.5, 108, 99, 94.5, 99, 108, 81, 85.5, 81, 72, 67.5, 72, 81, 94.5, 99, 94.5, 85.5, 81, 85.5, 94.5, 108, 112.5, 108, 99, 94.5, 99, 108, 81, 85.5, 81, 72, 67.5, 72, 81, 94.5, 99, 94.5, 85.5, 81, 85.5, 94.5, 81, 85.5, 81, 72, 67.5, 72, 81, 108, 112.5, 108, 99, 94.5, 99, 108, 81, 85.5, 81, 72, 67.5, 72, 81, 121.5, 126, 121.5, 112.5, 108, 112.5, 121.5, 310.5, 315, 310.5, 301.5, 297, 301.5, 310.5, 67.5, 72, 67.5, 58.5, 54, 58.5, 67.5, 81, 85.5, 81, 72, 67.5, 72, 81, 229.5, 234, 229.5, 220.5, 216, 220.5, 229.5, 216, 220.5, 216, 207, 202.5, 207, 216, 202.5, 207, 202.5, 193.5, 189, 193.5, 202.5, 202.5, 207, 202.5, 193.5, 189, 193.5, 202.5, 216, 220.5, 216, 207, 202.5, 207, 216, 229.5, 234, 229.5, 220.5, 216, 220.5, 229.5, 216, 220.5, 216, 207, 202.5, 207, 216, 108, 112.5, 108, 99, 94.5, 99, 108, 175.5, 180, 175.5, 166.5, 162, 166.5, 175.5, 189, 193.5, 189, 180, 175.5, 180, 189, 189, 193.5, 189, 180, 175.5, 180, 189, 189, 193.5, 189, 180, 175.5, 180, 189, 175.5, 180, 175.5, 166.5, 162, 166.5, 175.5, 175.5, 180, 175.5, 166.5, 162, 166.5, 175.5, 189, 193.5, 189, 180, 175.5, 180, 189, 175.5, 180, 175.5, 166.5, 162, 166.5, 175.5, 189, 193.5, 189, 180, 175.5, 180, 189, 229.5, 234, 229.5, 220.5, 216, 220.5, 229.5, 270, 274.5, 270, 261, 256.5, 261, 270, 216, 220.5, 216, 207, 202.5, 207, 216, 216, 220.5, 216, 207, 202.5, 207, 216, 243, 247.5, 243, 234, 229.5, 234, 243, 256.5, 261, 256.5, 247.5, 243, 247.5, 256.5, 283.5, 288, 283.5, 274.5, 270, 274.5, 283.5, 256.5, 261, 256.5, 247.5, 243, 247.5, 256.5, 283.5, 288, 283.5, 274.5, 270, 274.5, 283.5, 270, 274.5, 270, 261, 256.5, 261, 270, 229.5, 234, 229.5, 220.5, 216, 220.5, 229.5, 216, 220.5, 216, 207, 202.5, 207, 216, 189, 193.5, 189, 180, 175.5, 180, 189, 270, 274.5, 270, 261, 256.5, 261, 270, 310.5, 315, 310.5, 301.5, 297, 301.5, 310.5, 229.5, 234, 229.5, 220.5, 216, 220.5, 229.5, 256.5, 261, 256.5, 247.5, 243, 247.5, 256.5, 270, 274.5, 270, 261, 256.5, 261, 270, 202.5, 207, 202.5, 193.5, 189, 193.5, 202.5, 297, 301.5, 297, 288, 283.5, 288, 297, 270, 274.5, 270, 261, 256.5, 261, 270, 297, 301.5, 297, 288, 283.5, 288, 297, 243, 247.5, 243, 234, 229.5, 234, 243, 229.5, 234, 229.5, 220.5, 216, 220.5, 229.5, 243, 247.5, 243, 234, 229.5, 234, 243, 202.5, 207, 202.5, 193.5, 189, 193.5, 202.5, 310.5, 315, 310.5, 301.5, 297, 301.5, 310.5, 297, 301.5, 297, 288, 283.5, 288, 297, 283.5, 288, 283.5, 274.5, 270, 274.5, 283.5, 243, 247.5, 243, 234, 229.5, 234, 243, 256.5, 261, 256.5, 247.5, 243, 247.5, 256.5, 229.5, 234, 229.5, 220.5, 216, 220.5, 229.5, 216, 220.5, 216, 207, 202.5, 207, 216, 324, 328.5, 324, 315, 310.5, 315, 324, 283.5, 288, 283.5, 274.5, 270, 274.5, 283.5, 243, 247.5, 243, 234, 229.5, 234, 243, 135, 139.5, 135, 126, 121.5, 126, 135, 162, 166.5, 162, 153, 148.5, 153, 162, 148.5, 153, 148.5, 139.5, 135, 139.5, 148.5, 148.5, 153, 148.5, 139.5, 135, 139.5, 148.5, 162, 166.5, 162, 153, 148.5, 153, 162, 162, 166.5, 162, 153, 148.5, 153, 162, 162, 166.5, 162, 153, 148.5, 153, 162, 162, 166.5, 162, 153, 148.5, 153, 162, 162, 166.5, 162, 153, 148.5, 153, 162, 148.5, 153, 148.5, 139.5, 135, 139.5, 148.5, 148.5, 153, 148.5, 139.5, 135, 139.5, 148.5, 148.5, 153, 148.5, 139.5, 135, 139.5, 148.5, 162, 166.5, 162, 153, 148.5, 153, 162, 135, 139.5, 135, 126, 121.5, 126, 135, 148.5, 153, 148.5, 139.5, 135, 139.5, 148.5, 310.5, 315, 310.5, 301.5, 297, 301.5, 310.5, 40.5, 45, 40.5, 31.5, 27, 31.5, 40.5, 81, 85.5, 81, 72, 67.5, 72, 81, 81, 85.5, 81, 72, 67.5, 72, 81, 108, 112.5, 108, 99, 94.5, 99, 108, 81, 85.5, 81, 72, 67.5, 72, 81, 94.5, 99, 94.5, 85.5, 81, 85.5, 94.5, 81, 85.5, 81, 72, 67.5, 72, 81, 94.5, 99, 94.5, 85.5, 81, 85.5, 94.5, 94.5, 99, 94.5, 85.5, 81, 85.5, 94.5, 94.5, 99, 94.5, 85.5, 81, 85.5, 94.5, 94.5, 99, 94.5, 85.5, 81, 85.5, 94.5, 54, 58.5, 54, 45, 40.5, 45, 54, 40.5, 45, 40.5, 31.5, 27, 31.5, 40.5, 27, 31.5, 27, 18, 13.5, 18, 27, 27, 31.5, 27, 18, 13.5, 18, 27, 40.5, 45, 40.5, 31.5, 27, 31.5, 40.5, 27, 31.5, 27, 18, 13.5, 18, 27, 13.5, 18, 13.5, 4.5, 0, 4.5, 13.5, 27, 31.5, 27, 18, 13.5, 18, 27, 135, 139.5, 135, 126, 121.5, 126, 135, 135, 139.5, 135, 126, 121.5, 126, 135, 148.5, 153, 148.5, 139.5, 135, 139.5, 148.5, 121.5, 126, 121.5, 112.5, 108, 112.5, 121.5), id = c("ak00", "ak00", "ak00", "ak00", "ak00", "ak00", "ak00", "al01", "al01", "al01", "al01", "al01", "al01", "al01", "al02", "al02", "al02", "al02", "al02", "al02", "al02", "al03", "al03", "al03", "al03", "al03", "al03", "al03", "al04", "al04", "al04", "al04", "al04", "al04", "al04", "al05", "al05", "al05", "al05", "al05", "al05", "al05", "al06", "al06", "al06", "al06", "al06", "al06", "al06", "al07", "al07", "al07", "al07", "al07", "al07", "al07", "ar01", "ar01", "ar01", "ar01", "ar01", "ar01", "ar01", "ar02", "ar02", "ar02", "ar02", "ar02", "ar02", "ar02", "ar03", "ar03", "ar03", "ar03", "ar03", "ar03", "ar03", "ar04", "ar04", "ar04", "ar04", "ar04", "ar04", "ar04", "as00", "as00", "as00", "as00", "as00", "as00", "as00", "az01", "az01", "az01", "az01", "az01", "az01", "az01", "az02", "az02", "az02", "az02", "az02", "az02", "az02", "az03", "az03", "az03", "az03", "az03", "az03", "az03", "az04", "az04", "az04", "az04", "az04", "az04", "az04", "az05", "az05", "az05", "az05", "az05", "az05", "az05", "az06", "az06", "az06", "az06", "az06", "az06", "az06", "az07", "az07", "az07", "az07", "az07", "az07", "az07", "az08", "az08", "az08", "az08", "az08", "az08", "az08", "az09", "az09", "az09", "az09", "az09", "az09", "az09", "ca01", "ca01", "ca01", "ca01", "ca01", "ca01", "ca01", "ca02", "ca02", "ca02", "ca02", "ca02", "ca02", "ca02", "ca03", "ca03", "ca03", "ca03", "ca03", "ca03", "ca03", "ca04", "ca04", "ca04", "ca04", "ca04", "ca04", "ca04", "ca05", "ca05", "ca05", "ca05", "ca05", "ca05", "ca05", "ca06", "ca06", "ca06", "ca06", "ca06", "ca06", "ca06", "ca07", "ca07", "ca07", "ca07", "ca07", "ca07", "ca07", "ca08", "ca08", "ca08", "ca08", "ca08", "ca08", "ca08", "ca09", "ca09", "ca09", "ca09", "ca09", "ca09", "ca09", "ca10", "ca10", "ca10", "ca10", "ca10", "ca10", "ca10", "ca11", "ca11", "ca11", "ca11", "ca11", "ca11", "ca11", "ca12", "ca12", "ca12", "ca12", "ca12", "ca12", "ca12", "ca13", "ca13", "ca13", "ca13", "ca13", "ca13", "ca13", "ca14", "ca14", "ca14", "ca14", "ca14", "ca14", "ca14", "ca15", "ca15", "ca15", "ca15", "ca15", "ca15", "ca15", "ca16", "ca16", "ca16", "ca16", "ca16", "ca16", "ca16", "ca17", "ca17", "ca17", "ca17", "ca17", "ca17", "ca17", "ca18", "ca18", "ca18", "ca18", "ca18", "ca18", "ca18", "ca19", "ca19", "ca19", "ca19", "ca19", "ca19", "ca19", "ca20", "ca20", "ca20", "ca20", "ca20", "ca20", "ca20", "ca22", "ca22", "ca22", "ca22", "ca22", "ca22", "ca22", "ca23", "ca23", "ca23", "ca23", "ca23", "ca23", "ca23", "ca24", "ca24", "ca24", "ca24", "ca24", "ca24", "ca24", "ca25", "ca25", "ca25", "ca25", "ca25", "ca25", "ca25", "ca26", "ca26", "ca26", "ca26", "ca26", "ca26", "ca26", "ca27", "ca27", "ca27", "ca27", "ca27", "ca27", "ca27", "ca28", "ca28", "ca28", "ca28", "ca28", "ca28", "ca28", "ca29", "ca29", "ca29", "ca29", "ca29", "ca29", "ca29", "ca30", "ca30", "ca30", "ca30", "ca30", "ca30", "ca30", "ca31", "ca31", "ca31", "ca31", "ca31", "ca31", "ca31", "ca32", "ca32", "ca32", "ca32", "ca32", "ca32", "ca32", "ca33", "ca33", "ca33", "ca33", "ca33", "ca33", "ca33", "ca34", "ca34", "ca34", "ca34", "ca34", "ca34", "ca34", "ca35", "ca35", "ca35", "ca35", "ca35", "ca35", "ca35", "ca36", "ca36", "ca36", "ca36", "ca36", "ca36", "ca36", "ca37", "ca37", "ca37", "ca37", "ca37", "ca37", "ca37", "ca38", "ca38", "ca38", "ca38", "ca38", "ca38", "ca38", "ca39", "ca39", "ca39", "ca39", "ca39", "ca39", "ca39", "ca40", "ca40", "ca40", "ca40", "ca40", "ca40", "ca40", "ca41", "ca41", "ca41", "ca41", "ca41", "ca41", "ca41", "ca42", "ca42", "ca42", "ca42", "ca42", "ca42", "ca42", "ca43", "ca43", "ca43", "ca43", "ca43", "ca43", "ca43", "ca44", "ca44", "ca44", "ca44", "ca44", "ca44", "ca44", "ca45", "ca45", "ca45", "ca45", "ca45", "ca45", "ca45", "ca46", "ca46", "ca46", "ca46", "ca46", "ca46", "ca46", "ca47", "ca47", "ca47", "ca47", "ca47", "ca47", "ca47", "ca48", "ca48", "ca48", "ca48", "ca48", "ca48", "ca48", "ca49", "ca49", "ca49", "ca49", "ca49", "ca49", "ca49", "ca50", "ca50", "ca50", "ca50", "ca50", "ca50", "ca50", "ca51", "ca51", "ca51", "ca51", "ca51", "ca51", "ca51", "ca52", "ca52", "ca52", "ca52", "ca52", "ca52", "ca52", "ca53", "ca53", "ca53", "ca53", "ca53", "ca53", "ca53", "co01", "co01", "co01", "co01", "co01", "co01", "co01", "co02", "co02", "co02", "co02", "co02", "co02", "co02", "co03", "co03", "co03", "co03", "co03", "co03", "co03", "co04", "co04", "co04", "co04", "co04", "co04", "co04", "co05", "co05", "co05", "co05", "co05", "co05", "co05", "co06", "co06", "co06", "co06", "co06", "co06", "co06", "co07", "co07", "co07", "co07", "co07", "co07", "co07", "ct01", "ct01", "ct01", "ct01", "ct01", "ct01", "ct01", "ct02", "ct02", "ct02", "ct02", "ct02", "ct02", "ct02", "ct03", "ct03", "ct03", "ct03", "ct03", "ct03", "ct03", "ct04", "ct04", "ct04", "ct04", "ct04", "ct04", "ct04", "ct05", "ct05", "ct05", "ct05", "ct05", "ct05", "ct05", "dc00", "dc00", "dc00", "dc00", "dc00", "dc00", "dc00", "de00", "de00", "de00", "de00", "de00", "de00", "de00", "fl01", "fl01", "fl01", "fl01", "fl01", "fl01", "fl01", "fl02", "fl02", "fl02", "fl02", "fl02", "fl02", "fl02", "fl03", "fl03", "fl03", "fl03", "fl03", "fl03", "fl03", "fl04", "fl04", "fl04", "fl04", "fl04", "fl04", "fl04", "fl05", "fl05", "fl05", "fl05", "fl05", "fl05", "fl05", "fl06", "fl06", "fl06", "fl06", "fl06", "fl06", "fl06", "fl07", "fl07", "fl07", "fl07", "fl07", "fl07", "fl07", "fl08", "fl08", "fl08", "fl08", "fl08", "fl08", "fl08", "fl09", "fl09", "fl09", "fl09", "fl09", "fl09", "fl09", "fl10", "fl10", "fl10", "fl10", "fl10", "fl10", "fl10", "fl11", "fl11", "fl11", "fl11", "fl11", "fl11", "fl11", "fl12", "fl12", "fl12", "fl12", "fl12", "fl12", "fl12", "fl13", "fl13", "fl13", "fl13", "fl13", "fl13", "fl13", "fl14", "fl14", "fl14", "fl14", "fl14", "fl14", "fl14", "fl15", "fl15", "fl15", "fl15", "fl15", "fl15", "fl15", "fl16", "fl16", "fl16", "fl16", "fl16", "fl16", "fl16", "fl17", "fl17", "fl17", "fl17", "fl17", "fl17", "fl17", "fl18", "fl18", "fl18", "fl18", "fl18", "fl18", "fl18", "fl19", "fl19", "fl19", "fl19", "fl19", "fl19", "fl19", "fl20", "fl20", "fl20", "fl20", "fl20", "fl20", "fl20", "fl21", "fl21", "fl21", "fl21", "fl21", "fl21", "fl21", "fl22", "fl22", "fl22", "fl22", "fl22", "fl22", "fl22", "fl23", "fl23", "fl23", "fl23", "fl23", "fl23", "fl23", "fl24", "fl24", "fl24", "fl24", "fl24", "fl24", "fl24", "fl25", "fl25", "fl25", "fl25", "fl25", "fl25", "fl25", "fl26", "fl26", "fl26", "fl26", "fl26", "fl26", "fl26", "fl27", "fl27", "fl27", "fl27", "fl27", "fl27", "fl27", "ga01", "ga01", "ga01", "ga01", "ga01", "ga01", "ga01", "ga02", "ga02", "ga02", "ga02", "ga02", "ga02", "ga02", "ga03", "ga03", "ga03", "ga03", "ga03", "ga03", "ga03", "ga04", "ga04", "ga04", "ga04", "ga04", "ga04", "ga04", "ga05", "ga05", "ga05", "ga05", "ga05", "ga05", "ga05", "ga06", "ga06", "ga06", "ga06", "ga06", "ga06", "ga06", "ga07", "ga07", "ga07", "ga07", "ga07", "ga07", "ga07", "ga08", "ga08", "ga08", "ga08", "ga08", "ga08", "ga08", "ga09", "ga09", "ga09", "ga09", "ga09", "ga09", "ga09", "ga10", "ga10", "ga10", "ga10", "ga10", "ga10", "ga10", "ga11", "ga11", "ga11", "ga11", "ga11", "ga11", "ga11", "ga12", "ga12", "ga12", "ga12", "ga12", "ga12", "ga12", "ga13", "ga13", "ga13", "ga13", "ga13", "ga13", "ga13", "ga14", "ga14", "ga14", "ga14", "ga14", "ga14", "ga14", "gu00", "gu00", "gu00", "gu00", "gu00", "gu00", "gu00", "hi01", "hi01", "hi01", "hi01", "hi01", "hi01", "hi01", "hi02", "hi02", "hi02", "hi02", "hi02", "hi02", "hi02", "ia01", "ia01", "ia01", "ia01", "ia01", "ia01", "ia01", "ia02", "ia02", "ia02", "ia02", "ia02", "ia02", "ia02", "ia03", "ia03", "ia03", "ia03", "ia03", "ia03", "ia03", "ia04", "ia04", "ia04", "ia04", "ia04", "ia04", "ia04", "id01", "id01", "id01", "id01", "id01", "id01", "id01", "id02", "id02", "id02", "id02", "id02", "id02", "id02", "il01", "il01", "il01", "il01", "il01", "il01", "il01", "il02", "il02", "il02", "il02", "il02", "il02", "il02", "il03", "il03", "il03", "il03", "il03", "il03", "il03", "il04", "il04", "il04", "il04", "il04", "il04", "il04", "il05", "il05", "il05", "il05", "il05", "il05", "il05", "il06", "il06", "il06", "il06", "il06", "il06", "il06", "il07", "il07", "il07", "il07", "il07", "il07", "il07", "il08", "il08", "il08", "il08", "il08", "il08", "il08", "il09", "il09", "il09", "il09", "il09", "il09", "il09", "il10", "il10", "il10", "il10", "il10", "il10", "il10", "il11", "il11", "il11", "il11", "il11", "il11", "il11", "il12", "il12", "il12", "il12", "il12", "il12", "il12", "il13", "il13", "il13", "il13", "il13", "il13", "il13", "il14", "il14", "il14", "il14", "il14", "il14", "il14", "il15", "il15", "il15", "il15", "il15", "il15", "il15", "il16", "il16", "il16", "il16", "il16", "il16", "il16", "il17", "il17", "il17", "il17", "il17", "il17", "il17", "il18", "il18", "il18", "il18", "il18", "il18", "il18", "in01", "in01", "in01", "in01", "in01", "in01", "in01", "in02", "in02", "in02", "in02", "in02", "in02", "in02", "in03", "in03", "in03", "in03", "in03", "in03", "in03", "in04", "in04", "in04", "in04", "in04", "in04", "in04", "in05", "in05", "in05", "in05", "in05", "in05", "in05", "in06", "in06", "in06", "in06", "in06", "in06", "in06", "in07", "in07", "in07", "in07", "in07", "in07", "in07", "in08", "in08", "in08", "in08", "in08", "in08", "in08", "in09", "in09", "in09", "in09", "in09", "in09", "in09", "ks01", "ks01", "ks01", "ks01", "ks01", "ks01", "ks01", "ks02", "ks02", "ks02", "ks02", "ks02", "ks02", "ks02", "ks03", "ks03", "ks03", "ks03", "ks03", "ks03", "ks03", "ks04", "ks04", "ks04", "ks04", "ks04", "ks04", "ks04", "ky01", "ky01", "ky01", "ky01", "ky01", "ky01", "ky01", "ky02", "ky02", "ky02", "ky02", "ky02", "ky02", "ky02", "ky03", "ky03", "ky03", "ky03", "ky03", "ky03", "ky03", "ky04", "ky04", "ky04", "ky04", "ky04", "ky04", "ky04", "ky05", "ky05", "ky05", "ky05", "ky05", "ky05", "ky05", "ky06", "ky06", "ky06", "ky06", "ky06", "ky06", "ky06", "la01", "la01", "la01", "la01", "la01", "la01", "la01", "la02", "la02", "la02", "la02", "la02", "la02", "la02", "la03", "la03", "la03", "la03", "la03", "la03", "la03", "la04", "la04", "la04", "la04", "la04", "la04", "la04", "la05", "la05", "la05", "la05", "la05", "la05", "la05", "la06", "la06", "la06", "la06", "la06", "la06", "la06", "ma01", "ma01", "ma01", "ma01", "ma01", "ma01", "ma01", "ma02", "ma02", "ma02", "ma02", "ma02", "ma02", "ma02", "ma03", "ma03", "ma03", "ma03", "ma03", "ma03", "ma03", "ma04", "ma04", "ma04", "ma04", "ma04", "ma04", "ma04", "ma05", "ma05", "ma05", "ma05", "ma05", "ma05", "ma05", "ma06", "ma06", "ma06", "ma06", "ma06", "ma06", "ma06", "ma07", "ma07", "ma07", "ma07", "ma07", "ma07", "ma07", "ma08", "ma08", "ma08", "ma08", "ma08", "ma08", "ma08", "ma09", "ma09", "ma09", "ma09", "ma09", "ma09", "ma09", "md01", "md01", "md01", "md01", "md01", "md01", "md01", "md02", "md02", "md02", "md02", "md02", "md02", "md02", "md03", "md03", "md03", "md03", "md03", "md03", "md03", "md04", "md04", "md04", "md04", "md04", "md04", "md04", "md05", "md05", "md05", "md05", "md05", "md05", "md05", "md06", "md06", "md06", "md06", "md06", "md06", "md06", "md07", "md07", "md07", "md07", "md07", "md07", "md07", "md08", "md08", "md08", "md08", "md08", "md08", "md08", "me01", "me01", "me01", "me01", "me01", "me01", "me01", "me02", "me02", "me02", "me02", "me02", "me02", "me02", "mi01", "mi01", "mi01", "mi01", "mi01", "mi01", "mi01", "mi02", "mi02", "mi02", "mi02", "mi02", "mi02", "mi02", "mi03", "mi03", "mi03", "mi03", "mi03", "mi03", "mi03", "mi04", "mi04", "mi04", "mi04", "mi04", "mi04", "mi04", "mi05", "mi05", "mi05", "mi05", "mi05", "mi05", "mi05", "mi06", "mi06", "mi06", "mi06", "mi06", "mi06", "mi06", "mi07", "mi07", "mi07", "mi07", "mi07", "mi07", "mi07", "mi08", "mi08", "mi08", "mi08", "mi08", "mi08", "mi08", "mi09", "mi09", "mi09", "mi09", "mi09", "mi09", "mi09", "mi10", "mi10", "mi10", "mi10", "mi10", "mi10", "mi10", "mi11", "mi11", "mi11", "mi11", "mi11", "mi11", "mi11", "mi12", "mi12", "mi12", "mi12", "mi12", "mi12", "mi12", "mi13", "mi13", "mi13", "mi13", "mi13", "mi13", "mi13", "mi14", "mi14", "mi14", "mi14", "mi14", "mi14", "mi14", "mn01", "mn01", "mn01", "mn01", "mn01", "mn01", "mn01", "mn02", "mn02", "mn02", "mn02", "mn02", "mn02", "mn02", "mn03", "mn03", "mn03", "mn03", "mn03", "mn03", "mn03", "mn04", "mn04", "mn04", "mn04", "mn04", "mn04", "mn04", "mn05", "mn05", "mn05", "mn05", "mn05", "mn05", "mn05", "mn06", "mn06", "mn06", "mn06", "mn06", "mn06", "mn06", "mn07", "mn07", "mn07", "mn07", "mn07", "mn07", "mn07", "mn08", "mn08", "mn08", "mn08", "mn08", "mn08", "mn08", "mo01", "mo01", "mo01", "mo01", "mo01", "mo01", "mo01", "mo02", "mo02", "mo02", "mo02", "mo02", "mo02", "mo02", "mo03", "mo03", "mo03", "mo03", "mo03", "mo03", "mo03", "mo04", "mo04", "mo04", "mo04", "mo04", "mo04", "mo04", "mo05", "mo05", "mo05", "mo05", "mo05", "mo05", "mo05", "mo06", "mo06", "mo06", "mo06", "mo06", "mo06", "mo06", "mo07", "mo07", "mo07", "mo07", "mo07", "mo07", "mo07", "mo08", "mo08", "mo08", "mo08", "mo08", "mo08", "mo08", "mp00", "mp00", "mp00", "mp00", "mp00", "mp00", "mp00", "ms01", "ms01", "ms01", "ms01", "ms01", "ms01", "ms01", "ms02", "ms02", "ms02", "ms02", "ms02", "ms02", "ms02", "ms03", "ms03", "ms03", "ms03", "ms03", "ms03", "ms03", "ms04", "ms04", "ms04", "ms04", "ms04", "ms04", "ms04", "mt00", "mt00", "mt00", "mt00", "mt00", "mt00", "mt00", "nc01", "nc01", "nc01", "nc01", "nc01", "nc01", "nc01", "nc02", "nc02", "nc02", "nc02", "nc02", "nc02", "nc02", "nc03", "nc03", "nc03", "nc03", "nc03", "nc03", "nc03", "nc04", "nc04", "nc04", "nc04", "nc04", "nc04", "nc04", "nc05", "nc05", "nc05", "nc05", "nc05", "nc05", "nc05", "nc06", "nc06", "nc06", "nc06", "nc06", "nc06", "nc06", "nc07", "nc07", "nc07", "nc07", "nc07", "nc07", "nc07", "nc08", "nc08", "nc08", "nc08", "nc08", "nc08", "nc08", "nc09", "nc09", "nc09", "nc09", "nc09", "nc09", "nc09", "nc10", "nc10", "nc10", "nc10", "nc10", "nc10", "nc10", "nc11", "nc11", "nc11", "nc11", "nc11", "nc11", "nc11", "nc12", "nc12", "nc12", "nc12", "nc12", "nc12", "nc12", "nc13", "nc13", "nc13", "nc13", "nc13", "nc13", "nc13", "nd00", "nd00", "nd00", "nd00", "nd00", "nd00", "nd00", "ne01", "ne01", "ne01", "ne01", "ne01", "ne01", "ne01", "ne02", "ne02", "ne02", "ne02", "ne02", "ne02", "ne02", "ne03", "ne03", "ne03", "ne03", "ne03", "ne03", "ne03", "nh01", "nh01", "nh01", "nh01", "nh01", "nh01", "nh01", "nh02", "nh02", "nh02", "nh02", "nh02", "nh02", "nh02", "nj01", "nj01", "nj01", "nj01", "nj01", "nj01", "nj01", "nj02", "nj02", "nj02", "nj02", "nj02", "nj02", "nj02", "nj03", "nj03", "nj03", "nj03", "nj03", "nj03", "nj03", "nj04", "nj04", "nj04", "nj04", "nj04", "nj04", "nj04", "nj05", "nj05", "nj05", "nj05", "nj05", "nj05", "nj05", "nj06", "nj06", "nj06", "nj06", "nj06", "nj06", "nj06", "nj07", "nj07", "nj07", "nj07", "nj07", "nj07", "nj07", "nj08", "nj08", "nj08", "nj08", "nj08", "nj08", "nj08", "nj09", "nj09", "nj09", "nj09", "nj09", "nj09", "nj09", "nj10", "nj10", "nj10", "nj10", "nj10", "nj10", "nj10", "nj11", "nj11", "nj11", "nj11", "nj11", "nj11", "nj11", "nj12", "nj12", "nj12", "nj12", "nj12", "nj12", "nj12", "nm01", "nm01", "nm01", "nm01", "nm01", "nm01", "nm01", "nm02", "nm02", "nm02", "nm02", "nm02", "nm02", "nm02", "nm03", "nm03", "nm03", "nm03", "nm03", "nm03", "nm03", "nv01", "nv01", "nv01", "nv01", "nv01", "nv01", "nv01", "nv02", "nv02", "nv02", "nv02", "nv02", "nv02", "nv02", "nv03", "nv03", "nv03", "nv03", "nv03", "nv03", "nv03", "nv04", "nv04", "nv04", "nv04", "nv04", "nv04", "nv04", "ny01", "ny01", "ny01", "ny01", "ny01", "ny01", "ny01", "ny02", "ny02", "ny02", "ny02", "ny02", "ny02", "ny02", "ny03", "ny03", "ny03", "ny03", "ny03", "ny03", "ny03", "ny04", "ny04", "ny04", "ny04", "ny04", "ny04", "ny04", "ny05", "ny05", "ny05", "ny05", "ny05", "ny05", "ny05", "ny06", "ny06", "ny06", "ny06", "ny06", "ny06", "ny06", "ny07", "ny07", "ny07", "ny07", "ny07", "ny07", "ny07", "ny08", "ny08", "ny08", "ny08", "ny08", "ny08", "ny08", "ny09", "ny09", "ny09", "ny09", "ny09", "ny09", "ny09", "ny10", "ny10", "ny10", "ny10", "ny10", "ny10", "ny10", "ny11", "ny11", "ny11", "ny11", "ny11", "ny11", "ny11", "ny12", "ny12", "ny12", "ny12", "ny12", "ny12", "ny12", "ny13", "ny13", "ny13", "ny13", "ny13", "ny13", "ny13", "ny14", "ny14", "ny14", "ny14", "ny14", "ny14", "ny14", "ny15", "ny15", "ny15", "ny15", "ny15", "ny15", "ny15", "ny16", "ny16", "ny16", "ny16", "ny16", "ny16", "ny16", "ny17", "ny17", "ny17", "ny17", "ny17", "ny17", "ny17", "ny18", "ny18", "ny18", "ny18", "ny18", "ny18", "ny18", "ny19", "ny19", "ny19", "ny19", "ny19", "ny19", "ny19", "ny20", "ny20", "ny20", "ny20", "ny20", "ny20", "ny20", "ny21", "ny21", "ny21", "ny21", "ny21", "ny21", "ny21", "ny22", "ny22", "ny22", "ny22", "ny22", "ny22", "ny22", "ny23", "ny23", "ny23", "ny23", "ny23", "ny23", "ny23", "ny24", "ny24", "ny24", "ny24", "ny24", "ny24", "ny24", "ny25", "ny25", "ny25", "ny25", "ny25", "ny25", "ny25", "ny26", "ny26", "ny26", "ny26", "ny26", "ny26", "ny26", "ny27", "ny27", "ny27", "ny27", "ny27", "ny27", "ny27", "oh01", "oh01", "oh01", "oh01", "oh01", "oh01", "oh01", "oh02", "oh02", "oh02", "oh02", "oh02", "oh02", "oh02", "oh03", "oh03", "oh03", "oh03", "oh03", "oh03", "oh03", "oh04", "oh04", "oh04", "oh04", "oh04", "oh04", "oh04", "oh05", "oh05", "oh05", "oh05", "oh05", "oh05", "oh05", "oh06", "oh06", "oh06", "oh06", "oh06", "oh06", "oh06", "oh07", "oh07", "oh07", "oh07", "oh07", "oh07", "oh07", "oh08", "oh08", "oh08", "oh08", "oh08", "oh08", "oh08", "oh09", "oh09", "oh09", "oh09", "oh09", "oh09", "oh09", "oh10", "oh10", "oh10", "oh10", "oh10", "oh10", "oh10", "oh11", "oh11", "oh11", "oh11", "oh11", "oh11", "oh11", "oh12", "oh12", "oh12", "oh12", "oh12", "oh12", "oh12", "oh13", "oh13", "oh13", "oh13", "oh13", "oh13", "oh13", "oh14", "oh14", "oh14", "oh14", "oh14", "oh14", "oh14", "oh15", "oh15", "oh15", "oh15", "oh15", "oh15", "oh15", "oh16", "oh16", "oh16", "oh16", "oh16", "oh16", "oh16", "ok01", "ok01", "ok01", "ok01", "ok01", "ok01", "ok01", "ok02", "ok02", "ok02", "ok02", "ok02", "ok02", "ok02", "ok03", "ok03", "ok03", "ok03", "ok03", "ok03", "ok03", "ok04", "ok04", "ok04", "ok04", "ok04", "ok04", "ok04", "ok05", "ok05", "ok05", "ok05", "ok05", "ok05", "ok05", "or01", "or01", "or01", "or01", "or01", "or01", "or01", "or02", "or02", "or02", "or02", "or02", "or02", "or02", "or03", "or03", "or03", "or03", "or03", "or03", "or03", "or04", "or04", "or04", "or04", "or04", "or04", "or04", "or05", "or05", "or05", "or05", "or05", "or05", "or05", "pa01", "pa01", "pa01", "pa01", "pa01", "pa01", "pa01", "pa02", "pa02", "pa02", "pa02", "pa02", "pa02", "pa02", "pa03", "pa03", "pa03", "pa03", "pa03", "pa03", "pa03", "pa04", "pa04", "pa04", "pa04", "pa04", "pa04", "pa04", "pa05", "pa05", "pa05", "pa05", "pa05", "pa05", "pa05", "pa06", "pa06", "pa06", "pa06", "pa06", "pa06", "pa06", "pa07", "pa07", "pa07", "pa07", "pa07", "pa07", "pa07", "pa08", "pa08", "pa08", "pa08", "pa08", "pa08", "pa08", "pa09", "pa09", "pa09", "pa09", "pa09", "pa09", "pa09", "pa10", "pa10", "pa10", "pa10", "pa10", "pa10", "pa10", "pa11", "pa11", "pa11", "pa11", "pa11", "pa11", "pa11", "pa12", "pa12", "pa12", "pa12", "pa12", "pa12", "pa12", "pa13", "pa13", "pa13", "pa13", "pa13", "pa13", "pa13", "pa14", "pa14", "pa14", "pa14", "pa14", "pa14", "pa14", "pa15", "pa15", "pa15", "pa15", "pa15", "pa15", "pa15", "pa16", "pa16", "pa16", "pa16", "pa16", "pa16", "pa16", "pa17", "pa17", "pa17", "pa17", "pa17", "pa17", "pa17", "pa18", "pa18", "pa18", "pa18", "pa18", "pa18", "pa18", "pr00", "pr00", "pr00", "pr00", "pr00", "pr00", "pr00", "ri01", "ri01", "ri01", "ri01", "ri01", "ri01", "ri01", "ri02", "ri02", "ri02", "ri02", "ri02", "ri02", "ri02", "sc01", "sc01", "sc01", "sc01", "sc01", "sc01", "sc01", "sc02", "sc02", "sc02", "sc02", "sc02", "sc02", "sc02", "sc03", "sc03", "sc03", "sc03", "sc03", "sc03", "sc03", "sc04", "sc04", "sc04", "sc04", "sc04", "sc04", "sc04", "sc05", "sc05", "sc05", "sc05", "sc05", "sc05", "sc05", "sc06", "sc06", "sc06", "sc06", "sc06", "sc06", "sc06", "sc07", "sc07", "sc07", "sc07", "sc07", "sc07", "sc07", "sd00", "sd00", "sd00", "sd00", "sd00", "sd00", "sd00", "tn01", "tn01", "tn01", "tn01", "tn01", "tn01", "tn01", "tn02", "tn02", "tn02", "tn02", "tn02", "tn02", "tn02", "tn03", "tn03", "tn03", "tn03", "tn03", "tn03", "tn03", "tn04", "tn04", "tn04", "tn04", "tn04", "tn04", "tn04", "tn05", "tn05", "tn05", "tn05", "tn05", "tn05", "tn05", "tn06", "tn06", "tn06", "tn06", "tn06", "tn06", "tn06", "tn07", "tn07", "tn07", "tn07", "tn07", "tn07", "tn07", "tn08", "tn08", "tn08", "tn08", "tn08", "tn08", "tn08", "tn09", "tn09", "tn09", "tn09", "tn09", "tn09", "tn09", "tx01", "tx01", "tx01", "tx01", "tx01", "tx01", "tx01", "tx02", "tx02", "tx02", "tx02", "tx02", "tx02", "tx02", "tx03", "tx03", "tx03", "tx03", "tx03", "tx03", "tx03", "tx04", "tx04", "tx04", "tx04", "tx04", "tx04", "tx04", "tx05", "tx05", "tx05", "tx05", "tx05", "tx05", "tx05", "tx06", "tx06", "tx06", "tx06", "tx06", "tx06", "tx06", "tx07", "tx07", "tx07", "tx07", "tx07", "tx07", "tx07", "tx08", "tx08", "tx08", "tx08", "tx08", "tx08", "tx08", "tx09", "tx09", "tx09", "tx09", "tx09", "tx09", "tx09", "tx10", "tx10", "tx10", "tx10", "tx10", "tx10", "tx10", "tx11", "tx11", "tx11", "tx11", "tx11", "tx11", "tx11", "tx12", "tx12", "tx12", "tx12", "tx12", "tx12", "tx12", "tx13", "tx13", "tx13", "tx13", "tx13", "tx13", "tx13", "tx14", "tx14", "tx14", "tx14", "tx14", "tx14", "tx14", "tx15", "tx15", "tx15", "tx15", "tx15", "tx15", "tx15", "tx16", "tx16", "tx16", "tx16", "tx16", "tx16", "tx16", "tx17", "tx17", "tx17", "tx17", "tx17", "tx17", "tx17", "tx18", "tx18", "tx18", "tx18", "tx18", "tx18", "tx18", "tx19", "tx19", "tx19", "tx19", "tx19", "tx19", "tx19", "tx20", "tx20", "tx20", "tx20", "tx20", "tx20", "tx20", "tx21", "tx21", "tx21", "tx21", "tx21", "tx21", "tx21", "tx22", "tx22", "tx22", "tx22", "tx22", "tx22", "tx22", "tx23", "tx23", "tx23", "tx23", "tx23", "tx23", "tx23", "tx24", "tx24", "tx24", "tx24", "tx24", "tx24", "tx24", "tx25", "tx25", "tx25", "tx25", "tx25", "tx25", "tx25", "tx26", "tx26", "tx26", "tx26", "tx26", "tx26", "tx26", "tx27", "tx27", "tx27", "tx27", "tx27", "tx27", "tx27", "tx28", "tx28", "tx28", "tx28", "tx28", "tx28", "tx28", "tx29", "tx29", "tx29", "tx29", "tx29", "tx29", "tx29", "tx30", "tx30", "tx30", "tx30", "tx30", "tx30", "tx30", "tx31", "tx31", "tx31", "tx31", "tx31", "tx31", "tx31", "tx32", "tx32", "tx32", "tx32", "tx32", "tx32", "tx32", "tx33", "tx33", "tx33", "tx33", "tx33", "tx33", "tx33", "tx34", "tx34", "tx34", "tx34", "tx34", "tx34", "tx34", "tx35", "tx35", "tx35", "tx35", "tx35", "tx35", "tx35", "tx36", "tx36", "tx36", "tx36", "tx36", "tx36", "tx36", "ut01", "ut01", "ut01", "ut01", "ut01", "ut01", "ut01", "ut02", "ut02", "ut02", "ut02", "ut02", "ut02", "ut02", "ut03", "ut03", "ut03", "ut03", "ut03", "ut03", "ut03", "ut04", "ut04", "ut04", "ut04", "ut04", "ut04", "ut04", "va01", "va01", "va01", "va01", "va01", "va01", "va01", "va02", "va02", "va02", "va02", "va02", "va02", "va02", "va03", "va03", "va03", "va03", "va03", "va03", "va03", "va04", "va04", "va04", "va04", "va04", "va04", "va04", "va05", "va05", "va05", "va05", "va05", "va05", "va05", "va06", "va06", "va06", "va06", "va06", "va06", "va06", "va07", "va07", "va07", "va07", "va07", "va07", "va07", "va08", "va08", "va08", "va08", "va08", "va08", "va08", "va09", "va09", "va09", "va09", "va09", "va09", "va09", "va10", "va10", "va10", "va10", "va10", "va10", "va10", "va11", "va11", "va11", "va11", "va11", "va11", "va11", "vi00", "vi00", "vi00", "vi00", "vi00", "vi00", "vi00", "vt00", "vt00", "vt00", "vt00", "vt00", "vt00", "vt00", "wa01", "wa01", "wa01", "wa01", "wa01", "wa01", "wa01", "wa02", "wa02", "wa02", "wa02", "wa02", "wa02", "wa02", "wa03", "wa03", "wa03", "wa03", "wa03", "wa03", "wa03", "wa04", "wa04", "wa04", "wa04", "wa04", "wa04", "wa04", "wa05", "wa05", "wa05", "wa05", "wa05", "wa05", "wa05", "wa06", "wa06", "wa06", "wa06", "wa06", "wa06", "wa06", "wa07", "wa07", "wa07", "wa07", "wa07", "wa07", "wa07", "wa08", "wa08", "wa08", "wa08", "wa08", "wa08", "wa08", "wa09", "wa09", "wa09", "wa09", "wa09", "wa09", "wa09", "wa10", "wa10", "wa10", "wa10", "wa10", "wa10", "wa10", "wi01", "wi01", "wi01", "wi01", "wi01", "wi01", "wi01", "wi02", "wi02", "wi02", "wi02", "wi02", "wi02", "wi02", "wi03", "wi03", "wi03", "wi03", "wi03", "wi03", "wi03", "wi04", "wi04", "wi04", "wi04", "wi04", "wi04", "wi04", "wi05", "wi05", "wi05", "wi05", "wi05", "wi05", "wi05", "wi06", "wi06", "wi06", "wi06", "wi06", "wi06", "wi06", "wi07", "wi07", "wi07", "wi07", "wi07", "wi07", "wi07", "wi08", "wi08", "wi08", "wi08", "wi08", "wi08", "wi08", "wv01", "wv01", "wv01", "wv01", "wv01", "wv01", "wv01", "wv02", "wv02", "wv02", "wv02", "wv02", "wv02", "wv02", "wv03", "wv03", "wv03", "wv03", "wv03", "wv03", "wv03", "wy00", "wy00", "wy00", "wy00", "wy00", "wy00", "wy00"), order = c(1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L)), .Names = c("x", "y", "id", "order" ), row.names = c(NA, -3080L), class = c("tbl_df", "tbl", "data.frame")) -> gt_house_polys structure(list(x = c(4, 304, 254, 104, 144, 64, 194, 574, 444, 494, 404, 354, 64, 4, 234, 174, 264, 304, 254, 344, 254, 594, 464, 554, 334, 204, 264, 24, 284, 184, 444, 194, 224, 544, 524, 174, 144, 554, 354, 224, 114, 454, 534, 604, 424, 204, 334, 194, 154, 434, 594, 534, 114, 244, 384, 194), y = c(25.5, 214.5, 201, 322.5, 187.5, 214.5, 147, 66, 133.5, 120, 295.5, 228, 322.5, 79.5, 120, 120, 79.5, 106.5, 174, 160.5, 255, 39, 133.5, 12, 39, 79.5, 160.5, 322.5, 214.5, 106.5, 187.5, 93, 133.5, 25.5, 133.5, 174, 133.5, 93, 93, 187.5, 120, 93, 309, 79.5, 214.5, 106.5, 174, 255, 147, 147, 309, 39, 93, 25.5, 133.5, 120), lab = c("AK", "AL", "AR", "AS", "AZ", "CA", "CO", "CT", "DC", "DE", "FL", "GA", "GU", "HI", "IA", "ID", "IL", "IN", "KS", "KY", "LA", "MA", "MD", "ME", "MI", "MN", "MO", "MP", "MS", "MT", "NC", "ND", "NE", "NH", "NJ", "NM", "NV", "NY", "OH", "OK", "OR", "PA", "PR", "RI", "SC", "SD", "TN", "TX", "UT", "VA", "VI", "VT", "WA", "WI", "WV", "WY" )), .Names = c("x", "y", "lab"), class = c("tbl_df", "tbl", "data.frame" ), row.names = c(NA, -56L)) -> gt_house_labs structure(list(x = c(0, 10, 10, 20, 20, 20, 20, 10, 10, 0, 0, 0, 300, 310, 100, 110, 110, 120, 120, 120, 120, 110, 110, 100, 100, 100, 150, 160, 130, 140, 140, 150, 120, 130, 90, 80, 80, 80, 70, 80, 80, 70, 80, 80, 120, 120, 120, 130, 110, 120, 120, 120, 120, 130, 130, 130, 130, 120, 60, 70, 70, 60, 60, 50, 50, 50, 80, 70, 70, 70, 50, 60, 60, 60, 50, 40, 40, 40, 70, 60, 60, 50, 50, 50, 40, 30, 30, 30, 30, 20, 20, 20, 90, 100, 10, 20, 20, 10, 10, 10, 20, 20, 90, 90, 100, 100, 100, 90, 20, 10, 10, 10, 0, 10, 10, 0, 0, 0, 110, 110, 110, 100, 120, 120, 120, 110, 10, 20, 10, 10, 20, 30, 30, 40, 20, 20, 40, 50, 50, 60, 60, 70, 50, 50, 70, 80, 80, 90, 100, 110, 110, 120, 120, 120, 120, 110, 110, 110, 90, 100, 100, 110, 110, 120, 120, 130, 130, 130, 130, 120, 310, 320, 320, 330, 320, 310, 310, 310, 330, 340, 410, 410, 410, 400, 420, 410, 440, 440, 440, 430, 430, 420, 430, 440, 450, 450, 450, 440, 420, 430, 340, 350, 340, 340, 350, 360, 360, 370, 350, 350, 370, 380, 380, 390, 380, 380, 420, 420, 460, 460, 460, 450, 440, 440, 390, 400, 400, 410, 390, 390, 430, 440, 440, 430, 480, 480, 480, 470, 470, 470, 470, 460, 470, 480, 480, 490, 490, 490, 490, 480, 440, 440, 410, 420, 420, 430, 430, 420, 430, 440, 440, 450, 440, 430, 430, 430, 450, 460, 460, 470, 380, 390, 390, 400, 400, 400, 340, 350, 350, 360, 320, 330, 330, 340, 330, 320, 320, 320, 360, 370, 370, 380, 340, 340, 400, 410, 340, 330, 330, 330, 330, 340, 330, 330, 60, 70, 70, 80, 80, 80, 80, 70, 70, 60, 60, 60, 0, 10, 20, 20, 20, 10, 10, 0, 0, 0, 10, 20, 20, 30, 30, 30, 30, 20, 10, 10, 180, 170, 180, 190, 300, 290, 290, 300, 300, 300, 300, 290, 290, 290, 290, 290, 270, 270, 250, 260, 260, 270, 260, 260, 290, 300, 300, 290, 290, 290, 310, 300, 300, 300, 290, 300, 300, 290, 290, 290, 300, 300, 300, 310, 300, 300, 310, 310, 240, 230, 240, 240, 260, 270, 250, 260, 260, 260, 320, 310, 310, 300, 330, 320, 340, 330, 330, 330, 270, 280, 280, 290, 290, 290, 250, 260, 260, 270, 240, 250, 270, 260, 260, 250, 550, 560, 560, 570, 570, 580, 580, 590, 590, 600, 600, 610, 590, 580, 620, 620, 620, 610, 610, 600, 600, 600, 600, 590, 630, 630, 630, 620, 630, 640, 640, 640, 640, 630, 500, 510, 490, 490, 500, 490, 460, 460, 450, 460, 440, 450, 570, 580, 580, 580, 580, 570, 570, 570, 570, 560, 560, 550, 550, 550, 300, 310, 310, 310, 310, 300, 300, 290, 290, 290, 340, 330, 330, 320, 320, 320, 310, 320, 320, 310, 310, 310, 360, 350, 350, 340, 380, 380, 380, 370, 370, 360, 310, 320, 320, 310, 310, 310, 320, 320, 380, 390, 390, 390, 390, 380, 370, 370, 370, 380, 380, 380, 220, 230, 230, 240, 240, 250, 250, 250, 250, 240, 190, 200, 190, 190, 240, 240, 240, 230, 200, 200, 230, 230, 180, 190, 200, 190, 190, 180, 180, 180, 210, 200, 290, 290, 290, 280, 300, 300, 300, 290, 280, 280, 280, 270, 270, 260, 260, 270, 260, 260, 250, 260, 260, 250, 250, 240, 270, 280, 270, 270, 310, 300, 20, 30, 30, 40, 40, 40, 40, 30, 30, 20, 20, 20, 270, 280, 290, 290, 280, 270, 270, 270, 290, 300, 300, 300, 300, 290, 280, 280, 270, 280, 290, 290, 280, 270, 270, 270, 280, 290, 290, 300, 300, 300, 300, 290, 280, 280, 180, 190, 190, 180, 180, 180, 490, 490, 480, 490, 490, 500, 500, 500, 500, 490, 460, 470, 470, 470, 380, 390, 470, 480, 190, 200, 210, 210, 210, 200, 200, 190, 190, 190, 220, 230, 240, 240, 240, 230, 220, 220, 230, 240, 240, 250, 250, 250, 250, 240, 230, 230, 210, 220, 230, 230, 230, 220, 550, 560, 560, 570, 570, 570, 570, 560, 560, 560, 560, 550, 550, 540, 540, 540, 510, 520, 510, 510, 520, 530, 530, 540, 540, 540, 520, 520, 540, 550, 550, 550, 550, 560, 510, 510, 500, 510, 510, 500, 500, 500, 190, 180, 170, 170, 160, 170, 170, 160, 160, 160, 210, 200, 200, 190, 140, 140, 130, 140, 130, 140, 140, 150, 140, 130, 130, 130, 170, 170, 170, 160, 650, 660, 660, 660, 660, 650, 650, 640, 630, 640, 640, 650, 650, 650, 640, 630, 630, 620, 620, 620, 620, 630, 620, 610, 610, 600, 600, 600, 600, 610, 610, 620, 620, 620, 580, 590, 590, 600, 550, 560, 560, 550, 550, 550, 560, 570, 570, 580, 560, 560, 560, 560, 550, 560, 570, 560, 550, 550, 600, 610, 610, 610, 600, 590, 590, 580, 580, 570, 550, 550, 550, 540, 540, 550, 560, 560, 560, 550, 520, 530, 530, 540, 510, 520, 530, 520, 520, 510, 510, 510, 470, 470, 540, 540, 510, 500, 460, 470, 480, 470, 470, 460, 460, 460, 500, 490, 490, 480, 340, 350, 350, 360, 340, 340, 360, 370, 330, 330, 320, 330, 340, 330, 330, 320, 320, 320, 380, 370, 370, 360, 320, 330, 330, 320, 320, 320, 360, 350, 350, 340, 330, 340, 330, 330, 400, 390, 390, 380, 240, 240, 240, 230, 240, 250, 250, 250, 250, 240, 210, 200, 230, 230, 230, 220, 220, 210, 210, 210, 140, 150, 150, 160, 160, 160, 130, 140, 110, 120, 120, 130, 130, 130, 90, 100, 100, 110, 90, 90, 500, 510, 510, 520, 520, 520, 520, 510, 510, 510, 510, 500, 390, 400, 400, 390, 390, 390, 440, 450, 450, 460, 420, 410, 410, 400, 400, 400, 480, 490, 490, 500, 420, 430, 430, 440, 440, 430, 430, 420, 410, 420, 400, 400, 500, 500, 500, 490, 490, 480, 480, 470, 470, 460, 460, 470, 470, 480, 460, 450, 450, 440, 410, 410, 400, 390, 390, 390, 530, 540, 540, 550, 550, 550, 550, 540, 540, 530, 530, 530, 620, 630, 630, 630, 630, 620, 620, 610, 610, 610, 600, 610, 610, 620, 620, 620, 610, 600, 600, 600, 430, 440, 440, 450, 450, 450, 400, 410, 400, 400, 390, 400, 410, 400, 400, 390, 390, 390, 430, 430, 430, 420, 420, 410, 440, 430, 410, 420, 420, 430, 410, 410, 450, 460, 460, 460, 460, 450, 450, 440, 210, 220, 220, 220, 220, 210, 210, 200, 200, 200, 380, 390, 390, 390, 380, 370, 360, 370, 370, 380, 380, 380, 340, 350, 350, 360, 320, 330, 330, 340, 350, 340, 340, 330, 370, 360, 360, 350, 300, 310, 310, 320, 310, 300, 330, 320, 320, 310, 310, 310, 280, 290, 290, 300, 300, 290, 290, 280, 280, 280, 240, 250, 250, 250, 250, 240, 220, 210, 240, 240, 240, 230, 230, 220, 230, 230, 170, 160, 160, 160, 200, 200, 200, 190, 190, 180, 180, 180, 230, 240, 240, 240, 240, 230, 170, 180, 170, 170, 160, 150, 150, 150, 180, 170, 170, 170, 160, 170, 160, 160, 140, 150, 150, 140, 140, 140, 210, 220, 220, 220, 140, 150, 150, 140, 140, 140, 210, 210, 210, 200, 200, 210, 210, 210, 220, 230, 230, 230, 150, 150, 180, 190, 190, 200, 200, 200, 180, 180, 150, 160, 150, 150, 230, 240, 240, 240, 180, 180, 180, 170, 170, 160, 160, 160, 160, 170, 170, 180, 180, 180, 160, 160, 180, 190, 190, 190, 190, 180, 150, 160, 160, 150, 150, 150, 440, 450, 450, 460, 480, 490, 490, 500, 500, 500, 500, 490, 490, 480, 420, 430, 430, 440, 460, 470, 470, 480, 480, 470, 400, 410, 410, 420, 470, 470, 470, 460, 460, 450, 380, 390, 390, 400, 380, 380, 440, 440, 440, 430, 430, 420, 450, 440, 590, 600, 600, 610, 610, 610, 610, 600, 600, 590, 590, 590, 530, 540, 540, 550, 550, 550, 550, 540, 540, 530, 530, 530, 140, 130, 130, 120, 120, 110, 110, 100, 80, 90, 90, 100, 100, 100, 80, 80, 160, 160, 160, 150, 150, 140, 150, 160, 160, 170, 170, 170, 170, 160, 100, 90, 90, 80, 80, 80, 100, 110, 130, 140, 140, 150, 110, 120, 120, 130, 70, 80, 80, 70, 70, 70, 220, 230, 230, 240, 240, 240, 220, 220, 210, 220, 220, 210, 210, 210, 230, 220, 220, 220, 280, 290, 290, 300, 300, 300, 300, 290, 290, 280, 240, 250, 250, 250, 260, 270, 270, 280, 280, 270, 270, 260, 250, 250, 250, 240, 240, 230, 230, 230, 250, 260, 260, 250, 400, 410, 410, 420, 420, 420, 420, 410, 410, 400, 390, 400, 400, 390, 390, 380, 380, 380, 370, 380, 380, 390, 390, 390, 380, 370, 370, 370, 190, 200, 200, 210, 210, 210, 210, 200, 200, 190, 190, 190), y = c(27, 31.5, 31.5, 27, 27, 18, 18, 13.5, 13.5, 18, 18, 27, 243, 247.5, 324, 328.5, 328.5, 324, 324, 315, 315, 310.5, 310.5, 315, 315, 324, 202.5, 207, 202.5, 207, 207, 202.5, 207, 202.5, 121.5, 126, 126, 135, 148.5, 153, 135, 139.5, 153, 162, 162, 153, 153, 148.5, 193.5, 189, 189, 180, 180, 175.5, 175.5, 166.5, 166.5, 162, 153, 148.5, 139.5, 135, 135, 139.5, 139.5, 148.5, 162, 166.5, 166.5, 175.5, 166.5, 162, 162, 153, 148.5, 153, 153, 162, 175.5, 180, 180, 175.5, 175.5, 166.5, 162, 166.5, 166.5, 175.5, 175.5, 180, 180, 189, 220.5, 216, 202.5, 207, 189, 193.5, 193.5, 202.5, 207, 216, 229.5, 220.5, 243, 234, 234, 229.5, 216, 220.5, 220.5, 229.5, 243, 247.5, 229.5, 234, 234, 243, 256.5, 247.5, 247.5, 243, 270, 261, 261, 256.5, 256.5, 261, 247.5, 256.5, 270, 274.5, 274.5, 270, 261, 270, 270, 274.5, 283.5, 288, 288, 283.5, 274.5, 283.5, 283.5, 288, 288, 283.5, 216, 220.5, 220.5, 216, 216, 207, 207, 202.5, 202.5, 193.5, 283.5, 288, 288, 283.5, 283.5, 288, 288, 283.5, 283.5, 274.5, 274.5, 270, 256.5, 261, 261, 256.5, 243, 247.5, 247.5, 256.5, 256.5, 261, 256.5, 247.5, 247.5, 243, 261, 256.5, 270, 261, 261, 256.5, 256.5, 261, 283.5, 288, 283.5, 274.5, 274.5, 270, 288, 283.5, 270, 274.5, 261, 270, 283.5, 288, 288, 283.5, 274.5, 283.5, 283.5, 288, 297, 301.5, 288, 297, 297, 288, 297, 288, 288, 283.5, 288, 297, 310.5, 315, 315, 310.5, 301.5, 310.5, 310.5, 315, 297, 301.5, 324, 315, 315, 310.5, 310.5, 301.5, 301.5, 297, 337.5, 342, 342, 337.5, 337.5, 328.5, 328.5, 324, 315, 324, 310.5, 315, 315, 310.5, 301.5, 297, 337.5, 342, 342, 337.5, 324, 328.5, 328.5, 337.5, 337.5, 342, 342, 337.5, 243, 247.5, 247.5, 243, 243, 234, 243, 247.5, 247.5, 243, 243, 247.5, 247.5, 243, 229.5, 234, 234, 243, 243, 247.5, 247.5, 243, 207, 216, 234, 229.5, 216, 220.5, 220.5, 229.5, 202.5, 207, 193.5, 202.5, 324, 328.5, 328.5, 324, 324, 315, 315, 310.5, 310.5, 315, 315, 324, 81, 85.5, 81, 72, 72, 67.5, 67.5, 72, 72, 81, 94.5, 99, 99, 94.5, 94.5, 85.5, 85.5, 81, 85.5, 94.5, 99, 94.5, 126, 121.5, 72, 67.5, 58.5, 54, 54, 45, 45, 40.5, 67.5, 58.5, 40.5, 31.5, 112.5, 121.5, 94.5, 99, 108, 112.5, 99, 108, 94.5, 99, 81, 85.5, 85.5, 94.5, 67.5, 72, 72, 81, 121.5, 126, 108, 112.5, 112.5, 121.5, 99, 108, 135, 139.5, 126, 135, 139.5, 148.5, 162, 166.5, 153, 162, 180, 175.5, 193.5, 189, 189, 180, 153, 148.5, 148.5, 153, 148.5, 153, 135, 139.5, 139.5, 148.5, 256.5, 261, 261, 256.5, 256.5, 247.5, 256.5, 261, 261, 256.5, 261, 256.5, 220.5, 216, 216, 220.5, 58.5, 54, 54, 58.5, 58.5, 54, 54, 58.5, 58.5, 54, 54, 58.5, 31.5, 27, 27, 18, 18, 13.5, 13.5, 18, 18, 27, 27, 31.5, 40.5, 31.5, 31.5, 27, 58.5, 54, 54, 45, 45, 40.5, 153, 148.5, 121.5, 112.5, 126, 121.5, 126, 135, 121.5, 126, 126, 121.5, 31.5, 27, 27, 18, 18, 13.5, 13.5, 4.5, 4.5, 0, 0, 4.5, 4.5, 13.5, 18, 13.5, 13.5, 4.5, 4.5, 0, 0, 4.5, 4.5, 13.5, 18, 13.5, 13.5, 18, 18, 27, 40.5, 45, 27, 31.5, 31.5, 40.5, 18, 13.5, 13.5, 18, 27, 18, 18, 13.5, 13.5, 18, 67.5, 72, 54, 58.5, 58.5, 67.5, 45, 54, 45, 40.5, 40.5, 31.5, 31.5, 27, 67.5, 58.5, 58.5, 54, 54, 45, 99, 94.5, 94.5, 99, 99, 94.5, 94.5, 85.5, 85.5, 81, 67.5, 72, 58.5, 67.5, 81, 72, 72, 67.5, 72, 81, 67.5, 58.5, 54, 58.5, 45, 40.5, 40.5, 45, 45, 54, 40.5, 45, 148.5, 139.5, 139.5, 135, 162, 153, 153, 148.5, 135, 126, 126, 121.5, 121.5, 126, 162, 166.5, 153, 162, 148.5, 153, 126, 121.5, 121.5, 126, 175.5, 180, 166.5, 175.5, 166.5, 162, 324, 328.5, 328.5, 324, 324, 315, 315, 310.5, 310.5, 315, 315, 324, 202.5, 207, 202.5, 193.5, 189, 193.5, 193.5, 202.5, 220.5, 216, 216, 207, 207, 202.5, 207, 216, 229.5, 234, 229.5, 220.5, 216, 220.5, 220.5, 229.5, 243, 247.5, 247.5, 243, 243, 234, 234, 229.5, 234, 243, 108, 112.5, 94.5, 99, 99, 108, 175.5, 166.5, 189, 193.5, 193.5, 189, 189, 180, 180, 175.5, 207, 202.5, 202.5, 193.5, 189, 193.5, 193.5, 189, 94.5, 99, 94.5, 85.5, 85.5, 81, 81, 85.5, 85.5, 94.5, 135, 139.5, 135, 126, 126, 121.5, 126, 135, 148.5, 153, 153, 148.5, 148.5, 139.5, 139.5, 135, 139.5, 148.5, 121.5, 126, 121.5, 112.5, 112.5, 108, 40.5, 45, 45, 40.5, 40.5, 31.5, 31.5, 27, 27, 18, 18, 13.5, 13.5, 18, 18, 27, 148.5, 153, 139.5, 148.5, 162, 166.5, 166.5, 162, 162, 153, 153, 162, 153, 148.5, 148.5, 139.5, 139.5, 135, 112.5, 121.5, 135, 139.5, 121.5, 126, 126, 135, 166.5, 162, 166.5, 175.5, 189, 193.5, 175.5, 180, 180, 189, 166.5, 162, 162, 166.5, 126, 135, 121.5, 126, 148.5, 153, 153, 148.5, 135, 139.5, 139.5, 148.5, 121.5, 112.5, 112.5, 108, 112.5, 108, 108, 99, 99, 94.5, 94.5, 99, 121.5, 126, 126, 121.5, 121.5, 112.5, 99, 94.5, 94.5, 99, 99, 108, 126, 121.5, 108, 112.5, 112.5, 108, 108, 99, 135, 139.5, 139.5, 135, 135, 126, 135, 139.5, 139.5, 135, 121.5, 126, 108, 112.5, 112.5, 121.5, 135, 139.5, 139.5, 135, 126, 135, 99, 108, 94.5, 99, 85.5, 81, 85.5, 94.5, 99, 94.5, 94.5, 85.5, 81, 85.5, 85.5, 81, 81, 85.5, 67.5, 58.5, 58.5, 54, 81, 85.5, 81, 72, 72, 67.5, 81, 85.5, 85.5, 81, 85.5, 81, 31.5, 27, 27, 31.5, 31.5, 40.5, 58.5, 67.5, 54, 45, 40.5, 45, 54, 58.5, 45, 40.5, 40.5, 45, 45, 54, 45, 40.5, 40.5, 45, 135, 139.5, 139.5, 135, 126, 135, 135, 139.5, 85.5, 94.5, 81, 85.5, 72, 67.5, 67.5, 72, 72, 81, 72, 67.5, 67.5, 72, 108, 112.5, 94.5, 99, 99, 108, 72, 67.5, 67.5, 72, 121.5, 126, 112.5, 121.5, 72, 67.5, 67.5, 72, 189, 180, 180, 175.5, 207, 202.5, 202.5, 193.5, 193.5, 189, 175.5, 180, 175.5, 166.5, 166.5, 162, 162, 166.5, 166.5, 175.5, 108, 112.5, 112.5, 108, 108, 99, 112.5, 108, 121.5, 126, 126, 121.5, 121.5, 112.5, 121.5, 126, 126, 121.5, 112.5, 121.5, 108, 112.5, 112.5, 108, 108, 99, 99, 94.5, 94.5, 85.5, 85.5, 81, 94.5, 99, 81, 85.5, 85.5, 94.5, 108, 112.5, 112.5, 108, 72, 67.5, 67.5, 72, 72, 81, 108, 112.5, 112.5, 108, 108, 112.5, 112.5, 108, 72, 67.5, 67.5, 72, 112.5, 108, 99, 108, 81, 72, 72, 67.5, 67.5, 72, 72, 67.5, 67.5, 72, 108, 112.5, 112.5, 108, 72, 67.5, 67.5, 72, 121.5, 112.5, 108, 112.5, 112.5, 121.5, 310.5, 315, 315, 310.5, 310.5, 301.5, 301.5, 297, 297, 301.5, 301.5, 310.5, 72, 67.5, 67.5, 58.5, 58.5, 54, 54, 58.5, 58.5, 67.5, 81, 85.5, 85.5, 81, 81, 72, 67.5, 72, 72, 81, 229.5, 234, 234, 229.5, 229.5, 220.5, 216, 220.5, 207, 216, 202.5, 207, 193.5, 189, 189, 193.5, 193.5, 202.5, 202.5, 193.5, 193.5, 189, 189, 193.5, 207, 202.5, 229.5, 234, 234, 229.5, 220.5, 229.5, 220.5, 216, 216, 207, 207, 202.5, 202.5, 207, 112.5, 108, 108, 99, 99, 94.5, 94.5, 99, 99, 108, 180, 175.5, 175.5, 166.5, 162, 166.5, 189, 193.5, 193.5, 189, 189, 180, 189, 193.5, 193.5, 189, 189, 193.5, 193.5, 189, 166.5, 162, 162, 166.5, 166.5, 162, 162, 166.5, 189, 193.5, 193.5, 189, 175.5, 180, 166.5, 162, 162, 166.5, 166.5, 175.5, 189, 193.5, 193.5, 189, 180, 175.5, 175.5, 180, 180, 189, 234, 229.5, 229.5, 220.5, 220.5, 216, 207, 202.5, 216, 207, 207, 202.5, 202.5, 207, 256.5, 247.5, 202.5, 207, 207, 216, 189, 180, 180, 175.5, 175.5, 180, 180, 189, 274.5, 270, 270, 261, 261, 256.5, 310.5, 315, 301.5, 310.5, 216, 220.5, 220.5, 229.5, 189, 193.5, 193.5, 202.5, 297, 301.5, 288, 297, 270, 274.5, 256.5, 261, 261, 270, 301.5, 297, 297, 288, 243, 247.5, 229.5, 234, 234, 243, 202.5, 193.5, 193.5, 189, 315, 310.5, 310.5, 301.5, 288, 283.5, 283.5, 274.5, 247.5, 256.5, 324, 328.5, 328.5, 324, 324, 315, 315, 324, 283.5, 288, 274.5, 283.5, 247.5, 243, 243, 234, 135, 126, 126, 121.5, 121.5, 126, 126, 135, 162, 166.5, 166.5, 162, 162, 153, 153, 162, 153, 148.5, 148.5, 139.5, 139.5, 135, 148.5, 153, 135, 139.5, 139.5, 148.5, 162, 166.5, 166.5, 162, 162, 166.5, 166.5, 162, 162, 153, 153, 148.5, 148.5, 153, 162, 166.5, 166.5, 162, 162, 166.5, 166.5, 162, 153, 148.5, 162, 166.5, 166.5, 162, 148.5, 139.5, 139.5, 135, 135, 139.5, 162, 166.5, 166.5, 162, 153, 162, 135, 126, 126, 121.5, 121.5, 126, 139.5, 135, 310.5, 315, 315, 310.5, 310.5, 301.5, 301.5, 297, 297, 301.5, 301.5, 310.5, 40.5, 45, 45, 40.5, 40.5, 31.5, 31.5, 27, 27, 31.5, 31.5, 40.5, 72, 67.5, 67.5, 72, 72, 67.5, 67.5, 72, 108, 112.5, 112.5, 108, 108, 99, 99, 108, 81, 72, 72, 67.5, 67.5, 72, 94.5, 99, 99, 94.5, 94.5, 85.5, 85.5, 81, 72, 67.5, 67.5, 72, 72, 81, 99, 94.5, 94.5, 99, 99, 94.5, 94.5, 99, 99, 94.5, 94.5, 99, 81, 85.5, 85.5, 94.5, 54, 58.5, 58.5, 54, 54, 45, 45, 54, 40.5, 45, 27, 31.5, 31.5, 40.5, 13.5, 18, 18, 27, 27, 31.5, 31.5, 27, 27, 18, 18, 13.5, 13.5, 18, 45, 40.5, 40.5, 31.5, 27, 31.5, 31.5, 27, 18, 13.5, 13.5, 18, 13.5, 4.5, 4.5, 0, 0, 4.5, 4.5, 13.5, 31.5, 27, 18, 13.5, 135, 139.5, 139.5, 135, 135, 126, 126, 121.5, 121.5, 126, 139.5, 135, 126, 121.5, 121.5, 126, 126, 135, 148.5, 153, 153, 148.5, 148.5, 139.5, 135, 139.5, 139.5, 148.5, 121.5, 126, 126, 121.5, 121.5, 112.5, 112.5, 108, 108, 112.5, 112.5, 121.5), id = c(0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, 23, 23, 24, 24, 25, 25, 26, 26, 27, 27, 28, 28, 29, 29, 30, 30, 31, 31, 32, 32, 33, 33, 34, 34, 35, 35, 36, 36, 37, 37, 38, 38, 39, 39, 40, 40, 41, 41, 42, 42, 43, 43, 44, 44, 45, 45, 46, 46, 47, 47, 48, 48, 49, 49, 50, 50, 51, 51, 52, 52, 53, 53, 54, 54, 55, 55, 56, 56, 57, 57, 58, 58, 59, 59, 60, 60, 61, 61, 62, 62, 63, 63, 64, 64, 65, 65, 66, 66, 67, 67, 68, 68, 69, 69, 70, 70, 71, 71, 72, 72, 73, 73, 74, 74, 75, 75, 76, 76, 77, 77, 78, 78, 79, 79, 80, 80, 81, 81, 82, 82, 83, 83, 84, 84, 85, 85, 86, 86, 87, 87, 88, 88, 89, 89, 90, 90, 91, 91, 92, 92, 93, 93, 94, 94, 95, 95, 96, 96, 97, 97, 98, 98, 99, 99, 100, 100, 101, 101, 102, 102, 103, 103, 104, 104, 105, 105, 106, 106, 107, 107, 108, 108, 109, 109, 110, 110, 111, 111, 112, 112, 113, 113, 114, 114, 115, 115, 116, 116, 117, 117, 118, 118, 119, 119, 120, 120, 121, 121, 122, 122, 123, 123, 124, 124, 125, 125, 126, 126, 127, 127, 128, 128, 129, 129, 130, 130, 131, 131, 132, 132, 133, 133, 134, 134, 135, 135, 136, 136, 137, 137, 138, 138, 139, 139, 140, 140, 141, 141, 142, 142, 143, 143, 144, 144, 145, 145, 146, 146, 147, 147, 148, 148, 149, 149, 150, 150, 151, 151, 152, 152, 153, 153, 154, 154, 155, 155, 156, 156, 157, 157, 158, 158, 159, 159, 160, 160, 161, 161, 162, 162, 163, 163, 164, 164, 165, 165, 166, 166, 167, 167, 168, 168, 169, 169, 170, 170, 171, 171, 172, 172, 173, 173, 174, 174, 175, 175, 176, 176, 177, 177, 178, 178, 179, 179, 180, 180, 181, 181, 182, 182, 183, 183, 184, 184, 185, 185, 186, 186, 187, 187, 188, 188, 189, 189, 190, 190, 191, 191, 192, 192, 193, 193, 194, 194, 195, 195, 196, 196, 197, 197, 198, 198, 199, 199, 200, 200, 201, 201, 202, 202, 203, 203, 204, 204, 205, 205, 206, 206, 207, 207, 208, 208, 209, 209, 210, 210, 211, 211, 212, 212, 213, 213, 214, 214, 215, 215, 216, 216, 217, 217, 218, 218, 219, 219, 220, 220, 221, 221, 222, 222, 223, 223, 224, 224, 225, 225, 226, 226, 227, 227, 228, 228, 229, 229, 230, 230, 231, 231, 232, 232, 233, 233, 234, 234, 235, 235, 236, 236, 237, 237, 238, 238, 239, 239, 240, 240, 241, 241, 242, 242, 243, 243, 244, 244, 245, 245, 246, 246, 247, 247, 248, 248, 249, 249, 250, 250, 251, 251, 252, 252, 253, 253, 254, 254, 255, 255, 256, 256, 257, 257, 258, 258, 259, 259, 260, 260, 261, 261, 262, 262, 263, 263, 264, 264, 265, 265, 266, 266, 267, 267, 268, 268, 269, 269, 270, 270, 271, 271, 272, 272, 273, 273, 274, 274, 275, 275, 276, 276, 277, 277, 278, 278, 279, 279, 280, 280, 281, 281, 282, 282, 283, 283, 284, 284, 285, 285, 286, 286, 287, 287, 288, 288, 289, 289, 290, 290, 291, 291, 292, 292, 293, 293, 294, 294, 295, 295, 296, 296, 297, 297, 298, 298, 299, 299, 300, 300, 301, 301, 302, 302, 303, 303, 304, 304, 305, 305, 306, 306, 307, 307, 308, 308, 309, 309, 310, 310, 311, 311, 312, 312, 313, 313, 314, 314, 315, 315, 316, 316, 317, 317, 318, 318, 319, 319, 320, 320, 321, 321, 322, 322, 323, 323, 324, 324, 325, 325, 326, 326, 327, 327, 328, 328, 329, 329, 330, 330, 331, 331, 332, 332, 333, 333, 334, 334, 335, 335, 336, 336, 337, 337, 338, 338, 339, 339, 340, 340, 341, 341, 342, 342, 343, 343, 344, 344, 345, 345, 346, 346, 347, 347, 348, 348, 349, 349, 350, 350, 351, 351, 352, 352, 353, 353, 354, 354, 355, 355, 356, 356, 357, 357, 358, 358, 359, 359, 360, 360, 361, 361, 362, 362, 363, 363, 364, 364, 365, 365, 366, 366, 367, 367, 368, 368, 369, 369, 370, 370, 371, 371, 372, 372, 373, 373, 374, 374, 375, 375, 376, 376, 377, 377, 378, 378, 379, 379, 380, 380, 381, 381, 382, 382, 383, 383, 384, 384, 385, 385, 386, 386, 387, 387, 388, 388, 389, 389, 390, 390, 391, 391, 392, 392, 393, 393, 394, 394, 395, 395, 396, 396, 397, 397, 398, 398, 399, 399, 400, 400, 401, 401, 402, 402, 403, 403, 404, 404, 405, 405, 406, 406, 407, 407, 408, 408, 409, 409, 410, 410, 411, 411, 412, 412, 413, 413, 414, 414, 415, 415, 416, 416, 417, 417, 418, 418, 419, 419, 420, 420, 421, 421, 422, 422, 423, 423, 424, 424, 425, 425, 426, 426, 427, 427, 428, 428, 429, 429, 430, 430, 431, 431, 432, 432, 433, 433, 434, 434, 435, 435, 436, 436, 437, 437, 438, 438, 439, 439, 440, 440, 441, 441, 442, 442, 443, 443, 444, 444, 445, 445, 446, 446, 447, 447, 448, 448, 449, 449, 450, 450, 451, 451, 452, 452, 453, 453, 454, 454, 455, 455, 456, 456, 457, 457, 458, 458, 459, 459, 460, 460, 461, 461, 462, 462, 463, 463, 464, 464, 465, 465, 466, 466, 467, 467, 468, 468, 469, 469, 470, 470, 471, 471, 472, 472, 473, 473, 474, 474, 475, 475, 476, 476, 477, 477, 478, 478, 479, 479, 480, 480, 481, 481, 482, 482, 483, 483, 484, 484, 485, 485, 486, 486, 487, 487, 488, 488, 489, 489, 490, 490, 491, 491, 492, 492, 493, 493, 494, 494, 495, 495, 496, 496, 497, 497, 498, 498, 499, 499, 500, 500, 501, 501, 502, 502, 503, 503, 504, 504, 505, 505, 506, 506, 507, 507, 508, 508, 509, 509, 510, 510, 511, 511, 512, 512, 513, 513, 514, 514, 515, 515, 516, 516, 517, 517, 518, 518, 519, 519, 520, 520, 521, 521, 522, 522, 523, 523, 524, 524, 525, 525, 526, 526, 527, 527, 528, 528, 529, 529, 530, 530, 531, 531, 532, 532, 533, 533, 534, 534, 535, 535, 536, 536, 537, 537, 538, 538, 539, 539, 540, 540, 541, 541, 542, 542, 543, 543, 544, 544, 545, 545, 546, 546, 547, 547, 548, 548, 549, 549, 550, 550, 551, 551, 552, 552, 553, 553, 554, 554, 555, 555, 556, 556, 557, 557, 558, 558, 559, 559, 560, 560, 561, 561, 562, 562, 563, 563, 564, 564, 565, 565, 566, 566, 567, 567, 568, 568, 569, 569, 570, 570, 571, 571, 572, 572, 573, 573, 574, 574, 575, 575, 576, 576, 577, 577, 578, 578, 579, 579, 580, 580, 581, 581, 582, 582, 583, 583, 584, 584, 585, 585, 586, 586, 587, 587, 588, 588, 589, 589, 590, 590, 591, 591, 592, 592, 593, 593, 594, 594, 595, 595, 596, 596, 597, 597, 598, 598, 599, 599, 600, 600, 601, 601, 602, 602, 603, 603, 604, 604, 605, 605, 606, 606, 607, 607, 608, 608, 609, 609, 610, 610, 611, 611, 612, 612, 613, 613, 614, 614, 615, 615, 616, 616, 617, 617, 618, 618, 619, 619, 620, 620, 621, 621, 622, 622, 623, 623, 624, 624, 625, 625, 626, 626, 627, 627, 628, 628, 629, 629, 630, 630, 631, 631, 632, 632, 633, 633, 634, 634, 635, 635, 636, 636, 637, 637, 638, 638, 639, 639, 640, 640, 641, 641, 642, 642, 643, 643, 644, 644, 645, 645, 646, 646, 647, 647, 648, 648, 649, 649, 650, 650, 651, 651, 652, 652, 653, 653, 654, 654, 655, 655, 656, 656, 657, 657, 658, 658, 659, 659, 660, 660, 661, 661, 662, 662, 663, 663, 664, 664, 665, 665, 666, 666, 667, 667, 668, 668, 669, 669, 670, 670, 671, 671, 672, 672, 673, 673, 674, 674, 675, 675, 676, 676, 677, 677, 678, 678, 679, 679, 680, 680, 681, 681, 682, 682, 683, 683, 684, 684, 685, 685, 686, 686, 687, 687, 688, 688, 689, 689, 690, 690, 691, 691, 692, 692, 693, 693, 694, 694, 695, 695, 696, 696, 697, 697, 698, 698, 699, 699, 700, 700, 701, 701, 702, 702, 703, 703, 704, 704, 705, 705, 706, 706, 707, 707, 708, 708, 709, 709, 710, 710, 711, 711, 712, 712, 713, 713, 714, 714, 715, 715, 716, 716, 717, 717, 718, 718, 719, 719, 720, 720, 721, 721, 722, 722, 723, 723, 724, 724, 725, 725, 726, 726, 727, 727, 728, 728, 729, 729, 730, 730, 731, 731, 732, 732, 733, 733, 734, 734, 735, 735, 736, 736, 737, 737, 738, 738, 739, 739, 740, 740, 741, 741, 742, 742, 743, 743, 744, 744, 745, 745, 746, 746, 747, 747, 748, 748), order = c(1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L), size = c(0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.333333333333333, 0.333333333333333, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.666666666666667, 0.666666666666667, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.666666666666667, 0.666666666666667, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.333333333333333, 0.333333333333333, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.666666666666667, 0.666666666666667, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.333333333333333, 0.333333333333333, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.666666666666667, 0.666666666666667, 0.333333333333333, 0.333333333333333, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.666666666666667, 0.666666666666667, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.666666666666667, 0.666666666666667, 0.333333333333333, 0.333333333333333, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.333333333333333, 0.333333333333333, 0.666666666666667, 0.666666666666667, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.333333333333333, 0.333333333333333, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.333333333333333, 0.333333333333333, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.666666666666667, 0.666666666666667, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.666666666666667, 0.666666666666667, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.666666666666667, 0.666666666666667, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.333333333333333, 0.333333333333333, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.666666666666667, 0.666666666666667, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.333333333333333, 0.333333333333333, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.666666666666667, 0.666666666666667, 0.333333333333333, 0.333333333333333, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.333333333333333, 0.333333333333333, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.333333333333333, 0.333333333333333, 0.666666666666667, 0.666666666666667, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.666666666666667, 0.333333333333333, 0.333333333333333, 0.666666666666667, 0.666666666666667, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333, 0.333333333333333), color = c("#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#333333", "#333333", "#333333", "#333333", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#333333", "#333333", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#333333", "#333333", "#333333", "#333333", "#000000", "#000000", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#000000", "#000000", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#333333", "#333333", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#000000", "#000000", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#333333", "#333333", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#000000", "#000000", "#000000", "#000000", "#333333", "#333333", "#333333", "#333333", "#000000", "#000000", "#333333", "#333333", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#000000", "#000000", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#000000", "#000000", "#333333", "#333333", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#333333", "#333333", "#000000", "#000000", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#000000", "#000000", "#000000", "#000000", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#333333", "#333333", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#000000", "#000000", "#000000", "#000000", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#000000", "#000000", "#000000", "#000000", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#333333", "#333333", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#000000", "#000000", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#000000", "#000000", "#000000", "#000000", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#000000", "#000000", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#000000", "#000000", "#000000", "#000000", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#000000", "#000000", "#000000", "#000000", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#000000", "#000000", "#333333", "#333333", "#333333", "#333333", "#000000", "#000000", "#000000", "#000000", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#000000", "#000000", "#000000", "#000000", "#333333", "#333333", "#333333", "#333333", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#000000", "#000000", "#000000", "#000000", "#333333", "#333333", "#000000", "#000000", "#000000", "#000000", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#000000", "#000000", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#000000", "#000000", "#000000", "#000000", "#333333", "#333333", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#333333", "#333333", "#333333", "#333333", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#333333", "#333333", "#333333", "#333333", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#000000", "#000000", "#000000", "#000000", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#000000", "#000000", "#333333", "#333333", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#333333", "#333333", "#333333", "#333333", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#333333", "#333333", "#333333", "#333333", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#333333", "#333333", "#000000", "#000000", "#000000", "#000000", "#333333", "#333333", "#000000", "#000000", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#000000", "#333333", "#333333", "#000000", "#000000", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333", "#333333")), .Names = c("x", "y", "id", "order", "size", "color" ), row.names = c(NA, -1498L), class = c("tbl_df", "tbl", "data.frame")) -> gt_house_lines
/scratch/gouwar.j/cran-all/cranData/voteogram/R/aaa-gt-house-data.r
utils::globalVariables( c("district", "fill", "id", "lab", "party", "position", "state_abbrev", "x", "xmax", "y", "ymax") )
/scratch/gouwar.j/cran-all/cranData/voteogram/R/aaa-gv.R
structure(list(id = c("NM_3", "NM_2", "NM_1", "CA_12", "CA_5", "CA_3", "CA_1", "CA_2", "CA_46", "CA_6", "CA_9", "CA_11", "CA_13", "CA_53", "CA_17", "CA_4", "CA_7", "CA_14", "CA_16", "CA_18", "CA_19", "CA_10", "CA_15", "CA_8", "CA_23", "CA_22", "CA_21", "CA_20", "CA_30", "CA_33", "CA_25", "CA_26", "CA_24", "CA_38", "CA_34", "CA_28", "CA_29", "CA_37", "CA_32", "CA_27", "CA_47", "CA_43", "CA_44", "CA_41", "CA_35", "CA_45", "CA_48", "CA_39", "CA_40", "CA_36", "CA_42", "CA_31", "CA_51", "CA_52", "CA_49", "CA_50", "AK_1", "MO_3", "MO_2", "MO_4", "MO_5", "MO_6", "MO_1", "MO_8", "MO_7", "IA_4", "IA_1", "IA_2", "IA_3", "MN_7", "MN_8", "MN_3", "MN_2", "MN_6", "MN_1", "MN_5", "MN_4", "IN_2", "IN_1", "IN_3", "IN_5", "IN_4", "IN_8", "IN_7", "IN_6", "IN_9", "WI_2", "WI_5", "WI_4", "WI_1", "WI_7", "WI_8", "WI_6", "WI_3", "IL_14", "IL_2", "IL_10", "IL_6", "IL_7", "IL_12", "IL_11", "IL_17", "IL_18", "IL_15", "IL_16", "IL_5", "IL_9", "IL_8", "IL_1", "IL_3", "IL_4", "IL_13", "TN_2", "TN_7", "TN_8", "TN_5", "TN_9", "TN_3", "TN_1", "TN_4", "TN_6", "KY_6", "KY_5", "KY_2", "KY_3", "KY_1", "KY_4", "AL_2", "AL_1", "AL_3", "AL_7", "AL_5", "AL_4", "AL_6", "GA_12", "GA_14", "GA_10", "GA_13", "GA_11", "GA_9", "GA_8", "GA_3", "GA_2", "GA_4", "GA_1", "GA_7", "GA_6", "GA_5", "FL_7", "FL_3", "FL_6", "FL_27", "FL_13", "FL_15", "FL_17", "FL_12", "FL_10", "FL_9", "FL_8", "FL_14", "FL_19", "FL_11", "FL_16", "FL_22", "FL_4", "FL_24", "FL_26", "FL_1", "FL_21", "FL_23", "FL_2", "FL_5", "FL_18", "FL_20", "FL_25", "OH_13", "OH_15", "OH_6", "OH_14", "OH_16", "OH_7", "OH_10", "OH_2", "OH_4", "OH_11", "OH_3", "OH_12", "OH_1", "OH_5", "OH_9", "OH_8", "WV_1", "WV_2", "WV_3", "VA_9", "VA_7", "VA_8", "VA_5", "VA_11", "VA_6", "VA_2", "VA_4", "VA_1", "VA_3", "VA_10", "NJ_5", "NJ_11", "NJ_7", "NJ_12", "NJ_3", "NJ_4", "NJ_9", "NJ_2", "NJ_10", "NJ_1", "NJ_6", "NJ_8", "MD_6", "MD_8", "MD_7", "MD_3", "MD_4", "MD_1", "MD_5", "MD_2", "DE_1", "PA_9", "PA_18", "PA_4", "PA_11", "PA_12", "PA_17", "PA_5", "PA_3", "PA_10", "PA_2", "PA_13", "PA_14", "PA_16", "PA_6", "PA_7", "PA_15", "PA_8", "PA_1", "MI_14", "MI_12", "MI_13", "MI_10", "MI_8", "MI_3", "MI_7", "MI_9", "MI_5", "MI_2", "MI_4", "MI_1", "MI_6", "MI_11", "NY_20", "NY_27", "NY_19", "NY_24", "NY_14", "NY_21", "NY_7", "NY_25", "NY_6", "NY_2", "NY_3", "NY_1", "NY_17", "NY_23", "NY_26", "NY_13", "NY_16", "NY_22", "NY_18", "NY_12", "NY_15", "NY_5", "NY_10", "NY_11", "NY_4", "NY_8", "NY_9", "CT_3", "CT_4", "CT_1", "CT_2", "CT_5", "RI_2", "RI_1", "MA_2", "MA_1", "MA_9", "MA_3", "MA_6", "MA_7", "MA_4", "MA_5", "MA_8", "VT_1", "NH_2", "NH_1", "ME_2", "ME_1", "HI_2", "HI_1", "NC_12", "NC_10", "NC_5", "NC_7", "NC_2", "NC_11", "NC_9", "NC_8", "NC_6", "NC_13", "NC_1", "NC_4", "NC_3", "SC_3", "SC_6", "SC_5", "SC_2", "SC_7", "SC_1", "SC_4", "ND_1", "SD_1", "NE_2", "NE_1", "NE_3", "MT_1", "CO_4", "CO_1", "CO_3", "CO_2", "CO_6", "CO_7", "CO_5", "TX_24", "TX_27", "TX_26", "TX_11", "TX_16", "TX_4", "TX_6", "TX_33", "TX_23", "TX_32", "TX_1", "TX_8", "TX_31", "TX_25", "TX_21", "TX_14", "TX_34", "TX_15", "TX_28", "TX_7", "TX_36", "TX_2", "TX_9", "TX_35", "TX_18", "TX_22", "TX_13", "TX_3", "TX_19", "TX_10", "TX_29", "TX_20", "TX_12", "TX_17", "TX_30", "TX_5", "LA_5", "LA_2", "LA_3", "LA_6", "LA_1", "LA_4", "MS_1", "MS_3", "MS_2", "MS_4", "AR_1", "AR_2", "AR_3", "AR_4", "OK_3", "OK_2", "OK_5", "OK_1", "OK_4", "KS_2", "KS_4", "KS_1", "KS_3", "WY_1", "AZ_9", "AZ_8", "AZ_1", "AZ_7", "AZ_2", "AZ_4", "AZ_5", "AZ_6", "AZ_3", "UT_2", "UT_1", "UT_4", "UT_3", "NV_2", "NV_3", "NV_1", "NV_4", "ID_1", "ID_2", "OR_2", "OR_3", "OR_4", "OR_5", "OR_1", "WA_7", "WA_2", "WA_1", "WA_8", "WA_5", "WA_4", "WA_3", "WA_10", "WA_9", "WA_6"), x = c(160.88, 181.822, 160.88, 14.283, 77.11, 56.167, 35.225, 14.283, 77.11, 77.11, 56.167, 35.225, 14.283, 77.11, 77.11, 56.167, 35.225, 14.283, 98.052, 77.11, 56.167, 35.225, 14.283, 98.052, 77.11, 56.167, 35.225, 14.283, 98.052, 77.11, 56.167, 35.225, 14.283, 98.052, 77.11, 56.167, 35.225, 14.283, 98.052, 77.11, 56.167, 35.225, 14.283, 98.052, 77.11, 56.167, 35.225, 14.283, 98.052, 77.11, 56.167, 98.052, 77.11, 56.167, 56.167, 56.167, 12.293, 307.477, 328.418, 307.477, 286.534, 286.534, 328.418, 328.418, 307.477, 286.534, 307.477, 307.477, 286.534, 286.534, 307.477, 307.477, 307.477, 286.534, 286.534, 286.534, 307.477, 412.189, 391.247, 433.131, 433.131, 412.189, 412.189, 433.131, 433.131, 412.189, 328.418, 349.362, 349.362, 328.418, 328.418, 349.362, 349.362, 328.418, 370.304, 391.247, 391.247, 370.304, 370.304, 349.362, 370.304, 328.418, 328.418, 349.362, 349.362, 391.247, 370.304, 349.362, 391.247, 391.247, 370.304, 349.362, 412.189, 370.304, 349.362, 370.304, 349.362, 412.189, 433.131, 391.247, 391.247, 454.074, 433.131, 412.189, 433.131, 412.189, 454.074, 454.074, 412.189, 454.074, 433.131, 433.131, 412.189, 433.131, 558.785, 475.016, 558.785, 516.9, 475.016, 495.959, 537.844, 475.016, 516.9, 537.844, 558.785, 516.9, 495.959, 537.844, 516.9, 475.016, 495.959, 537.844, 495.959, 475.016, 516.9, 475.016, 495.959, 537.844, 537.844, 516.9, 516.9, 454.074, 495.959, 558.785, 454.074, 558.785, 517.424, 433.131, 558.785, 537.844, 433.131, 454.074, 558.785, 537.844, 537.844, 495.959, 495.959, 495.959, 495.959, 495.959, 475.016, 475.016, 475.016, 475.016, 475.016, 454.074, 454.074, 454.074, 433.131, 454.074, 454.074, 516.9, 537.844, 516.9, 475.016, 537.844, 600.67, 495.959, 579.729, 516.9, 600.67, 558.785, 558.785, 579.729, 537.844, 642.555, 663.498, 642.555, 663.498, 684.439, 705.383, 684.439, 705.383, 684.439, 684.439, 705.383, 705.383, 558.785, 579.729, 600.67, 621.613, 621.613, 663.498, 642.555, 642.555, 663.498, 537.844, 516.9, 558.785, 558.785, 516.9, 579.729, 537.844, 516.9, 558.785, 600.67, 621.613, 537.844, 579.729, 621.613, 600.67, 579.729, 621.613, 600.67, 433.131, 391.247, 412.189, 433.131, 433.131, 391.247, 412.189, 454.074, 412.189, 370.304, 391.247, 349.362, 391.247, 412.189, 621.613, 516.9, 642.555, 558.785, 642.555, 642.555, 558.785, 537.844, 642.555, 642.555, 663.498, 684.439, 558.785, 537.844, 516.9, 621.613, 600.67, 579.729, 621.613, 600.67, 579.729, 621.613, 600.67, 579.729, 621.613, 600.67, 579.729, 684.439, 663.498, 663.498, 684.439, 663.498, 705.383, 705.383, 663.498, 663.498, 747.268, 684.439, 705.383, 726.324, 684.439, 705.383, 726.324, 684.439, 705.383, 726.324, 705.383, 726.324, 14.283, 35.225, 454.074, 475.016, 475.016, 495.959, 537.844, 454.074, 475.016, 516.9, 495.959, 495.959, 537.844, 516.9, 558.785, 495.959, 537.844, 537.844, 516.9, 558.785, 558.785, 516.9, 160.88, 160.88, 265.592, 244.649, 223.707, 139.937, 223.707, 202.765, 181.822, 202.765, 202.765, 181.822, 181.822, 244.649, 244.649, 223.707, 202.765, 181.822, 307.477, 244.649, 223.707, 181.822, 202.765, 307.477, 265.592, 223.707, 202.765, 181.822, 307.477, 244.649, 223.707, 202.765, 307.477, 286.534, 244.649, 223.707, 244.649, 286.534, 265.592, 202.765, 286.534, 223.707, 286.534, 265.592, 265.592, 244.649, 286.534, 265.592, 265.592, 349.362, 349.362, 328.418, 328.418, 349.362, 328.418, 391.247, 370.304, 370.304, 391.247, 328.418, 328.418, 307.477, 307.477, 244.649, 286.534, 286.534, 265.592, 265.592, 265.592, 244.649, 223.707, 286.534, 139.937, 139.937, 139.937, 118.995, 118.995, 139.937, 118.995, 118.995, 139.937, 118.995, 139.937, 139.937, 160.88, 160.88, 98.052, 118.995, 98.052, 118.995, 98.052, 118.995, 98.052, 77.11, 56.167, 35.225, 14.283, 14.283, 35.225, 56.167, 77.11, 98.052, 98.052, 77.11, 56.167, 35.225, 14.283), y = c(320.941, 341.885, 342.094, 320.941, 237.172, 237.172, 237.172, 237.172, 446.598, 258.115, 258.115, 258.115, 258.115, 488.691, 279.057, 279.057, 279.057, 279.057, 300, 300, 300, 300, 300, 320.941, 320.941, 320.941, 383.77, 362.826, 341.885, 341.885, 341.885, 404.713, 383.77, 362.826, 362.826, 362.826, 425.654, 404.713, 383.77, 383.77, 383.77, 446.598, 425.654, 404.713, 404.713, 404.713, 467.539, 446.598, 425.654, 425.654, 425.654, 446.598, 467.539, 488.691, 446.598, 467.539, 6.806, 258.115, 279.057, 279.057, 279.057, 258.115, 258.115, 300, 300, 216.23, 216.23, 237.172, 237.172, 132.46, 132.46, 153.403, 195.288, 153.403, 195.288, 174.345, 174.345, 195.288, 195.288, 195.288, 216.23, 216.23, 237.172, 237.172, 258.115, 258.115, 174.345, 174.345, 195.288, 195.288, 132.46, 132.46, 153.403, 153.403, 195.288, 300, 216.23, 216.23, 279.057, 279.057, 300, 216.23, 237.172, 300, 237.172, 237.172, 237.172, 216.23, 279.057, 258.115, 258.115, 258.115, 341.885, 341.885, 320.941, 320.941, 341.885, 320.941, 320.941, 341.885, 320.941, 279.057, 300, 279.057, 279.057, 300, 300, 383.77, 383.77, 362.826, 383.77, 341.885, 362.826, 362.826, 404.713, 362.826, 383.77, 383.77, 383.77, 383.77, 425.654, 404.713, 425.654, 404.713, 425.654, 404.713, 404.713, 383.77, 446.598, 425.654, 425.654, 551.309, 467.539, 446.598, 488.482, 467.539, 446.598, 467.539, 446.598, 467.539, 509.424, 446.598, 488.482, 509.424, 404.713, 530.367, 572.252, 404.713, 488.482, 530.367, 425.654, 425.654, 467.539, 488.482, 509.424, 216.23, 237.172, 258.115, 174.345, 195.288, 216.23, 237.172, 258.115, 195.288, 174.345, 216.23, 237.172, 258.115, 174.345, 174.345, 195.288, 237.172, 237.172, 258.115, 279.057, 279.057, 258.115, 279.057, 258.115, 279.057, 279.057, 279.057, 258.115, 279.057, 258.115, 195.288, 195.288, 216.23, 216.23, 237.172, 237.172, 195.288, 258.115, 216.23, 258.115, 216.23, 195.288, 237.172, 237.172, 237.172, 237.172, 258.115, 258.115, 258.115, 237.172, 237.172, 216.23, 216.23, 216.23, 195.288, 195.288, 195.288, 174.345, 174.345, 174.345, 174.345, 195.288, 195.288, 216.23, 216.23, 216.23, 174.345, 174.345, 195.288, 153.403, 153.403, 153.403, 111.518, 132.46, 132.46, 174.345, 132.46, 111.518, 111.518, 111.518, 111.518, 174.345, 132.46, 69.633, 132.46, 90.576, 111.518, 111.518, 69.633, 132.46, 132.46, 132.46, 153.403, 153.403, 153.403, 153.403, 153.403, 153.403, 90.576, 90.576, 90.576, 111.518, 111.518, 111.518, 132.46, 132.46, 132.46, 153.403, 153.403, 153.403, 111.518, 132.46, 90.576, 90.576, 111.518, 111.518, 90.576, 48.691, 69.633, 69.633, 48.691, 48.691, 48.691, 69.633, 69.633, 69.633, 27.749, 27.749, 27.749, 6.806, 6.806, 572.252, 572.252, 341.885, 320.941, 300, 341.885, 320.941, 320.941, 341.885, 320.941, 300, 320.941, 300, 300, 300, 362.826, 362.826, 341.885, 362.826, 341.885, 362.826, 341.885, 237.172, 258.115, 279.057, 279.057, 279.057, 237.172, 320.941, 300, 279.057, 279.057, 320.941, 300, 320.941, 362.826, 404.713, 362.826, 362.826, 362.826, 362.826, 383.77, 383.77, 383.77, 383.77, 383.77, 404.713, 404.713, 404.713, 404.713, 404.713, 467.539, 425.654, 425.654, 425.654, 404.713, 446.598, 446.598, 425.654, 446.598, 446.598, 341.885, 362.826, 341.885, 425.654, 383.77, 425.654, 341.885, 383.77, 467.539, 362.826, 362.826, 383.77, 404.713, 383.77, 404.713, 362.826, 362.826, 383.77, 362.826, 383.77, 320.941, 341.885, 320.941, 341.885, 320.941, 341.885, 320.941, 320.941, 341.885, 300, 300, 300, 300, 258.115, 362.826, 320.629, 320.941, 362.826, 383.77, 300, 383.77, 342.094, 342.094, 300, 279.057, 279.057, 300, 258.115, 279.057, 279.057, 258.115, 237.172, 237.172, 216.23, 216.23, 216.23, 216.23, 216.23, 174.345, 174.345, 174.345, 174.345, 174.345, 195.288, 195.288, 195.288, 195.288, 195.288), height = c(20.943, 20.941, 20.943, 20.943, 20.942, 20.942, 20.942, 20.942, 20.941, 20.942, 20.942, 20.942, 20.942, 20.941, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.943, 20.943, 20.943, 20.943, 20.943, 20.941, 20.941, 20.941, 20.941, 20.943, 20.943, 20.943, 20.943, 20.943, 20.941, 20.943, 20.943, 20.943, 20.941, 20.943, 20.941, 20.941, 20.941, 20.943, 20.941, 20.943, 20.943, 20.943, 20.941, 20.943, 20.941, 20.941, 20.943, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.941, 20.941, 20.943, 20.943, 20.941, 20.943, 20.943, 20.941, 20.943, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.943, 20.943, 20.943, 20.943, 20.941, 20.943, 20.943, 20.941, 20.943, 20.943, 20.943, 20.943, 20.943, 20.943, 20.941, 20.943, 20.941, 20.943, 20.941, 20.941, 20.943, 20.941, 20.943, 20.943, 20.943, 20.943, 20.941, 20.941, 20.943, 20.941, 20.943, 20.941, 20.943, 20.943, 20.941, 20.941, 20.943, 20.941, 20.941, 20.941, 20.941, 20.941, 20.941, 20.943, 20.943, 20.943, 20.941, 20.943, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.941, 20.941, 20.941, 20.943, 20.942, 20.941, 20.943, 20.943, 20.941, 20.943, 20.942, 20.943, 20.942, 20.942, 20.942, 20.943, 20.943, 20.941, 20.943, 20.941, 20.943, 20.941, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.943, 20.942, 20.942, 20.942, 20.943, 20.942, 20.943, 20.943, 20.941, 20.943, 20.943, 20.943, 20.943, 20.943, 20.943, 20.943, 20.943, 20.943, 20.941, 20.941, 20.941, 20.941, 20.941, 20.943, 20.943, 20.943, 20.943, 20.941, 20.941, 20.941, 20.943, 20.941, 20.941, 20.941, 20.943, 20.941, 20.943, 20.943, 20.943, 20.941, 20.943, 20.943, 20.943, 20.943, 20.943, 20.941, 20.943, 20.941, 20.943, 20.943, 20.943, 20.943, 20.943, 20.943, 20.941, 20.943, 20.941, 20.943, 20.941, 20.943, 20.943, 20.941, 20.942, 20.942, 20.942, 20.942, 20.942, 20.943, 20.941, 20.943, 20.943, 20.943, 20.942, 20.943, 20.943, 20.943, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942), width = c(20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.943, 20.942, 20.942, 20.942, 20.943, 20.943, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.941, 20.943, 20.943, 20.943, 20.941, 20.941, 20.943, 20.943, 20.941, 20.943, 20.942, 20.942, 20.943, 20.943, 20.942, 20.942, 20.943, 20.942, 20.943, 20.943, 20.942, 20.942, 20.942, 20.942, 20.943, 20.943, 20.942, 20.942, 20.943, 20.942, 20.942, 20.943, 20.943, 20.942, 20.942, 20.941, 20.942, 20.942, 20.942, 20.942, 20.941, 20.943, 20.943, 20.943, 20.941, 20.943, 20.941, 20.943, 20.941, 20.941, 20.941, 20.941, 20.941, 20.943, 20.943, 20.941, 20.943, 20.943, 20.943, 20.943, 20.943, 20.943, 20.941, 20.941, 20.943, 20.943, 20.941, 20.943, 20.943, 20.941, 20.941, 20.943, 20.943, 20.941, 20.941, 20.941, 20.943, 20.943, 20.943, 20.941, 20.941, 20.941, 20.943, 20.943, 20.941, 20.941, 20.943, 20.941, 20.943, 20.943, 20.943, 20.943, 20.941, 20.943, 20.941, 20.943, 20.941, 20.941, 20.941, 20.941, 20.941, 20.941, 20.941, 20.943, 20.943, 20.943, 20.943, 20.943, 20.941, 20.941, 20.941, 20.943, 20.941, 20.941, 20.943, 20.941, 20.943, 20.943, 20.941, 20.943, 20.941, 20.941, 20.943, 20.943, 20.943, 20.943, 20.941, 20.941, 20.943, 20.941, 20.943, 20.941, 20.943, 20.941, 20.943, 20.941, 20.943, 20.943, 20.941, 20.941, 20.943, 20.941, 20.943, 20.941, 20.941, 20.941, 20.943, 20.943, 20.941, 20.941, 20.943, 20.943, 20.943, 20.943, 20.941, 20.941, 20.943, 20.943, 20.943, 20.941, 20.941, 20.941, 20.941, 20.943, 20.941, 20.941, 20.943, 20.943, 20.943, 20.941, 20.943, 20.943, 20.943, 20.941, 20.941, 20.941, 20.942, 20.943, 20.942, 20.943, 20.941, 20.941, 20.943, 20.943, 20.943, 20.943, 20.943, 20.943, 20.941, 20.943, 20.943, 20.941, 20.943, 20.943, 20.941, 20.943, 20.941, 20.943, 20.941, 20.941, 20.943, 20.941, 20.941, 20.943, 20.941, 20.941, 20.943, 20.941, 20.943, 20.941, 20.941, 20.943, 20.941, 20.941, 20.941, 20.941, 20.941, 20.941, 20.943, 20.941, 20.943, 20.943, 20.941, 20.943, 20.943, 20.941, 20.943, 20.941, 20.943, 20.942, 20.942, 20.941, 20.943, 20.943, 20.941, 20.941, 20.941, 20.943, 20.943, 20.941, 20.941, 20.941, 20.943, 20.943, 20.941, 20.941, 20.941, 20.943, 20.943, 20.943, 20.943, 20.942, 20.942, 20.942, 20.942, 20.942, 20.943, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.943, 20.943, 20.942, 20.943, 20.943, 20.942, 20.942, 20.943, 20.943, 20.943, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.943, 20.943, 20.943, 20.942, 20.942, 20.943, 20.942, 20.942, 20.943, 20.942, 20.943, 20.943, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942, 20.942), xmax = c(181.822, 202.764, 181.822, 35.225, 98.052, 77.109, 56.167, 35.225, 98.052, 98.052, 77.109, 56.167, 35.225, 98.052, 98.052, 77.109, 56.167, 35.225, 118.994, 98.052, 77.109, 56.167, 35.225, 118.994, 98.052, 77.109, 56.167, 35.225, 118.994, 98.052, 77.109, 56.167, 35.225, 118.994, 98.052, 77.109, 56.167, 35.225, 118.994, 98.052, 77.109, 56.167, 35.225, 118.994, 98.052, 77.109, 56.167, 35.225, 118.994, 98.052, 77.109, 118.994, 98.052, 77.109, 77.109, 77.109, 33.235, 328.419, 349.361, 328.419, 307.476, 307.476, 349.361, 349.361, 328.419, 307.476, 328.419, 328.419, 307.476, 307.476, 328.419, 328.419, 328.419, 307.476, 307.476, 307.476, 328.419, 433.13, 412.19, 454.074, 454.074, 433.13, 433.13, 454.074, 454.074, 433.13, 349.361, 370.304, 370.304, 349.361, 349.361, 370.304, 370.304, 349.361, 391.246, 412.19, 412.19, 391.246, 391.246, 370.304, 391.246, 349.361, 349.361, 370.304, 370.304, 412.19, 391.246, 370.304, 412.19, 412.19, 391.246, 370.304, 433.13, 391.246, 370.304, 391.246, 370.304, 433.13, 454.074, 412.19, 412.19, 475.015, 454.074, 433.13, 454.074, 433.13, 475.015, 475.015, 433.13, 475.015, 454.074, 454.074, 433.13, 454.074, 579.728, 495.959, 579.728, 537.843, 495.959, 516.9, 558.785, 495.959, 537.843, 558.785, 579.728, 537.843, 516.9, 558.785, 537.843, 495.959, 516.9, 558.785, 516.9, 495.959, 537.843, 495.959, 516.9, 558.785, 558.785, 537.843, 537.843, 475.015, 516.9, 579.728, 475.015, 579.728, 538.367, 454.074, 579.728, 558.785, 454.074, 475.015, 579.728, 558.785, 558.785, 516.9, 516.9, 516.9, 516.9, 516.9, 495.959, 495.959, 495.959, 495.959, 495.959, 475.015, 475.015, 475.015, 454.074, 475.015, 475.015, 537.843, 558.785, 537.843, 495.959, 558.785, 621.613, 516.9, 600.67, 537.843, 621.613, 579.728, 579.728, 600.67, 558.785, 663.498, 684.439, 663.498, 684.439, 705.382, 726.324, 705.382, 726.324, 705.382, 705.382, 726.324, 726.324, 579.728, 600.67, 621.613, 642.554, 642.554, 684.439, 663.498, 663.498, 684.439, 558.785, 537.843, 579.728, 579.728, 537.843, 600.67, 558.785, 537.843, 579.728, 621.613, 642.554, 558.785, 600.67, 642.554, 621.613, 600.67, 642.554, 621.613, 454.074, 412.19, 433.13, 454.074, 454.074, 412.19, 433.13, 475.015, 433.13, 391.246, 412.19, 370.304, 412.19, 433.13, 642.554, 537.843, 663.498, 579.728, 663.498, 663.498, 579.728, 558.785, 663.498, 663.498, 684.439, 705.382, 579.728, 558.785, 537.843, 642.554, 621.613, 600.67, 642.554, 621.613, 600.67, 642.554, 621.613, 600.67, 642.554, 621.613, 600.67, 705.382, 684.439, 684.439, 705.382, 684.439, 726.324, 726.324, 684.439, 684.439, 768.209, 705.382, 726.324, 747.267, 705.382, 726.324, 747.267, 705.382, 726.324, 747.267, 726.324, 747.267, 35.225, 56.167, 475.015, 495.959, 495.959, 516.9, 558.785, 475.015, 495.959, 537.843, 516.9, 516.9, 558.785, 537.843, 579.728, 516.9, 558.785, 558.785, 537.843, 579.728, 579.728, 537.843, 181.822, 181.822, 286.534, 265.591, 244.649, 160.88, 244.649, 223.707, 202.764, 223.707, 223.707, 202.764, 202.764, 265.591, 265.591, 244.649, 223.707, 202.764, 328.419, 265.591, 244.649, 202.764, 223.707, 328.419, 286.534, 244.649, 223.707, 202.764, 328.419, 265.591, 244.649, 223.707, 328.419, 307.476, 265.591, 244.649, 265.591, 307.476, 286.534, 223.707, 307.476, 244.649, 307.476, 286.534, 286.534, 265.591, 307.476, 286.534, 286.534, 370.304, 370.304, 349.361, 349.361, 370.304, 349.361, 412.19, 391.246, 391.246, 412.19, 349.361, 349.361, 328.419, 328.419, 265.591, 307.476, 307.476, 286.534, 286.534, 286.534, 265.591, 244.649, 307.476, 160.88, 160.88, 160.88, 139.937, 139.937, 160.88, 139.937, 139.937, 160.88, 139.937, 160.88, 160.88, 181.822, 181.822, 118.994, 139.937, 118.994, 139.937, 118.994, 139.937, 118.994, 98.052, 77.109, 56.167, 35.225, 35.225, 56.167, 77.109, 98.052, 118.994, 118.994, 98.052, 77.109, 56.167, 35.225), ymax = c(341.884, 362.826, 363.037, 341.884, 258.114, 258.114, 258.114, 258.114, 467.539, 279.057, 279.057, 279.057, 279.057, 509.632, 299.999, 299.999, 299.999, 299.999, 320.942, 320.942, 320.942, 320.942, 320.942, 341.884, 341.884, 341.884, 404.713, 383.769, 362.826, 362.826, 362.826, 425.654, 404.713, 383.769, 383.769, 383.769, 446.597, 425.654, 404.713, 404.713, 404.713, 467.539, 446.597, 425.654, 425.654, 425.654, 488.482, 467.539, 446.597, 446.597, 446.597, 467.539, 488.482, 509.632, 467.539, 488.482, 27.748, 279.057, 299.999, 299.999, 299.999, 279.057, 279.057, 320.942, 320.942, 237.172, 237.172, 258.114, 258.114, 153.402, 153.402, 174.345, 216.23, 174.345, 216.23, 195.287, 195.287, 216.23, 216.23, 216.23, 237.172, 237.172, 258.114, 258.114, 279.057, 279.057, 195.287, 195.287, 216.23, 216.23, 153.402, 153.402, 174.345, 174.345, 216.23, 320.942, 237.172, 237.172, 299.999, 299.999, 320.942, 237.172, 258.114, 320.942, 258.114, 258.114, 258.114, 237.172, 299.999, 279.057, 279.057, 279.057, 362.826, 362.826, 341.884, 341.884, 362.826, 341.884, 341.884, 362.826, 341.884, 299.999, 320.942, 299.999, 299.999, 320.942, 320.942, 404.713, 404.713, 383.769, 404.713, 362.826, 383.769, 383.769, 425.654, 383.769, 404.713, 404.713, 404.713, 404.713, 446.597, 425.654, 446.597, 425.654, 446.597, 425.654, 425.654, 404.713, 467.539, 446.597, 446.597, 572.252, 488.482, 467.539, 509.423, 488.482, 467.539, 488.482, 467.539, 488.482, 530.367, 467.539, 509.423, 530.367, 425.654, 551.308, 593.193, 425.654, 509.423, 551.308, 446.597, 446.597, 488.482, 509.423, 530.367, 237.172, 258.114, 279.057, 195.287, 216.23, 237.172, 258.114, 279.057, 216.23, 195.287, 237.172, 258.114, 279.057, 195.287, 195.287, 216.23, 258.114, 258.114, 279.057, 299.999, 299.999, 279.057, 299.999, 279.057, 299.999, 299.999, 299.999, 279.057, 299.999, 279.057, 216.23, 216.23, 237.172, 237.172, 258.114, 258.114, 216.23, 279.057, 237.172, 279.057, 237.172, 216.23, 258.114, 258.114, 258.114, 258.114, 279.057, 279.057, 279.057, 258.114, 258.114, 237.172, 237.172, 237.172, 216.23, 216.23, 216.23, 195.287, 195.287, 195.287, 195.287, 216.23, 216.23, 237.172, 237.172, 237.172, 195.287, 195.287, 216.23, 174.345, 174.345, 174.345, 132.46, 153.402, 153.402, 195.287, 153.402, 132.46, 132.46, 132.46, 132.46, 195.287, 153.402, 90.575, 153.402, 111.518, 132.46, 132.46, 90.575, 153.402, 153.402, 153.402, 174.345, 174.345, 174.345, 174.345, 174.345, 174.345, 111.518, 111.518, 111.518, 132.46, 132.46, 132.46, 153.402, 153.402, 153.402, 174.345, 174.345, 174.345, 132.46, 153.402, 111.518, 111.518, 132.46, 132.46, 111.518, 69.633, 90.575, 90.575, 69.633, 69.633, 69.633, 90.575, 90.575, 90.575, 48.691, 48.691, 48.691, 27.748, 27.748, 593.193, 593.193, 362.826, 341.884, 320.942, 362.826, 341.884, 341.884, 362.826, 341.884, 320.942, 341.884, 320.942, 320.942, 320.942, 383.769, 383.769, 362.826, 383.769, 362.826, 383.769, 362.826, 258.114, 279.057, 299.999, 299.999, 299.999, 258.114, 341.884, 320.942, 299.999, 299.999, 341.884, 320.942, 341.884, 383.769, 425.654, 383.769, 383.769, 383.769, 383.769, 404.713, 404.713, 404.713, 404.713, 404.713, 425.654, 425.654, 425.654, 425.654, 425.654, 488.482, 446.597, 446.597, 446.597, 425.654, 467.539, 467.539, 446.597, 467.539, 467.539, 362.826, 383.769, 362.826, 446.597, 404.713, 446.597, 362.826, 404.713, 488.482, 383.769, 383.769, 404.713, 425.654, 404.713, 425.654, 383.769, 383.769, 404.713, 383.769, 404.713, 341.884, 362.826, 341.884, 362.826, 341.884, 362.826, 341.884, 341.884, 362.826, 320.942, 320.942, 320.942, 320.942, 279.057, 383.769, 341.57, 341.884, 383.769, 404.713, 320.942, 404.713, 363.037, 363.037, 320.942, 299.999, 299.999, 320.942, 279.057, 299.999, 299.999, 279.057, 258.114, 258.114, 237.172, 237.172, 237.172, 237.172, 237.172, 195.287, 195.287, 195.287, 195.287, 195.287, 216.23, 216.23, 216.23, 216.23, 216.23)), .Names = c("id", "x", "y", "height", "width", "xmax", "ymax"), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, -435L)) -> house_df structure(list(x = c(454.074, 454.074, 370.304, 370.304, 579.729, 370.304, 139.937, 98.052, 161.089, 139.937, 14.283, 35.225, 98.052, 118.995, 55.958, 181.822, 202.765, 223.707, 286.534, 516.9, 433.131, 454.074, 475.016, 495.959, 517.424, 558.785, 516.9, 558.785, 558.785, 747.268, 684.439, 684.439, 558.785, 663.498, 621.613, 579.729, 516.9, 307.477, 328.418, 244.859, 223.707, 223.707, 391.247, 391.247, 412.189, 433.131, 475.016, 621.613, 642.555, 642.555, 516.9, 663.498, 684.439, 705.383, 705.383, 663.498, 558.785, 475.016, 663.498, 663.498, 642.555, 537.844, 433.131, 349.362, 412.189, 454.074, 495.959, 516.9, 558.785, 433.131, 495.959, 516.9, 475.016, 349.362, 433.131, 286.534, 328.418, 286.534, 181.822, 14.283, 14.283, 14.283, 286.534, 265.592, 181.822, 160.88, 328.418, 433.131, 307.477, 286.534, 244.649, 516.9, 538.367, 516.9, 223.707, 202.765, 12.293, 33.236, 286.534, 328.418, 412.189, 454.074, 516.9, 642.555, 663.498, 349.362, 454.074, 475.016, 454.074, 516.9, 558.785, 579.729, 621.613, 663.498, 684.439, 768.209, 705.383, 726.324, 454.074, 475.016, 495.959, 558.785, 579.729, 621.613, 558.785, 579.729, 558.785, 537.844, 579.729, 726.324, 705.383, 747.268, 705.383, 705.383, 537.844, 621.613, 558.785, 684.439, 663.498, 684.439, 475.016, 516.9, 349.362, 328.418, 286.534, 433.131, 370.304, 391.247, 391.247, 181.822, 139.937, 98.052, 118.786, 13.34, 13.236, 181.822, 181.822, 244.649, 307.477, 370.304, 412.189, 475.016, 475.016, 495.959, 349.362, 433.131, 516.9, 454.074, 223.707, 202.765, 181.822, 265.592, 160.88, 35.225, 118.995, 55.225, 98.052, 12.293, 12.293, 98.052, 13.34, 13.34, 35.225, 35.225, 35.225, 35.225, 56.167, 12.293, 55.225, 12.293, 12.293, 475.016, 475.016, 391.247, 391.247, 621.613, 433.131, 182.765, 139.728, 202.974, 181.822, 33.236, 55.225, 118.995, 160.88, 97.843, 202.765, 223.707, 244.649, 307.477, 537.844, 454.074, 475.016, 495.959, 516.9, 558.785, 579.1, 537.215, 579.729, 579.729, 768.209, 705.383, 726.324, 579.729, 684.439, 663.498, 621.613, 558.785, 328.418, 370.304, 286.534, 307.477, 349.362, 412.189, 433.131, 475.016, 454.074, 579.729, 726.324, 726.324, 705.383, 642.555, 768.209, 747.268, 747.268, 745.172, 705.383, 621.613, 537.844, 684.439, 684.439, 663.498, 558.785, 642.555, 454.074, 475.016, 495.959, 579.729, 579.729, 579.729, 454.074, 516.9, 558.785, 516.9, 412.189, 475.016, 349.362, 370.304, 370.304, 286.534, 181.822, 118.786, 118.786, 328.418, 433.131, 265.592, 160.88, 328.418, 433.131, 307.477, 286.534, 244.649, 516.9, 538.367, 516.9, 223.707, 202.765, 12.293, 33.236, 286.534, 328.418, 412.189, 454.074, 516.9, 642.555, 663.498, 349.362, 454.074, 475.016, 454.074, 516.9, 558.785, 579.729, 621.613, 663.498, 684.439, 768.209, 705.383, 726.324, 454.074, 475.016, 495.959, 558.785, 579.729, 621.613, 558.785, 579.729, 558.785, 537.844, 579.729, 726.324, 705.383, 747.268, 705.383, 705.383, 537.844, 621.613, 558.785, 684.439, 663.498, 684.439, 475.016, 516.9, 349.362, 328.418, 286.534, 433.131, 370.304, 391.247, 391.247, 181.822, 139.937, 98.052, 118.786, 13.34, 13.236, 181.822, 181.822, 244.649, 307.477, 370.304, 412.189, 475.016, 475.016, 495.959, 349.362, 433.131, 516.9, 454.074, 223.707, 202.765, 181.822, 265.592, 160.88, 35.225, 118.995, 55.225, 181.822, 33.236, 33.236, 98.052, 32.293, 32.293, 56.167, 56.167, 35.225, 35.225, 56.167, 12.293, 55.225, 56.167, 55.225), y = c(153.403, 132.46, 132.46, 195.288, 300, 404.713, 280.105, 300, 363.141, 320.941, 468.168, 489.529, 467.539, 404.713, 509.844, 425.654, 446.598, 468.586, 467.539, 530.367, 446.598, 467.539, 488.482, 509.424, 572.252, 551.309, 593.193, 467.539, 446.598, 69.633, 27.749, 132.46, 111.518, 48.691, 69.633, 90.576, 132.46, 446.598, 425.654, 489.529, 301.047, 320.941, 216.23, 195.288, 279.057, 195.288, 300, 279.057, 195.288, 174.345, 237.172, 90.576, 48.691, 27.749, 6.806, 153.403, 258.115, 279.057, 237.172, 258.115, 237.172, 258.115, 174.345, 111.518, 320.941, 362.826, 383.77, 341.885, 320.941, 341.885, 362.826, 446.598, 425.654, 320.941, 404.713, 258.115, 216.23, 132.46, 280.105, 237.172, 216.23, 173.298, 216.23, 363.875, 341.885, 280.105, 446.598, 446.598, 467.539, 489.529, 489.529, 530.367, 593.193, 593.193, 467.539, 446.598, 27.749, 27.749, 300, 258.115, 320.941, 279.057, 279.057, 237.172, 153.403, 132.46, 132.46, 153.403, 174.345, 174.345, 132.46, 111.518, 90.576, 69.633, 48.691, 90.576, 174.345, 132.46, 467.539, 488.482, 509.424, 341.885, 320.941, 300, 467.539, 446.598, 572.252, 569.109, 551.309, 279.057, 27.749, 69.633, 48.691, 132.46, 279.057, 279.057, 258.115, 279.057, 258.115, 153.403, 320.941, 446.598, 320.941, 216.23, 279.057, 195.288, 216.23, 195.288, 216.23, 280.105, 320.629, 300, 234.345, 468.168, 342.303, 323.037, 425.654, 341.885, 362.826, 425.654, 404.713, 425.654, 404.713, 383.77, 362.826, 362.826, 362.826, 362.826, 320.941, 362.826, 341.885, 363.875, 402.723, 488.586, 467.121, 509.844, 259.163, 6.806, 27.749, 508.795, 362.199, 342.303, 383.875, 320.941, 383.455, 342.303, 383.77, 593.193, 593.193, 572.252, 593.193, 153.403, 132.46, 132.46, 195.288, 300, 404.713, 280.105, 300, 363.141, 320.941, 468.168, 489.529, 467.539, 404.713, 509.844, 425.654, 446.598, 468.586, 467.539, 530.367, 446.598, 467.539, 488.482, 509.424, 572.252, 551.309, 593.193, 467.539, 446.598, 69.633, 27.749, 132.46, 111.518, 48.691, 69.633, 90.576, 132.46, 446.598, 425.654, 489.529, 301.047, 320.941, 216.23, 195.288, 279.057, 195.288, 300, 279.057, 195.288, 174.345, 237.172, 90.576, 48.691, 27.749, 6.806, 153.403, 258.115, 279.057, 237.172, 258.115, 237.172, 258.115, 174.345, 111.518, 320.941, 362.826, 383.77, 341.885, 320.941, 341.885, 362.826, 446.598, 425.654, 320.941, 404.713, 258.115, 216.23, 132.46, 280.105, 237.172, 216.23, 173.298, 216.23, 363.875, 341.885, 237.172, 363.875, 404.713, 446.598, 467.539, 469.633, 509.424, 572.252, 572.252, 446.598, 425.654, 6.806, 6.806, 279.057, 216.23, 216.23, 195.288, 174.345, 174.345, 69.633, 111.518, 111.518, 132.46, 153.403, 132.46, 111.518, 90.576, 69.633, 48.691, 27.749, 69.633, 153.403, 90.576, 446.598, 467.539, 488.482, 320.941, 300, 279.057, 446.598, 341.885, 551.309, 530.367, 467.539, 195.288, 6.806, 6.806, 27.749, 90.576, 258.115, 258.115, 237.172, 237.172, 237.172, 132.46, 279.057, 425.654, 258.115, 132.46, 132.46, 174.345, 132.46, 132.46, 195.288, 237.172, 237.172, 237.172, 173.298, 364.607, 173.298, 281.152, 363.875, 320.941, 301.047, 363.875, 363.875, 404.713, 362.826, 362.826, 320.941, 341.885, 341.885, 320.941, 280.105, 341.885, 320.941, 341.99, 320.941, 468.168, 300, 490.156, 259.163, 6.806, 27.749, 468.168, 362.199, 342.303, 383.875, 320.941, 362.199, 320.941, 322.094, 572.252, 572.252, 572.252, 593.193 ), id = c(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 13L, 14L, 15L, 16L, 17L, 18L, 19L, 20L, 21L, 22L, 23L, 24L, 25L, 26L, 27L, 28L, 29L, 30L, 31L, 32L, 33L, 34L, 35L, 36L, 37L, 38L, 39L, 40L, 41L, 42L, 43L, 44L, 45L, 46L, 47L, 48L, 49L, 50L, 51L, 52L, 53L, 54L, 55L, 56L, 57L, 58L, 59L, 60L, 61L, 62L, 63L, 64L, 65L, 66L, 67L, 68L, 69L, 70L, 71L, 72L, 73L, 74L, 75L, 76L, 77L, 78L, 79L, 80L, 81L, 82L, 83L, 84L, 85L, 86L, 87L, 88L, 89L, 90L, 91L, 92L, 93L, 94L, 95L, 96L, 97L, 98L, 99L, 100L, 101L, 102L, 103L, 104L, 105L, 106L, 107L, 108L, 109L, 110L, 111L, 112L, 113L, 114L, 115L, 116L, 117L, 118L, 119L, 120L, 121L, 122L, 123L, 124L, 125L, 126L, 127L, 128L, 129L, 130L, 131L, 132L, 133L, 134L, 135L, 136L, 137L, 138L, 139L, 140L, 141L, 142L, 143L, 144L, 145L, 146L, 147L, 148L, 149L, 150L, 151L, 152L, 153L, 154L, 155L, 156L, 157L, 158L, 159L, 160L, 161L, 162L, 163L, 164L, 165L, 166L, 167L, 168L, 169L, 170L, 171L, 172L, 173L, 174L, 175L, 176L, 177L, 178L, 179L, 180L, 181L, 182L, 183L, 184L, 185L, 186L, 187L, 188L, 189L, 190L, 191L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 13L, 14L, 15L, 16L, 17L, 18L, 19L, 20L, 21L, 22L, 23L, 24L, 25L, 26L, 27L, 28L, 29L, 30L, 31L, 32L, 33L, 34L, 35L, 36L, 37L, 38L, 39L, 40L, 41L, 42L, 43L, 44L, 45L, 46L, 47L, 48L, 49L, 50L, 51L, 52L, 53L, 54L, 55L, 56L, 57L, 58L, 59L, 60L, 61L, 62L, 63L, 64L, 65L, 66L, 67L, 68L, 69L, 70L, 71L, 72L, 73L, 74L, 75L, 76L, 77L, 78L, 79L, 80L, 81L, 82L, 83L, 84L, 85L, 86L, 87L, 88L, 89L, 90L, 91L, 92L, 93L, 94L, 95L, 96L, 97L, 98L, 99L, 100L, 101L, 102L, 103L, 104L, 105L, 106L, 107L, 108L, 109L, 110L, 111L, 112L, 113L, 114L, 115L, 116L, 117L, 118L, 119L, 120L, 121L, 122L, 123L, 124L, 125L, 126L, 127L, 128L, 129L, 130L, 131L, 132L, 133L, 134L, 135L, 136L, 137L, 138L, 139L, 140L, 141L, 142L, 143L, 144L, 145L, 146L, 147L, 148L, 149L, 150L, 151L, 152L, 153L, 154L, 155L, 156L, 157L, 158L, 159L, 160L, 161L, 162L, 163L, 164L, 165L, 166L, 167L, 168L, 169L, 170L, 171L, 172L, 173L, 174L, 175L, 176L, 177L, 178L, 179L, 180L, 181L, 182L, 183L, 184L, 185L, 186L, 187L, 188L, 189L, 190L, 191L )), .Names = c("x", "y", "id"), row.names = c(NA, -382L), class = c("tbl_df", "tbl", "data.frame")) -> house_lines
/scratch/gouwar.j/cran-all/cranData/voteogram/R/aaa-house-data.r
structure(list(id = c("AL_1", "AL_2", "AK_1", "AK_2", "AZ_1", "AZ_2", "AR_1", "AR_2", "CA_1", "CA_2", "CO_1", "CO_2", "CT_1", "CT_2", "DE_1", "DE_2", "FL_1", "FL_2", "GA_1", "GA_2", "HI_1", "HI_2", "ID_1", "ID_2", "IL_1", "IL_2", "IN_1", "IN_2", "IA_1", "IA_2", "KS_1", "KS_2", "KY_1", "KY_2", "LA_1", "LA_2", "ME_1", "ME_2", "MD_1", "MD_2", "MA_1", "MA_2", "MI_1", "MI_2", "MN_1", "MN_2", "MS_1", "MS_2", "MO_1", "MO_2", "MT_1", "MT_2", "NE_1", "NE_2", "NV_1", "NV_2", "NH_1", "NH_2", "NJ_1", "NJ_2", "NM_1", "NM_2", "NY_1", "NY_2", "NC_1", "NC_2", "ND_1", "ND_2", "OH_1", "OH_2", "OK_1", "OK_2", "OR_1", "OR_2", "PA_1", "PA_2", "RI_1", "RI_2", "SC_1", "SC_2", "SD_1", "SD_2", "TN_1", "TN_2", "TX_1", "TX_2", "UT_1", "UT_2", "VT_1", "VT_2", "VA_1", "VA_2", "WV_1", "WV_2", "WI_1", "WI_2", "WY_1", "WY_2", "WA_1", "WA_2"), x = c(-8.2, 4.2, -157.8, -145.2, -133.2, -120.8, -58.2, -45.8, -158.1, -145.8, -108.2, -95.8, 66.8, 79.2, 66.8, 79.2, 41.8, 54.2, 17.2, 29.6, -157.7, -145.1, -133.2, -120.8, -33.2, -20.8, -33.2, -20.8, -58.2, -45.8, -83.2, -70.8, -33.2, -20.8, -58.2, -45.8, 91.8, 104.2, 41.8, 54.2, 66.8, 79.2, -8.2, 4.2, -58.2, -45.8, -33.2, -20.8, -58.2, -45.8, -108.2, -95.8, -83.2, -70.8, -133.2, -120.8, 91.8, 104.2, 41.8, 54.2, -108.2, -95.8, 41.8, 54.2, 4.2, -8.2, -83.2, -70.8, -8.2, 4.2, -83.2, -70.8, -158.1, -145.8, 16.8, 29.2, 91.8, 104.2, 16.8, 29.2, -83.2, -70.8, -33.2, -20.8, -83.2, -70.8, -133.2, -120.8, 66.8, 79.2, 16.8, 29.2, -8.2, 4.2, -58.2, -45.8, -108.2, -95.8, -158.1, -145.8), y = c(446.9, 446.9, 300.1, 300.1, 421.9, 421.9, 421.9, 421.9, 396.9, 396.9, 396.9, 396.9, 371.9, 371.9, 396.9, 396.9, 471.9, 471.9, 446.9, 446.9, 471.9, 471.9, 346.9, 346.9, 346.9, 346.9, 371.9, 371.9, 371.9, 371.9, 421.9, 421.9, 396.9, 396.9, 446.9, 446.9, 296.9, 296.9, 396.9, 396.9, 346.9, 346.9, 346.9, 346.9, 321.9, 321.9, 446.9, 446.9, 396.9, 396.9, 346.9, 346.9, 396.9, 396.9, 371.9, 371.9, 321.9, 321.9, 371.9, 371.9, 421.9, 421.9, 346.9, 346.9, 421.9, 421.9, 346.9, 346.9, 371.9, 371.9, 446.9, 446.9, 371.9, 371.9, 371.9, 371.9, 371.9, 371.9, 421.9, 421.9, 371.9, 371.9, 421.9, 421.9, 471.9, 471.9, 396.9, 396.9, 321.9, 321.9, 396.9, 396.9, 396.9, 396.9, 346.9, 346.9, 371.9, 371.9, 346.9, 346.9), height = c(24L, 24L, 24L, 24L, 24L, 24L, 24L, 24L, 24L, 24L, 24L, 24L, 24L, 24L, 24L, 24L, 24L, 24L, 24L, 24L, 24L, 24L, 24L, 24L, 24L, 24L, 24L, 24L, 24L, 24L, 24L, 24L, 24L, 24L, 24L, 24L, 24L, 24L, 24L, 24L, 24L, 24L, 24L, 24L, 24L, 24L, 24L, 24L, 24L, 24L, 24L, 24L, 24L, 24L, 24L, 24L, 24L, 24L, 24L, 24L, 24L, 24L, 24L, 24L, 24L, 24L, 24L, 24L, 24L, 24L, 24L, 24L, 24L, 24L, 24L, 24L, 24L, 24L, 24L, 24L, 24L, 24L, 24L, 24L, 24L, 24L, 24L, 24L, 24L, 24L, 24L, 24L, 24L, 24L, 24L, 24L, 24L, 24L, 24L, 24L), width = c(11.5, 11.5, 11.5, 11.5, 11.5, 11.5, 11.5, 11.5, 11.5, 11.5, 11.5, 11.5, 11.5, 11.5, 11.5, 11.5, 11.5, 11.5, 11.5, 11.5, 11.5, 11.5, 11.5, 11.5, 11.5, 11.5, 11.5, 11.5, 11.5, 11.5, 11.5, 11.5, 11.5, 11.5, 11.5, 11.5, 11.5, 11.5, 11.5, 11.5, 11.5, 11.5, 11.5, 11.5, 11.5, 11.5, 11.5, 11.5, 11.5, 11.5, 11.5, 11.5, 11.5, 11.5, 11.5, 11.5, 11.5, 11.5, 11.5, 11.5, 11.5, 11.5, 11.5, 11.5, 11.5, 11.5, 11.5, 11.5, 11.5, 11.5, 11.5, 11.5, 11.5, 11.5, 11.5, 11.5, 11.5, 11.5, 11.5, 11.5, 11.5, 11.5, 11.5, 11.5, 11.5, 11.5, 11.5, 11.5, 11.5, 11.5, 11.5, 11.5, 11.5, 11.5, 11.5, 11.5, 11.5, 11.5, 11.5, 11.5), xmax = c(3.3, 15.7, -146.3, -133.7, -121.7, -109.3, -46.7, -34.3, -146.6, -134.3, -96.7, -84.3, 78.3, 90.7, 78.3, 90.7, 53.3, 65.7, 28.7, 41.1, -146.2, -133.6, -121.7, -109.3, -21.7, -9.3, -21.7, -9.3, -46.7, -34.3, -71.7, -59.3, -21.7, -9.3, -46.7, -34.3, 103.3, 115.7, 53.3, 65.7, 78.3, 90.7, 3.3, 15.7, -46.7, -34.3, -21.7, -9.3, -46.7, -34.3, -96.7, -84.3, -71.7, -59.3, -121.7, -109.3, 103.3, 115.7, 53.3, 65.7, -96.7, -84.3, 53.3, 65.7, 15.7, 3.3, -71.7, -59.3, 3.3, 15.7, -71.7, -59.3, -146.6, -134.3, 28.3, 40.7, 103.3, 115.7, 28.3, 40.7, -71.7, -59.3, -21.7, -9.3, -71.7, -59.3, -121.7, -109.3, 78.3, 90.7, 28.3, 40.7, 3.3, 15.7, -46.7, -34.3, -96.7, -84.3, -146.6, -134.3), ymax = c(470.9, 470.9, 324.1, 324.1, 445.9, 445.9, 445.9, 445.9, 420.9, 420.9, 420.9, 420.9, 395.9, 395.9, 420.9, 420.9, 495.9, 495.9, 470.9, 470.9, 495.9, 495.9, 370.9, 370.9, 370.9, 370.9, 395.9, 395.9, 395.9, 395.9, 445.9, 445.9, 420.9, 420.9, 470.9, 470.9, 320.9, 320.9, 420.9, 420.9, 370.9, 370.9, 370.9, 370.9, 345.9, 345.9, 470.9, 470.9, 420.9, 420.9, 370.9, 370.9, 420.9, 420.9, 395.9, 395.9, 345.9, 345.9, 395.9, 395.9, 445.9, 445.9, 370.9, 370.9, 445.9, 445.9, 370.9, 370.9, 395.9, 395.9, 470.9, 470.9, 395.9, 395.9, 395.9, 395.9, 395.9, 395.9, 445.9, 445.9, 395.9, 395.9, 445.9, 445.9, 495.9, 495.9, 420.9, 420.9, 345.9, 345.9, 420.9, 420.9, 420.9, 420.9, 370.9, 370.9, 395.9, 395.9, 370.9, 370.9)), .Names = c("id", "x", "y", "height", "width", "xmax", "ymax"), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, -100L)) -> senate_df
/scratch/gouwar.j/cran-all/cranData/voteogram/R/aaa-senate-data.r
#' Produce a ProPublica- or GovTrack-style House roll call vote cartogram #' #' @md #' @param vote_tally either a `pprc` object (the result of a call to [roll_call()]) or #' a `data.frame` of vote tallies for the house It expects 3 columns. `state_abbrev` : the #' 2-letter U.S. state abbreviation; `district` : either `1` or `2` to distinguish between #' each representative; `party` : `R`, `D` or `ID`; `position` : `yes`, `no`, `present`, `none` for #' how the representative voted. #' @param style either ProPublica-ish (`pp` or `propublica`) or GovTrack-ish (`gt` or `govtrack`) #' @param pp_square if `TRUE` then no "state borders" will be drawn, but distinct Representative #' squares. If `FALSE` then the cartogram will be very close to the ProPublica cartograms. #' @return a `ggplot2` object that you can further customize with scales, labels, etc. #' @note No "themeing" is applied to the returned ggplot2 object. You can use [theme_voteogram()] #' if you need a base theme. Also, GovTrack-style cartograms will have `coord_equal()` #' applied by default. #' @export #' @examples \dontrun{ #' # what you'd normally do #' rep <- roll_call("house", 115, 1, 256) #' } #' #' # using a saved object #' rep <- readRDS(system.file("extdata", "rep.rds", package = "voteogram")) #' #' house_carto(rep, pp_square = TRUE) house_carto <- function(vote_tally, style = c("pp", "gt", "propublica", "govtrack"), pp_square = FALSE) { if (inherits(vote_tally, "pprc")) vote_tally <- vote_tally$votes if (!inherits(vote_tally, "data.frame")) stop("Needs a data.frame", call. = FALSE) style <- match.arg(tolower(style), c("pp", "gt", "propublica", "govtrack")) cdiff <- setdiff(c("state_abbrev", "party", "district", "position"), colnames(vote_tally)) if (length(cdiff) > 0) stop(sprintf("Missing: %s", paste0(cdiff, collapse = ", ")), call. = FALSE) if (style %in% c("pp", "propublica")) { vote_tally <- dplyr::mutate(vote_tally, id = sprintf("%s_%s", toupper(state_abbrev), district)) vote_tally <- dplyr::mutate(vote_tally, fill = sprintf("%s-%s", toupper(party), tolower(position))) vote_tally <- dplyr::mutate(vote_tally, fill = ifelse(grepl("acant", fill), "Vacant", fill)) plot_df <- dplyr::left_join(house_df, vote_tally, by = "id") if (pp_square) { ggplot(plot_df) + geom_rect( aes( xmin = x, ymin = y, xmax = xmax, ymax = ymax, fill = fill ), color = "white", linewidth = 0.25 ) + scale_y_reverse() + scale_fill_manual( name = NULL, values = vote_carto_fill ) + labs(x = NULL, y = NULL) } else { ggplot() + geom_rect( data = plot_df, aes( xmin = x, ymin = y, xmax = xmax, ymax = ymax, fill = fill, color = fill ), linewidth = 0.25 ) + geom_line( data = house_lines, aes(x, y, group = id), color = "white", lineend = "round", linejoin = "round", linewidth = 0.5 ) + scale_y_reverse() + scale_color_manual( name = NULL, values = vote_carto_color ) + scale_fill_manual( name = NULL, values = vote_carto_fill ) + labs(x = NULL, y = NULL) } } else { zeroes <- c("ak", "as", "dc", "de", "gu", "mp", "mt", "nd", "pr", "sd", "vi", "vt", "wy") vote_tally <- dplyr::mutate(vote_tally, district = ifelse(tolower(state_abbrev) %in% zeroes, 0, district)) vote_tally <- dplyr::mutate(vote_tally, id = sprintf("%s%02d", tolower(state_abbrev), district)) vote_tally <- dplyr::mutate(vote_tally, fill = sprintf("%s-%s", toupper(party), tolower(position))) vote_tally <- dplyr::mutate(vote_tally, fill = ifelse(grepl("acant", fill), "Vacant", fill)) plot_df <- dplyr::left_join(gt_house_polys, vote_tally, by = "id") plot_df <- dplyr::filter(plot_df, !is.na(fill)) ggplot() + geom_polygon( data = plot_df, aes(x, y, group = id, fill = fill), linewidth = 0 ) + geom_line( data = gt_house_lines, aes(x, y, group = id), linewidth = gt_house_lines$size, color = gt_house_lines$color, lineend = "round", linejoin = "round" ) + geom_text( data = gt_house_labs, aes(x, y, label = lab), size = 2.25, hjust = 0, vjust = 0 ) + scale_y_reverse() + scale_fill_manual( name = NULL, values = vote_carto_fill, na.value = "white" ) + coord_equal() + labs(x = NULL, y = NULL) } }
/scratch/gouwar.j/cran-all/cranData/voteogram/R/gghouse.r
#' Produce a Senate cartogram #' #' @md #' @param vote_tally either a `pprc` object (the result of a call to [roll_call()]) or #' a `data.frame` of vote tallies for the senate. It expects 3 columns. `state_abbrev` : the #' 2-letter U.S. state abbreviation; `district` : either `1` or `2` to distinguish between #' each senator; `party` : `R`, `D` or `ID`; `position` : `yes`, `no`, `present`, `none` for #' how the senator voted. #' @return a `ggplot2` object that you can further customize with scales, labels, etc. #' @note No "themeing" is applied to the returned ggplot2 object. You can use [theme_voteogram()] #' if you need a base theme. #' @export #' @examples \dontrun{ #' # what you'd normally do #' sen <- roll_call("senate", 115, 1, 110) #' } #' #' # Using a saved object #' sen <- readRDS(system.file("extdata", "sen.rds", package = "voteogram")) #' #' senate_carto(sen) senate_carto <- function(vote_tally) { if (inherits(vote_tally, "pprc")) vote_tally <- vote_tally$votes if (!inherits(vote_tally, "data.frame")) stop("Needs a data.frame", call. = FALSE) cdiff <- setdiff(c("state_abbrev", "party", "district", "position"), colnames(vote_tally)) if (length(cdiff) > 0) stop(sprintf("Missing: %s", paste0(cdiff, collapse = ", ")), call. = FALSE) vote_tally <- dplyr::mutate(vote_tally, id = sprintf("%s_%s", toupper(state_abbrev), district)) vote_tally <- dplyr::mutate(vote_tally, fill = sprintf("%s-%s", toupper(party), tolower(position))) vote_tally <- dplyr::mutate(vote_tally, fill = ifelse(grepl("acant", fill), "Vacant", fill)) plot_df <- dplyr::left_join(senate_df, vote_tally, by = "id") ggplot(plot_df) + geom_rect( aes( xmin = x, ymin = y, xmax = xmax, ymax = ymax, fill = fill ), color = "white", linewidth = 0.25 ) + scale_y_reverse() + scale_fill_manual( name = NULL, values = vote_carto_fill ) + labs(x = NULL, y = NULL) }
/scratch/gouwar.j/cran-all/cranData/voteogram/R/ggsenate.r
#' Get Voting Record for House or Senate By Number, Session & Roll Call Number #' #' @param critter one of `house` or `senate` #' @param number valid congress number. ProPublica seems to have data going back to the 101st #' Congress, so valid values are `101`-present Congress number (`115` as of the creation #' date of the package). #' @param session a valid session numbner (i.e. `1` or `2` and valid for current year) #' @param rcall roll call vote number #' @return a `list`, one component of which is a `votes` `data.frame` #' @note Try to cache this data if at all possible. ProPublica is a non-profit organization #' and this data comes from their Amazon S3 buckets. Every access in a given month #' ticks down the "free" counter. #' @export #' @examples \dontrun{ #' # these make API calls so they aren't run in the examples #' rep <- roll_call("house", 115, 1, 256) #' sen <- roll_call("senate", 115, 1, 110) #' } roll_call <- function(critter = c("house", "senate"), number, session = c(1L,2L), rcall) { critter <- match.arg(tolower(critter), c("house", "senate")) session <- as.integer(match.arg(as.character(session), as.character(1:2))) number <- as.integer(number) if (number < 101L) stop("ProPublica does not have data going that far back", call.=FALSE) rcall <- as.integer(rcall) base_url <- "https://pp-projects-static.s3.amazonaws.com/congress/assets/%s_%s_%s_%s.json" base_url <- sprintf(base_url, critter, number, session, rcall) res <- jsonlite::fromJSON(base_url) res$votes <- tibble::as_tibble(res$votes) class(res) <- c("pprc", class(res)) res } #' Fortify a [roll_call()] (`pprc`) object #' #' @md #' @param model a [roll_call()] (`pprc`) object #' @param data unused #' @param ... unused #' @export fortify.pprc <- function(model, data, ...) { model$votes } #' Better default `print` function for [roll_call()] (`pprc`) objects #' #' @md #' @param x a [roll_call()] (`pprc`) object #' @param ... ignored #' @export print.pprc <- function(x, ...) { cat(sprintf("%s Congress / Session: %s / %s Roll Call: %s / %s\n\n%s\n\nResult: %s\n", scales::ordinal(x$congress), x$session, x$chamber, x$roll_call, x$date_of_vote, if (x$description == "") x$question else x$description , x$result)) }
/scratch/gouwar.j/cran-all/cranData/voteogram/R/roll-call.r
#' voteogram ggplot2 theme #' #' Provides a very basic theme with no background, grid, axis text or axis ticks and #' an easy way to turn the legend on or off. #' #' @param legend if `FALSE` no legend is shown #' @export #' @examples \dontrun{ #' # what you'd normally do #' sen <- roll_call("senate", 115, 1, 110) #' } #' #' # using a saved object #' sen <- readRDS(system.file("extdata", "sen.rds", package="voteogram")) #' #' senate_carto(sen) + #' theme_voteogram() theme_voteogram <- function(legend=TRUE) { theme(panel.background=element_blank()) + theme(panel.grid=element_blank()) + theme(axis.ticks=element_blank()) + theme(axis.text=element_blank()) -> th if (!legend) th <- th + theme(legend.position="FALSE") th }
/scratch/gouwar.j/cran-all/cranData/voteogram/R/theme.r
#' U.S. House and Senate Voting Cartogram Generators #' #' ProPublica' <https://projects.propublica.org/represent/> makes United States #' Congress member votes available and has developed their own unique cartogram to visually #' represent this data. Tools are provided to retrieve voting data, prepare voting data #' for plotting with 'ggplot2', create vote cartograms and theme them. #' #' @name voteogram #' @docType package #' @author Bob Rudis (bob@@rud.is) #' @import ggplot2 #' @importFrom tibble as_tibble #' @importFrom dplyr left_join mutate filter %>% #' @importFrom jsonlite fromJSON #' @importFrom scales ordinal #' @importFrom utils globalVariables NULL #' voteogram exported operators #' #' The following functions are imported and then re-exported #' from the voteogram package to enable use of the magrittr #' pipe operator with no additional library calls #' #' @name voteogram-exports NULL #' @name %>% #' @export #' @rdname voteogram-exports NULL
/scratch/gouwar.j/cran-all/cranData/voteogram/R/voteogram-package.R
## ----setup, include = FALSE--------------------------------------------------- knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ## ----libs, message = FALSE, warning = FALSE----------------------------------- library(voteogram) library(ggplot2) ## ----data, eval=FALSE--------------------------------------------------------- # sen <- roll_call("senate", 115, 1, 110) # rep <- roll_call("house", 115, 1, 256) ## ----real_data, echo=FALSE---------------------------------------------------- sen <- readRDS(system.file("extdata", "sen.rds", package="voteogram")) rep <- readRDS(system.file("extdata", "rep.rds", package="voteogram")) ## ----------------------------------------------------------------------------- str(sen) sen$votes ## ----------------------------------------------------------------------------- str(rep) fortify(rep) ## ----sen, fig.width=8, fig.height=5------------------------------------------- senate_carto(sen) + labs(title="Senate Vote 110 - Invokes Cloture on Neil Gorsuch Nomination") + theme_voteogram() ## ----rep_pp_square, fig.width=8, fig.height=5--------------------------------- house_carto(rep, pp_square=TRUE) + labs(x=NULL, y=NULL, title="House Vote 256 - Passes American Health Care Act,\nRepealing Obamacare") + theme_voteogram() ## ----rep_pp_orig, fig.width=8, fig.height=5----------------------------------- house_carto(rep, pp_square=FALSE) + labs(x=NULL, y=NULL, title="House Vote 256 - Passes American Health Care Act,\nRepealing Obamacare") + theme_voteogram() ## ----rep_gt, fig.width=8, fig.height=5---------------------------------------- house_carto(rep, "gt") + labs(x=NULL, y=NULL, title="House Vote 256 - Passes American Health Care Act,\nRepealing Obamacare") + theme_voteogram() ## ----sen_small, fig.width=3, fig.height=2.1----------------------------------- senate_carto(sen) + theme_voteogram(legend=FALSE) ## ----rep_small, fig.width=3, fig.height=2.1----------------------------------- house_carto(rep) + theme_voteogram(legend=FALSE) ## ----rep_small_1, fig.width=3, fig.height=2.1--------------------------------- house_carto(rep, pp_square=TRUE) + theme_voteogram(legend=FALSE)
/scratch/gouwar.j/cran-all/cranData/voteogram/inst/doc/intro_to_voteogram.R
--- title: "Introduction to the voteogram package" author: "Bob Rudis" date: "`r Sys.Date()`" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Introduction to the voteogram package} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r setup, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ``` Basic usage only requires this package and `ggplot2`: ```{r libs, message = FALSE, warning = FALSE} library(voteogram) library(ggplot2) ``` ## Getting Vote Data The cartograms need data and the best way to do that is by obtaining roll call vote data from ProPublica via the `roll_call()` function. Data can be retrieved for any House or Senate vote by specificing the target vote parameters: ```{r data, eval=FALSE} sen <- roll_call("senate", 115, 1, 110) rep <- roll_call("house", 115, 1, 256) ``` ```{r real_data, echo=FALSE} sen <- readRDS(system.file("extdata", "sen.rds", package="voteogram")) rep <- readRDS(system.file("extdata", "rep.rds", package="voteogram")) ``` Their structures look the same and there is a print-method to make the console output easier on the eyes: ```{r} str(sen) sen$votes ``` ```{r} str(rep) fortify(rep) ``` That data may be useful on its own (ouside of plotting). Note, also, that `ggplot2`'s `fortify()` method uses the provided object class method for roll call objects to know how to extract the rectangular data necessary for plotting. ## Making Cartograms These cartograms have a few style options: ### ProPublica ```{r sen, fig.width=8, fig.height=5} senate_carto(sen) + labs(title="Senate Vote 110 - Invokes Cloture on Neil Gorsuch Nomination") + theme_voteogram() ``` ```{r rep_pp_square, fig.width=8, fig.height=5} house_carto(rep, pp_square=TRUE) + labs(x=NULL, y=NULL, title="House Vote 256 - Passes American Health Care Act,\nRepealing Obamacare") + theme_voteogram() ``` ```{r rep_pp_orig, fig.width=8, fig.height=5} house_carto(rep, pp_square=FALSE) + labs(x=NULL, y=NULL, title="House Vote 256 - Passes American Health Care Act,\nRepealing Obamacare") + theme_voteogram() ``` ### GovTrack ```{r rep_gt, fig.width=8, fig.height=5} house_carto(rep, "gt") + labs(x=NULL, y=NULL, title="House Vote 256 - Passes American Health Care Act,\nRepealing Obamacare") + theme_voteogram() ``` They can be shrunk down well (though that likely means annotating them in some other way): ### Tiny Cartograms ```{r sen_small, fig.width=3, fig.height=2.1} senate_carto(sen) + theme_voteogram(legend=FALSE) ``` ```{r rep_small, fig.width=3, fig.height=2.1} house_carto(rep) + theme_voteogram(legend=FALSE) ``` ```{r rep_small_1, fig.width=3, fig.height=2.1} house_carto(rep, pp_square=TRUE) + theme_voteogram(legend=FALSE) ```
/scratch/gouwar.j/cran-all/cranData/voteogram/inst/doc/intro_to_voteogram.Rmd
--- title: "Introduction to the voteogram package" author: "Bob Rudis" date: "`r Sys.Date()`" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Introduction to the voteogram package} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r setup, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ``` Basic usage only requires this package and `ggplot2`: ```{r libs, message = FALSE, warning = FALSE} library(voteogram) library(ggplot2) ``` ## Getting Vote Data The cartograms need data and the best way to do that is by obtaining roll call vote data from ProPublica via the `roll_call()` function. Data can be retrieved for any House or Senate vote by specificing the target vote parameters: ```{r data, eval=FALSE} sen <- roll_call("senate", 115, 1, 110) rep <- roll_call("house", 115, 1, 256) ``` ```{r real_data, echo=FALSE} sen <- readRDS(system.file("extdata", "sen.rds", package="voteogram")) rep <- readRDS(system.file("extdata", "rep.rds", package="voteogram")) ``` Their structures look the same and there is a print-method to make the console output easier on the eyes: ```{r} str(sen) sen$votes ``` ```{r} str(rep) fortify(rep) ``` That data may be useful on its own (ouside of plotting). Note, also, that `ggplot2`'s `fortify()` method uses the provided object class method for roll call objects to know how to extract the rectangular data necessary for plotting. ## Making Cartograms These cartograms have a few style options: ### ProPublica ```{r sen, fig.width=8, fig.height=5} senate_carto(sen) + labs(title="Senate Vote 110 - Invokes Cloture on Neil Gorsuch Nomination") + theme_voteogram() ``` ```{r rep_pp_square, fig.width=8, fig.height=5} house_carto(rep, pp_square=TRUE) + labs(x=NULL, y=NULL, title="House Vote 256 - Passes American Health Care Act,\nRepealing Obamacare") + theme_voteogram() ``` ```{r rep_pp_orig, fig.width=8, fig.height=5} house_carto(rep, pp_square=FALSE) + labs(x=NULL, y=NULL, title="House Vote 256 - Passes American Health Care Act,\nRepealing Obamacare") + theme_voteogram() ``` ### GovTrack ```{r rep_gt, fig.width=8, fig.height=5} house_carto(rep, "gt") + labs(x=NULL, y=NULL, title="House Vote 256 - Passes American Health Care Act,\nRepealing Obamacare") + theme_voteogram() ``` They can be shrunk down well (though that likely means annotating them in some other way): ### Tiny Cartograms ```{r sen_small, fig.width=3, fig.height=2.1} senate_carto(sen) + theme_voteogram(legend=FALSE) ``` ```{r rep_small, fig.width=3, fig.height=2.1} house_carto(rep) + theme_voteogram(legend=FALSE) ``` ```{r rep_small_1, fig.width=3, fig.height=2.1} house_carto(rep, pp_square=TRUE) + theme_voteogram(legend=FALSE) ```
/scratch/gouwar.j/cran-all/cranData/voteogram/vignettes/intro_to_voteogram.Rmd
#' Get candidate data by last name #' #' @param last_names Vector of candidate last names #' @param election_years Vector of election years. Default is the current year. #' @param stage_ids The \code{stage_id} of the election (\code{"P"} for primary or \code{"G"} for general). See also \code{\link{election_get_election_by_year_state}}. #' @param all Boolean: should all possible combinations of the variables be searched for, or just the exact combination of them in the order they are supplied? #' @param verbose Should cases when no data is available be messaged? #' #' @return A dataframe of candidates and their attributes. If a given \code{last_name} + \code{election_year} + \code{stage_id} combination returns no data, that row will be filled with \code{NA}s. #' @export #' #' @examples #' \dontrun{ #' candidates_get_by_lastname(c("Ocasio-Cortez", "Omar"), 2018) #' } candidates_get_by_lastname <- function( last_names, election_years = lubridate::year(lubridate::today()), stage_ids = "", all = TRUE, verbose = TRUE) { last_names %<>% as_char_vec() election_years %<>% as_char_vec() stage_ids %<>% as_char_vec() if (all) { query_df <- expand_grid( last_name = last_names, election_year = election_years, stage_id = stage_ids ) %>% mutate( query = glue::glue( "&lastName={last_name}&electionYear={election_year}&stageId={stage_id}" ) ) } else { arg_lengths <- c(length(last_names), length(election_years), length(stage_ids)) %>% magrittr::extract( !. == 1 ) if (length(arg_lengths) > 1 && (max(arg_lengths) - min(arg_lengths) != 0)) { stop("If `all` is FALSE, lengths of inputs must be equivalent to each other, or 1.") } query_df <- tibble( last_name = last_names, election_year = election_years, stage_id = stage_ids ) %>% mutate( query = glue::glue( "&lastName={last_name}&electionYear={election_year}&stageId={stage_id}" ) ) } r <- "Candidates.getByLastname?" out <- tibble() for (i in 1:nrow(query_df)) { q <- query_df$query[i] last_name <- query_df$last_name[i] election_year <- query_df$election_year[i] stage_id <- query_df$stage_id[i] if (verbose) { message(glue::glue( "Requesting data for {{last_name: {last_name}, election_year: {election_year}, stage_id: {stage_id}}}." )) } this <- get( req = r, query = q, level_one = "candidateList", level_two = "candidate" ) if (all(is.na(this))) { if (verbose) { message(glue::glue( "No results found for query {q}." )) } this <- query_df %>% select(-query) %>% vs_na_if("") } else { this %<>% mutate( election_year = election_year, stage_id = stage_id ) %>% transform_election_special() %>% select( candidate_id, first_name, nick_name, middle_name, last_name, suffix, title, ballot_name, stage_id, election_year, everything() ) } out %<>% bind_rows(this) } out %>% distinct() }
/scratch/gouwar.j/cran-all/cranData/votesmart/R/candidates_get_by_lastname.R
#' Get candidate data by Levenshtein distance from last name #' #' From the API docs, \url{http://api.votesmart.org/docs/Candidates.html}, "This method grabs a list of candidates according to a fuzzy lastname match." #' #' The actual Levenshtein distance of the result from the \code{last_name} provided is not available from the API. #' #' @param last_names Vector of candidate last names #' @param election_years Vector of election years. Default is the current year. #' @param stage_ids The \code{stage_id} of the election (\code{"P"} for primary or \code{"G"} for general). See also \code{\link{election_get_election_by_year_state}}. #' @param all Boolean: should all possible combinations of the variables be searched for, or just the exact combination of them in the order they are supplied? #' @param verbose Should cases when no data is available be messaged? #' #' @return A dataframe of candidates and their attributes. If a given \code{last_name} + \code{election_year} + \code{stage_id} combination returns no data, that row will be filled with \code{NA}s. #' @export #' #' @examples #' \dontrun{ #' candidates_get_by_levenshtein(c("Bookr", "Klobucar"), 2020) #' } candidates_get_by_levenshtein <- function( last_names, election_years = lubridate::year(lubridate::today()), stage_ids = "", all = TRUE, verbose = TRUE) { last_names %<>% as_char_vec() election_years %<>% as_char_vec() stage_ids %<>% as_char_vec() if (all) { query_df <- expand_grid( last_name = last_names, election_year = election_years, stage_id = stage_ids ) %>% mutate( query = glue::glue( "&lastName={last_name}&electionYear={election_year}&stageId={stage_id}" ) ) } else { arg_lengths <- c(length(last_names), length(election_years), length(stage_ids)) %>% magrittr::extract( !. == 1 ) if (length(arg_lengths) > 1 && (max(arg_lengths) - min(arg_lengths) != 0)) { stop("If `all` is FALSE, lengths of inputs must be equivalent to each other, or 1.") } query_df <- tibble( last_name = last_names, election_year = election_years, stage_id = stage_ids ) %>% mutate( query = glue::glue( "&lastName={last_name}&electionYear={election_year}&stageId={stage_id}" ) ) } r <- "Candidates.getByLevenshtein?" out <- tibble() for (i in 1:nrow(query_df)) { q <- query_df$query[i] last_name <- query_df$last_name[i] election_year <- query_df$election_year[i] stage_id <- query_df$stage_id[i] if (verbose) { message(glue::glue( "Requesting data for {{last_name: {last_name}, election_year: {election_year}, stage_id: {stage_id}}}." )) } this <- get( req = r, query = q, level_one = "candidateList", level_two = "candidate" ) if (all(is.na(this))) { if (verbose) { message(glue::glue( "No results found for query {q}." )) } this <- query_df %>% select(-query) %>% vs_na_if("") } else { this %<>% mutate( election_year = election_year, stage_id = stage_id ) %>% transform_election_special() %>% select( candidate_id, first_name, nick_name, middle_name, last_name, suffix, title, ballot_name, stage_id, election_year, everything() ) } out %<>% bind_rows(this) } out %>% distinct() }
/scratch/gouwar.j/cran-all/cranData/votesmart/R/candidates_get_by_levenshtein.R
#' Get candidates by the state in which they hold office #' #' @param state_ids Optional: vector of state abbreviations. Default is \code{NA}, for national-level offices (e.g. US President and Vice President). For all other offices the \code{state_id} must be supplied. #' @param office_ids Required: vector of office ids that candidates hold. See \code{\link{office_get_levels}} and \code{\link{office_get_offices_by_level}} for office ids. #' @param election_years Optional: vector of election years in which the candidate held office. Default is the current year. #' @param all Boolean: should all possible combinations of the variables be searched for, or just the exact combination of them in the order they are supplied? #' @param verbose Should cases when no data is available be messaged? #' #' @return A dataframe of candidates and their attributes. If a given \code{state_id} + \code{office_id} + \code{election_year} combination returns no data, that row will be filled with \code{NA}s. #' @export #' #' @examples #' \dontrun{ #' candidates_get_by_office_state( #' state_ids = c(NA, "NY", "CA"), #' office_ids = c("1", "6"), #' verbose = TRUE #' ) #' } candidates_get_by_office_state <- function( state_ids = NA, office_ids, election_years = lubridate::year(lubridate::today()), all = TRUE, verbose = TRUE) { state_ids %<>% as_char_vec() office_ids %<>% as_char_vec() election_years %<>% as_char_vec() if (all) { query_df <- expand_grid( state_id = state_ids, office_id = office_ids, election_year = election_years ) %>% mutate( query = glue::glue( "&stateId={state_id}&officeId={office_id}&electionYear={election_year}" ) ) } else { arg_lengths <- c(length(state_ids), length(office_ids), length(election_years)) %>% magrittr::extract( !. == 1 ) if (length(arg_lengths) > 1 && (max(arg_lengths) - min(arg_lengths) != 0)) { stop("If `all` is FALSE, lengths of inputs must be equivalent to each other, or 1.") } query_df <- tibble( state_id = state_ids, office_id = office_ids, election_year = election_years ) %>% mutate( query = glue::glue( "&stateId={state_id}&officeId={office_id}&electionYear={election_year}" ) ) } r <- "Candidates.getByOfficeState?" out <- tibble() for (i in 1:nrow(query_df)) { q <- query_df$query[i] this_state_id <- query_df$state_id[i] this_office_id <- query_df$office_id[i] this_election_year <- query_df$election_year[i] if (verbose) { message(glue::glue( "Requesting data for {{state_id: {this_state_id}, office_id: {this_office_id}, election_year: {this_election_year}}}." )) } this <- get( req = r, query = q, level_one = "candidateList", level_two = "candidate" ) if (all(is.na(this))) { if (verbose) { message(glue::glue( "No results found for query {q}." )) } # Other cols will be NA this <- query_df %>% select(-query) %>% rename( office_state_id = state_id ) %>% vs_na_if("") } else { # Turn each element into a tibble and rowbind them this %<>% mutate( # Sometimes these are off so set them explicitly office_state_id = office_state_id %>% coalesce(this_state_id), election_state_id = election_state_id %>% coalesce(this_state_id), office_id = office_id %>% coalesce(this_office_id), election_year = election_year %>% coalesce(this_election_year), ) %>% transform_election_special() %>% select( candidate_id, first_name, nick_name, middle_name, last_name, suffix, title, ballot_name, office_state_id, office_id, election_year, everything() ) } out %<>% bind_rows(this) } out %>% distinct() }
/scratch/gouwar.j/cran-all/cranData/votesmart/R/candidates_get_by_office_state.R
#' Endpoint-Input Mapping #' #' Unnested tibble containing the mapping between each endpoint, the inputs it takes, and whether those inputs are required. One or more input rows per endpoint. #' #' @format A tibble with 108 rows and 3 variables: #' \describe{ #' \item{endpoint}{name of the API endpoint} #' \item{input}{one or multiple inputs that can be used in the request to that endpoint} #' \item{required}{boolean: whether that input is required for that endpoint} #' } #' @source \url{http://api.votesmart.org/docs/} "endpoint_input_mapping" #' Nested Endpoint-Input Mapping #' #' Nested tibble containing the mapping between each endpoint, the inputs it takes, and whether those inputs are required. #' #' @format A tibble with 70 rows and 2 variables: #' \describe{ #' \item{endpoint}{name of the API endpoint} #' \item{inputs}{a list column containing one or more inputs and a boolean indicating whether they are required for that endpoint. Can be unnested with \code{tidyr::unnest}} #' } #' @source \url{http://api.votesmart.org/docs/} "endpoint_input_mapping_nested"
/scratch/gouwar.j/cran-all/cranData/votesmart/R/data.R
#' Get election info by election year and state #' #' @param years A vector of election years. #' @param state_ids A vector of state abbreviations. #' @param all Boolean: should all possible combinations of the variables be searched for, or just the exact combination of them in the order they are supplied? #' @param verbose Should cases when no data is available be messaged? #' #' @return A dataframe of candidates and their attributes. If a given \code{year} + \code{state_id} returns no data, that row will be filled with \code{NA}s. #' @export #' #' @examples #' \dontrun{ #' election_get_election_by_year_state(years = c(2016, 2017)) #' } election_get_election_by_year_state <- function( years = lubridate::year(lubridate::today()), state_ids = "", all = TRUE, verbose = TRUE) { years %<>% as_char_vec() state_ids %<>% as_char_vec() if (all) { query_df <- expand_grid( year = years, state_id = state_ids ) %>% mutate( query = glue::glue( "&year={year}&stateId={state_id}" ) ) } else { arg_lengths <- c(length(years), length(state_ids)) %>% magrittr::extract( !. == 1 ) if (length(arg_lengths) > 1 && (max(arg_lengths) - min(arg_lengths) != 0)) { stop("If `all` is FALSE, lengths of inputs must be equivalent to each other, or 1.") } query_df <- tibble( year = years, state_id = state_ids, query = glue::glue( "&year={year}&stateId={state_id}" ) ) } r <- "Election.getElectionByYearState?" out <- tibble() for (i in 1:nrow(query_df)) { q <- query_df$query[i] year <- query_df$year[i] state_id <- query_df$state_id[i] if (verbose) { message(glue::glue( "Requesting data for {{year: {year}, state_id: {state_id}}}." )) } this <- get_election( req = r, query = q ) if (all(is.na(this))) { if (verbose) { message(glue::glue( "No results found for query {q}." )) } this <- query_df %>% select(-query) %>% rename( election_year = year ) %>% vs_na_if("") } else { this %<>% mutate( election_year = year ) %>% select( election_id, election_year, state_id, name, everything() ) } out %<>% bind_rows(this) } out %>% distinct() }
/scratch/gouwar.j/cran-all/cranData/votesmart/R/election_get_election_by_year_state.R
globalVariables( c( ".", "ballot_name", "bill_id", "bill_number", "candidate_id", "categories", "categoryId", "chunk", "con_url", "data", "description", "election_date", "election_electionstage_id", "election_id", "election_state_id", "election_type", "election_year", "endpoint", "endpoint_input_mapping_nested", "first_name", "input", "last_name", "measure_code", "measure_id", "measure_text", "middle_name", "name", "nick_name", "no", "office_id", "office_level_id", "office_state_id", "outcome", "parent_id", "pro_url", "query", "rating", "rating_id", "rating_id_nester", "rating_name", "rating_text", "rn", "sig_id", "stage", "state.abb", "state_id", "state_id_parent", "suffix", "summary_url", "text_url", "timespan", "title", "type", "value", "vote", "yes" ) )
/scratch/gouwar.j/cran-all/cranData/votesmart/R/globals.R
#' Get information on a ballot measure #' #' Ballot measure ids can be found with the \code{\link{measure_get_measures_by_year_state}} function. #' #' @param measure_ids Vector of ballot measure ids. #' @param verbose Should cases when no data is available be messaged? #' #' @return A dataframe with the columns \code{measure_id, measure_code, title, election_date, election_type, outcome, yes_votes, no_votes, summary, summary_url, measure_text, text_url, pro_url, con_url}. #' @export #' #' @examples #' \dontrun{ #' measure_get_measures("1234") #' } measure_get_measures <- function( measure_ids, verbose = TRUE) { measure_ids %<>% as_char_vec() query_df <- tibble( measure_id = measure_ids ) %>% mutate( query = glue::glue( "&measureId={measure_id}" ) ) r <- "Measure.getMeasure?" out <- tibble() for (i in 1:nrow(query_df)) { measure_id <- query_df$measure_id[i] q <- query_df$query[i] message(glue::glue( "Requesting data for {{measure_id: {measure_id}}." )) this <- get( req = r, query = q, level_one = "measure", level_two = NA ) if (all(is.na(this))) { if (verbose) { message(glue::glue( "No results found for query {q}." )) } this <- query_df %>% select(-query) %>% vs_na_if("") } else { this %<>% transmute( measure_id, measure_code, title, election_date = lubridate::as_date(election_date), election_type, outcome, yes_votes = yes %>% as.integer(), no_votes = no %>% as.integer(), summary, summary_url, measure_text, text_url, pro_url, con_url ) } out %<>% bind_rows(this) } out %>% distinct() }
/scratch/gouwar.j/cran-all/cranData/votesmart/R/measure_get_measures.R
#' Get a dataframe of ballot measures by year and state #' #' More information about these ballot measures can be found using the \code{\link{measure_get_measures}} function. #' #' @param years A vector of election years. #' @param state_ids A vector of state abbreviations. #' @param all Boolean: should all possible combinations of the variables be searched for, or just the exact combination of them in the order they are supplied? #' @param verbose Should cases when no data is available be messaged? #' #' @return A dataframe of ballot measures and their attributes. If a given \code{year} + \code{state_id} returns no data, that row will be filled with \code{NA}s. #' @export #' #' @examples #' \dontrun{ #' measure_get_measures_by_year_state(years = c(2016, 2018), state_ids = c("MO", "IL", "VT")) #' } measure_get_measures_by_year_state <- function(years = lubridate::year(lubridate::today()), state_ids = state.abb, all = TRUE, verbose = TRUE) { r <- "Measure.getMeasuresByYearState?" if (all) { query_df <- expand_grid( year = years, state_id = state_ids ) %>% mutate( query = glue::glue( "&year={year}&stateId={state_id}" ) ) } else { arg_lengths <- c(length(years), length(state_ids)) %>% magrittr::extract( !. == 1 ) if (length(arg_lengths) > 1 && (max(arg_lengths) - min(arg_lengths) != 0)) { stop("If `all` is FALSE, lengths of inputs must be equivalent to each other, or 1.") } query_df <- tibble( year = years, state_id = state_ids, query = glue::glue( "&year={year}&stateId={state_id}" ) ) } out <- tibble() for (i in 1:nrow(query_df)) { q <- query_df$query[i] year <- query_df$year[i] state_id <- query_df$state_id[i] if (verbose) { message(glue::glue( "Requesting data for {{year: {year}, state_id: {state_id}}}." )) } this <- get( req = r, query = q, level_one = "measures", level_two = "measure" ) if (all(is.na(this)) || nrow(this) == 0) { if (verbose) { message(glue::glue( "No results found for query {q}." )) } this <- query_df %>% slice(i) %>% select(-query) %>% rename( election_year = year, state_id = state_id ) %>% vs_na_if("") } else { this %<>% mutate( election_year = year, state_id = state_id ) %>% select( measure_id, election_year, state_id, title, outcome ) } out %<>% bind_rows(this) } out %>% distinct() }
/scratch/gouwar.j/cran-all/cranData/votesmart/R/measure_get_measures_by_year_state.R
#' Get office levels #' #' These are currently: F for Federal, S for State, and L for Local. #' #' @return A dataframe with the columns \code{office_level_id} and \code{name}. #' @export #' #' @examples #' \dontrun{ #' office_get_levels() #' } office_get_levels <- function() { r <- "Office.getLevels?" out <- get( req = r, query = "", level_one = "levels", level_two = "level" ) if (all(is.na(out))) { message("Error getting office levels.") return(tibble()) } out }
/scratch/gouwar.j/cran-all/cranData/votesmart/R/office_get_levels.R
#' Get offices by level #' #' @param office_level_ids Vector of office levels. #' #' @return A dataframe with columns \code{office_id, name, title, office_level_id, office_type_id, office_branch_id, short_title}. #' @export #' #' @examples #' \dontrun{ #' office_get_offices_by_level("F") #' #' office_get_levels() %>% #' pull(office_level_id) %>% #' .[1] %>% #' office_get_offices_by_level() #' } office_get_offices_by_level <- function(office_level_ids) { office_level_ids %<>% as_char_vec() r <- "Office.getOfficesByLevel?" out <- tibble() for (l in office_level_ids) { q <- glue::glue("&levelId={l}") this <- get( req = r, query = q, level_one = "offices", level_two = "office" ) out %<>% bind_rows(this) } out %>% select( office_id, name, title, office_level_id, everything() ) %>% distinct() }
/scratch/gouwar.j/cran-all/cranData/votesmart/R/office_get_offices_by_level.R
#' Get SIG (Special Interest Group) ratings for candidates #' #' @param candidate_ids A vector of candidate ids. #' @param sig_ids A vector of SIG ids. Default is \code{""} for all SIGs. #' @param all Boolean: should all possible combinations of the variables be searched for, or just the exact combination of them in the order they are supplied? #' @param verbose Should cases when no data is available be messaged? #' #' @return A dataframe with the columns \code{rating_id, candidate_id, sig_id, rating, rating_name, timespan, categories, rating_text}. #' @export #' #' @examples #' \dontrun{ #' pelosi_id <- "26732" #' rating_get_candidate_ratings(pelosi_id) #' } rating_get_candidate_ratings <- function( candidate_ids, sig_ids = "", all = TRUE, verbose = TRUE) { candidate_ids %<>% as_char_vec() sig_ids %<>% as_char_vec() if (all) { query_df <- expand_grid( candidate_id = candidate_ids, sig_id = sig_ids ) %>% mutate( query = glue::glue("&candidateId={candidate_id}&sigId={sig_id}") ) } else { arg_lengths <- c(length(candidate_ids), length(sig_ids)) %>% magrittr::extract( !. == 1 ) if (length(arg_lengths) > 1 && (max(arg_lengths) - min(arg_lengths) != 0)) { stop("If `all` is FALSE, lengths of inputs must be equivalent to each other, or 1.") } query_df <- tibble( candidate_id = candidate_ids, sig_id = sig_ids ) %>% mutate( query = glue::glue("&candidateId={candidate_id}&sigId={sig_id}") ) } r <- "Rating.getCandidateRating?" out <- tibble() for (i in 1:nrow(query_df)) { candidate_id <- query_df$candidate_id[i] sig_id <- query_df$sig_id[i] q <- query_df$query[i] message(glue::glue( "Requesting data for {{candidate_id: {candidate_id}, sig_id: {sig_id}}}." )) suppressWarnings( this <- get( req = r, query = q, level_one = "candidateRating", level_two = "rating" ) ) if (all(is.na(this))) { if (verbose) { message(glue::glue( "No results found for query {q}." )) } this <- query_df %>% select(-query) %>% vs_na_if("") } else { suppressWarnings({ # For the case where we fixed up the JSON which didn't end with `}}` if ("categories" %in% names(this) && nrow(this) > 1) { this$categories %<>% purrr::map(as_tibble) %>% purrr::map(distinct) %>% purrr::map(mutate, rn = row_number()) %>% purrr::map( tidyr::pivot_wider, values_from = c(categoryId, name), names_from = rn ) this %<>% tidyr::unnest(categories) %>% clean_df() } else { this %<>% rename_all( stringr::str_remove, "categories_" ) %>% rename_all( stringr::str_remove, "_category" ) this %<>% # Distinct all the category values which are sometimes doubled up tidyr::pivot_longer(contains("category")) %>% group_by(rating_id) %>% distinct(value, .keep_all = TRUE) %>% ungroup() %>% tidyr::drop_na(value) %>% mutate( rating_id_nester = rating_id ) %>% # Split into individual tibbles by rating_id, apply chunk_it to each, and then recombine tidyr::nest(-rating_id_nester) %>% pull(data) %>% purrr::map(chunk_it, n_per_chunk = 2) %>% bind_rows() %>% rowwise() %>% # Rename categories now that we've deduped mutate( type = case_when( stringr::str_detect(value, "[0-9]") ~ "id", TRUE ~ "name" ), name = glue::glue("category_{type}_{chunk}") ) %>% select(-chunk, -type) %>% # Back to wide format tidyr::pivot_wider() %>% ungroup() %>% tidyr::unnest() } }) this %<>% mutate( candidate_id = candidate_id ) %>% select( rating_id, candidate_id, sig_id, rating, rating_name, timespan, rating_text, everything() ) out %<>% bind_rows(this) } } if ("categories" %in% names(out)) { out %<>% select(-categories) } suppressWarnings( out %>% tidyr::unnest() %>% distinct() ) }
/scratch/gouwar.j/cran-all/cranData/votesmart/R/rating_get_candidate_ratings.R
#' Get categories that contain ratings by state #' #' @param state_ids A vector of state abbreviations. Defaults to \code{NA} for national. #' #' @return A dataframe with columns \code{category_id, name, state_id}. #' @export #' #' @examples #' \dontrun{ #' rating_get_categories("NM") #' } rating_get_categories <- function(state_ids = NA) { state_ids %<>% as_char_vec() r <- "Rating.getCategories?" out <- tibble() for (s in state_ids) { message(glue::glue( "Beginning to get categories for state {s}." )) q <- glue::glue("&stateId={s}") this <- get( req = r, query = q, level_one = "categories", level_two = "category" ) %>% mutate( state_id = s ) out %<>% bind_rows(this) } out %>% distinct() }
/scratch/gouwar.j/cran-all/cranData/votesmart/R/rating_get_categories.R
#' Get information on a SIG (Special Interest Group) by its ID #' #' @param sig_ids Vector of SIG ids. #' @param verbose Should cases when no data is available be messaged? #' #' @return A dataframe with the columns \code{sig_id, name, description, state_id, address, city, state, zip, phone_1, phone_2, fax, email, url, contact_name}. #' @export #' #' @examples #' \dontrun{ #' rating_get_sig_list(2) %>% #' dplyr::pull(sig_id) %>% #' sample(3) %>% #' rating_get_sig() #' } rating_get_sig <- function( sig_ids, verbose = TRUE) { sig_ids %<>% as_char_vec() query_df <- tibble( sig_id = sig_ids ) %>% mutate( query = glue::glue( "&sigId={sig_id}" ) ) r <- "Rating.getSig?" out <- tibble() for (i in 1:nrow(query_df)) { sig_id <- query_df$sig_id[i] q <- query_df$query[i] message(glue::glue( "Requesting data for {{sig_id: {sig_id}}." )) this <- get( req = r, query = q, level_one = "sig", level_two = NA ) if (all(is.na(this))) { if (verbose) { message(glue::glue( "No results found for query {q}." )) } this <- query_df %>% select(-query) %>% vs_na_if("") } else { this %<>% select(-parent_id) %>% select( sig_id, name, description, everything() ) } out %<>% bind_rows(this) } out %>% distinct() }
/scratch/gouwar.j/cran-all/cranData/votesmart/R/rating_get_sig.R
#' Get SIG (Special Interest Group) list by category and state #' #' @param category_ids Vector of category ids. #' @param state_ids Vector of state abbreviations. Default \code{NA} for national. #' @param all Boolean: should all possible combinations of the variables be searched for, or just the exact combination of them in the order they are supplied? #' @param verbose Should cases when no data is available be messaged? #' #' @return A dataframe with the columns \code{sig_id, name, category_id, state_id}. #' @export #' #' @examples #' \dontrun{ #' rating_get_categories() %>% #' dplyr::pull(category_id) %>% #' sample(3) %>% #' rating_get_sig_list() #' } rating_get_sig_list <- function( category_ids, state_ids = NA, all = TRUE, verbose = TRUE) { category_ids %<>% as_char_vec() state_ids %<>% as_char_vec() if (all) { query_df <- expand_grid( category_id = category_ids, state_id = state_ids ) %>% mutate( query = glue::glue( "&categoryId={category_id}&stateId={state_id}" ) ) } else { arg_lengths <- c(length(category_ids), length(state_ids)) %>% magrittr::extract( !. == 1 ) if (length(arg_lengths) > 1 && (max(arg_lengths) - min(arg_lengths) != 0)) { stop("If `all` is FALSE, lengths of inputs must be equivalent to each other, or 1.") } query_df <- tibble( category_id = category_ids, state_id = state_ids ) %>% mutate( query = glue::glue( "&categoryId={category_id}&stateId={state_id}" ) ) } r <- "Rating.getSigList?" out <- tibble() for (i in 1:nrow(query_df)) { category_id <- query_df$category_id[i] state_id <- query_df$state_id[i] q <- query_df$query[i] message(glue::glue( "Requesting data for {{category_id: {category_id}, state_id: {state_id}}}." )) this <- get( req = r, query = q, level_one = "sigs", level_two = "sig" ) if (all(is.na(this))) { if (verbose) { message(glue::glue( "No results found for query {q}." )) } this <- query_df %>% select(-query) %>% vs_na_if("") } else { this %<>% mutate( category_id = category_id, state_id = state_id ) %>% select( sig_id, name, category_id, state_id ) } out %<>% bind_rows(this) } out %>% distinct() }
/scratch/gouwar.j/cran-all/cranData/votesmart/R/rating_get_sig_list.R
BASE_URL <- "http://api.votesmart.org/" get_key <- function() { key <- Sys.getenv("VOTESMART_API_KEY") if (identical(key, "")) { message("No VOTESMART_API_KEY key found.") } key } construct_url <- function(req, query = "") { key <- get_key() glue::glue("{BASE_URL}{req}key={key}{query}&o=JSON") } try_parse_content <- purrr::possibly( httr::content, otherwise = tibble(), quiet = FALSE ) fixup_content <- function(resp) { httr::content( resp, as = "text", encoding = "UTF-8" ) %>% stringr::str_c("}}", collapse = TRUE) %>% jsonlite::fromJSON() } try_fixup_content <- purrr::possibly( fixup_content, otherwise = tibble(), quiet = FALSE ) request <- function(url, verbose = FALSE) { if (verbose) { message(glue::glue( "Requesting: {url}." )) } resp <- httr::GET(url) %>% httr::stop_for_status() parsed <- try_parse_content(resp) if (identical(parsed, tibble())) { message("Error parsing JSON. Attempting to fix up raw.") parsed <- try_fixup_content(resp) if (identical(parsed, tibble())) { message("Unable to fix up raw.") return(tibble()) } else { message("Successfully fixed raw.") } } parsed } try_request <- purrr::possibly( request, otherwise = tibble(), quiet = FALSE ) # Special treatment for election_get_election_by_year_state get_election <- function(req, query) { url <- construct_url(req, query) raw <- try_request(url) if (identical(raw, tibble())) { message("Error requesting data.") return(tibble()) } lst <- raw$elections$election # We've gotten an error that there's no data if (is.null(lst)) { return(tibble()) } # Extra nested when state is NA if ("stage" %in% names(lst)) { # Only one element if (length(lst$stage$stageId) == 1) { lst$stage %<>% list } lst$stage %<>% purrr::map(as_tibble) %>% bind_rows() %>% purrr::map_dfc(as.character) %>% purrr::map_dfc(stringr::str_squish) %>% clean_df() # This stage name becomes name.1 in the state version and we take it out there, so do the same here if ("name" %in% names(lst$stage)) { lst$stage %<>% select(-name) } lst$stage %<>% list() out <- lst %>% as_tibble() %>% tidyr::unnest(stage) %>% rename( state_id_parent = state_id ) %>% select( # This isn't in the state equivalent -state_id_parent ) %>% clean_df() } else { out <- lst %>% purrr::map(purrr::flatten) %>% purrr::map(as.data.frame) %>% purrr::map(mutate_all, as.character) %>% bind_rows() %>% as_tibble() %>% select(-contains(".")) %>% clean_df() } out %>% rename( election_stage_id = election_electionstage_id ) } get <- function(req, query, level_one, level_two) { url <- construct_url(req, query) raw <- try_request(url) if (identical(raw, tibble())) { message("Error requesting data.") return(tibble()) } if (is.na(level_two)) { lst <- raw[[level_one]] if ("generalInfo" %in% names(lst)) { idx <- which(names(lst) == "generalInfo") lst <- lst[-idx] } } else { lst <- # Data is contained two levels down. These have different names for each endpoint. raw[[level_one]][[level_two]] } # We've gotten an error that there's no data if (is.null(lst)) { return(tibble()) } # We've fixed up the request and already used jsonlite::toJSON to end up with a dataframe here if (inherits(lst, "data.frame")) { out <- lst %>% as_tibble() out$categories <- out$categories$category return(out) } # Case where there will only be one row once we make into a tibble if (length(lst[[1]]) == 1) { out <- lst %>% as_tibble() pluck_it <- function(x, to_pluck) { x %>% purrr::modify_depth(2, purrr::pluck, to_pluck) %>% purrr::flatten() %>% purrr::flatten() %>% purrr::as_vector() %>% unique() } if ("categories" %in% names(out)) { if (purrr::vec_depth(out$categories) == 3) { out$category_id <- out$categories$category$categoryId out$category_name <- out$categories$category$categoryId } else { out$category_id <- out$categories %>% pluck_it("categoryId") %>% list() out$category_name <- out$categories %>% pluck_it("name") %>% list() } suppressWarnings({ out %<>% select(-categories) %>% tidyr::unnest() }) } # Otherwise there are multiple rows } else { out <- lst %>% # Not tibble because that will give us a list-col we have to explode purrr::map(as.data.frame) %>% # So that we don't end up combining factor and character in bind_rows purrr::map(mutate_all, as.character) %>% bind_rows() %>% as_tibble() } out %>% clean_df() }
/scratch/gouwar.j/cran-all/cranData/votesmart/R/request.R
#' Pipe operator #' #' See \code{magrittr::\link[magrittr:pipe]{\%>\%}} for details. #' #' @name %>% #' @rdname pipe #' @keywords internal #' @return The left hand side object with the right hand side applied to it. Does not reassign this value to the left hand side. #' @export #' @importFrom magrittr %>% #' @usage lhs \%>\% rhs NULL #' Assignment pipe operator #' #' See \code{magrittr::\link[magrittr:compound]{\%<>\%}} for details. #' #' @name %<>% #' @rdname assignment_pipe #' @keywords internal #' @return The left hand side object with the right hand side applied to it. Does reassign this value to the left hand side. #' @export #' @importFrom magrittr %<>% #' @usage lhs \%<>\% rhs NULL
/scratch/gouwar.j/cran-all/cranData/votesmart/R/utils-pipe.R
clean_df <- function(df) { df %>% rename_all( snakecase::to_snake_case ) %>% as_tibble() %>% vs_na_if("") %>% vs_na_if("NA") %>% # Remove \"s purrr::map_dfc( stringr::str_remove_all, '\\\"' ) %>% purrr::map_dfc(as.character) %>% purrr::map_dfc(stringr::str_squish) } clean_html <- function( x, split_on_nbsp = TRUE, split_on_newline = FALSE, remove_empty = TRUE) { if (split_on_nbsp) { x %<>% stringr::str_split("&nbsp") %>% purrr::as_vector() } if (split_on_newline) { x %<>% stringr::str_split("\\n") %>% purrr::as_vector() } x %<>% stringr::str_squish() %>% stringr::str_remove_all("[\\n\\r\\t]") if (remove_empty) { x %<>% magrittr::extract( !. == "" ) } x } as_char_vec <- function(x) { x %>% purrr::as_vector() %>% as.character() } expand_grid <- function(...) { expand.grid(...) %>% as_tibble() %>% purrr::map_dfc(as.character) } transform_election_special <- function(tbl) { if ("election_special" %in% names(tbl)) { tbl %>% mutate( election_special = case_when( election_special == "f" ~ FALSE, is.na(election_special) ~ NA, TRUE ~ TRUE ) ) } } chunk_it <- function( tbl, n_per_chunk = NA, n_chunks = NA, list_it = FALSE) { if ((is.na(n_per_chunk) && is.na(n_chunks)) || !is.na(n_per_chunk) && !is.na(n_chunks)) { stop("Exactly one of n_per_chunk or n_chunks must be set.") } if (!is.na(n_per_chunk)) { if (n_per_chunk > nrow(tbl)) { message("n_per_chunk is more than the number of rows. Only one chunk assigned.") } n_chunks <- ceiling(nrow(tbl) / n_per_chunk) } else { if (n_chunks > nrow(tbl)) { message("n_chunks is more than the number of rows. Assigning one chunk to each row.") n_chunks <- nrow(tbl) } } if (n_chunks == 1) { # Setting `breaks` to 1 in `cut` will break it tbl %<>% mutate( chunk = 1 ) } else { tbl %<>% mutate( chunk = cut(row_number(), n_chunks, labels = FALSE) ) } if (list_it) { suppressWarnings( tbl %<>% tidyr::nest(-chunk) %>% pull(data) ) } tbl } skip_if_no_auth <- function() { if (identical(Sys.getenv("VOTESMART_API_KEY"), "")) { testthat::skip("No authentication available") } } #' Turn all character strings matching a value to \code{NA} in a dataframe #' #' @param tbl A data.frame or tibble #' @param pattern Pattern to turn to \code{NA} #' @noRd #' @examples #' tibble(x = c("", "not empty"), y = c("not empty", "")) %>% #' vs_na_if() vs_na_if <- function(tbl, pattern = "") { tbl %>% mutate_if(is.character, list(~ na_if(., pattern))) }
/scratch/gouwar.j/cran-all/cranData/votesmart/R/utils.R
#' Get votes by official #' #' @param candidate_ids Vector of candidate_ids (required). See \link{candidates_get_by_lastname}, \link{candidates_get_by_levenshtein}, and \link{candidates_get_by_office_state}. #' @param office_ids Vector of office_ids. See \link{office_get_offices_by_level}. #' @param category_ids Vector of category_ids. See \link{rating_get_categories}. #' @param years Vector of years in which the vote was taken. #' @param all Boolean: should all possible combinations of the variables be searched for, or just the exact combination of them in the order they are supplied? #' @param verbose Should cases when no data is available be messaged? #' #' @return A dataframe of candidates' votes on bills and their attributes. If a given input combination returns no data, that row will be filled with \code{NA}s. #' @export #' #' @examples #' \dontrun{ #' aoc <- candidates_get_by_lastname( #' "ocasio-cortez", #' election_years = "2018" #' ) #' votes_get_by_official(aoc$candidate_id) #' } votes_get_by_official <- function( candidate_ids, office_ids = "", category_ids = "", years = "", all = TRUE, verbose = TRUE) { candidate_ids %<>% as_char_vec() office_ids %<>% as_char_vec() category_ids %<>% as_char_vec() years %<>% as_char_vec() if (all) { query_df <- expand_grid( candidate_id = candidate_ids, office_id = office_ids, category_id = category_ids, year = years ) %>% mutate( query = glue::glue( "&candidateId={candidate_id}&officeId={office_id}&categoryId={category_id}&year={year}" ) ) } else { arg_lengths <- c(length(candidate_ids), length(office_ids), length(category_ids), length(years)) %>% magrittr::extract( !. == 1 ) if (length(arg_lengths) > 1 && (max(arg_lengths) - min(arg_lengths) != 0)) { stop("If `all` is FALSE, lengths of inputs must be equivalent to each other, or 1.") } query_df <- tibble( candidate_id = candidate_ids, office_id = office_ids, category_id = category_ids, year = years ) %>% mutate( query = glue::glue( "&candidateId={candidate_id}&officeId={office_id}&categoryId={category_id}&year={year}" ) ) } r <- "Votes.getByOfficial?" out <- tibble() for (i in 1:nrow(query_df)) { q <- query_df$query[i] candidate_id <- query_df$candidate_id[i] office_id <- query_df$office_id[i] category_id <- query_df$category_id[i] year <- query_df$year[i] if (verbose) { message(glue::glue( "Requesting data for {{candidate_id: {candidate_id}, office_id: {office_id}, category_id: {category_id}, year: {year}}}." )) } this <- get( req = r, query = q, level_one = "bills", level_two = "bill" ) if (all(is.na(this))) { if (verbose) { message(glue::glue( "No results found for query {q}." )) } # Other cols will be NA this <- query_df %>% select(-query) %>% rename( category_id_1 = category_id ) %>% vs_na_if("") } else { # Turn each element into a tibble and rowbind them this %<>% mutate( candidate_id = candidate_id, year = year ) %>% rename_all( stringr::str_remove, "categories_category_" ) %>% select( bill_id, candidate_id, bill_number, title, vote, office_id, everything() ) } out %<>% bind_rows(this) } out %>% distinct() }
/scratch/gouwar.j/cran-all/cranData/votesmart/R/votes_get_by_official.R
#' @keywords internal "_PACKAGE" #' @import dplyr ## usethis namespace: start ## usethis namespace: end NULL
/scratch/gouwar.j/cran-all/cranData/votesmart/R/votesmart-package.R
## ---- include = FALSE--------------------------------------------------------- knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ## ----setup-------------------------------------------------------------------- library(votesmart) ## ----------------------------------------------------------------------------- # If our key is not registered in this environment variable, # the result of `Sys.getenv("VOTESMART_API_KEY")` will be `""` (i.e. a string of `nchar` 0) key <- Sys.getenv("VOTESMART_API_KEY") key_exists <- (nchar(key) > 0) if (!key_exists) knitr::knit_exit() ## ----------------------------------------------------------------------------- suppressPackageStartupMessages(library(dplyr)) conflicted::conflict_prefer("filter", "dplyr") ## ----------------------------------------------------------------------------- (franks <- candidates_get_by_lastname( last_names = "frank", election_years = c(2000, 2004) ) ) ## ----------------------------------------------------------------------------- (barneys <- franks %>% filter(first_name == "Barney") %>% select( candidate_id, first_name, last_name, election_year, election_state_id, election_office ) ) ## ----------------------------------------------------------------------------- (barney_id <- barneys %>% pull(candidate_id) %>% unique() ) ## ----------------------------------------------------------------------------- (barney_ratings <- rating_get_candidate_ratings( candidate_ids = barney_id, sig_ids = "" # All SIGs ) ) ## ----------------------------------------------------------------------------- main_cols <- c("rating", "category_name_1", "sig_id", "timespan") ## ----------------------------------------------------------------------------- (barney_on_env <- barney_ratings %>% filter(category_name_1 == "Environment") %>% select(main_cols) ) ## ----------------------------------------------------------------------------- barney_ratings %>% filter( stringr::str_detect(rating, "[A-Z]") ) %>% select(rating, category_name_1) ## ----------------------------------------------------------------------------- barney_on_env %>% group_by(timespan) %>% summarise( avg_rating = mean(as.numeric(rating), na.rm = TRUE) ) %>% arrange(desc(timespan)) ## ----------------------------------------------------------------------------- barney_ratings %>% filter(category_name_1 == "Abortion") %>% select( rating, sig_id, category_name_1 ) ## ----------------------------------------------------------------------------- (some_sigs <- barney_ratings %>% pull(sig_id) %>% unique() %>% sample(3) ) ## ----------------------------------------------------------------------------- rating_get_sig( sig_ids = some_sigs ) ## ----------------------------------------------------------------------------- (category_df <- rating_get_categories( state_ids = NA # NA for national ) %>% distinct() %>% sample_n(nrow(.)) # Sampling so we can see multiple categories in the 10 rows shown here ) ## ----------------------------------------------------------------------------- (some_categories <- category_df$category_id %>% sample(3)) ## ----------------------------------------------------------------------------- (sigs <- rating_get_sig_list( category_ids = some_categories, state_ids = NA ) %>% select(sig_id, name, category_id, state_id) %>% sample_n(nrow(.)) ) ## ----------------------------------------------------------------------------- sigs %>% rename( sig_name = name ) %>% left_join( category_df, by = c("state_id", "category_id") ) %>% rename( category_name_1 = name ) %>% sample_n(nrow(.))
/scratch/gouwar.j/cran-all/cranData/votesmart/inst/doc/votesmart.R
--- title: "votesmart" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{votesmart} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ``` ```{r setup} library(votesmart) ``` The first step to using the `votesmart` package is to register an API key and store it in an environment variable by following [these instructions](https://github.com/decktools/votesmart#api-keys). Let's make sure our API key is set. ```{r} # If our key is not registered in this environment variable, # the result of `Sys.getenv("VOTESMART_API_KEY")` will be `""` (i.e. a string of `nchar` 0) key <- Sys.getenv("VOTESMART_API_KEY") key_exists <- (nchar(key) > 0) if (!key_exists) knitr::knit_exit() ``` We'll also attach `dplyr` for working with dataframes. ```{r} suppressPackageStartupMessages(library(dplyr)) conflicted::conflict_prefer("filter", "dplyr") ``` <br> ### Motivation Some of these functions are necessary precursors to obtain data you might want. For instance, in order to get candidates' ratings by SIGs, you'll need to get `office_level_id`s in order to get `office_id`s, which is a required argument to get candidate information using `candidates_get_by_office_state`. We'll go through what might be a typical example of how you might use the `votesmart` package. <br> ## Get Candidate Info There are currently three functions for getting data on VoteSmart candidates: `candidates_get_by_lastname`, `candidates_get_by_levenshtein`, and `candidates_get_by_office_state`. Let's search for former US House Rep [Barney Frank](https://en.wikipedia.org/wiki/Barney_Frank) using `candidates_get_by_lastname`. <br> From `?candidates_get_by_lastname`, this function's defaults are: ``` candidates_get_by_lastname( last_names, election_years = lubridate::year(lubridate::today()), stage_ids = "", all = TRUE, verbose = TRUE ) ``` Since the default election year is the current year and Barney Frank left office in 2013, we'll specify a few years in which he ran for office. ```{r} (franks <- candidates_get_by_lastname( last_names = "frank", election_years = c(2000, 2004) ) ) ``` Looking at the `first_name` column, are a number of non-Barneys returned. We can next filter our results to Barney. ```{r} (barneys <- franks %>% filter(first_name == "Barney") %>% select( candidate_id, first_name, last_name, election_year, election_state_id, election_office ) ) ``` The two rows returned correspond to the two `election_year`s we specified. Each candidate gets their own unique `candidate_id`, which we can `pull` out. ```{r} (barney_id <- barneys %>% pull(candidate_id) %>% unique() ) ``` <br> ## Get Candidates' Ratings One of the most powerful things about VoteSmart is its wealth of information about candidates' positions on issues as rated by a number of Special Interest Groups, or SIGs. Given a `candidate_id`, we can ask for those ratings using `rating_get_candidate_ratings`. ```{r} (barney_ratings <- rating_get_candidate_ratings( candidate_ids = barney_id, sig_ids = "" # All SIGs ) ) ``` There are a lot of columns here because some ratings are tagged with multiple categories. ```{r} main_cols <- c("rating", "category_name_1", "sig_id", "timespan") ``` We'll filter to Barney's ratings on the environment using just the first category name. ```{r} (barney_on_env <- barney_ratings %>% filter(category_name_1 == "Environment") %>% select(main_cols) ) ``` Something to be aware of is that some SIGs give ratings as letter grades: ```{r} barney_ratings %>% filter( stringr::str_detect(rating, "[A-Z]") ) %>% select(rating, category_name_1) ``` But using just Barney's number grades, we can get his average rating on this category per `timespan`: ```{r} barney_on_env %>% group_by(timespan) %>% summarise( avg_rating = mean(as.numeric(rating), na.rm = TRUE) ) %>% arrange(desc(timespan)) ``` Keep in mind that these are ratings given by SIGs, which often have very different baseline stances on issues. For example, a pro-life group might give a candidate a rating of 0 whereas a pro-choice group might give that same candidate a 100. ```{r} barney_ratings %>% filter(category_name_1 == "Abortion") %>% select( rating, sig_id, category_name_1 ) ``` <br> ## SIGs When it comes to the Special Interest Groups themselves, the result of `rating_get_candidate_ratings` only supplies us with a `sig_id`. We can get more information about these SIGs given these IDs with `rating_get_sig`. ```{r} (some_sigs <- barney_ratings %>% pull(sig_id) %>% unique() %>% sample(3) ) ``` ```{r} rating_get_sig( sig_ids = some_sigs ) ``` <br> Or, if we don't yet know any `sig_id`s, we can get a dataframe of them with the function `rating_get_sig_list`. That function requires a vector of issue `category_ids`, however, so let's first get a vector of some `category_ids`. ```{r} (category_df <- rating_get_categories( state_ids = NA # NA for national ) %>% distinct() %>% sample_n(nrow(.)) # Sampling so we can see multiple categories in the 10 rows shown here ) ``` Now we can get our dataframe of SIGs given some categories. ```{r} (some_categories <- category_df$category_id %>% sample(3)) ``` ```{r} (sigs <- rating_get_sig_list( category_ids = some_categories, state_ids = NA ) %>% select(sig_id, name, category_id, state_id) %>% sample_n(nrow(.)) ) ``` We already have the category names corresponding to those `category_id`s in our `category_df`, so we can join `category_df` onto `sigs`s to attach `category_name_1`s to each of those SIGs. ```{r} sigs %>% rename( sig_name = name ) %>% left_join( category_df, by = c("state_id", "category_id") ) %>% rename( category_name_1 = name ) %>% sample_n(nrow(.)) ``` <br> *** For more info or to report a bug to VoteSmart, please refer to the [VoteSmart API docs](http://api.votesmart.org/docs/index.html)!
/scratch/gouwar.j/cran-all/cranData/votesmart/inst/doc/votesmart.Rmd
--- title: "votesmart" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{votesmart} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ``` ```{r setup} library(votesmart) ``` The first step to using the `votesmart` package is to register an API key and store it in an environment variable by following [these instructions](https://github.com/decktools/votesmart#api-keys). Let's make sure our API key is set. ```{r} # If our key is not registered in this environment variable, # the result of `Sys.getenv("VOTESMART_API_KEY")` will be `""` (i.e. a string of `nchar` 0) key <- Sys.getenv("VOTESMART_API_KEY") key_exists <- (nchar(key) > 0) if (!key_exists) knitr::knit_exit() ``` We'll also attach `dplyr` for working with dataframes. ```{r} suppressPackageStartupMessages(library(dplyr)) conflicted::conflict_prefer("filter", "dplyr") ``` <br> ### Motivation Some of these functions are necessary precursors to obtain data you might want. For instance, in order to get candidates' ratings by SIGs, you'll need to get `office_level_id`s in order to get `office_id`s, which is a required argument to get candidate information using `candidates_get_by_office_state`. We'll go through what might be a typical example of how you might use the `votesmart` package. <br> ## Get Candidate Info There are currently three functions for getting data on VoteSmart candidates: `candidates_get_by_lastname`, `candidates_get_by_levenshtein`, and `candidates_get_by_office_state`. Let's search for former US House Rep [Barney Frank](https://en.wikipedia.org/wiki/Barney_Frank) using `candidates_get_by_lastname`. <br> From `?candidates_get_by_lastname`, this function's defaults are: ``` candidates_get_by_lastname( last_names, election_years = lubridate::year(lubridate::today()), stage_ids = "", all = TRUE, verbose = TRUE ) ``` Since the default election year is the current year and Barney Frank left office in 2013, we'll specify a few years in which he ran for office. ```{r} (franks <- candidates_get_by_lastname( last_names = "frank", election_years = c(2000, 2004) ) ) ``` Looking at the `first_name` column, are a number of non-Barneys returned. We can next filter our results to Barney. ```{r} (barneys <- franks %>% filter(first_name == "Barney") %>% select( candidate_id, first_name, last_name, election_year, election_state_id, election_office ) ) ``` The two rows returned correspond to the two `election_year`s we specified. Each candidate gets their own unique `candidate_id`, which we can `pull` out. ```{r} (barney_id <- barneys %>% pull(candidate_id) %>% unique() ) ``` <br> ## Get Candidates' Ratings One of the most powerful things about VoteSmart is its wealth of information about candidates' positions on issues as rated by a number of Special Interest Groups, or SIGs. Given a `candidate_id`, we can ask for those ratings using `rating_get_candidate_ratings`. ```{r} (barney_ratings <- rating_get_candidate_ratings( candidate_ids = barney_id, sig_ids = "" # All SIGs ) ) ``` There are a lot of columns here because some ratings are tagged with multiple categories. ```{r} main_cols <- c("rating", "category_name_1", "sig_id", "timespan") ``` We'll filter to Barney's ratings on the environment using just the first category name. ```{r} (barney_on_env <- barney_ratings %>% filter(category_name_1 == "Environment") %>% select(main_cols) ) ``` Something to be aware of is that some SIGs give ratings as letter grades: ```{r} barney_ratings %>% filter( stringr::str_detect(rating, "[A-Z]") ) %>% select(rating, category_name_1) ``` But using just Barney's number grades, we can get his average rating on this category per `timespan`: ```{r} barney_on_env %>% group_by(timespan) %>% summarise( avg_rating = mean(as.numeric(rating), na.rm = TRUE) ) %>% arrange(desc(timespan)) ``` Keep in mind that these are ratings given by SIGs, which often have very different baseline stances on issues. For example, a pro-life group might give a candidate a rating of 0 whereas a pro-choice group might give that same candidate a 100. ```{r} barney_ratings %>% filter(category_name_1 == "Abortion") %>% select( rating, sig_id, category_name_1 ) ``` <br> ## SIGs When it comes to the Special Interest Groups themselves, the result of `rating_get_candidate_ratings` only supplies us with a `sig_id`. We can get more information about these SIGs given these IDs with `rating_get_sig`. ```{r} (some_sigs <- barney_ratings %>% pull(sig_id) %>% unique() %>% sample(3) ) ``` ```{r} rating_get_sig( sig_ids = some_sigs ) ``` <br> Or, if we don't yet know any `sig_id`s, we can get a dataframe of them with the function `rating_get_sig_list`. That function requires a vector of issue `category_ids`, however, so let's first get a vector of some `category_ids`. ```{r} (category_df <- rating_get_categories( state_ids = NA # NA for national ) %>% distinct() %>% sample_n(nrow(.)) # Sampling so we can see multiple categories in the 10 rows shown here ) ``` Now we can get our dataframe of SIGs given some categories. ```{r} (some_categories <- category_df$category_id %>% sample(3)) ``` ```{r} (sigs <- rating_get_sig_list( category_ids = some_categories, state_ids = NA ) %>% select(sig_id, name, category_id, state_id) %>% sample_n(nrow(.)) ) ``` We already have the category names corresponding to those `category_id`s in our `category_df`, so we can join `category_df` onto `sigs`s to attach `category_name_1`s to each of those SIGs. ```{r} sigs %>% rename( sig_name = name ) %>% left_join( category_df, by = c("state_id", "category_id") ) %>% rename( category_name_1 = name ) %>% sample_n(nrow(.)) ``` <br> *** For more info or to report a bug to VoteSmart, please refer to the [VoteSmart API docs](http://api.votesmart.org/docs/index.html)!
/scratch/gouwar.j/cran-all/cranData/votesmart/vignettes/votesmart.Rmd
bOttlEnEck <- function(d) { nrc <- nrow(d) if (is.data.frame(d)) d <- as.matrix(d) # data.frame is dangerous p <- d p[p != 0] <- 0 for (i in 1:nrc) { for (j in 1:nrc) { if (i != j) { if (d[i, j] > d[j, i]) { p[i, j] <- d[i, j] } else { p[i, j] <- 0 } } } } for (i in 1:nrc) { for (j in 1:nrc) { if (i != j) { for (k in 1:nrc) { if (k != i & k != j) { p[j, k] <- max(p[j, k], min(p[j, i], p[i, k])) } } } } } p } fInd_cdc_mAtrIx <- function(x, dup_ok = TRUE, available = 1) { class1 <- class(x)[1] message("CREATING CDC MATRIX") if (class1 == "vote") { candidate <- x$candidate candidate_num <- x$candidate_num ballot_num <- x$ballot_num compute_cdc <- FLEXIBLE_rOw2cdc(x, ARG_dup_ok = dup_ok, ARG_available = available) cdc_matrix <- compute_cdc[[1]] dif_matrix <- compute_cdc[[2]] valid_ballot_num <- compute_cdc[[3]] } else if (class1 == "matrix") { message("------USE INPUT MATRIX") if (nrow(x) != ncol(x)) stop("x must be a square matrix.") diag(x) <- 0 # should be 0 cdc_matrix <- x dif_matrix <- NULL ballot_num <- NULL valid_ballot_num <- NULL ini_cn <- colnames(x) ini_rn <- rownames(x) if (is.null(ini_cn) & is.null(ini_rn)) { add_rcname <- fUll_dIgIt(nrow(x), "x") colnames(cdc_matrix) <- add_rcname rownames(cdc_matrix) <- add_rcname } else if (is.null(ini_cn) & !is.null(ini_rn)) { colnames(cdc_matrix) <- rownames(cdc_matrix) } else if (!is.null(ini_cn) & is.null(ini_rn)) { rownames(cdc_matrix) <- colnames(cdc_matrix) } else if (!is.null(ini_cn) & !is.null(ini_rn)) { if (!identical(ini_cn, ini_rn)) stop(" Rownames and colnames of x must be the same.") } candidate <- rownames(cdc_matrix) candidate_num <- length(candidate) } else { cdc_matrix <- x$cdc # for condorcet obj dif_matrix <- x$dif ballot_num <- x$ballot_num valid_ballot_num <- x$valid_ballot_num candidate <- rownames(cdc_matrix) candidate_num <- length(candidate) } # search task finished binary_m <- if (class1 == "condorcet") x$binary else cdc2bInAry(cdc_matrix) cdc_m_res <- list(input_object = class1, candidate = candidate, candidate_num = candidate_num, ballot_num = ballot_num, valid_ballot_num = valid_ballot_num, cdc = cdc_matrix, dif = dif_matrix, binary = binary_m) return(cdc_m_res) } FLEXIBLE_rOw2cdc <- function(x, ARG_dup_ok, ARG_available) { candidate_num <- x$candidate_num candidate <- x$candidate CDC <- NULL # no need to calculate if (ARG_dup_ok == TRUE | length(x$row_with_dup) == 0) { if (ARG_available == candidate_num) { message("------USE CDC MATRIX IN x") CDC <- x$cdc DIF <- x$dif VALID_BALLOT_NUM <- nrow(x$ballot) - length(x$row_with_na) } else if (ARG_available == 1) { message("------USE CDC MATRIX WITH NA IN x") CDC <- x$cdc_with_na DIF <- x$dif_with_na VALID_BALLOT_NUM <- nrow(x$ballot) - length(which(x$num_non_na == 0)) } } # need to recalculate if (is.null(CDC)) { message("------RECALCULATING CDC MATRIX") get_na_ok <- which(x$num_non_na < ARG_available) if (length(get_na_ok) > 0) get_na_ok <- x$row_with_na[get_na_ok] get_dup <- if (ARG_dup_ok == TRUE) integer(0) else x$row_with_dup should_del <- unique(c(get_dup, get_na_ok)) length_should_del <- length(should_del) VALID_BALLOT_NUM <- nrow(x$ballot) - length_should_del if (VALID_BALLOT_NUM == 0) stop("No ballot is OK.") # maybe no usable ballot if (length_should_del > 0) { x <- x$ballot[-should_del, ] } else { x <- x$ballot } convert_v <- candidate_num # equal to candidate number, the highest(worst) score # start to compute CDC <- matrix(0, nrow = candidate_num, ncol = candidate_num) colnames(CDC) <- candidate rownames(CDC) <- candidate DIF <- CDC if (class(x)[1] != "data.table") x <- data.table::data.table(x) R <- data.table::frankv(x, ties.method = "dense") RT <- table(R) tlen <- length(RT) ttn <- as.numeric(names(RT)) RT <- as.numeric(RT) xx <- matrix(NA, nrow = tlen, ncol = ncol(x)) for (i in 1:tlen) { instance <- match(ttn[i], R) xx[i, ] <- as.numeric(x[instance, ]) # must add as.numeric } rm(x) for (r in 1:nrow(xx)) { rr <- as.numeric(xx[r, ]) r_uni <- RT[r] rr_which_na <- which(is.na(rr)) rr[rr_which_na] <- convert_v for (i in 1:candidate_num) { ii <- rr[i] for (j in 1:candidate_num) { jj <- rr[j] if (ii < jj) { iimjj <- (jj - ii) * r_uni CDC[i, j] <- CDC[i, j] + r_uni DIF[i, j] <- DIF[i, j] + iimjj } } } } } y <- list(CDC, DIF, valid_ballot_num = VALID_BALLOT_NUM) return(y) } lock_winner <- function(x, CAND) { colnames(x) <- NULL # must do this nrx <- nrow(x) res <- list(x[1, ]) for (i in 2:nrx) { ii <- x[i, ] iir <- rev(ii) have_anti <- 0 for (j in 1:length(res)) { if (identical(iir, res[[j]])) have_anti <- have_anti + 1 } if (have_anti == 0) { ii1 <- ii[1] ii2 <- ii[2] bigger <- c() smaller <- c() for (k in 1:length(res)) { kk <- res[[k]] kk1 <- kk[1] kk2 <- kk[2] if (kk2 == ii1) bigger <- append(bigger, kk1) if (kk1 == ii2) smaller <- append(smaller, kk2) } res[[length(res) + 1]] <- ii if (length(bigger) > 0) { for (p in bigger) res[[length(res) + 1]] <- c(p, ii2) } if (length(smaller) > 0) { for (q in smaller) res[[length(res) + 1]] <- c(ii1, q) } res <- unique(res) } } res <- do.call(rbind, res) which_not <- as.character(res[, 2]) # candidate who does not appear here is the winner which_not <- which(!CAND %in% which_not) which_not <- CAND[which_not] y <- list(res, which_not) y } RP_TIE_SOLVE <- function(x, zeroone) { TIE_SOLVE <- TRUE DF <- data.frame("", "", 0, 0, stringsAsFactors = FALSE) only_num_df <- as.matrix(x[, c(3, 4)]) only_num_df <- unique(only_num_df) for (i in 1:nrow(only_num_df)) { ii <- only_num_df[i, ] subi <- subset(x, x[, 3] == ii[1] & x[, 4] == ii[2]) if (nrow(subi) == 1) { DF[nrow(DF) + 1, ] <- subi } else { unique1 <- uniqueN(subi[, 1]) unique2 <- uniqueN(subi[, 2]) if (!unique1 == 1 & !unique2 == 1) { for (j in 1:nrow(subi)) DF[nrow(DF) + 1, ] <- subi[j, ] TIE_SOLVE <- FALSE } if (unique1 == 1) { need_name <- subi[, 2] need_m <- zeroone[need_name, need_name] need_score <- rowSums(need_m) if (length(need_score) != length(unique(need_score))) TIE_SOLVE <- FALSE o_need <- order(need_score) subi <- subi[o_need, ] for (j in 1:nrow(subi)) DF[nrow(DF) + 1, ] <- subi[j, ] } if (unique2 == 1) { need_name <- subi[, 1] need_m <- zeroone[need_name, need_name] need_score <- rowSums(need_m) if (length(need_score) != length(unique(need_score))) TIE_SOLVE <- FALSE o_need <- order(need_score, decreasing = TRUE) subi <- subi[o_need, ] for (j in 1:nrow(subi)) DF[nrow(DF) + 1, ] <- subi[j, ] } } } DF <- DF[-1, ] colnames(DF) <- colnames(x) rownames(DF) <- NULL return(list(TIE_SOLVE, DF)) } sUmmAry_101 <- function(x, rname) { y <- matrix(0, nrow = nrow(x), ncol = 3) colnames(y) <- c(-1, 0, 1) rownames(y) <- rname for (i in 1:nrow(x)) { ib <- append(x[i, ], c(-1, 1)) y[i, ] <- as.numeric(table(ib)) - 1 # minus 1 from -1, 1, and the diag 0 } y } cdc2bInAry <- function(x) { nrc <- nrow(x) y <- matrix(0, nrow = nrc, ncol = nrc) colnames(y) <- colnames(x) rownames(y) <- rownames(x) for (i in 1:nrc) { for (j in 1:nrc) { if (i > j) { dif_ij <- x[i, j] - x[j, i] if (dif_ij > 0) { y[i, j] <- 1 y[j, i] <- -1 } if (dif_ij < 0) { y[i, j] <- -1 y[j, i] <- 1 } } } } y } #' @import gtools AlllInkstrEngth=function(x, candname, keep=FALSE){ nx=nrow(x) # expand.grid is too slow and memory-costing # allcombi=expand.grid(rep(list(1: nx), nx)) # checkinvalid=apply(allcombi, 1, FUN=function(x) if (anyDuplicated(x) != 0) FALSE else TRUE) # allcombi=allcombi[checkinvalid, ] # rownames(allcombi)=NULL # rm(checkinvalid) allcombi=gtools::permutations(nx, nx) dUAlsUm=function(i1, i2, datam) `[`(datam, i1, i2) SCORE <- rep(0, nrow(allcombi)) for (i in 1: (nx-1)){ for (j in 2: nx){ if (i < j){ SCORE=SCORE+mapply(FUN=dUAlsUm, allcombi[, i], allcombi[, j], MoreArgs=list(datam=x), SIMPLIFY=TRUE) } } } whichlink=which(SCORE == max(SCORE)) linkv=SCORE[whichlink] WINLINK=list() for (r in whichlink){ rr=as.numeric(allcombi[r, ]) WINLINK[[length(WINLINK)+1]]=candname[rr] } truewinner=unique(unlist(lapply(WINLINK, `[`, 1))) WINLINK=do.call(rbind, WINLINK) # must after truewinner if (keep==FALSE){ res=list(truewinner, WINLINK, linkv) } else { RANKLINK=cbind(allcombi, SCORE)[order(SCORE, decreasing=TRUE), ] colnames(RANKLINK)=c(1: (ncol(RANKLINK)-1), "score") rownames(RANKLINK)=NULL res=list(truewinner, WINLINK, linkv, RANKLINK) } res }
/scratch/gouwar.j/cran-all/cranData/votesys/R/UsEIncdc.R
#' Approval Method #' #' In approval method, each voter is required to mention #' one or more candidates, and the winner is the one #' who gets the top frequency. For this function, a ballot #' with candidates more than required and #' different scores is also valid. For a score matrix, the function will #' check the positions j, k...which have the #' lowest scores (in a \code{vote} object, #' the lower, the better) in the ith row. However, the function will #' first check the \code{approval_able} element of #' the \code{vote} object. If it is FALSE, the winner will be NULL. #' #' @param x an object of class \code{vote}. #' @param min_valid default is 1. If the number of valid entries of #' a ballot is less than this value, the ballot will not be used. #' @param n the number of candidates written down by a #' voter should not larger than this value. #' #' @return a list object. #' \itemize{ #' \item (1) \code{call} the function call. #' \item (2) \code{method} the counting method. #' \item (3) \code{candidate} candidate names. #' \item (4) \code{candidate_num} number of candidate. #' \item (5) \code{ballot_num} number of ballots in x. #' \item (6) \code{valid_ballot_num} number of ballots that are #' used to compute the result. #' \item (7) \code{winner} the winners, may be one, more than one or NULL. #' \item (8) \code{n} equal to the argument \code{n}. #' \item (9) \code{other_info} frequencies of candidates mentioned #' by voters. #' } #' #' @export #' @examples #' raw <- matrix(NA, nrow = 22, ncol = 5) #' for (i in 1: 20){ #' set.seed(i) #' raw[i, ] <- sample(c(1: 5, NA, NA, NA), 5) #' } #' raw[21, ] <- c(4, 5, 3, 1, 2) #' raw[22, ] <- c(3, 5, 1, 2, 4) #' vote <- create_vote(raw, xtype = 1) #' y <- approval_method(vote, n = 3) #' y <- approval_method(vote, n = 3, min_valid = 5) #' y <- approval_method(vote, n = 4, min_valid = 3) approval_method <- function(x, min_valid = 1, n) { method <- "approval" if (!class(x)[1] == "vote") stop("x must be a vote object.") do_ok <- if (x$approval_able == FALSE) FALSE else TRUE if (min_valid < 1) stop("Minimux number of min_valid is 1.") candidate <- x$candidate NBALLOT <- x$ballot_num candidate_num <- x$candidate_num if (n < 1 | n > candidate_num) stop("n should be >=1 and <= the number of candidates.") if (do_ok == TRUE){ should_del <- c() if (length(x$row_with_na) > 0) { get_na_ok <- which(x$num_non_na < min_valid) if (length(get_na_ok) > 0) should_del <- x$row_with_na[get_na_ok] } length_should_del <- length(should_del) VALID_BALLOT_NUM <- NBALLOT - length_should_del if (VALID_BALLOT_NUM == 0) stop("No ballot is OK.") x <- if (length_should_del > 0) x$ballot[-should_del, ] else x$ballot message("SELECTING") COUNT <- rep(0, candidate_num) for (i in 1:nrow(x)) { ii <- x[i, ] len_not_na <- length(ii[!is.na(ii)]) ii <- order(ii)[1:min(len_not_na, n)] COUNT[ii] <- COUNT[ii] + 1 } winner <- which(COUNT == max(COUNT)) winner <- candidate[winner] names(COUNT) <- candidate } message("COLLECTING RESULT") if (do_ok == TRUE){ over <- list(call = match.call(), method = method, candidate = candidate, candidate_num = candidate_num, ballot_num = NBALLOT, valid_ballot_num = VALID_BALLOT_NUM, winner = winner, n = n, other_info = list(count = COUNT)) } else { over <- list(call = match.call(), method = method, candidate = candidate, candidate_num = candidate_num, ballot_num = NBALLOT, valid_ballot_num = NULL, winner = NULL, n = n, other_info = NULL) message("The winner is NULL, for approval can only be used when x$approval_able is TRUE.\n") message("You can ckeck x$row_with_dup to delete rows with duplicated values.\n") } message("DONE") return(over) }
/scratch/gouwar.j/cran-all/cranData/votesys/R/approval_method.R
#' Convert Incomplete ranking/rating matrix into full matrix #' #' This function deals with incomplete ranking and rating matrix #' (e. g., created by \code{create_vote} and stored in \code{$ballot}), #' so as to convert it into full ranking and rating. #' In each row of the score matrix, the #' smallest value represents the most preferred #' and the biggest value represents the most hated. #' For the methods used by this function, see Details. #' See Examples for how to modify an object of class #' vote created with incomplete data. #' #' Three methods are used and you should choose #' according to your need. #' \itemize{ #' \item (1) "valid": the default method. For the vector #' \code{c(3, 1, 2, 2, NA, NA)}, as there should be 6 values #' but only 4 are given, 4 is the valid number, and the NAs #' will be converted to 4. However, if the argument #' \code{plus} is a value other than 0, than NAs will be #' equal to the valid number plus that value. For example, #' if \code{plus = 10}, the NAs will be 14 (4 + 10). #' \item (2) "max": the maximum value in each row plus the value #' given by \code{plus}. So for \code{c(3, 1, 2, 2, NA, NA)}, #' and \code{plus = 0}, NAs will be 3 (3 + 0). #' \item (3) "len": In the case of topKlist, #' interviewees may, for example, choose 4 or 5 items #' from a 20-item list. When the method is "len", use \code{n} to #' indicate the total number of items or any other number. #' The default value of \code{n} is \code{ncol(x)}, #' which is equivalent to the way \code{create_vote} used to #' convert NAs so as to #' calculate the Condorcet matrix. #' } #' #' @param x the score matrix, should be a matrix, data.frame, #' or data.table. #' @param method see Details, default is "valid". #' @param plus see Details, default is 0. #' @param n see Details, default is 0. #' #' @return Always a matrix. NAs are converted to numbers. #' However, if all entries in a row of the input data are NAs, #' then that row will NOT be modified. NOTE: the order of #' the returned matrix (the 1st row, the 2nd row, the 3rd row, etc) #' is DIFFERENT from the input data. #' #' @export #' @examples #' raw <- list2ballot(string = c("1: a, b, c", "2: b, c", "3: a, b")) #' vote <- create_vote(raw, xtype = 3, candidate = c("a", "b", "c")) #' ballot <- as_complete(vote$ballot, method = "max", plus = 5) #' ballot <- as_complete(vote$ballot, method = "len", n = 10) #' # Now re-create the vote object #' vote <- create_vote(ballot, xtype = 1) #' #' m <- matrix(c( #' 1, 2, 3, NA, NA, NA, #' 1, 1.1, 2.2, 8.8, NA, NA, #' 1, 1.1, 2.2, 8.8, NA, NA, #' 1, 1.1, 2.2, 8.8, NA, NA, #' 1, 1.1, 2.2, 8.8, NA, NA, #' NA, NA, NA, NA, NA, NA, #' 3, 2, NA, NA, NA, NA, #' 3, 2, NA, NA,NA,NA, #' 1, 2, 3, 4, 5, 6), ncol = 6, byrow = TRUE) #' colnames(m) <- LETTERS[1: 6] #' y <- as_complete(m, method = "valid", plus = 30) as_complete <- function(x, method = c("valid", "max", "len"), plus = 0, n=NULL){ classx <- class(x)[1] if (! classx %in% c("matrix", "data.table", "data.frame")) stop("x must be of class matrix, data.frame or data.table.") xnc <- ncol(x) nmx <- colnames(x) method <- method[1] if (! method %in% c("valid", "max", "len")) stop("method must be one of valid, max or len.") plus <- plus[1] if (! is.numeric(plus)) stop ("plus must be numeric.") LONG <- if (is.null(n)) xnc else n rownames(x) <- NULL if (classx != "data.table") x <- data.table::data.table(x) R <- data.table::frankv(x, ties.method = "dense") RT <- table(R) tlen <- length(RT) ttn <- as.numeric(names(RT)) RT <- as.numeric(RT) xx <- matrix(NA, nrow = tlen, ncol = ncol(x)) for (i in 1:tlen) { instance <- match(ttn[i], R) xx[i, ] <- as.numeric(x[instance, ]) # must add as.numeric } rm(x) InnEr_vAlId=function(v, ME, PL, vlen, long){ posna=which(is.na(v)) if (length(posna) %in% c(0, vlen)){ return(v) } else { if (ME=="len"){ v[posna]=long } else if(ME=="valid"){ v[posna]=vlen-length(posna)+PL } else if (ME=="max"){ v[posna]=max(v, na.rm=TRUE)+PL } return(v) } } y=t(apply(xx, 1, InnEr_vAlId, ME=method, PL=plus, vlen=xnc, long=LONG)) y=y[rep(1: nrow(y), RT), ] colnames(y)=nmx y }
/scratch/gouwar.j/cran-all/cranData/votesys/R/as_complete.R
chEck_stAndArd_mAtrIx <- function(x, len = ncol(x), numeric_na = NULL) { ROWHAVENA <- c() NOTNANUM <- c() ROWHAVEDUP <- c() for (i in 1:nrow(x)) { ii <- as.numeric(x[i, ]) pos_not_in <- which(!ii %in% numeric_na) len_notna <- length(pos_not_in) if (len_notna < len) { ROWHAVENA <- append(ROWHAVENA, i) NOTNANUM <- append(NOTNANUM, len_notna) } ii <- ii[pos_not_in] length_ok <- length(ii) if (length_ok > 0) { if (anyDuplicated(ii) != 0) ROWHAVEDUP <- append(ROWHAVEDUP, i) } } check_result <- list(ROWHAVENA, NOTNANUM, ROWHAVEDUP) check_result } fUll_dIgIt <- function(n, p = NULL) { nchar_nc <- nchar(as.character(n)) num <- as.character(1:n) nchar_num <- nchar(num) nchar_dif <- nchar_nc - nchar_num y <- c() for (i in 1:n) y[i] <- paste(rep(0, nchar_dif[i]), collapse = "") y <- paste(y, num, sep = "") if (!is.null(p)) y <- paste(p, y, sep = "") y } rOw2cdc <- function(x) { len <- ncol(x) xcn <- colnames(x) CDC <- matrix(0, nrow = len, ncol = len) colnames(CDC) <- xcn rownames(CDC) <- xcn CDCNA <- CDC DIF <- CDC DIFNA <- CDC if (class(x)[1] != "data.table") x <- data.table::data.table(x) R <- data.table::frankv(x, ties.method = "dense") RT <- table(R) tlen <- length(RT) ttn <- as.numeric(names(RT)) RT <- as.numeric(RT) xx <- matrix(NA, nrow = tlen, ncol = ncol(x)) for (i in 1:tlen) { instance <- match(ttn[i], R) xx[i, ] <- as.numeric(x[instance, ]) # must add as.numeric } rm(x) for (r in 1:nrow(xx)) { rr <- as.numeric(xx[r, ]) r_uni <- RT[r] rr_which_na <- which(is.na(rr)) num_na <- length(rr_which_na) if (num_na == 0) { # if there is no NA for (i in 1:len) { ii <- rr[i] for (j in 1:len) { jj <- rr[j] if (ii < jj) { iimjj <- (jj - ii) * r_uni CDC[i, j] <- CDC[i, j] + r_uni CDCNA[i, j] <- CDCNA[i, j] + r_uni DIF[i, j] <- DIF[i, j] + iimjj DIFNA[i, j] <- DIFNA[i, j] + iimjj } } } } else if (num_na > 0 & num_na < len) { rr[rr_which_na] <- len for (i in 1:len) { ii <- rr[i] for (j in 1:len) { jj <- rr[j] if (ii < jj) { iimjj <- (jj - ii) * r_uni CDCNA[i, j] <- CDCNA[i, j] + r_uni DIFNA[i, j] <- DIFNA[i, j] + iimjj } } } } } cdclist <- list(CDC, CDCNA, DIF, DIFNA) cdclist }
/scratch/gouwar.j/cran-all/cranData/votesys/R/bAllOt_clEAn.R
#' Borda Count Method #' #' Both ordinary Borda method and modified Borda method are #' available. In an ordinary Borda system, voters are required to #' assign score values to candidates. See Details. #' #' Suppose there are 5 #' candidates. A voter's 1st choice gets 1 point, the 2nd choice #' gets 2 points... Candidate with the smallest total score wins. #' The function does not require voters to assign scores to all #' candidates, for NAs are automatically assigned the #' highest (worst) score. Duplicated values (two #' or more candidates share #' the same score) are also allowed (note: NAs and ties may #' not be allowed in real ballots). #' #' In modified Borda, #' the rule changes. Suppose there are 5 candidates. A voter #' writes down 5 candidates and his 1st choice gets 5 points. #' The one who gets the largest total score wins. However, #' if the voter only write down 2 names, then, his 1st choice #' gets only 2 points rather than 5 points. Thus the modified #' Borda encourages voters to write down more names. #' Besides, in modified Borda, only the ranks of true scores, #' rather than the true scores themselves, are used. #' If the raw data is a list each ballot of which #' contains candidate names, scores can also be extracted, that #' is, the 1st position is the 1st choice which gets 1 point, the #' 2nd position, 2 points, and so on. #' #' @param x an object of class \code{vote}. #' @param allow_dup whether ballots with duplicated score values #' are taken into account. Default is TRUE. #' @param min_valid default is 1. If the number of valid entries of #' a ballot is less than this value, the ballot will not be used. #' @param modified if the modified Borda is to be used. Default #' is FALSE. #' #' @return a list object. #' \itemize{ #' \item (1) \code{call} the function call. #' \item (2) \code{method} the counting method. #' \item (3) \code{candidate} candidate names. #' \item (4) \code{candidate_num} number of candidate. #' \item (5) \code{ballot_num} number of ballots in x. #' \item (6) \code{valid_ballot_num} number of ballots that are #' used to compute the result. #' \item (7) \code{winner} the winners. #' \item (8) \code{modified} whether the modified Borda is used. #' \item (9) \code{other_info} a list with 2 elements, if \code{modified} #' is FALSE, then \code{count_min} records the total #' scores, \code{count_max} #' is NULL; if \code{modified} is TRUE, the vice versa. #' } #' #' @export #' @examples #' raw <- c( #' rep(c('m', 'n', 'c', 'k'), 42), #' rep(c('n', 'c', 'k', 'm'), 26), #' rep(c('c', 'k', 'n', 'm'), 15), #' rep(c('k', 'c', 'n', 'm'), 17) #' ) #' raw <- matrix(raw, ncol = 4, byrow = TRUE) #' vote <- create_vote(raw, xtype = 2, candidate = c('m', 'n', 'c', 'k')) #' y <- borda_method(vote) #' #' raw <- list(c('a', 'e', 'c', 'd', 'b'), c('b', 'a', 'e'), #' c('c', 'd', 'b'), c('d', 'a', 'e') #' ) #' vote <- create_vote(raw, xtype = 3, candidate = c('a', 'b', 'c', 'd', 'e')) #' y <- borda_method(vote, modified = TRUE) borda_method <- function(x, allow_dup = TRUE, min_valid = 1, modified = FALSE) { method <- "borda" if (!class(x)[1] == "vote") stop("x must be a vote object.") if (min_valid < 1) stop("Minimux number of min_valid is 1.") stopifnot(allow_dup %in% c(TRUE, FALSE)) stopifnot(modified %in% c(TRUE, FALSE)) candidate <- x$candidate NBALLOT <- x$ballot_num candidate_num <- x$candidate_num if (modified == TRUE & allow_dup == TRUE) { allow_dup <- FALSE message("When modified is TRUE, allow_dup is automatically set to FALSE, ignoring value given by user.") } should_del <- c() if (allow_dup == FALSE & length(x$row_with_dup) != 0) should_del <- append(should_del, x$row_with_dup) if (length(x$row_with_na) > 0) { get_na_ok <- which(x$num_non_na < min_valid) if (length(get_na_ok) > 0) should_del <- append(should_del, x$row_with_na[get_na_ok]) } should_del <- unique(should_del) length_should_del <- length(should_del) VALID_BALLOT_NUM <- NBALLOT - length_should_del if (VALID_BALLOT_NUM == 0) stop("No ballot is OK.") x <- if (length_should_del > 0) x$ballot[-should_del, ] else x$ballot message("SELECTING") if (modified == FALSE) { x[is.na(x)] <- candidate_num B <- colSums(x) # min, better winner <- which(B == min(B)) } if (modified == TRUE) { maxplus <- candidate_num + 1 for (i in 1:nrow(x)) { ii <- maxplus - x[i, ] x[i, ] <- data.table::frank(ii, na.last = "keep") } B <- colSums(x, na.rm = TRUE) winner <- which(B == max(B)) } winner <- candidate[winner] message("COLLECTING RESULT") over <- list(call = match.call(), method = method, candidate = candidate, candidate_num = candidate_num, ballot_num = NBALLOT, valid_ballot_num = VALID_BALLOT_NUM, winner = winner, modified = modified, other_info = list(count_min = NULL, count_max = NULL)) if (modified == FALSE) { over$other_info$count_min <- B message("Winner is with the lowest score, for modified is FALSE.") } else { over$other_info$count_max <- B message("Winner is with the largest score, for modified is TRUE.") } message("DONE") return(over) }
/scratch/gouwar.j/cran-all/cranData/votesys/R/borda_method.R
#' Copeland Method #' #' Candidates enter into pairwise comparison. #' if the number of voters who prefer a is larger than the #' number of voters who prefer b, then a wins b, a gets 1 #' point, b gets -1 point. If the numbers are equal, then both #' of them gets 0 point. #' Then, sum up each one's comparison points. #' For example, a wins 3 times, loses 1 time, has equal #' votes with 2 candidate, his score is #' 3 * 1 + (-1) * 1 + 0 * 2 = 2. #' The one gets the most points wins. Essentially, this #' is a way to solve ties in ordinary Condorcet method. #' However, there may be 2 or more winners. The other #' type of Copeland method is to count only the times of wins, #' that is, the loser in pairwise comparison gets 0 point #' rather than -1 point. #' #' @param x it accepts the following types of input: #' 1st, it can be an object of class \code{vote}. #' 2nd, it can be a user-given Condorcet matrix, #' 3rd, it can be a result of another Condorcet method, #' which is of class \code{condorcet}. #' @param allow_dup whether ballots with duplicated score values #' are taken into account. Default is TRUE. #' @param min_valid default is 1. If the number of valid entries of #' a ballot is less than this value, it will not be used. #' @param lose the point the pairwise loser gets, should be #' -1 (default) or 0. #' #' @return a \code{condorcet} object, which is essentially #' a list. #' \itemize{ #' \item (1) \code{call} the function call. #' \item (2) \code{method} the counting method. #' \item (3) \code{candidate} candidate names. #' \item (4) \code{candidate_num} number of candidate. #' \item (5) \code{ballot_num} number of ballots in \code{x}. When #' x is not a \code{vote} object, it may be NULL. #' \item (6) \code{valid_ballot_num} number of ballots that are #' actually used to compute the result. When #' x is not a \code{vote} object, it may be NULL. #' \item (7) \code{winner} the winners. #' \item (8) \code{input_object} the class of \code{x}. #' \item (9) \code{cdc} the Condorcet matrix which is actually used. #' \item (10) \code{dif} the score difference matrix. When #' x is not a \code{vote} object, it may be NULL. #' \item (11) \code{binary} win and loss recorded with 1 (win), #' 0 (equal) and -1 (loss). #' \item (12) \code{summary_m} times of win (1), equal (0) #' and loss (-1). #' \item (13) \code{other_info} a list with 2 elements, the 1st is the point #' the loser gets, it is equal to \code{lose}. The 2nd contains the scores. #' } #' #' @references #' \itemize{ #' \item Merlin, V. & Saari, D. 1996. The Copeland #' method: I.: Relationships and the dictionary. #' Economic Theory, 8(1), 51-76. #' } #' #' @export #' @examples #' raw <- c( #' rep(c('m', 'n', 'c', 'k'), 42), rep(c('n', 'c', 'k', 'm'), 26), #' rep(c('c', 'k', 'n', 'm'), 15), rep(c('k', 'c', 'n', 'm'), 17) #' ) #' raw <- matrix(raw, ncol = 4, byrow = TRUE) #' vote <- create_vote(raw, xtype = 2, candidate = c('m', 'n', 'k', 'c')) #' win1 <- cdc_simple(vote) #' win2 <- cdc_copeland(vote) # winner is n #' win2 <- cdc_copeland(win1$cdc) #' win3 <- cdc_copeland(win2, lose = 0) cdc_copeland <- function(x, allow_dup = TRUE, min_valid = 1, lose = -1) { method <- "copeland" if (!class(x)[1] %in% c("vote", "matrix", "condorcet")) stop("x must be a vote, condorcet or matrix object.") if (min_valid < 1) stop("Minimux number of min_valid is 1.") stopifnot(allow_dup %in% c(TRUE, FALSE)) stopifnot(lose %in% c(0, -1)) CORE_M <- fInd_cdc_mAtrIx(x, dup_ok = allow_dup, available = min_valid) message("EXTRACTING INFO") class1 <- CORE_M$input_object candidate <- CORE_M$candidate candidate_num <- CORE_M$candidate_num ballot_num <- CORE_M$ballot_num valid_ballot_num <- CORE_M$valid_ballot_num cdc_matrix <- CORE_M$cdc # find cdc matrix dif_matrix <- CORE_M$dif binary_m <- CORE_M$binary # find binary message("SELECTING") summary_m <- sUmmAry_101(x = binary_m, rname = candidate) if (lose == -1){ net_m <- t(apply(summary_m, 1, `*`, c(-1, 0, 1))) row_sumup <- rowSums(net_m) } else { to_zero <- binary_m to_zero[to_zero == -1] <- 0 row_sumup <- rowSums(to_zero) } winner <- which(row_sumup == max(row_sumup)) winner <- candidate[winner] message("COLLECTING RESULT") over <- list(call = match.call(), method = method, candidate = candidate, candidate_num = candidate_num, ballot_num = ballot_num, valid_ballot_num = valid_ballot_num, winner = winner, input_object = class1, cdc = cdc_matrix, dif = dif_matrix, binary = binary_m, summary_m = summary_m, other_info = list(lose = lose, copeland_score = row_sumup)) class(over) <- "condorcet" message("DONE") if (over$candidate_num < 5 & lose == -1) message("It is better to have at least 5 candidates when lose = -1.") return(over) }
/scratch/gouwar.j/cran-all/cranData/votesys/R/cdc_copeland.R
#' Dodgson Method #' #' The original Dodgson method checks the number of #' votes each candidate has to rob from other candidates; #' the winner is with the smallest number. However, the #' function \code{cdc_dodgson} uses two alternative methods #' rather than the original Dodgson method. The two methods #' are Tideman score method and Dodgson Quick method. #' See Details. #' #' Suppose the candidates are A, B, C and D. If A wins B in pairwise #' comparison or has equal votes with B, then add 0 to A. If C wins A, #' then add to A adv(C, A), that is, the number of voters that prefer #' C than A, minus the number of voters that prefer A than A. #' Again, if D wins A, then add to A that number. Then, we sum up #' the points belong to A. We do the same thing to B, C and D. The one #' gets the least points is the winner. This is what we do in Tideman #' score method. In Dodgson Quick method, we first compute the number #' of votes, then divide it by 2 and get the ceiling, and sum #' all of them up. #' #' @param x it accepts the following types of input: #' 1st, it can be an object of class \code{vote}. #' 2nd, it can be a user-given Condorcet matrix, #' 3rd, it can be a result of another Condorcet method, #' which is of class \code{condorcet}. #' @param allow_dup whether ballots with duplicated score values #' are taken into account. Default is TRUE. #' @param min_valid default is 1. If the number of valid entries of #' a ballot is less than this value, it will not be used. #' @param dq_t the alternative Dodgson methods to be used. #' Default is "dq", for Dodgson Quick method; it can also be "t", #' Tideman score method. #' #' @return a \code{condorcet} object, which is essentially #' a list. #' \itemize{ #' \item (1) \code{call} the function call. #' \item (2) \code{method} the counting method. #' \item (3) \code{candidate} candidate names. #' \item (4) \code{candidate_num} number of candidate. #' \item (5) \code{ballot_num} number of ballots in x. When #' x is not a \code{vote} object, it may be NULL. #' \item (6) \code{valid_ballot_num} number of ballots that are #' actually used to compute the result. When #' x is not a \code{vote} object, it may be NULL. #' \item (7) \code{winner} the winners. #' \item (8) \code{input_object} the class of x. #' \item (9) \code{cdc} the Condorcet matrix which is actually used. #' \item (10) \code{dif} the score difference matrix. When #' x is not a \code{vote} object, it may be NULL. #' \item (11) \code{binary} win and loss recorded with 1 (win), #' 0 (equal) and -1 (loss). #' \item (12) \code{summary_m} times of win (1), equal (0) #' and loss (-1). #' \item (13) \code{other_info} a list with four elements. The 1st #' indicates the method used to compute score. The 2nd is the score #' for pairwise comparison #' (number of votes one has to rob). The 3rd is Tideman score #' summary (the smaller the better). #' The 4th is Dodgson Quick summary (the smaller the better). #' } #' #' @references #' \itemize{ #' \item McCabe-Dansted, J. & Slinko, A. 2008. Approximability of Dodgson's Rule. Social Choice and Welfare, Feb, 1-26. #' } #' #' @export #' @examples #' raw <- list2ballot( #' x = list( #' c('A', 'B', 'C', 'D', 'E', 'F'), #' c('F', 'A', 'B', 'C', 'D', 'E'), #' c('E', 'D', 'C', 'B', 'F', 'A'), #' c('B', 'A', 'C', 'D', 'E', 'F'), #' c('F', 'E', 'D', 'C', 'B', 'A'), #' c('F', 'B', 'A', 'C', 'D', 'E'), #' c('E', 'D', 'C', 'A', 'F', 'B'), #' c('E', 'B', 'A', 'C', 'D', 'F'), #' c('F', 'D', 'C', 'A', 'E', 'B'), #' c('D', 'B', 'A', 'C', 'E', 'F'), #' c('F', 'E', 'C', 'A', 'D', 'B') #' ), #' n = c(19, 12, 12, 9, 9, 10, 10 , 10 , 10, 10, 10) #' ) #' vote <- create_vote(raw, xtype = 3, candidate = c('A', 'B', 'C', 'D', 'E', 'F')) #' win1 <- cdc_simple(vote) # no winner #' win2 <- cdc_dodgson(vote, dq_t = "dq") # A #' win2 <- cdc_dodgson(win1, dq_t = "dq") # A #' win3 <- cdc_dodgson(vote, dq_t = "t") # B #' win3 <- cdc_dodgson(win2, dq_t = "t") # B cdc_dodgson <- function(x, allow_dup = TRUE, min_valid = 1, dq_t = "dq") { method <- "dodgson" if (!class(x)[1] %in% c("vote", "matrix", "condorcet")) stop("x must be a vote, condorcet or matrix object.") if (min_valid < 1) stop("Minimux number of min_valid is 1.") stopifnot(allow_dup %in% c(TRUE, FALSE)) if (!dq_t[1] %in% c("dq", "t")) stop("dq_t must be dq or t.") CORE_M <- fInd_cdc_mAtrIx(x, dup_ok = allow_dup, available = min_valid) message("EXTRACTING INFO") class1 <- CORE_M$input_object candidate <- CORE_M$candidate candidate_num <- CORE_M$candidate_num ballot_num <- CORE_M$ballot_num valid_ballot_num <- CORE_M$valid_ballot_num cdc_matrix <- CORE_M$cdc dif_matrix <- CORE_M$dif binary_m <- CORE_M$binary message("SELECTING") summary_m <- sUmmAry_101(x = binary_m, rname = candidate) nrc <- nrow(cdc_matrix) swap_m <- matrix(0, nrow = nrc, ncol = nrc) rownames(swap_m) <- rownames(cdc_matrix) colnames(swap_m) <- colnames(cdc_matrix) for (i in 1:nrc) { for (j in 1:nrc) { if (i != j) { ij <- cdc_matrix[i, j] ji <- cdc_matrix[j, i] ijdif <- ij - ji # this is adv(a, b) if (ijdif > 0) swap_m[i, j] <- 0 if (ijdif == 0) swap_m[i, j] <- 0 if (ijdif < 0) swap_m[i, j] <- -ijdif } } } t_row_sumup <- rowSums(swap_m) dq_row_sumup <- apply(swap_m, 1, FUN = function(x) sum(ceiling(x/2))) if (dq_t == "t") { winner <- which(t_row_sumup == min(t_row_sumup)) } else if (dq_t == "dq") { winner <- which(dq_row_sumup == min(dq_row_sumup)) } winner <- candidate[winner] message("COLLECTING RESULT") over <- list(call = match.call(), method = method, candidate = candidate, candidate_num = candidate_num, ballot_num = ballot_num, valid_ballot_num = valid_ballot_num, winner = winner, input_object = class1, cdc = cdc_matrix, dif = dif_matrix, binary = binary_m, summary_m = summary_m, other_info = list(dq_t = dq_t, swap = swap_m, tideman = t_row_sumup, dodgson_quick = dq_row_sumup)) class(over) <- "condorcet" message("DONE") return(over) }
/scratch/gouwar.j/cran-all/cranData/votesys/R/cdc_dodgson.R
#' Kemeny-Young Method #' #' Kemeny-Young method first lists all the permutations of #' candidates, that is, all possible orders, or possible ordered #' links. Then, it computes the sums of strength of these links. #' The top link is the one with the highest strength score, and #' the winner is the first one in this link. Currently, the maximum #' candidate number is 8 for speed and memory reasons. #' #' @param x it accepts the following types of input: #' 1st, it can be an object of class \code{vote}. #' 2nd, it can be a user-given Condorcet matrix, #' 3rd, it can be a result of another Condorcet method, #' which is of class \code{condorcet}. #' @param allow_dup whether ballots with duplicated score values #' are taken into account. Default is TRUE. #' @param min_valid default is 1. If the number of valid entries of #' a ballot is less than this value, it will not be used. #' @param margin if it is FALSE (default), the values in Condorcet #' matrix are used, that is: if A vs. B is 30, B vs. A is 18, then 30 and 18 are #' used to calculate link strength; if it is TRUE, then 30 - 18 = 12 and #' -12 are used. #' @param keep_all_link if TRUE, the result will store #' all the links and their strength. However, it is quite memory-costing, #' so the default is FALSE. #' #' @return a \code{condorcet} object, which is essentially #' a list. #' \itemize{ #' \item (1) \code{call} the function call. #' \item (2) \code{method} the counting method. #' \item (3) \code{candidate} candidate names. #' \item (4) \code{candidate_num} number of candidate. #' \item (5) \code{ballot_num} number of ballots in \code{x}. When #' x is not a \code{vote} object, it may be NULL. #' \item (6) \code{valid_ballot_num} number of ballots that are #' actually used to compute the result. When #' x is not a \code{vote} object, it may be NULL. #' \item (7) \code{winner} the winner. #' \item (8) \code{input_object} the class of \code{x}. #' \item (9) \code{cdc} the Condorcet matrix which is actually used. #' \item (10) \code{dif} the score difference matrix. When #' x is not a \code{vote} object, it may be NULL. #' \item (11) \code{binary} win and loss recorded with 1 (win), #' 0 (equal) and -1 (loss). #' \item (12) \code{summary_m} times of win (1), equal (0) #' and loss (-1). #' \item (13) \code{other_info} a list with 3 elements. \code{win_link} #' is the link with the highest strength. Note: it is a matrix, maybe with 2 #' or more rows. \code{win_link_value} is the strength of the link. #' \code{all_link} is NULL when \code{keep_all_link} is FALSE. if TRUE, #' it stores all the links and scores sorted by scores in decreasing order (this #' costs much memory on your computer). #' } #' #' @references #' \itemize{ #' \item Young, H. & Levenglick, A. 1978. #' A consistent extension of Condorcet's election principle. #' Society for Industrial and Applied Mathematics, 35(2), 285-300. #' } #' #' @export #' @examples #' m <- matrix(c(0, 58, 58, 58, 42, 0, 32, 32, 42, 68, 0, 17, 42, 68, 83, 0), nr = 4) #' colnames(m) <- c('m', 'n', 'c', 'k') #' rownames(m) <- c('m', 'n', 'c', 'k') #' y <- cdc_kemenyyoung(m, keep_all_link = TRUE) # winner is n cdc_kemenyyoung=function(x, allow_dup = TRUE, min_valid = 1, margin=FALSE, keep_all_link=FALSE){ method <- "kemenyyoung" if (!class(x)[1] %in% c("vote", "matrix", "condorcet")) stop("x must be a vote, condorcet or matrix object.") if (min_valid < 1) stop("Minimux number of min_valid is 1.") # each vote has at least one valid value\t stopifnot(allow_dup %in% c(TRUE, FALSE)) stopifnot(margin %in% c(TRUE, FALSE)) CORE_M <- fInd_cdc_mAtrIx(x, dup_ok = allow_dup, available = min_valid) message("EXTRACTING INFO") class1 <- CORE_M$input_object candidate <- CORE_M$candidate candidate_num <- CORE_M$candidate_num ballot_num <- CORE_M$ballot_num valid_ballot_num <- CORE_M$valid_ballot_num cdc_matrix <- CORE_M$cdc dif_matrix <- CORE_M$dif binary_m <- CORE_M$binary if (candidate_num > 8){ message("You have ", candidate_num, " candidates.") stop("In Kemeny Young method, currently the maximum candidate number is 8.") } rm(x) summary_m <- sUmmAry_101(x = binary_m, rname = candidate) used_matrix=cdc_matrix if (margin==TRUE){ used_matrix=matrix(0, nrow=candidate_num, ncol=candidate_num) for (i in 1: candidate_num){ for (j in 1: candidate_num){ if (i > j){ ii_jj=cdc_matrix[i, j]-cdc_matrix[j, i] used_matrix[i, j]=ii_jj used_matrix[j, i]=-ii_jj } } } } message("SELECTING") if (keep_all_link==FALSE){ LINKS=AlllInkstrEngth(used_matrix, candname=candidate, keep=FALSE) message("COLLECTING RESULT") over <- list(call = match.call(), method = method, candidate = candidate, candidate_num = candidate_num, ballot_num = ballot_num, valid_ballot_num = valid_ballot_num, winner = LINKS[[1]], input_object = class1, cdc = cdc_matrix, dif = dif_matrix, binary = binary_m, summary_m = summary_m, other_info = list(win_link=LINKS[[2]], win_link_value=LINKS[[3]], all_link=NULL)) } else { LINKS=AlllInkstrEngth(used_matrix, candname=candidate, keep=TRUE) message("COLLECTING RESULT") over <- list(call = match.call(), method = method, candidate = candidate, candidate_num = candidate_num, ballot_num = ballot_num, valid_ballot_num = valid_ballot_num, winner = LINKS[[1]], input_object = class1, cdc = cdc_matrix, dif = dif_matrix, binary = binary_m, summary_m = summary_m, other_info = list(win_link=LINKS[[2]], win_link_value=LINKS[[3]], all_link=LINKS[[4]])) } class(over) <- "condorcet" message("DONE") return(over) }
/scratch/gouwar.j/cran-all/cranData/votesys/R/cdc_kemenyyoung.R
#' Minmax Method #' #' Minmax method (also known as Simpson-Kramer method, #' successive reversal method) #' means three different methods. #' The first is winning votes method. In pairwise comparison, #' if a wins b, a gets 0 point, the number of points for b is the #' number of voters who prefer a than b. #' The second method is to use margins. In pairwise comparison, #' a gets b - a points and b gets a - b points. #' The third method is pairwise opposition method. The number #' of points for a is the number of voters who prefer b than a; the #' number of points for b is the number of voters who prefer a #' than b. #' Although the point-assigning methods are different for the #' above three methods, they nonetheless do the same thing: #' to check to what extent one candidate is defeated by others. #' So the summarizing method is the same: for each candidate, #' we extract the maximum target points, and the one with the #' minimum points wins. #' #' @param x it accepts the following types of input: #' 1st, it can be an object of class \code{vote}. #' 2nd, it can be a user-given Condorcet matrix, #' 3rd, it can be a result of another Condorcet method, #' which is of class \code{condorcet}. #' @param allow_dup whether ballots with duplicated score values #' are taken into account. Default is TRUE. #' @param min_valid default is 1. If the number of valid entries of #' a ballot is less than this value, it will not be used. #' @param variant should be 1, 2 or 3. 1 (default) for winning votes #' method, 2 for margins method, 3 for pairwise comparison method. #' #' @return a \code{condorcet} object, which is essentially #' a list. #' \itemize{ #' \item (1) \code{call} the function call. #' \item (2) \code{method} the counting method. #' \item (3) \code{candidate} candidate names. #' \item (4) \code{candidate_num} number of candidate. #' \item (5) \code{ballot_num} number of ballots in x. When #' x is not a \code{vote} object, it may be NULL. #' \item (6) \code{valid_ballot_num} number of ballots that are #' actually used to compute the result. When #' x is not a \code{vote} object, it may be NULL. #' \item (7) \code{winner} the winners. #' \item (8) \code{input_object} the class of x. #' \item (9) \code{cdc} the Condorcet matrix which is actually used. #' \item (10) \code{dif} the score difference matrix. When #' x is not a \code{vote} object, it may be NULL. #' \item (11) \code{binary} win and loss recorded with 1 (win), #' 0 (equal) and -1 (loss). #' \item (12) \code{summary_m} times of win (1), equal (0) #' and loss (-1). #' \item (13) \code{other_info} a list of 4 elements. The 1st is #' the method, which is equal to \code{variant}. The 2nd is the #' winning votes matrix. The 3rd is the margins matrix. The 4th #' is the pairwise comparison matrix. #' } #' #' @references #' \itemize{ #' \item https://en.wikipedia.org/wiki/Minimax_Condorcet_method #' } #' #' @export #' @examples #' raw <- c( #' rep(c('m', 'n', 'c', 'k'), 42), rep(c('n', 'c', 'k', 'm'), 26), #' rep(c('c', 'k', 'n', 'm'), 15), rep(c('k', 'c', 'n', 'm'), 17) #' ) #' raw <- matrix(raw, ncol = 4, byrow = TRUE) #' vote <- create_vote(raw, xtype = 2, candidate = c('m', 'n', 'k', 'c')) #' win1 <- cdc_simple(vote) #' win2 <- cdc_minmax(vote) # winner is n #' win3 <- cdc_minmax(win1, variant = 2) #' win4 <- cdc_minmax(win3$cdc, variant = 3) cdc_minmax <- function(x, allow_dup = TRUE, min_valid = 1, variant = 1) { method <- "minmax" if (!class(x)[1] %in% c("vote", "matrix", "condorcet")) stop("x must be a vote, condorcet or matrix object.") if (min_valid < 1) stop("Minimux number of min_valid is 1.") stopifnot(allow_dup %in% c(TRUE, FALSE)) if (!variant[1] %in% c(1, 2, 3)) stop("variant must be 1, 2 or 3.") CORE_M <- fInd_cdc_mAtrIx(x, dup_ok = allow_dup, available = min_valid) message("EXTRACTING INFO") class1 <- CORE_M$input_object candidate <- CORE_M$candidate candidate_num <- CORE_M$candidate_num ballot_num <- CORE_M$ballot_num valid_ballot_num <- CORE_M$valid_ballot_num cdc_matrix <- CORE_M$cdc dif_matrix <- CORE_M$dif binary_m <- CORE_M$binary message("SELECTING") summary_m <- sUmmAry_101(x = binary_m, rname = candidate) nrc <- nrow(cdc_matrix) WV <- matrix(0, nrow = nrc, ncol = nrc) # pairwise defeat (winning votes) rownames(WV) <- rownames(cdc_matrix) colnames(WV) <- colnames(cdc_matrix) MA <- WV # worst pairwise defeat (margins) PO <- cdc_matrix # worst pairwise opposition for (i in 1:nrc) { for (j in 1:nrc) { if (i > j) { ij <- cdc_matrix[i, j] ji <- cdc_matrix[j, i] ijdif <- ij - ji if (ijdif > 0) { WV[i, j] <- 0 WV[j, i] <- cdc_matrix[i, j] } if (ijdif < 0) { WV[i, j] <- cdc_matrix[j, i] WV[j, i] <- 0 } if (ijdif == 0) { WV[i, j] <- 0 WV[j, i] <- 0 } MA[i, j] <- -ijdif MA[j, i] <- ijdif PO[i, j] <- cdc_matrix[j, i] PO[j, i] <- cdc_matrix[i, j] } } } if (variant == 1) { row_max <- apply(WV, 1, max) winner <- which(row_max == min(row_max)) } if (variant == 2) { row_max <- apply(MA, 1, max) winner <- which(row_max == min(row_max)) } if (variant == 3) { row_max <- apply(PO, 1, max) winner <- which(row_max == min(row_max)) } winner <- candidate[winner] message("COLLECTING RESULT") over <- list(call = match.call(), method = method, candidate = candidate, candidate_num = candidate_num, ballot_num = ballot_num, valid_ballot_num = valid_ballot_num, winner = winner, input_object = class1, cdc = cdc_matrix, dif = dif_matrix, binary = binary_m, summary_m = summary_m, other_info = list(variant = variant, winning_votes = WV, margins = MA, pairwise_opposition = PO)) class(over) <- "condorcet" message("DONE") return(over) }
/scratch/gouwar.j/cran-all/cranData/votesys/R/cdc_minmax.R
#' Ranked Pairs Method #' #' It is also called Tideman method. See details. #' #' The method first summarizes the result of pairwise comparison, #' the order used is the order of winning votes from large to small. #' So if pairwise comparison has ties (that is, the number of voters #' who prefer a than b is equal to the number of voters who prefer #' b than a, the method will fail, and the winner will be NULL). #' #' The second step is called tally. #' If a wins b with 100 votes, b wins c with 80 votes, then #' we put a-b-100 ahead of b-c-80. Suppose a wins b with 100 votes, #' a wins c with 100 votes, then we have a tie; so we have to check #' the relation between b and c. If b wins c, then we put a-c-100 #' ahead of a-b-100. Suppose a wins b with 100 votes, d wins b with #' 100 votes, then again we have a tie and have to check the a-d #' relation. If d wins a, then we put d-b-100 ahead of a-b-100. Suppose #' a wins b with 100 votes, e wins f with 100 votes, then the ties cannot #' be solved, so the winner will be NULL. #' #' The third step, after the above mentioned tally, is called lock-in. #' As the relations have been sorted according to their strength #' from large to small in the tally step, we now add them one #' by one. The rule is: if a relation is contradictory with those #' already locked in relations, this relation will be discarded. #' #' For example, suppose we have already add relation a > b and #' b > c, then the two relations are locked in. As a result, we should #' not add b > a. Also, as a > b and b > c indicate a > c, so we should #' not add c > a. After this process, we will finally find the winner who #' defeats all others. #' #' @param x it accepts the following types of input: #' 1st, it can be an object of class \code{vote}. #' 2nd, it can be a user-given Condorcet matrix, #' 3rd, it can be a result of another Condorcet method, #' which is of class \code{condorcet}. #' @param allow_dup whether ballots with duplicated score values #' are taken into account. Default is TRUE. #' @param min_valid default is 1. If the number of valid entries of #' a ballot is less than this value, it will not be used. #' #' @return a \code{condorcet} object, which is essentially #' a list. #' \itemize{ #' \item (1) \code{call} the function call. #' \item (2) \code{method} the counting method. #' \item (3) \code{candidate} candidate names. #' \item (4) \code{candidate_num} number of candidate. #' \item (5) \code{ballot_num} number of ballots in x. When #' x is not a \code{vote} object, it may be NULL. #' \item (6) \code{valid_ballot_num} the number of ballots that are #' actually used to compute the result. When #' x is not a \code{vote} object, it may be NULL. #' \item (7) \code{winner} the winner, may be NULL. #' \item (8) \code{input_object} the class of x. #' \item (9) \code{cdc} the Condorcet matrix which is actually used. #' \item (10) \code{dif} the score difference matrix. When #' x is not a \code{vote} object, it may be NULL. #' \item (11) \code{binary} win and loss recorded with 1 (win), #' 0 (equal) and -1 (loss). #' \item (12) \code{summary_m} times of win (1), equal (0) #' and loss (-1). #' \item (13) \code{other_info} a list of 3 elements. The 1st #' is the reason of failure. If winner exists, it will be blank. The 2nd #' is the tally result (it may contain unsolved ties). #' The 3rd is the lock-in result; if the method fails, #' it will be NULL. #' } #' #' @references #' \itemize{ #' \item Tideman, T. 1987. Independence of clones as a #' criterion for voting rules. Social Choice and Welfare, 4(3), 185-206. #' } #' #' @export #' @examples #' raw <- rbind(c('m', 'n', 'c', 'k'), c('n', 'c', 'k', 'm'), #' c('c', 'k', 'n', 'm'), c('k', 'c', 'n', 'm')) #' raw <- list2ballot(m = raw, n = c(42, 26, 15, 17)) #' vote <- create_vote(raw, xtype = 2, candidate = c('m', 'n', 'c', 'k')) #' y <- cdc_rankedpairs(vote) cdc_rankedpairs <- function(x, allow_dup = TRUE, min_valid = 1) { method <- "rankedpairs" if (min_valid < 1) stop("Minimux number of min_valid is 1.") if (!class(x)[1] %in% c("vote", "matrix", "condorcet")) stop("x must be a vote, condorcet or matrix object.") stopifnot(allow_dup %in% c(TRUE, FALSE)) CORE_M <- fInd_cdc_mAtrIx(x, dup_ok = allow_dup, available = min_valid) message("EXTRACTING INFO") class1 <- CORE_M$input_object candidate <- CORE_M$candidate candidate_num <- CORE_M$candidate_num ballot_num <- CORE_M$ballot_num valid_ballot_num <- CORE_M$valid_ballot_num cdc_matrix <- CORE_M$cdc dif_matrix <- CORE_M$dif binary_m <- CORE_M$binary message("SELECTING") summary_m <- sUmmAry_101(x = binary_m, rname = candidate) result_ID <- 0 # decide the type of result message("------PAIRWISE") win_side <- c() lose_side <- c() win_num <- c() lose_num <- c() pair_have_tie <- 0 for (i in 1:nrow(cdc_matrix)) { for (j in 1:ncol(cdc_matrix)) { if (i > j) { ij <- cdc_matrix[i, j] ji <- cdc_matrix[j, i] if (ij >= ji) { win_side <- append(win_side, candidate[i]) lose_side <- append(lose_side, candidate[j]) win_num <- append(win_num, ij) lose_num <- append(lose_num, ji) if (ij == ji) pair_have_tie <- 1 } else if (ij < ji) { win_side <- append(win_side, candidate[j]) lose_side <- append(lose_side, candidate[i]) win_num <- append(win_num, ji) lose_num <- append(lose_num, ij) } } } } tally <- data.frame(win_side, lose_side, win_num, lose_num, stringsAsFactors = FALSE) if (pair_have_tie == 0) result_ID <- 1 # if pairwise has no tie, then result_ID=1, then go ahead if (result_ID == 1) { message("------SORTING") tally_o <- order((-1) * tally[, 3], tally[, 4]) tally <- tally[tally_o, ] nr_tally <- nrow(tally) only_num_df <- tally[, c(3, 4)] if (nr_tally == nrow(unique(only_num_df))) { # do NOT use uniqueN result_ID <- 2 } else { BI_ZERO_ONE <- binary_m BI_ZERO_ONE[BI_ZERO_ONE == -1] <- 0 re_tally <- RP_TIE_SOLVE(x = tally, zeroone = BI_ZERO_ONE) if (re_tally[[1]] == TRUE) result_ID <- 2 tally <- re_tally[[2]] } } # if sort has no tie, then result_ID=2, then go ahead if (result_ID == 2) { message("------LOCKING IN") name_m <- as.matrix(tally[, c(1, 2)]) the_source <- lock_winner(name_m, CAND = candidate) winner <- the_source[[2]] LOCK_IN <- the_source[[1]] } message("COLLECTING RESULT") over <- list(call = match.call(), method = method, candidate = candidate, candidate_num = candidate_num, ballot_num = ballot_num, valid_ballot_num = valid_ballot_num, winner = NULL, input_object = class1, cdc = cdc_matrix, dif = dif_matrix, binary = binary_m, summary_m = summary_m, other_info = NULL) if (result_ID == 0) { over$other_info <- list(failure = "Pairwise comparison has ties, i. e., the number of people who prefer i than j is equal to the number of people who prefer j than i.", tally = tally, lock_in = NULL) } if (result_ID == 1) { over$other_info <- list(failure = "There are unsolved ties when sorting the tally.", tally = tally, lock_in = NULL) } if (result_ID == 2) { over$winner <- winner over$other_info <- list(failure = "", tally = tally, lock_in = LOCK_IN) } class(over) <- "condorcet" message("DONE") return(over) }
/scratch/gouwar.j/cran-all/cranData/votesys/R/cdc_rankedpairs.R
#' Schulze Method #' #' Schulze method is essentially a widest path problem. #' With the Condorcet matrix, we must find the so called #' the strongest path a > b > c > d, and the winner is a. #' The strength of a path is the strength of its weakest link. #' #' @param x it accepts the following types of input: #' 1st, it can be an object of class \code{vote}. #' 2nd, it can be a user-given Condorcet matrix, #' 3rd, it can be a result of another Condorcet method, #' which is of class \code{condorcet}. #' @param allow_dup whether ballots with duplicated score values #' are taken into account. Default is TRUE. #' @param min_valid default is 1. If the number of valid entries of #' a ballot is less than this value, it will not be used. #' #' @return a \code{condorcet} object, which is essentially #' a list. #' \itemize{ #' \item (1) \code{call} the function call. #' \item (2) \code{method} the counting method. #' \item (3) \code{candidate} candidate names. #' \item (4) \code{candidate_num} number of candidate. #' \item (5) \code{ballot_num} number of ballots in x. When #' x is not a \code{vote} object, it may be NULL. #' \item (6) \code{valid_ballot_num} number of ballots that are #' actually used to compute the result. When #' x is not a \code{vote} object, it may be NULL. #' \item (7) \code{winner} the winners, may be NULL. #' \item (8) \code{input_object} the class of x. #' \item (9) \code{cdc} the Condorcet matrix which is actually used. #' \item (10) \code{dif} the score difference matrix. When #' x is not a \code{vote} object, it may be NULL. #' \item (11) \code{binary} win and loss recorded with 1 (win), #' 0 (equal) and -1 (loss). #' \item (12) \code{summary_m} times of win (1), equal (0) #' and loss (-1). #' \item (13) \code{other_info} a list of 2 elements. The 1st is the strength #' comparison matrix. The 2nd is the strength comparison matrix in binary #' mode, 1 for win, 0 for else. #' } #' #' @references #' \itemize{ #' \item Schulze, M. 2010. A new monotonic, #' clone-independent, reversal symmetric, #' and Condorcet-consistent single-winner election method. #' Social Choice and Welfare, 36(2), 267-303. #' } #' #' @export #' @examples #' raw <- list2ballot( #' x = list( #' c('a', 'c', 'b', 'e', 'd'), #' c('a', 'd', 'e', 'c', 'b'), #' c('b', 'e', 'd', 'a', 'c'), #' c('c', 'a', 'b', 'e', 'd'), #' c('c', 'a', 'e', 'b', 'd'), #' c('c', 'b', 'a', 'd', 'e'), #' c('d', 'c', 'e', 'b', 'a'), #' c('e', 'b', 'a', 'd', 'c') #' ), #' n = c(5, 5, 8, 3, 7, 2, 7, 8) #' ) #' vote <- create_vote(raw, xtype = 3, candidate = c('a', 'b', 'c', 'd', 'e')) #' win1 <- cdc_simple(vote) # no winner #' win2 <- cdc_schulze(vote) # winner is e #' win2 <- cdc_schulze(win1) cdc_schulze <- function(x, allow_dup = TRUE, min_valid = 1) { method <- "schulze" if (min_valid < 1) stop("Minimux number of min_valid is 1.") stopifnot(allow_dup %in% c(TRUE, FALSE)) if (!class(x)[1] %in% c("vote", "matrix", "condorcet")) stop("x must be a vote, condorcet or matrix object.") CORE_M <- fInd_cdc_mAtrIx(x, dup_ok = allow_dup, available = min_valid) message("EXTRACTING INFO") class1 <- CORE_M$input_object candidate <- CORE_M$candidate candidate_num <- CORE_M$candidate_num ballot_num <- CORE_M$ballot_num valid_ballot_num <- CORE_M$valid_ballot_num cdc_matrix <- CORE_M$cdc dif_matrix <- CORE_M$dif binary_m <- CORE_M$binary message("SELECTING") summary_m <- sUmmAry_101(x = binary_m, rname = candidate) strength_schu <- bOttlEnEck(cdc_matrix) nrc_str <- nrow(strength_schu) check_strength <- matrix(0, nrow = nrc_str, ncol = nrc_str) for (i in 1:nrc_str) { for (j in 1:nrc_str) { if (i != j) { if (strength_schu[i, j] > strength_schu[j, i]) { check_strength[i, j] <- 1 } } } } row_sumup <- rowSums(check_strength) winner <- which(row_sumup == candidate_num - 1) winner <- if (length(winner) == 0) NULL else candidate[winner] message("COLLECTING RESULT") over <- list(call = match.call(), method = method, candidate = candidate, candidate_num = candidate_num, ballot_num = ballot_num, valid_ballot_num = valid_ballot_num, winner = winner, input_object = class1, cdc = cdc_matrix, dif = dif_matrix, binary = binary_m, summary_m = summary_m, other_info = list(strength = strength_schu, binary_strength = check_strength)) class(over) <- "condorcet" message("DONE") return(over) }
/scratch/gouwar.j/cran-all/cranData/votesys/R/cdc_schulze.R
#' Ordinary Condorcet Method #' #' Candidates enter into pairwise comparison. #' if the number of voters who prefer a is larger than the #' number of voters who prefer b, then a wins b, a gets 1 #' point, b gets 0 point. If the numbers are equal, then both #' of them gets 0 point. #' Suppose there are n candidates, the one gets n-1 #' points wins (that is, he wins in all pairwise comparison). #' There may be no Condorcet winner. If thus, you can #' try other Condorcet family methods. #' #' @param x it accepts the following types of input: #' 1st, it can be an object of class \code{vote}. #' 2nd, it can be a user-given Condorcet matrix, #' 3rd, it can be a result of another Condorcet method, #' which is of class \code{condorcet}. #' @param allow_dup whether ballots with duplicated score values #' are taken into account. Default is TRUE. #' @param min_valid default is 1. If the number of valid entries of #' a ballot is less than this value, it will not be used. #' #' @return a \code{condorcet} object, which is essentially #' a list. #' \itemize{ #' \item (1) \code{call} the function call. #' \item (2) \code{method} the counting method. #' \item (3) \code{candidate} candidate names. #' \item (4) \code{candidate_num} number of candidate. #' \item (5) \code{ballot_num} number of ballots in \code{x}. When #' x is not a \code{vote} object, it may be NULL. #' \item (6) \code{valid_ballot_num} number of ballots that are #' actually used to compute the result. When #' x is not a \code{vote} object, it may be NULL. #' \item (7) \code{winner} the winner; may be NULL. #' \item (8) \code{input_object} the class of \code{x}. #' \item (9) \code{cdc} the Condorcet matrix which is actually used. #' \item (10) \code{dif} the score difference matrix. When #' x is not a \code{vote} object, it may be NULL. #' \item (11) \code{binary} win and loss recorded with 1 (win), #' 0 (equal) and -1 (loss). #' \item (12) \code{summary_m} times of win (1), equal (0) #' and loss (-1). #' \item (13) \code{other_info} currently nothing. #' } #' #' @export #' @examples #' raw <- c( #' rep(c('m', 'n', 'c', 'k'), 42), rep(c('n', 'c', 'k', 'm'), 26), #' rep(c('c', 'k', 'n', 'm'), 15), rep(c('k', 'c', 'n', 'm'), 17) #' ) #' raw <- matrix(raw, ncol = 4, byrow = TRUE) #' vote <- create_vote(raw, xtype = 2, candidate = c('m', 'n', 'k', 'c')) #' win1 <- cdc_simple(vote) # winner is n #' win2 <- cdc_simple(win1$cdc) # use a Condorceit matrix #' win2 <- cdc_simple(win1) # use an existent result cdc_simple <- function(x, allow_dup = TRUE, min_valid = 1) { method <- "simple" if (!class(x)[1] %in% c("vote", "matrix", "condorcet")) stop("x must be a vote, condorcet or matrix object.") if (min_valid < 1) stop("Minimux number of min_valid is 1.") # each vote has at least one valid value\t stopifnot(allow_dup %in% c(TRUE, FALSE)) CORE_M <- fInd_cdc_mAtrIx(x, dup_ok = allow_dup, available = min_valid) message("EXTRACTING INFO") class1 <- CORE_M$input_object candidate <- CORE_M$candidate candidate_num <- CORE_M$candidate_num ballot_num <- CORE_M$ballot_num valid_ballot_num <- CORE_M$valid_ballot_num cdc_matrix <- CORE_M$cdc # find cdc matrix dif_matrix <- CORE_M$dif binary_m <- CORE_M$binary # find binary message("SELECTING") summary_m <- sUmmAry_101(x = binary_m, rname = candidate) winner <- which(summary_m[, 3] == candidate_num - 1) winner_num <- length(winner) winner <- if (winner_num == 0) NULL else candidate[winner] message("COLLECTING RESULT") over <- list(call = match.call(), method = method, candidate = candidate, candidate_num = candidate_num, ballot_num = ballot_num, valid_ballot_num = valid_ballot_num, winner = winner, input_object = class1, cdc = cdc_matrix, dif = dif_matrix, binary = binary_m, summary_m = summary_m, other_info = NULL) class(over) <- "condorcet" message("DONE") return(over) }
/scratch/gouwar.j/cran-all/cranData/votesys/R/cdc_simple.R
#' Check Ballots with Duplicated Values, Mistakes, or without Any Valid Entry #' #' The function simply checks validity of ballots and shows the check result. If #' you want a one-step clean, set \code{clean} to TRUE and a set of cleaned ballots #' will be returned. Here, duplicated values mean that the voter write the #' same candidate more than one time, or, when #' he assigns scores, he assigns the same score #' to more than one candidates. Mistakes are names that do not appear in the candidate #' list, or score values that are illegal (e.g., if voters are required to assign 1-5 to candidates, #' then 6 is an illegal value). Ballots without a valid entry (that is, all entries are NAs) are also #' to be picked out. Different formats can be input into the function, see Details. #' #' The function accepts the following input: #' \itemize{ #' \item (1) when \code{xtype} is 1, x must be a matrix. Column names are candidate names (if #' column names are NULL, they will be created: x1, x2, x3...). Candidate number is the number #' of columns of the matrix. Entry ij is the numeric score assigned #' by the ith voter to the jth candidate. #' \item (2) when \code{xtype} is 2, x can be a matrix or data.frame. Candidate #' number is the length of \code{candidate}. #' Entries are names (character or numeric) of candidates. #' The i1, i2, i3... entries are the 1st, 2nd, #' 3rd... preferences of voter i. #' \item (3) when \code{xtype} is 3, \code{x} should be a list. #' Each element of the list is a ballot, a vector #' contains the names (character or numeric) of candidates. The 1st #' preference is in the 1st position of #' the vector, the 2nd preference is in the 2nd position... The number of candidates is the length #' of \code{candidate}; as a result, a ballot with number of names larger than candidate number is #' labelled as wrong. #' } #' #' @param x a data.frame, matrix or list of raw ballots. See Details. #' @param xtype should be 1, 2 (default) or 3, designating the type of x. See Details. #' @param candidate if \code{xtype} is 1, this argument is ignored. #' If \code{xtype} is 2 or3, candidate names #' must be given as a character or numeric vector. If a name is not given, #' but is still on a ballot, then the ballot is labelled as wrong. #' @param vv if \code{xtype} is 2 or 3, it is ignored. #' If \code{xtype} is 1, this gives the valid score values for x. #' @param isna entries which should be taken as NAs. \code{NA} in \code{x} # will always #' be taken as missing value, #' however, you can add more (e.g., you may use 99, 999 as missing values). #' If x contains characters, #' this argument should also be provided with a character vector, and #' if numeric, then numeric vector. Do #' not add NA to \code{isna}, because the default (NULL) #' means \code{NA} is already included. #' @param clean the default is FALSE, that is, it does not return the cleaned data. If it is TRUE, #' a set of ballots without duplicated values, without mistakes and with #' at least one valid value, is #' returned. #' #' @return a list with 3 or 4 elements: \code{row_with_dup} is #' the rows (not row names) of rows that have #' duplicated values; \code{row_with_wrong} is the rows with illegal names or the #' lengths of them are larger than candidate number (this could only happen when x #' is a list). \code{row_all_na} is the rows the entries of which are all NAs. For a list, #' elements with NULL are also taken as all-NA ballots. #' #' @export #' @examples #' raw=list( #' c('a', 'e', 'c', 'd', 'b'), #' c('b', 'a', 'e'), #' c('c', 'd', 'b'), #' c('d', 'a', 'b'), #' c('a', 'a', 'b', 'b', 'b'), #' c(NA, NA, NA, NA), #' v7=NULL, #' v8=c('a', NA, NA, NA, NA, NA, NA), #' v9=rep(" ", 3) #' ) #' y=check_dup_wrong(raw, xtype=3, candidate=letters[1: 5]) #' y=check_dup_wrong(raw, xtype=3, candidate=letters[1: 4]) check_dup_wrong <- function(x, xtype = 2, candidate = NULL, vv = NULL, isna = NULL, clean = FALSE) { class1 <- class(x)[1] cat("Class of raw data is: ", class1, "\n") if (!class1 %in% c("matrix", "data.frame", "list")) stop("x must be a matrix, data.frame or list.") # xtype is 2, 3 check if (xtype %in% c(2, 3)) { if (xtype == 2) cat("xtype is 2 means each row of the raw data contains the preference of a voter.\n") if (xtype == 3) cat("xtype is 3 means each element of the raw data list contains the preference of a voter.\n") lengthcand <- length(candidate) if (lengthcand < 2) stop("Less than 2 candidates.") if (any(is.na(candidate))) stop("candidate should not have NA.") isna <- if (class1 == "matrix") c(isna, NA) else c(as.character(isna), NA, "", " ") if (!class1 == "matrix") candidate <- as.character(candidate) dup_row <- c() wrong_row <- c() all_na <- c() if (class1 == "list") { for (i in 1:length(x)) { ii <- as.character(x[[i]]) lengthii <- length(ii) if (lengthii == 0) ii <- rep(NA, length(candidate)) # list element is NULL ii <- ii[!ii %in% isna] len_ii <- length(ii) if (len_ii == 0) { all_na <- append(all_na, i) if (lengthii > lengthcand) wrong_row <- append(wrong_row, i) } else { if (any(!ii %in% candidate) | lengthii > lengthcand) wrong_row <- append(wrong_row, i) if (anyDuplicated(ii) != 0) dup_row <- append(dup_row, i) } } } if (class1 == "data.frame") { for (j in 1:ncol(x)) { if (class(x[, j]) != "character") x[, j] <- as.character(x[, j]) } for (i in 1:nrow(x)) { ii <- as.character(x[i, ]) ii <- ii[!ii %in% isna] len_ii <- length(ii) if (len_ii > 0) { if (any(!ii %in% candidate)) wrong_row <- append(wrong_row, i) if (anyDuplicated(ii) != 0) dup_row <- append(dup_row, i) } else { all_na <- append(all_na, i) } } } if (class1 == "matrix") { if (!class(x[1, 1]) %in% c("integer", "numeric", "character")) stop("If x is a matrix, cells must be of class numeric, integer, character.") if (class(x[1, 1]) %in% c("integer", "numeric")) { if (!class(candidate) %in% c("integer", "numeric")) stop("If x is a matrix, cells must be of the same class as candidate.") } else { if (class(candidate) != "character") stop("If x is a matrix, cells must be of the same class as candidate.") } for (i in 1:nrow(x)) { ii <- x[i, ] ii <- ii[!ii %in% isna] len_ii <- length(ii) if (len_ii > 0) { if (any(!ii %in% candidate)) wrong_row <- append(wrong_row, i) if (anyDuplicated(ii) != 0) dup_row <- append(dup_row, i) } else { all_na <- append(all_na, i) } } } # xtype is 1 check } else if (xtype == 1) { cat("xtype is 1 mean the colnames are candidates and cells contain the numeric values given by voters.\n") if (class1 == "matrix") { if (!is.numeric(x[1, 1])) stop("x must be with numeric cells.") } if (class1 == "data.frame") stop("If xtype is 1, x must be a matrix.") if (ncol(x) < 2) stop("Less than 2 candidates.") if (is.null(vv)) { vv <- 1:ncol(x) } else { if (!is.numeric(vv)) stop("If xtype is 1, vv must be numeric.") if (any(is.na(vv))) stop("vv must not have NA.") } isna <- c(isna, NA) dup_row <- c() wrong_row <- c() all_na <- c() for (i in 1:nrow(x)) { ii <- x[i, ] ii <- ii[!ii %in% isna] len_ii <- length(ii) if (len_ii > 0) { if (any(! ii %in% vv)) wrong_row <- append(wrong_row, i) if (anyDuplicated(ii) != 0) dup_row <- append(dup_row, i) } else { all_na <- append(all_na, i) } } } else { stop("Sorry, currently xtype can only be 1, 2 or 3.") } result <- list(row_with_dup = dup_row, row_with_wrong = wrong_row, row_all_na = all_na) if (clean == TRUE) { rrr <- c(dup_row, wrong_row, all_na) rrr <- unique(rrr) if (length(rrr) > 0) { if (class1 == "list") { result$clean <- x[-rrr] if (length(result$clean) == 0) { warning("No vote is left.") result$clean <- NULL } } else { result$clean <- x[-rrr, ] if (nrow(result$clean) == 0) { warning("No vote is left.") result$clean <- NULL } } } } result }
/scratch/gouwar.j/cran-all/cranData/votesys/R/check_dup_wrong.R
#' Create a vote Object that can be used in counting methods #' #' Some counting methods in this package only accept \code{vote} object created by #' this function. So the first step should always be using this function. The function #' will return the modified ballots and some other helpful information. See Details #' and Values. #' #' The function accepts the following input: #' \itemize{ #' \item (1) when \code{xtype} is 1, x must be a matrix. Column names are candidate names (if #' column names are NULL, they will be created: x1, x2, x3...). Candidate number is the number #' of columns of the matrix. Entry ij is the numeric score assigned by #' the ith voter to the jth candidate. #' \item (2) when \code{xtype} is 2, x can be a matrix or data.frame. #' Candidate number is the length of \code{candidate}. #' Entries are names (character or numeric) of candidates. #' The i1, i2, i3... entries are the 1st, 2nd, #' 3rd... preferences of voter i. #' \item (3) when \code{xtype} is 3, x should be a list. #' Each element of the list is a ballot, a vector #' contains the names (character or numeric) of candidates. #' The 1st preference is in the 1st position of #' the vector, the 2nd preference is in the 2nd position... The number of candidates is the length #' of \code{candidate}; as a result, a ballot with number of names #' larger than candidate number is #' labelled as wrong. #' } #' #' The function also returns Condorcet matrix. Suppose candidates are i, j, k. #' The voter likes i best, so he assigns 1 to i. The 2nd choice is j, so #' he assigns 2 to j, leaving k as NA. Now computing the Condorcet matrix: #' since i's score is smaller than j' score, we add 1 to the ij cell of the matrix, #' and add 0 to the ji cell. Candidate k's NA is automatically set to the #' highest (that is, the worst) score: 3 (since there are 3 candidates); i < k, so #' we add 1 to the ik cell and add 0 to ki cell. Besides, there is also a score #' difference matrix: we add 2 - 1 = 1 to the ij cell of score difference matrix, #' and add 3 - 1 = 2 to the ik cell. If tie appears, both sides acquire 0. #' #' Note the ways we calculate the Condorcet matrix. (1) It allow ties, that is, #' duplicated score values. (2) NA is deems as the worst, which means: if a #' voter does not mention a candidate, the candidate will be given the #' highest (worst) score. (3) Ballots mention only one name are assumed #' to express preference, since unmentioned candidates are assumed to #' be equally hated. (4) The Condorcet matrix returned #' by \code{create_vote} uses ballots that may have duplicated values #' and have only one valid entry. However, Condorcet family #' methods in this package provide possibility to recalculate the matrix. #' And, the simplest way to get rid of duplicated values and NAs is #' to delete some ballots. #' #' @param x a data.frame, matrix or list of raw ballots. See Details. #' @param xtype should be 1, 2 (default) or 3, designating the #' type of \code{x}. See Details. #' @param candidate if \code{xtype} is 1, this argument is ignored. #' If \code{xtype} is 2 or 3, candidate names #' must be given as a character or numeric vector. If a name is not given, #' but is still on a ballot, then the name is ignored ! #' @param isna entries which should be taken as NAs. #' \code{NA} in \code{x} will always be taken as missing value, #' however, you can add more (e.g., you may use 99, 999 as missing values). #' If x contains characters, #' this argument should also be provided with a #' character vector, and if numeric, then numeric vector. Do #' not add \code{NA} to \code{isna}, because the default (NULL) #' means \code{NA} is already included. #' #' @return an object of class \code{vote} is returned, which #' is essentially a list. It has the following elements. #' \itemize{ #' \item (1) \code{call} the call. #' \item (2) \code{ballot} the returned ballot. It is always a score matrix. #' The column names are candidate names; entries are numeric scores #' assigned by voters. Missing values are all set to NA. #' \item (3) \code{nas} those which are taken as NA in data cleaning. #' \item (4) \code{candidate} candidate names. #' \item (5) \code{candidate_num} number of candidates. #' \item (6) \code{ballot_num} number of ballots. #' \item (7) \code{ballot_at_least_one} number of ballots that mention #' at least one candidate. #' \item (8) \code{cdc} the Condorcet matrix calculated with ballots #' that have no NA entries. #' \item (9) \code{cdc_with_na} the Condorcet matrix calculated with #' ballots that have at least one valid entry. #' \item (10) \code{dif} the score difference matrix calculated with #' ballots that have no NA entries. #' \item (11) \code{dif_with_na} the score difference matrix calculated #' with ballots that have at least one valid entry. #' \item (12) \code{row_with_na} rows of \code{ballot} with NAs. #' \item (13) \code{row_non_na} for rows with NAs, the number of #' non-NA entries of them. #' \item (14) \code{row_with_dup} rows of \code{ballot} with #' duplicated score values. #' \item (15) \code{approval_able} if length of \code{row_non_dup} #' is 0, then it is TRUE, else, FALSE. It indicates whether approval #' method can be used. When \code{xtype} is 2 or 3, it is always TRUE. #' } #' #' @export #' @import data.table #' @examples #' # xtype is 2 #' raw <- c( #' rep(c('m', 'n', 'c', 'k'), 42), #' rep(c('n', 'c', 'k', 'm'), 26), #' rep(c('c', 'k', 'n', 'm'), 15), #' rep(c('k', 'c', 'n', 'm'), 17) #' ) #' raw <- matrix(raw, ncol = 4, byrow = TRUE) #' vote <- create_vote(raw, xtype = 2, candidate = c('m', 'n', 'k', 'c')) #' #' # xtype is 3 #' raw <- list( #' c('a', 'e', 'c', 'd', 'b'), #' c('b', 'a', 'e'), #' c('c', 'd', 'b'), #' c('d', 'a', 'b'), #' c('a', 'a', 'b', 'b', 'b'), #' c(NA, NA, NA, NA), #' v7 = NULL, #' v8 = c('a', NA, NA, NA, NA, NA, NA), #' v9 = rep(" ", 3) #' ) #' y <- check_dup_wrong(raw, xtype = 3, candidate = letters[1: 4]) #' raw2 <- raw[-y$row_with_wrong] #' vote <- create_vote(raw2, xtype = 3, candidate = letters[1: 4]) #' #' # xtype is 1 #' raw <- rbind( #' c(1, 2, 5, 3, 3), #' c(2, 1, 1, 3, 5), #' c(1, 2, 5, 3, 4), #' c(1, 2, 5, 3, 4), #' c(NA, NA, NA, NA, NA), #' c(NA, 3, 5, 1, 2), #' c(NA, 999, NA, 1, 5) #' ) #' vote <- create_vote(raw, xtype = 1, isna = 999) create_vote=function(x, xtype=2, candidate=NULL, isna=NULL){ if (! xtype[1] %in% c(1, 2, 3)) stop('Sorry, currently xtype can only be 1, 2 or 3.') if (xtype %in% c(2, 3)){ if (is.null(candidate)) stop('When xtype is 2 or 3, candidate must be given.') if (any(is.na(candidate))) stop('Argument candidate must not have NA.') if (length(candidate)<2) stop('Less than 2 candidate.') } if (!is.null(isna)){ if (any(is.na(isna))) stop('Argument isna should either be NULL or a vector without NA.') } message('MATCHING NAMES AND SCORES') class1=class(x)[1] if(xtype==1){ if (! class1 %in% c('matrix')) stop('When xtype is 1, raw data must be a matrix.') isna=c(isna, NA) if (ncol(x)<2) stop('Less than 2 candidates.') if (!is.null(colnames(x))){ candidate=colnames(x) } else { candidate=fUll_dIgIt(ncol(x), "x") } if (!is.numeric(x[, 1])) stop('When xtype is 1, each column of x must be numeric.') x[x %in% isna]=NA VOTE_M=x } else if(xtype==3){ if (class1 !='list') stop('When xtype is 3, x must be a list.') candidate=as.character(candidate) candidate_num=length(candidate) check_list_len=unlist(lapply(x, length)) if (any(check_list_len > candidate_num)) stop("Lengths of some elements of list are larger than candidate number.") isna=c(as.character(isna), NA, "", " ") VOTE_M=matrix(as.integer(NA), ncol=length(x), nrow=candidate_num) VOTE_M=data.table::data.table(VOTE_M) for (i in 1: length(x)){ ii=as.character(x[[i]]) if (length(ii)==0) ii=rep(NA, candidate_num) lengthii=length(ii) ii[ii %in% isna]=NA if (any(!is.na(ii))){ match_name=match(ii, candidate) not_na=!is.na(match_name) match_name=match_name[not_na] match_value=c(1: lengthii)[not_na] VOTE_M[match_name, (i) := match_value] } } } else if(xtype==2){ if (! class1 %in% c('matrix', 'data.frame')) stop('When xtype is 2, x must be a matrix or data.frame.') if (! class1=='matrix') candidate=as.character(candidate) candidate_num=length(candidate) if (ncol(x)>candidate_num) stop("Column number is larger than candidate number.") if (class1 =='data.frame'){ isna=c(as.character(isna), NA, "", " ") for (j in 1: ncol(x)){ if (class(x[, j]) != 'character') x[, j] = as.character(x[, j]) } VOTE_M=matrix(as.integer(NA), ncol=nrow(x), nrow=candidate_num) VOTE_M=data.table::data.table(VOTE_M) for (i in 1: nrow(x)){ ii=as.character(x[i, ]) ii[ii %in% isna]=NA if (any(!is.na(ii))){ match_name=match(ii, candidate) not_na=!is.na(match_name) match_name=match_name[not_na] match_value=c(1: length(ii))[not_na] VOTE_M[match_name, (i) := match_value] } } } else if (class1 == 'matrix'){ if (! class(x[1, 1]) %in% c("integer", "numeric", "character")){ stop("When xtype is 2 and x is matrix, cells of x must be integer, numeric or character.") } isna <- if (class(x[1, 1])=="character") c(as.character(isna), NA, "", " ") else c(NA, isna) VOTE_M=matrix(as.integer(NA), ncol=nrow(x), nrow=candidate_num) VOTE_M=data.table::data.table(VOTE_M) for (i in 1: nrow(x)){ ii=x[i, ] ii[ii %in% isna]=NA if (any(!is.na(ii))){ match_name=match(ii, candidate) not_na=!is.na(match_name) match_name=match_name[not_na] match_value=c(1: length(ii))[not_na] VOTE_M[match_name, (i) := match_value] } } } } rm(x) if (xtype != 1) VOTE_M=data.table::transpose(VOTE_M) colnames(VOTE_M)=as.character(candidate) message('COUNTING NA AND DUP VALUES') COUNT_NA_DUP=chEck_stAndArd_mAtrIx(VOTE_M, numeric_na=isna) message('MAKING CONDORCET TABLE') CDC_RESULT=rOw2cdc(VOTE_M) if (xtype %in% c(2, 3)){ APPROVAL_OK=TRUE } else if (xtype==1){ APPROVAL_OK=if (length(COUNT_NA_DUP[[3]])==0) TRUE else FALSE } message('COLLECTING RESULT') NBALLOT=nrow(VOTE_M) num_of_all_na=if (length(COUNT_NA_DUP[[2]]) == 0) 0 else length(which(COUNT_NA_DUP[[2]]==0)) NBALLOT_HAVE_ONE=NBALLOT-num_of_all_na candidate_num=length(candidate) Y=list(call=match.call(), ballot=if(is.matrix(VOTE_M)) VOTE_M else as.matrix(VOTE_M), nas=isna, candidate=candidate, candidate_num=candidate_num, ballot_num=NBALLOT, ballot_at_least_one=NBALLOT_HAVE_ONE, cdc=CDC_RESULT[[1]], cdc_with_na=CDC_RESULT[[2]], dif=CDC_RESULT[[3]], dif_with_na=CDC_RESULT[[4]], row_with_na=COUNT_NA_DUP[[1]], num_non_na=COUNT_NA_DUP[[2]], row_with_dup=COUNT_NA_DUP[[3]], approval_able=APPROVAL_OK ) class(Y)="vote" message('DONE') return(Y) }
/scratch/gouwar.j/cran-all/cranData/votesys/R/create_vote.R
#' Dowdall Method #' #' This is an alternative Borda method. Voters are required #' to assign preference scores to every candidate and one #' score value cannot be shared by two or more candidates. #' For a voter, his 1st choice gets 1, his 2nd choice gets #' 1/2, his 3rd choice gets 1/3... The candidate who gets #' the most points wins. For the function #' \code{dowdall_method}, ranks, rather than true #' values, are used. So 1, 3, 5 are ranked as 1, 2, 3, and the #' scores are 1/1, 1/2, 1/3. #' #' @param x an object of class \code{vote}. The ballots in #' the object should not have duplicated values and NAs. #' @param stop default is FALSE, when ballots do have #' duplicated values or NAs, error will not be raised, but #' the winner will be NULL. If TRUE, an error will be raised. #' #' @return a list object. #' \itemize{ #' \item (1) \code{call} the function call. #' \item (2) \code{method} the counting method. #' \item (3) \code{candidate} candidate names. #' \item (4) \code{candidate_num} number of candidate. #' \item (5) \code{ballot_num} number of ballots in x. #' \item (6) \code{valid_ballot_num} number of ballots that are #' used to compute the result. #' \item (7) \code{winner} the winners. #' \item (8) \code{other_info} total scores. #' } #' #' @references #' \itemize{ #' \item https://en.wikipedia.org/wiki/Borda_count #' } #' #' @export #' @examples #' raw <- list2ballot(string = #' c("51: a>c>b>d", "5: c>b>d>a", "23: b>c>d>a", "21: d>c>b>a") #' ) #' vote <- create_vote(raw, xtype = 3, candidate = c("a", "b", "c", "d")) #' y1 <- borda_method(vote) # winner is c #' y2 <- dowdall_method(vote) # winner is a dowdall_method <- function(x, stop = FALSE) { method <- "dowdall" if (!class(x)[1] == "vote") stop("x must be a vote object.") stopifnot(stop %in% c(TRUE, FALSE)) candidate <- x$candidate NBALLOT <- x$ballot_num candidate_num <- x$candidate_num do_compute <- TRUE if (length(x$row_with_dup) > 0 | length(x$row_with_na) > 0) { if (stop == TRUE) { stop("Some ballots in x have duplicated values or NAs.") } else { winner <- NULL SCORE <- NULL VALID_BALLOT_NUM <- NULL do_compute <- FALSE message("Method fails, winner will be NULL.") } } if (do_compute) { message("SELECTING") VALID_BALLOT_NUM <- NBALLOT rankdivide <- apply(x$ballot, 1, FUN = function(x) 1/rank(x)) SCORE <- rowSums(rankdivide) winner <- which(SCORE == max(SCORE)) winner <- candidate[winner] } message("COLLECTING RESULT") over <- list(call = match.call(), method = method, candidate = candidate, candidate_num = candidate_num, ballot_num = NBALLOT, valid_ballot_num = VALID_BALLOT_NUM, winner = winner, other_info = list(score = SCORE)) message("DONE") return(over) }
/scratch/gouwar.j/cran-all/cranData/votesys/R/dowdall_method.R
#' Instant-Runoff Voting Method #' #' Instant-runoff voting (IRV) method is also #' called alternative voting, #' transferable voting, ranked-choice voting, #' single-seat ranked-choice voting, or preferential voting. #' In the 1st round, the candidate with absolute majority (that #' is, with more than 50 percent) wins. If no absolute winner exists, #' the one who gets the least votes is deleted, all other #' candidates enter into the 2nd round. Again, if no #' absolute winner exists, let the one with the least votes go and #' start the 3rd round... Finally, an absolute winner will #' appear. Ties are solved with different methods in reality; however, #' this function applies the following rules: (a) if more than #' one candidate gets the least votes, let all of them go; (b) if #' all the candidates get the same number of votes in a certain round, #' then all of them are winners. Note: the function accepts #' object of class \code{vote} and the method can only be #' used when x$approval_able is TRUE, that is, there is #' no duplicated values in the score matrix; otherwise, #' the winner will be NULL. #' #' @param x an object of class \code{vote}. #' @param min_valid default is 1. If the number of valid entries of #' a ballot is less than this value, the ballot will not be used. #' #' @return a list object. #' \itemize{ #' \item (1) \code{call} the function call. #' \item (2) \code{method} the counting method. #' \item (3) \code{candidate} candidate names. #' \item (4) \code{candidate_num} number of candidate. #' \item (5) \code{ballot_num} number of ballots in x. #' \item (6) \code{valid_ballot_num} number of ballots that are #' used to compute the result. #' \item (7) \code{winner} the winners, may be NULL. #' \item (8) \code{absolute} whether the winner wins absolute majority in the #' 1st round. #' \item (9) \code{other_info} the IRV may run for 2 or more rounds. So here #' the summary information of each round is recorded. The length of the list is #' equal to the number of rounds. #' } #' #' @references #' \itemize{ #' \item Reilly, B. 2004. The global spread of preferential #' voting: Australian institutional imperialism? #' Australian Journal of Political Science, 39(2), 253-266. #' } #' #' @export #' @examples #' raw <- c( #' rep(c('m', 'n', 'c', 'k'), 42), rep(c('n', 'c', 'k', 'm'), 26), #' rep(c('c', 'k', 'n', 'm'), 15), rep(c('k', 'c', 'n', 'm'), 17) #' ) #' raw <- matrix(raw, ncol = 4, byrow = TRUE) #' vote <- create_vote(raw, xtype = 2, candidate = c('m', 'n', 'k', 'c')) #' y <- irv_method(vote) # winner is k irv_method <- function(x, min_valid = 1) { method <- "irv" if (!class(x)[1] == "vote") stop("x must be a vote object.") do_ok <- if (x$approval_able == FALSE) FALSE else TRUE if (min_valid < 1) stop("Minimux number of min_valid is 1.") candidate <- x$candidate NBALLOT <- x$ballot_num candidate_num <- x$candidate_num if (do_ok == TRUE){ should_del <- c() if (length(x$row_with_na) > 0) { get_na_ok <- which(x$num_non_na < min_valid) if (length(get_na_ok) > 0) should_del <- x$row_with_na[get_na_ok] } length_should_del <- length(should_del) VALID_BALLOT_NUM <- NBALLOT - length_should_del if (VALID_BALLOT_NUM == 0) stop("No ballot is OK.") x <- if (length_should_del > 0) x$ballot[-should_del, ] else x$ballot message("SELECTING") round_summary <- list() absolute <- FALSE winner_appear <- FALSE winner <- NULL deleted <- c() ROUND <- 1 while (winner_appear == FALSE) { message("------ROUND: ", ROUND) W <- append(apply(x, 1, which.min), 1:candidate_num) tta <- table(W) - 1 if (length(deleted) > 0) tta <- tta[-deleted] ttn <- as.numeric(names(tta)) names(tta) <- candidate[ttn] round_summary[[length(round_summary) + 1]] <- tta tta <- as.numeric(tta) perc <- tta/sum(tta) which_half <- which(perc > 0.5) if (length(which_half) > 0) { # if single wins winner_appear <- TRUE winner <- ttn[which_half] } else { whichmin <- which(tta == min(tta)) if (length(whichmin) == length(tta)) { # if all have min winner_appear <- TRUE winner <- ttn[whichmin] message("More than one winner.") } else { for (i in ttn[whichmin]) x[, i] <- NA x <- x[apply(x, 1, FUN = function(x) !all(is.na(x))), ] deleted <- append(deleted, ttn[whichmin]) ROUND <- ROUND + 1 } } } winner <- candidate[winner] if (length(round_summary) == 1 & length(winner) == 1) absolute <- TRUE } message("COLLECTING RESULT") if (do_ok == TRUE){ over <- list(call = match.call(), method = method, candidate = candidate, candidate_num = candidate_num, ballot_num = NBALLOT, valid_ballot_num = VALID_BALLOT_NUM, winner = winner, absolute = absolute, other_info = round_summary) } else { over <- list(call = match.call(), method = method, candidate = candidate, candidate_num = candidate_num, ballot_num = NBALLOT, valid_ballot_num = NULL, winner = NULL, absolute = NULL, other_info = NULL) message("The winner is NULL, for IRV can only be used when x$approval_able is TRUE.") message("You can ckeck x$row_with_dup to delete rows with duplicated values.") } message("DONE") return(over) }
/scratch/gouwar.j/cran-all/cranData/votesys/R/irv_method.R
#' Repeat ith element of list x or row of matrix/data.frames #' for j times #' #' Suppose you have 3 different unique ballots and the amount #' of each ballot is 10, 20, 30. Now you want to create raw #' ballots as a list. Then you can use this function. See examples #' for usage. #' @param x a list, each element of which should be a vector. Note: #' only one of \code{x}, \code{m} and \code{string} #' can be a non-NULL object #' @param n how many times each element of \code{x} #' or each row of \code{m} should be replicated. #' It should be a numeric vector of non-negative integers and the #' length of it should be equal to that of \code{x} or the row number #' of \code{m}. #' The default is 1 for each element of \code{x}. #' @param m a matrix or dataframe, the number of rows should be #' equal to the length of n. #' @param string default is NULL. If it is not NULL, \code{x}, \code{m} #' and \code{n} are ignored. It should be a character vector. Each #' one contains two parts, the 1st is the amount of #' that ballot, and the 2nd part contains the names. The 1st and #' 2nd parts, as well as the names, should be split by spaces #' or punctuations. But no space and punctuation is allowed #' inside the names ("_" is not taken to be #' a punctuation). See examples. #' #' @return a list with replicated vectors, if \code{x} is not NULL, #' or a matrix/data.frame with duplicated rows, if #' \code{m} is not NULL. #' @export #' @examples #' # Use x and n #' unique_ballot <- list( #' c("A", "B", "C"), c("F", "A", "B"), #' c("E", "D", "C", "B", "F", "A"), c("x","x", "A") #' ) #' r <- c(1, 2, 3, 0) #' y <- list2ballot(unique_ballot, r) #' #' # Use string, x and n will be ignored. #' # The characters can be written in a very loose way as follows, #' # for the function will automatically delete unwanted parts. #' # But do make sure there is no space or punctuation #' # inside the names. #' unique_ballot <- c( #' "2, Bob, Mike Jane", "3: barack_obama;;Bob>Jane", #' "0 Smith Jane", " 1 Mike???!!!" #' ) #' y <- list2ballot(string = unique_ballot) #' # Use a matrix. #' m <- matrix(c(1, 2, 3, 3, 1, 2), nrow = 2, byrow = TRUE) #' colnames(m) <- c("p1", "p2", "p3") #' r <- c(3, 5) #' y <- list2ballot(m = m, n = r) list2ballot <- function(x = NULL, n = rep(1, length(x)), m = NULL, string = NULL) { # 1 is not null, other all null stringnull <- ! is.null(string) mnull <- ! is.null(m) xnnull <- ! is.null(x) & ! is.null(n) null3 <- sum(stringnull+mnull+xnnull) if (null3 != 1) stop("One and only one of x/n, m, string should not be NULL.") if (xnnull) { if (!is.list(x)) stop("x must be a list.") if (!is.numeric(n)) stop("n must be numeric.") if (length(x) == 0) stop("x must be of length larger than 0.") if (length(x) != length(n)) stop("x and n must be of the same length.") all_cl <- sapply(x, is.vector) if (any(all_cl == FALSE)) stop("Every element of list x should be of class vector.") } if (stringnull) { if (!is.character(string)) stop("string must be a character vector.") if (!is.vector(string)) stop("string must be a character vector.") if (length(string) == 0) stop("string must have at least 1 element.") string <- gsub("^\\W+|\\W+$", "", string) n <- c() x <- list() for (i in 1:length(string)) { ii <- unlist(strsplit(string[i], "\\W+")) if (length(ii) < 2) stop("Each string must have two parts, the 1st is the amount of the ballots, the 2nd contains candidate names.") n[i] <- ii[1] iii <- ii[-1] iii[iii == "NA"] <- NA x[[i]] <- iii } n <- suppressWarnings(as.numeric(n)) if (any(is.na(n))) stop("Coercion fails. You should make sure the 1st valid part of each string is something numeric.") } nis0 <- which(n == 0) if (length(nis0) == length(n)) stop("There is actually no ballot.") if (xnnull == TRUE | stringnull == TRUE){ if (length(nis0) > 0) { n <- n[-nis0] x <- x[-nis0] } LL=x[rep(seq_len(length(x)), n)] names(LL) <- NULL } if (mnull == TRUE){ LL=m[rep(seq_len(nrow(m)), n), ] rownames(LL) <- NULL colnames(LL) <- colnames(m) } LL }
/scratch/gouwar.j/cran-all/cranData/votesys/R/list2ballot.R
#' @title Voting Systems, Instant-Runoff Voting, Borda Method, Various Condorcet Methods #' #' @description #' This package provides different methods for counting ballots, which #' can be used in election, decision making and evaluation. The basic #' idea is: different forms of ballots can all be transformed into a #' score matrix; then the score matrix can be put into different #' counting methods. The functions #' in this package provide more flexibility to deal with duplicated #' values (ties) and missing values. And the comparison of results #' of different methods is also made easy. #' #' @docType package #' @name votesys-package #' @aliases votesys #' @rdname votesys-package #' @author Jiang Wu #' @family votesys_general_topics #' @examples #' # Suppose we have the following ballot data #' raw <- list2ballot( #' x = list( #' c('m', 'n', 'c', 'k'), c('n', 'c', 'k', 'm'), #' c('c', 'k', 'n', 'm'), c('k', 'c', 'n', 'm'), c(NA, NA, NA, NA) #' ) , #' n = c(42, 26, 15, 17, 3) #' ) #' #' # Step 1: check validity of ballots. Delete #' # some of them, if needed. #' check_validity <- check_dup_wrong(raw, #' xtype = 3, #' candidate = c("m", "n", "k", "c") #' ) #' raw <- raw[- check_validity$row_all_na] #' #' # Step 2: create a vote object #' vote <- create_vote(raw, xtype = 3, candidate = c("m", "n", "k", "c")) #' #' # Step 3: use one or more methods #' y <- plurality_method(vote) # winner is m #' y <- irv_method(vote) # winner is k #' y <- cdc_simple(vote) # winner is n #' y <- cdc_rankedpairs(vote) # winner is n NULL
/scratch/gouwar.j/cran-all/cranData/votesys/R/package-votesys.R
#' Plurality Method to Find Absolute or Relative Majority #' #' Although with plurality method each voter is required to mention #' only one candidate, a ballot with more than one candidate and #' different scores is also valid. For a score matrix, the function will #' check the position j which has the lowest score (in a \code{vote} object, #' the lower, the better) in the ith row. Duplicated values may or may #' not be a problem. For instance, \code{c(2, 3, 3)} is valid, for the #' lowest value is 2 and it is in the 1st position. However, #' \code{c(2, 2, 3)} is a problem, for the 1st and 2nd positions #' all have the lowest value 2. If this problem exists, the winner #' returned by this function will be NULL. #' #' @param x an object of class \code{vote}. #' @param allow_dup whether ballots with duplicated score values #' are taken into account. Default is TRUE. #' @param min_valid default is 1. If the number of valid entries of #' a ballot is less than this value, the ballot will not be used. #' #' @return a list object. #' \itemize{ #' \item (1) \code{call} the function call. #' \item (2) \code{method} the counting method. #' \item (3) \code{candidate} candidate names. #' \item (4) \code{candidate_num} number of candidate. #' \item (5) \code{ballot_num} number of ballots in x. #' \item (6) \code{valid_ballot_num} number of ballots that are #' used to compute the result. #' \item (7) \code{winner} the winners, may be one, more than one or NULL. #' \item (8) \code{absolute} whether the winner is of absolute majority. #' \item (9) \code{other_info} a list with 2 elements, the 1st is the #' frequencies of candidates mentioned as 1st choice; the second element is #' the percentage. If winner is NULL, these two are NULL. #' } #' #' @export #' @examples #' raw <- rbind( #' c(1, 2, 5, 3, 3), c(1, 2, 5, 3, 4), c(1, 2, 5, 3, 4), #' c(NA, NA, NA, NA, NA), c(NA, 3, 5, 1, 2), #' c(NA, NA, NA, 2, 3), c(NA, NA, 1, 2, 3), #' c(NA, NA, NA, NA, 2), c(NA, NA, NA, 2, 2), #' c(NA, NA, 1, 1, 2), c(1, 1, 5, 5, NA) #' ) #' vote <- create_vote(raw, xtype = 1) #' y <- plurality_method(vote, allow_dup = FALSE) #' y <- plurality_method(vote, allow_dup=FALSE, min_valid = 3) plurality_method <- function(x, allow_dup = TRUE, min_valid = 1) { method <- "plurality" if (!class(x)[1] == "vote") stop("x must be a vote object.") if (min_valid < 1) stop("Minimux number of min_valid is 1.") candidate <- x$candidate NBALLOT <- x$ballot_num candidate_num <- x$candidate_num stopifnot(allow_dup %in% c(TRUE, FALSE)) should_del <- c() if (allow_dup == FALSE & length(x$row_with_dup) != 0) should_del <- append(should_del, x$row_with_dup) if (length(x$row_with_na) > 0) { get_na_ok <- which(x$num_non_na < min_valid) if (length(get_na_ok) > 0) should_del <- append(should_del, x$row_with_na[get_na_ok]) } should_del <- unique(should_del) length_should_del <- length(should_del) VALID_BALLOT_NUM <- NBALLOT - length_should_del if (VALID_BALLOT_NUM == 0) stop("No ballot is OK.") x <- if (length_should_del > 0) x$ballot[-should_del, ] else x$ballot message("SELECTING") mAjtOp <- function(x) if (length(which(x == min(x, na.rm = TRUE))) == 1) which.min(x) else -1 W <- apply(x, 1, mAjtOp) over <- list(call = match.call(), method = method, candidate = candidate, candidate_num = candidate_num, ballot_num = NBALLOT, valid_ballot_num = VALID_BALLOT_NUM, winner = NULL, absolute = NULL, other_info = NULL) message("COLLECTING RESULT") if (any(W == -1)) { over$other_info <- list(count = NULL, percent = NULL) } else { W <- append(W, 1:candidate_num) tta <- table(W) - 1 table_name <- candidate[as.numeric(names(tta))] each_have <- as.numeric(tta) whowin <- which(each_have == max(each_have)) over$winner <- candidate[whowin] percent <- each_have/sum(each_have) over$absolute <- if (any(percent > 0.5)) TRUE else FALSE names(each_have) <- table_name names(percent) <- table_name over$other_info <- list(count = each_have, percent = percent) } message("DONE") return(over) }
/scratch/gouwar.j/cran-all/cranData/votesys/R/plurality_method.R
#' User Preference Aggregation #' #' The function uses a simple method to #' calculate the aggregation scores of user #' ratings, which is described #' in Langville, A. and Meyer, C. (2012: 128). #' Input data can be stored in a sparse matrix. #' Suppose there are 100 films and users are required to assign #' scores. However, each user only watched several of them. Thus, #' when comparing two films A and B, the method only takes account #' ratings from those who watched both A and B. #' #' @param x a numeric matrix, or, \code{dgCMatrix} and #' \code{dgeMatrix} matrix created with the Matrix package. #' 0 in the data means no score is given; and valid score values #' should all be larger than 0. The function will do NOTHING #' to check the validity. #' Besides, NA also means no score is given. If your data has NA, #' set \code{check_na} to TRUE so as to convert NA to 0. #' @param show_name the default is FALSE, that is to say, the function #' does not store and show candidate names in the result and you #' cannot see them. However, you can set it to TRUE. #' @param check_na if it is TRUE, the function will check NAs and convert #' them to 0s. If NAs do exist and \code{check_na} is FALSE, error will be #' raised. #' #' @return a list object. #' \itemize{ #' \item (1) \code{call} the function call. #' \item (2) \code{method} the counting method. #' \item (3) \code{candidate} candidate names. If #' \code{show_name} is FALSE, this will be NULL. #' \item (4) \code{candidate_num} number of candidate. #' \item (5) \code{ballot_num} number of ballots in x. #' \item (6) \code{valid_ballot_num} number of ballots that are #' used to compute the result. #' \item (7) \code{winner} the winner. If \code{show_name} is FALSE, #' this only shows the number in \code{1: ncol(x)}. #' \item (8) \code{winner_score} the winner's score, which is the highest score. #' \item (9) \code{other_info} scores of all the candidates. #' } #' #' @references #' \itemize{ #' \item Langville, A. and Meyer, C. 2012. #' Who's #1? The Science of Rating and Ranking. #' Princeton University Press, p. 128. #' } #' #' @import Matrix #' @export #' @examples #' # Example from Langville and Meyer, 2012: 128. #' # 4 films are rated by 10 users; 0 means no score. #' raw <- c(4, 3, 1, 2, 0, 2, 0, 3, 0, 2, 2, 1, 0, 4, 3, 3, 4, #' 1, 3, 0, 2, 0, 2, 2, 2, 0, 1, 1, 2, 2, 0, 2, 0, 0, 5, 0, 3, #' 0, 5, 4 #' ) #' m <- matrix(raw, ncol = 4) #' colnames(m) <- paste("film", 1: 4, sep = "") #' y <- star_rating(m, show_name = TRUE) # winner is film4 star_rating=function(x, show_name=FALSE, check_na=TRUE){ method="star" class1=class(x)[1] stopifnot(check_na %in% c(TRUE, FALSE)) stopifnot(show_name %in% c(TRUE, FALSE)) if (! class1 %in% c("matrix", "dgCMatrix", "dgeMatrix")) stop('x must be of class matrix, dgeMatrix or dgCMatrix.') nc=ncol(x) nr=nrow(x) if (nc<2 | nr<2) stop('At least 2 rows and 2 columns.') candidate=colnames(x) # later deal with null names colnames(x) = NULL if (check_na) x[is.na(x)] <- 0 message("The function assumes that 0 means no score is given, and, all other valid score values should be larger than 0. The function do NOT automatically check validity, so please make sure.") # S matrix # num of co_raters message("SELECTING") s_matrix=Matrix::Matrix(0, nrow=nc, ncol=nc) # for every col of raw data, p, q for (p in 1: nc){ for (q in 1: nc){ if (p<q){ rate_co=x[pmin(x[, p], x[, q]) != 0, c(p, q)] if (! is.vector(rate_co)){ n_co=nrow(rate_co) } else { n_co=1 rate_co=matrix(rate_co, nrow=1) } if (nrow(rate_co)>0){ s_matrix[p, q] <- sum(rate_co[, 1])/n_co s_matrix[q, p] <- sum(rate_co[, 2])/n_co } } } } # K matrix k_matrix=Matrix::Matrix(0, nrow=nc, ncol=nc) for (p in 1: nc){ for (q in 1: nc){ if (p>q){ kpq=s_matrix[p, q]-s_matrix[q, p] k_matrix[p, q] <- kpq k_matrix[q, p] <- -kpq } } } # r r=Matrix::rowSums(k_matrix)/nc maxr=max(r) if (is.na(maxr)) stop("NAs exist in your data, please check !") winner=which(r==maxr) message("COLLECTING RESULT") if (show_name==FALSE){ over <- list(call = match.call(), method = method, candidate = NULL, candidate_num = nc, ballot_num = nr, valid_ballot_num = nr, winner = winner, winner_score=maxr, other_info = list(all_score=r)) } if (show_name==TRUE){ candidate=if (!is.null(candidate)) candidate else fUll_dIgIt(nc) names(r)=candidate over <- list(call = match.call(), method = method, candidate = candidate, candidate_num = nc, ballot_num = nr, valid_ballot_num = nr, winner = candidate[winner], winner_score=maxr, other_info = list(all_score=r) ) } if (length(over$winner)==0) over$winner=NULL message("DONE") return(over) }
/scratch/gouwar.j/cran-all/cranData/votesys/R/star_rating.R
vottrans <- function(Ro,Rn,v=1,nw=FALSE){ X2<-Ro; Y2<-Rn # Ro beinhaltet die Ergebnisse der Vergleichswahl in Absolutzahlen; Rn die der aktuellen Wahl; die erste Spalte muss die Anzahl der Wahlberechtigten enthalten N1<-nrow(X2); I<-ncol(X2)-1; J<- ncol(Y2)-1 # N= Anzahl der Gemeinden/Sprengel, I= Anzahl der Parteien bei der Vergleichswahl; I=Anzahl der Parteien bei er aktuellen Wahl if(nw==TRUE){Y2[,(I+1)]<-Y2[,(I+1)]+Y2[,1]-X2[,1]} #Option, welche die Differenz der Wahlberechtigten zur Anzahl der NW bei der aktuellen Wahl addiert loeschen<-function(A){k<-1; b<-ncol(A); while(k<(N1+1)){if(A[k,b]<0){A<-A[-k,]; N1<-N1-1} else{k<-k+1}};return(A)} # Loescht Eintraege mit negativen Werten fuer Nichtwaehler X<-loeschen(X2) Y<-loeschen(Y2) N<-nrow(X) Xabs<-X[,-1];Yabs<-Y[,-1]; #Erstellt Matrix, welche die Ergebnisse ohne die erste Spalte enthaelt Diag<-function(X){E<-X[,1]; DD<- matrix(0,N,N) ; for(i in 1:N){DD[i,i]<-E[i]};return(DD)} # erstellt eine Diagonalmatrix deren Eintraege die Anzahl der Wahlberechtigten sind DD<-Diag(Y) Xpro<-solve(Diag(X))%*% Xabs Ypro<-solve(Diag(Y))%*% Yabs #berechnet die Ergebnismatrix in Prozent teilcode<-function(A,i){r<-nrow(A); teilcode<-matrix(7,r,1); k<-1; while(k<i){teilcode<-cbind(teilcode, matrix(0,r,I)); k<-k+1}; teilcode<-cbind(teilcode,A); k<-0 ; while(k<(J-i)){teilcode<-cbind(teilcode,matrix(0,r,I));k<-k+1}; teilcode<-teilcode[,-1];return(teilcode)} #erstellt zeilenweise Teile der geblockten Matrix DD geblockt<-function(A){geblockt<-matrix(7,1,ncol(A)*J); k<-1; while(k<(J+1)){geblockt<-rbind(geblockt,teilcode(A,k)); k<-k+1};geblockt<-geblockt[-1,]; return(geblockt)} #erstellt eine grosze geblockte Matrix mit den Elementen von 'teilcode' Ygeb<-function(C){Ygeb<-c(1); k<-1; while(k<(J+1)){Ygeb<-matrix(rbind(Ygeb,matrix(c(C[,k]))),ncol=1); k<-k+1}; Ygeb<-Ygeb[-1,]; return(Ygeb)} Y1<-Ygeb(Ypro) # blockt die aktuellen Ergebnisse der einzelnen Parteien zu einem Spaltenvektor summe<-function(F){summe<-c(1); ges<-sum(F[,1]); k<-2; while(k< (ncol(F)+1)){summe<-cbind(summe,sum(F[,k])/ges); k<-k+1}; summe<-summe[,-1]; return(summe)} summealt<-summe(X) summeneu<-summe(Y) #berechnet die Gesamtergebnisse der Vorwahl der einzelnen Parteien teila<-function(){teila<-matrix(7,I,1); k<-0; while(k<J){teila<-cbind(teila,diag(I)); k<-k+1}; teila<-teila[,-1]; return(teila)} teilcode1<-function(i){teilcode1<-c(7); k<-1 ; while(k<i){teilcode1<-cbind(teilcode1, matrix(0,1,I)); k<-k+1}; teilcode1<-cbind(teilcode1, matrix(summealt,1)); k<-0; while(k<J-i){teilcode1<-cbind(teilcode1,matrix(0,1,I)); k<-k+1}; teilcode1<-teilcode1[,-1]; return(teilcode1)} #erstellt ersten Teil der Nebenbedingungsmatrix Amat teilb<-function(){teilb<-matrix(7,1,I*J); k<-1; while(k<(J+1)){teilb<-rbind(teilb,teilcode1(k)); k<-k+1}; teilb<-teilb[-1,]; return(teilb)} #erstellt zweiten Teil der Nebenbedingungsmatrix Amat Amat<-rbind(teila(),teilb(),diag(I*J)) bvec<-rbind(matrix(1,I,1),matrix(summeneu,ncol=1),matrix(0,I*J,1)) if(v ==1){vottrans<-solve.QP(geblockt(t(Xpro)%*%Xabs)*1e-9,t(Y1%*%geblockt(Xabs))*1e-9,t(Amat),bvec,meq=2*I)} if(v ==2){vottrans<-solve.QP(geblockt(t(Xpro)%*%Xpro)*1e-9,t(Y1%*%geblockt(Xpro))*1e-9,t(Amat),bvec,meq=2*I)} if(v ==3){vottrans<-solve.QP(geblockt(t(Xabs)%*%Xabs)*1e-9,t(Y1%*%geblockt(Xabs))*1e-9,t(Amat),bvec,meq=2*I)} solution1<-vottrans[1] teil<-function(A,n){teil<-c(1); for(k in (I*(n-1)+1):(I*n)){teil<-rbind(teil,A[[1]][k]); k<-k+1}; teil<-teil[-1,]} gesamtf<-function(A){gesamtf<-matrix(7,I,1); for(k in 1:J){gesamtf<-cbind(gesamtf, teil(A,k)); k<-k+1}; gesamtf<-gesamtf[,-1]; return(gesamtf)} gesamt<-gesamtf(solution1) #waehlt die gewuenschte Loesung aus der Ausgabe von solve.QP aus und formt diese in eine Matrix mit den Uebergangswahrscheinlichkeiten um. return(gesamt) }
/scratch/gouwar.j/cran-all/cranData/vottrans/R/vottrans.R
null_transformer <- function(str = "NULL") { function(text, envir) { out <- glue::identity_transformer(text, envir) if (is.null(out)) { return(str) } out } } parse_duration <- function(duration) { if (!is.null(duration)) { if (!duration %in% c("fastest", "faster", "fast", "slow", "slower", "slowest")) { warning( call. = FALSE, "You gave [", duration, "] but `duration` expects one of:", paste("\n*", c("fastest", "faster", "fast", "slow", "slower", "slowest")), "\n~ Defaulting to [fast]" ) "fast" } else { duration } } } parse_delay <- function(delay) { if (!is.null(delay)) { if (!delay %in% c("0", "1", "2", "3", "4", "5")) { warning( call. = FALSE, "You gave [", delay, "] but `delay` expects one of:", paste("\n*", c("0", "1", "2", "3", "4", "5")), "\n~ Defaulting to [NULL], no delay" ) NULL } else { glue::glue("t-{delay}") } } } parse_steps <- function(steps) { if (!is.null(steps)) { if (!steps %in% c("10", "20", "30", "40", "50")) { warning( call. = FALSE, "You gave [", steps, "] but `steps` expects one of:", paste("\n*", c("10", "20", "30", "40", "50")), "\n~ Defaulting to [NULL], no steps" ) NULL } else { glue::glue("f-{steps}") } } } parse_iteration <- function(iteration) { if (!is.null(iteration)) { if (iteration != "infinite") { if (!iteration %in% c("1", "2", "3", "4", "5")) { warning( call. = FALSE, "You gave [", iteration, "] but `iteration` expects one of:", paste("\n*", c("1", "2", "3", "4", "5")), "\n~ Defaulting to [NULL], no iteration" ) NULL } else { glue::glue("c-{iteration}") } } else { "infinite" } } } parse_animation <- function(class, duration, delay, steps, iteration) { duration <- parse_duration(duration) delay <- parse_delay(delay) steps <- parse_steps(steps) iteration <- parse_iteration(iteration) x <- glue::glue( "vov {class} {duration} {delay} {steps} {iteration}", .transformer = null_transformer("") ) trimws(gsub("\\s+", " ", x)) }
/scratch/gouwar.j/cran-all/cranData/vov/R/utils.R
vov_params <- function() { c( '@param ui A UI element', '@param duration Duration of animation', '@param delay Delay in seconds before animation starts', '@param steps Animation steps', '@param iteration Iteration of animation', '@details \\itemize{ \\item Duration expects one of: "fast" = 800 milliseconds, "faster" = 500 milliseconds, "fastest" = 300 milliseconds, "slow" = 2 seconds, "slower" = 3 seconds, "slowest" = 4 seconds, \\item Delay expects one of: 0, 1, 2, 3, 4, 5, no delay if left NULL \\item Steps expects one of: 10, 20, 30, 40, 50, no steps if left NULL \\item Iteration expects one of: 1, 2, 3, 4, 5, infinite, no iteration if left NULL }' ) } # vov_details <- function() { # '@details # \\itemize{ # \\item Duration expects one of: "fast" = 800 milliseconds, "faster" = 500 milliseconds, "fastest" = 300 milliseconds, "slow" = 2 seconds, "slower" = 3 seconds, "slowest" = 4 seconds, # \\item Delay expects one of: 1, 2, 3, 4, 5, no delay if left NULL # \\item Steps expects one of: 10, 20, 30, 40, 50, no steps if left NULL # \\item Iteration expects one of: 1, 2, 3, 4, 5, infinite, no iteration if left NULL # }' # } #' Use the vov package #' #' @description Enables vov by including the CSS file necessary for the #' animations. #' #' @examples #' if (interactive()) { #' library(shiny) #' library(vov) #' #' ui <- fluidPage( #' use_vov(), #' fade_in( #' h1("Hello world!") #' ) #' ) #' #' server <- function(input, output, session) {} #' #' shinyApp(ui, server) #' } #' @export use_vov <- function() { css <- system.file("extdata", "vov.css", package = "vov") shiny::includeCSS(css) } #' Run a demo application #' #' @description Run a demo version of the app to try out all the animations. #' #' @examples #' if (interactive()) { #' run_demo() #' } #' @export run_demo <- function() { shiny::runApp(system.file("extdata", "app.R", package = "vov")) } #' Fade in bottom left #' #' @description Animation to fade in a UI element from the bottom left. #' #' @eval vov_params() #' #' @examples #' if (interactive()) { #' library(shiny) #' library(vov) #' #' ui <- fluidPage( #' use_vov(), #' fade_in_bottom_left( #' h1("Hello world!") #' ) #' ) #' #' server <- function(input, output, session) {} #' #' shinyApp(ui, server) #' } #' @export fade_in_bottom_left <- function(ui, duration = NULL, delay = NULL, steps = NULL, iteration = NULL) { x <- parse_animation("fade-in-bottom-left", duration, delay, steps, iteration) htmltools::tagAppendAttributes(ui, class = x) } #' Fade in bottom right #' #' @description Animation to fade in a UI element from the bottom right. #' #' @eval vov_params() #' #' @examples #' if (interactive()) { #' library(shiny) #' library(vov) #' #' ui <- fluidPage( #' use_vov(), #' fade_in_bottom_right( #' h1("Hello world!") #' ) #' ) #' #' server <- function(input, output, session) {} #' #' shinyApp(ui, server) #' } #' @export fade_in_bottom_right <- function(ui, duration = NULL, delay = NULL, steps = NULL, iteration = NULL) { x <- parse_animation("fade-in-bottom-right", duration, delay, steps, iteration) htmltools::tagAppendAttributes(ui, class = x) } #' Fade in down #' #' @description Animation to fade in a UI element downward. #' #' @eval vov_params() #' #' @examples #' if (interactive()) { #' library(shiny) #' library(vov) #' #' ui <- fluidPage( #' use_vov(), #' fade_in_down( #' h1("Hello world!") #' ) #' ) #' #' server <- function(input, output, session) {} #' #' shinyApp(ui, server) #' } #' @export fade_in_down <- function(ui, duration = NULL, delay = NULL, steps = NULL, iteration = NULL) { x <- parse_animation("fade-in-down", duration, delay, steps, iteration) htmltools::tagAppendAttributes(ui, class = x) } #' Fade in left #' #' @description Animation to fade in a UI element from the left. #' #' @eval vov_params() #' #' @examples #' if (interactive()) { #' library(shiny) #' library(vov) #' #' ui <- fluidPage( #' use_vov(), #' fade_in_left( #' h1("Hello world!") #' ) #' ) #' #' server <- function(input, output, session) {} #' #' shinyApp(ui, server) #' } #' @export fade_in_left <- function(ui, duration = NULL, delay = NULL, steps = NULL, iteration = NULL) { x <- parse_animation("fade-in-left", duration, delay, steps, iteration) htmltools::tagAppendAttributes(ui, class = x) } #' Fade in right #' #' @description Animation to fade in a UI element from the right. #' #' @eval vov_params() #' #' @examples #' if (interactive()) { #' library(shiny) #' library(vov) #' #' ui <- fluidPage( #' use_vov(), #' fade_in_right( #' h1("Hello world!") #' ) #' ) #' #' server <- function(input, output, session) {} #' #' shinyApp(ui, server) #' } #' @export fade_in_right <- function(ui, duration = NULL, delay = NULL, steps = NULL, iteration = NULL) { x <- parse_animation("fade-in-right", duration, delay, steps, iteration) htmltools::tagAppendAttributes(ui, class = x) } #' Fade in top left #' #' @description Animation to fade in a UI element from the top left. #' #' @eval vov_params() #' #' @examples #' if (interactive()) { #' library(shiny) #' library(vov) #' #' ui <- fluidPage( #' use_vov(), #' fade_in_top_left( #' h1("Hello world!") #' ) #' ) #' #' server <- function(input, output, session) {} #' #' shinyApp(ui, server) #' } #' @export fade_in_top_left <- function(ui, duration = NULL, delay = NULL, steps = NULL, iteration = NULL) { x <- parse_animation("fade-in-top-left", duration, delay, steps, iteration) htmltools::tagAppendAttributes(ui, class = x) } #' Fade in top right #' #' @description Animation to fade in a UI element from the top right. #' #' @eval vov_params() #' #' @examples #' if (interactive()) { #' library(shiny) #' library(vov) #' #' ui <- fluidPage( #' use_vov(), #' fade_in_top_right( #' h1("Hello world!") #' ) #' ) #' #' server <- function(input, output, session) {} #' #' shinyApp(ui, server) #' } #' @export fade_in_top_right <- function(ui, duration = NULL, delay = NULL, steps = NULL, iteration = NULL) { x <- parse_animation("fade-in-top-right", duration, delay, steps, iteration) htmltools::tagAppendAttributes(ui, class = x) } #' Fade in up #' #' @description Animation to fade in a UI element upward. #' #' @eval vov_params() #' #' @examples #' if (interactive()) { #' library(shiny) #' library(vov) #' #' ui <- fluidPage( #' use_vov(), #' fade_in_up( #' h1("Hello world!") #' ) #' ) #' #' server <- function(input, output, session) {} #' #' shinyApp(ui, server) #' } #' @export fade_in_up <- function(ui, duration = NULL, delay = NULL, steps = NULL, iteration = NULL) { x <- parse_animation("fade-in-up", duration, delay, steps, iteration) htmltools::tagAppendAttributes(ui, class = x) } #' Fade in #' #' @description Animation to fade in a UI element. #' #' @eval vov_params() #' #' @examples #' if (interactive()) { #' library(shiny) #' library(vov) #' #' ui <- fluidPage( #' use_vov(), #' fade_in( #' h1("Hello world!") #' ) #' ) #' #' server <- function(input, output, session) {} #' #' shinyApp(ui, server) #' } #' @export fade_in <- function(ui, duration = NULL, delay = NULL, steps = NULL, iteration = NULL) { x <- parse_animation("fade-in", duration, delay, steps, iteration) htmltools::tagAppendAttributes(ui, class = x) } #' Fade out bottom left #' #' @description Animation to fade out (disappear) a UI element from the #' bottom left. #' #' @eval vov_params() #' #' @examples #' if (interactive()) { #' library(shiny) #' library(vov) #' #' ui <- fluidPage( #' use_vov(), #' fade_out_bottom_left( #' h1("Hello world!") #' ) #' ) #' #' server <- function(input, output, session) {} #' #' shinyApp(ui, server) #' } #' @export fade_out_bottom_left <- function(ui, duration = NULL, delay = NULL, steps = NULL, iteration = NULL) { x <- parse_animation("fade-out-bottom-left", duration, delay, steps, iteration) htmltools::tagAppendAttributes(ui, class = x) } #' Fade out bottom right #' #' @description Animation to fade out (disappear) a UI element from the #' bottom right #' #' @eval vov_params() #' #' @examples #' if (interactive()) { #' library(shiny) #' library(vov) #' #' ui <- fluidPage( #' use_vov(), #' fade_out_bottom_right( #' h1("Hello world!") #' ) #' ) #' #' server <- function(input, output, session) {} #' #' shinyApp(ui, server) #' } #' @export fade_out_bottom_right <- function(ui, duration = NULL, delay = NULL, steps = NULL, iteration = NULL) { x <- parse_animation("fade-out-bottom-right", duration, delay, steps, iteration) htmltools::tagAppendAttributes(ui, class = x) } #' Fade out down #' #' @description Animation to fade out (disappear) a UI element downward. #' #' @eval vov_params() #' #' @examples #' if (interactive()) { #' library(shiny) #' library(vov) #' #' ui <- fluidPage( #' use_vov(), #' fade_out_down( #' h1("Hello world!") #' ) #' ) #' #' server <- function(input, output, session) {} #' #' shinyApp(ui, server) #' } #' @export fade_out_down <- function(ui, duration = NULL, delay = NULL, steps = NULL, iteration = NULL) { x <- parse_animation("fade-out-down", duration, delay, steps, iteration) htmltools::tagAppendAttributes(ui, class = x) } #' Fade out left #' #' @description Animation to fade out (disappear) a UI element from the left. #' #' @eval vov_params() #' #' @examples #' if (interactive()) { #' library(shiny) #' library(vov) #' #' ui <- fluidPage( #' use_vov(), #' fade_out_left( #' h1("Hello world!") #' ) #' ) #' #' server <- function(input, output, session) {} #' #' shinyApp(ui, server) #' } #' @export fade_out_left <- function(ui, duration = NULL, delay = NULL, steps = NULL, iteration = NULL) { x <- parse_animation("fade-out-left", duration, delay, steps, iteration) htmltools::tagAppendAttributes(ui, class = x) } #' Fade out right #' #' @description Animation to fade out (disappear) a UI element from the right. #' #' @eval vov_params() #' #' @examples #' if (interactive()) { #' library(shiny) #' library(vov) #' #' ui <- fluidPage( #' use_vov(), #' fade_out_right( #' h1("Hello world!") #' ) #' ) #' #' server <- function(input, output, session) {} #' #' shinyApp(ui, server) #' } #' @export fade_out_right <- function(ui, duration = NULL, delay = NULL, steps = NULL, iteration = NULL) { x <- parse_animation("fade-out-right", duration, delay, steps, iteration) htmltools::tagAppendAttributes(ui, class = x) } #' Fade out top left #' #' @description Animation to fade out (disappear) a UI element from the top #' left. #' #' @eval vov_params() #' #' @examples #' if (interactive()) { #' library(shiny) #' library(vov) #' #' ui <- fluidPage( #' use_vov(), #' fade_out_top_left( #' h1("Hello world!") #' ) #' ) #' #' server <- function(input, output, session) {} #' #' shinyApp(ui, server) #' } #' @export fade_out_top_left <- function(ui, duration = NULL, delay = NULL, steps = NULL, iteration = NULL) { x <- parse_animation("fade-out-top-left", duration, delay, steps, iteration) htmltools::tagAppendAttributes(ui, class = x) } #' Fade out top right #' #' @description Animation to fade out (disappear) a UI element from the top #' right. #' #' @eval vov_params() #' #' @examples #' if (interactive()) { #' library(shiny) #' library(vov) #' #' ui <- fluidPage( #' use_vov(), #' fade_out_top_right( #' h1("Hello world!") #' ) #' ) #' #' server <- function(input, output, session) {} #' #' shinyApp(ui, server) #' } #' @export fade_out_top_right <- function(ui, duration = NULL, delay = NULL, steps = NULL, iteration = NULL) { x <- parse_animation("fade-out-top-right", duration, delay, steps, iteration) htmltools::tagAppendAttributes(ui, class = x) } #' Fade out up #' #' @description Animation to fade out (disappear) a UI element upwards. #' #' @eval vov_params() #' #' @examples #' if (interactive()) { #' library(shiny) #' library(vov) #' #' ui <- fluidPage( #' use_vov(), #' fade_out_up( #' h1("Hello world!") #' ) #' ) #' #' server <- function(input, output, session) {} #' #' shinyApp(ui, server) #' } #' @export fade_out_up <- function(ui, duration = NULL, delay = NULL, steps = NULL, iteration = NULL) { x <- parse_animation("fade-out-up", duration, delay, steps, iteration) htmltools::tagAppendAttributes(ui, class = x) } #' Fade out #' #' @description Animation to fade out (disappear) a UI element. #' #' @eval vov_params() #' #' @examples #' if (interactive()) { #' library(shiny) #' library(vov) #' #' ui <- fluidPage( #' use_vov(), #' fade_out( #' h1("Hello world!") #' ) #' ) #' #' server <- function(input, output, session) {} #' #' shinyApp(ui, server) #' } #' @export fade_out <- function(ui, duration = NULL, delay = NULL, steps = NULL, iteration = NULL) { x <- parse_animation("fade-out", duration, delay, steps, iteration) htmltools::tagAppendAttributes(ui, class = x) } #' Roll in left #' #' @description Animation to roll in a UI element from the left. #' #' @eval vov_params() #' #' @examples #' if (interactive()) { #' library(shiny) #' library(vov) #' #' ui <- fluidPage( #' use_vov(), #' roll_in_left( #' h1("Hello world!") #' ) #' ) #' #' server <- function(input, output, session) {} #' #' shinyApp(ui, server) #' } #' @export roll_in_left <- function(ui, duration = NULL, delay = NULL, steps = NULL, iteration = NULL) { x <- parse_animation("roll-in-left", duration, delay, steps, iteration) htmltools::tagAppendAttributes(ui, class = x) } #' Roll in right #' #' @description Animation to roll in a UI element from the right. #' #' @eval vov_params() #' #' @examples #' if (interactive()) { #' library(shiny) #' library(vov) #' #' ui <- fluidPage( #' use_vov(), #' roll_in_right( #' h1("Hello world!") #' ) #' ) #' #' server <- function(input, output, session) {} #' #' shinyApp(ui, server) #' } #' @export roll_in_right <- function(ui, duration = NULL, delay = NULL, steps = NULL, iteration = NULL) { x <- parse_animation("roll-in-right", duration, delay, steps, iteration) htmltools::tagAppendAttributes(ui, class = x) } #' Roll out left #' #' @description Animation to roll out (disappear) a UI element from the left. #' #' @eval vov_params() #' #' @examples #' if (interactive()) { #' library(shiny) #' library(vov) #' #' ui <- fluidPage( #' use_vov(), #' roll_out_left( #' h1("Hello world!") #' ) #' ) #' #' server <- function(input, output, session) {} #' #' shinyApp(ui, server) #' } #' @export roll_out_left <- function(ui, duration = NULL, delay = NULL, steps = NULL, iteration = NULL) { x <- parse_animation("roll-out-left", duration, delay, steps, iteration) htmltools::tagAppendAttributes(ui, class = x) } #' Roll out right #' #' @description Animation to roll out (disappear) a UI element from the right. #' #' @eval vov_params() #' #' @examples #' if (interactive()) { #' library(shiny) #' library(vov) #' #' ui <- fluidPage( #' use_vov(), #' roll_out_right( #' h1("Hello world!") #' ) #' ) #' #' server <- function(input, output, session) {} #' #' shinyApp(ui, server) #' } #' @export roll_out_right <- function(ui, duration = NULL, delay = NULL, steps = NULL, iteration = NULL) { x <- parse_animation("roll-out-right", duration, delay, steps, iteration) htmltools::tagAppendAttributes(ui, class = x) } #' Shake vertical #' #' @description Animation to shake a UI element vertically. #' #' @eval vov_params() #' #' @examples #' if (interactive()) { #' library(shiny) #' library(vov) #' #' ui <- fluidPage( #' use_vov(), #' shake_vertical( #' h1("Hello world!") #' ) #' ) #' #' server <- function(input, output, session) {} #' #' shinyApp(ui, server) #' } #' @export shake_vertical <- function(ui, duration = NULL, delay = NULL, steps = NULL, iteration = NULL) { x <- parse_animation("shake-vertical", duration, delay, steps, iteration) htmltools::tagAppendAttributes(ui, class = x) } #' Shake horizontal #' #' @description Animation to shake a UI element horizontally. #' #' @eval vov_params() #' #' @examples #' if (interactive()) { #' library(shiny) #' library(vov) #' #' ui <- fluidPage( #' use_vov(), #' shake_horizontal( #' h1("Hello world!") #' ) #' ) #' #' server <- function(input, output, session) {} #' #' shinyApp(ui, server) #' } #' @export shake_horizontal <- function(ui, duration = NULL, delay = NULL, steps = NULL, iteration = NULL) { x <- parse_animation("shake-horizontal", duration, delay, steps, iteration) htmltools::tagAppendAttributes(ui, class = x) } #' Shake diagonally #' #' @description Animation to shake a UI element diagonally. #' #' @eval vov_params() #' #' @examples #' if (interactive()) { #' library(shiny) #' library(vov) #' #' ui <- fluidPage( #' use_vov(), #' shake_diagonally( #' h1("Hello world!") #' ) #' ) #' #' server <- function(input, output, session) {} #' #' shinyApp(ui, server) #' } #' @export shake_diagonally <- function(ui, duration = NULL, delay = NULL, steps = NULL, iteration = NULL) { x <- parse_animation("shake-diagonally", duration, delay, steps, iteration) htmltools::tagAppendAttributes(ui, class = x) } #' Shake diagonally inverse #' #' @description Animation to shake a UI element diagonally. #' #' @eval vov_params() #' #' @examples #' if (interactive()) { #' library(shiny) #' library(vov) #' #' ui <- fluidPage( #' use_vov(), #' shake_i_diagonally( #' h1("Hello world!") #' ) #' ) #' #' server <- function(input, output, session) {} #' #' shinyApp(ui, server) #' } #' @export shake_i_diagonally <- function(ui, duration = NULL, delay = NULL, steps = NULL, iteration = NULL) { x <- parse_animation("shake-i-diagonally", duration, delay, steps, iteration) htmltools::tagAppendAttributes(ui, class = x) } #' Blur in #' #' @description Animation to blur in a UI element. #' #' @eval vov_params() #' #' @examples #' if (interactive()) { #' library(shiny) #' library(vov) #' #' ui <- fluidPage( #' use_vov(), #' blur_in( #' h1("Hello world!") #' ) #' ) #' #' server <- function(input, output, session) {} #' #' shinyApp(ui, server) #' } #' @export blur_in <- function(ui, duration = NULL, delay = NULL, steps = NULL, iteration = NULL) { x <- parse_animation("blur-in", duration, delay, steps, iteration) htmltools::tagAppendAttributes(ui, class = x) } #' Blur out #' #' @description Animation to blur out (disappear) a UI element. #' #' @eval vov_params() #' #' @examples #' if (interactive()) { #' library(shiny) #' library(vov) #' #' ui <- fluidPage( #' use_vov(), #' blur_out( #' h1("Hello world!") #' ) #' ) #' #' server <- function(input, output, session) {} #' #' shinyApp(ui, server) #' } #' @export blur_out <- function(ui, duration = NULL, delay = NULL, steps = NULL, iteration = NULL) { x <- parse_animation("blur-out", duration, delay, steps, iteration) htmltools::tagAppendAttributes(ui, class = x) } #' Slide in down #' #' @description Animation to slide in a UI element downward. #' #' @eval vov_params() #' #' @examples #' if (interactive()) { #' library(shiny) #' library(vov) #' #' ui <- fluidPage( #' use_vov(), #' slide_in_down( #' h1("Hello world!") #' ) #' ) #' #' server <- function(input, output, session) {} #' #' shinyApp(ui, server) #' } #' @export slide_in_down <- function(ui, duration = NULL, delay = NULL, steps = NULL, iteration = NULL) { x <- parse_animation("slide-in-down", duration, delay, steps, iteration) htmltools::tagAppendAttributes(ui, class = x) } #' Slide in left #' #' @description Animation to slide in a UI element from the left. #' #' @eval vov_params() #' #' @examples #' if (interactive()) { #' library(shiny) #' library(vov) #' #' ui <- fluidPage( #' use_vov(), #' slide_in_left( #' h1("Hello world!") #' ) #' ) #' #' server <- function(input, output, session) {} #' #' shinyApp(ui, server) #' } #' @export slide_in_left <- function(ui, duration = NULL, delay = NULL, steps = NULL, iteration = NULL) { x <- parse_animation("slide-in-left", duration, delay, steps, iteration) htmltools::tagAppendAttributes(ui, class = x) } #' Slide in right #' #' @description Animation to slide in a UI element from the right. #' #' @eval vov_params() #' #' @examples #' if (interactive()) { #' library(shiny) #' library(vov) #' #' ui <- fluidPage( #' use_vov(), #' slide_in_right( #' h1("Hello world!") #' ) #' ) #' #' server <- function(input, output, session) {} #' #' shinyApp(ui, server) #' } #' @export slide_in_right <- function(ui, duration = NULL, delay = NULL, steps = NULL, iteration = NULL) { x <- parse_animation("slide-in-right", duration, delay, steps, iteration) htmltools::tagAppendAttributes(ui, class = x) } #' Slide in up #' #' @description Animation to slide in a UI element upward. #' #' @eval vov_params() #' #' @examples #' if (interactive()) { #' library(shiny) #' library(vov) #' #' ui <- fluidPage( #' use_vov(), #' slide_in_up( #' h1("Hello world!") #' ) #' ) #' #' server <- function(input, output, session) {} #' #' shinyApp(ui, server) #' } #' @export slide_in_up <- function(ui, duration = NULL, delay = NULL, steps = NULL, iteration = NULL) { x <- parse_animation("slide-in-up", duration, delay, steps, iteration) htmltools::tagAppendAttributes(ui, class = x) } #' Slide out down #' #' @description Animation to slide in a UI element downward. #' #' @eval vov_params() #' #' @examples #' if (interactive()) { #' library(shiny) #' library(vov) #' #' ui <- fluidPage( #' use_vov(), #' slide_out_down( #' h1("Hello world!") #' ) #' ) #' #' server <- function(input, output, session) {} #' #' shinyApp(ui, server) #' } #' @export slide_out_down <- function(ui, duration = NULL, delay = NULL, steps = NULL, iteration = NULL) { x <- parse_animation("slide-out-down", duration, delay, steps, iteration) htmltools::tagAppendAttributes(ui, class = x) } #' Slide out left #' #' @description Animation to slide out (disappear) a UI element from the left. #' #' @eval vov_params() #' #' @examples #' if (interactive()) { #' library(shiny) #' library(vov) #' #' ui <- fluidPage( #' use_vov(), #' slide_out_left( #' h1("Hello world!") #' ) #' ) #' #' server <- function(input, output, session) {} #' #' shinyApp(ui, server) #' } #' @export slide_out_left <- function(ui, duration = NULL, delay = NULL, steps = NULL, iteration = NULL) { x <- parse_animation("slide-out-left", duration, delay, steps, iteration) htmltools::tagAppendAttributes(ui, class = x) } #' Slide out right #' #' @description Animation to slide out (disappear) a UI element from the right. #' #' @eval vov_params() #' #' @examples #' if (interactive()) { #' library(shiny) #' library(vov) #' #' ui <- fluidPage( #' use_vov(), #' slide_out_right( #' h1("Hello world!") #' ) #' ) #' #' server <- function(input, output, session) {} #' #' shinyApp(ui, server) #' } #' @export slide_out_right <- function(ui, duration = NULL, delay = NULL, steps = NULL, iteration = NULL) { x <- parse_animation("slide-out-right", duration, delay, steps, iteration) htmltools::tagAppendAttributes(ui, class = x) } #' Slide out up #' #' @description Animation to slide out (disappear) a UI element upward. #' #' @eval vov_params() #' #' @examples #' if (interactive()) { #' library(shiny) #' library(vov) #' #' ui <- fluidPage( #' use_vov(), #' slide_out_up( #' h1("Hello world!") #' ) #' ) #' #' server <- function(input, output, session) {} #' #' shinyApp(ui, server) #' } #' @export slide_out_up <- function(ui, duration = NULL, delay = NULL, steps = NULL, iteration = NULL) { x <- parse_animation("slide-out-up", duration, delay, steps, iteration) htmltools::tagAppendAttributes(ui, class = x) } #' Throb #' #' @description Animation to throb a UI element outward. #' #' @eval vov_params() #' #' @examples #' if (interactive()) { #' library(shiny) #' library(vov) #' #' ui <- fluidPage( #' use_vov(), #' throb( #' h1("Hello world!") #' ) #' ) #' #' server <- function(input, output, session) {} #' #' shinyApp(ui, server) #' } #' @export throb <- function(ui, duration = NULL, delay = NULL, steps = NULL, iteration = NULL) { x <- parse_animation("throb", duration, delay, steps, iteration) htmltools::tagAppendAttributes(ui, class = x) } #' I-Throb #' #' @description Animation to throb a UI element inward. #' #' @eval vov_params() #' #' @examples #' if (interactive()) { #' library(shiny) #' library(vov) #' #' ui <- fluidPage( #' use_vov(), #' i_throb( #' h1("Hello world!") #' ) #' ) #' #' server <- function(input, output, session) {} #' #' shinyApp(ui, server) #' } #' @export i_throb <- function(ui, duration = NULL, delay = NULL, steps = NULL, iteration = NULL) { x <- parse_animation("i-throb", duration, delay, steps, iteration) htmltools::tagAppendAttributes(ui, class = x) } #' Swivel horizontal #' #' @description Animation to swivel a UI element horizontally. #' #' @eval vov_params() #' #' @examples #' if (interactive()) { #' library(shiny) #' library(vov) #' #' ui <- fluidPage( #' use_vov(), #' swivel_horizontal( #' h1("Hello world!") #' ) #' ) #' #' server <- function(input, output, session) {} #' #' shinyApp(ui, server) #' } #' @export swivel_horizontal <- function(ui, duration = NULL, delay = NULL, steps = NULL, iteration = NULL) { x <- parse_animation("swivel-horizontal", duration, delay, steps, iteration) htmltools::tagAppendAttributes(ui, class = x) } #' Swivel horizontal double #' #' @description Animation to swivel a UI element horizontally, twice. #' #' @eval vov_params() #' #' @examples #' if (interactive()) { #' library(shiny) #' library(vov) #' #' ui <- fluidPage( #' use_vov(), #' swivel_horizontal_double( #' h1("Hello world!") #' ) #' ) #' #' server <- function(input, output, session) {} #' #' shinyApp(ui, server) #' } #' @export swivel_horizontal_double <- function(ui, duration = NULL, delay = NULL, steps = NULL, iteration = NULL) { x <- parse_animation("swivel-horizontal-double", duration, delay, steps, iteration) htmltools::tagAppendAttributes(ui, class = x) } #' Swivel vertical #' #' @description Animation to swivel a UI element vertically. #' #' @eval vov_params() #' #' @examples #' if (interactive()) { #' library(shiny) #' library(vov) #' #' ui <- fluidPage( #' use_vov(), #' swivel_vertical( #' h1("Hello world!") #' ) #' ) #' #' server <- function(input, output, session) {} #' #' shinyApp(ui, server) #' } #' @export swivel_vertical <- function(ui, duration = NULL, delay = NULL, steps = NULL, iteration = NULL) { x <- parse_animation("swivel-vertical", duration, delay, steps, iteration) htmltools::tagAppendAttributes(ui, class = x) } #' Swivel vertical double #' #' @description Animation to swivel a UI element vertically, twice. #' #' @eval vov_params() #' #' @examples #' if (interactive()) { #' library(shiny) #' library(vov) #' #' ui <- fluidPage( #' use_vov(), #' swivel_vertical_double( #' h1("Hello world!") #' ) #' ) #' #' server <- function(input, output, session) {} #' #' shinyApp(ui, server) #' } #' @export swivel_vertical_double <- function(ui, duration = NULL, delay = NULL, steps = NULL, iteration = NULL) { x <- parse_animation("swivel-vertical-double", duration, delay, steps, iteration) htmltools::tagAppendAttributes(ui, class = x) } #' Wheel in left #' #' @description Animation to wheel in a UI element from the left. #' #' @eval vov_params() #' #' @examples #' if (interactive()) { #' library(shiny) #' library(vov) #' #' ui <- fluidPage( #' use_vov(), #' wheel_in_left( #' h1("Hello world!") #' ) #' ) #' #' server <- function(input, output, session) {} #' #' shinyApp(ui, server) #' } #' @export wheel_in_left <- function(ui, duration = NULL, delay = NULL, steps = NULL, iteration = NULL) { x <- parse_animation("wheel-in-left", duration, delay, steps, iteration) htmltools::tagAppendAttributes(ui, class = x) } #' Wheel in right #' #' @description Animation to wheel in a UI element from the right. #' #' @eval vov_params() #' #' @examples #' if (interactive()) { #' library(shiny) #' library(vov) #' #' ui <- fluidPage( #' use_vov(), #' wheel_in_right( #' h1("Hello world!") #' ) #' ) #' #' server <- function(input, output, session) {} #' #' shinyApp(ui, server) #' } #' @export wheel_in_right <- function(ui, duration = NULL, delay = NULL, steps = NULL, iteration = NULL) { x <- parse_animation("wheel-in-right", duration, delay, steps, iteration) htmltools::tagAppendAttributes(ui, class = x) } #' Wheel out left #' #' @description Animation to wheel out (disappear) a UI element from the left. #' #' @eval vov_params() #' #' @examples #' if (interactive()) { #' library(shiny) #' library(vov) #' #' ui <- fluidPage( #' use_vov(), #' wheel_out_left( #' h1("Hello world!") #' ) #' ) #' #' server <- function(input, output, session) {} #' #' shinyApp(ui, server) #' } #' @export wheel_out_left <- function(ui, duration = NULL, delay = NULL, steps = NULL, iteration = NULL) { x <- parse_animation("wheel-out-left", duration, delay, steps, iteration) htmltools::tagAppendAttributes(ui, class = x) } #' Wheel out right #' #' @description Animation to wheel out (disappear) a UI element from the right. #' #' @eval vov_params() #' #' @examples #' if (interactive()) { #' library(shiny) #' library(vov) #' #' ui <- fluidPage( #' use_vov(), #' wheel_out_right( #' h1("Hello world!") #' ) #' ) #' #' server <- function(input, output, session) {} #' #' shinyApp(ui, server) #' } #' @export wheel_out_right <- function(ui, duration = NULL, delay = NULL, steps = NULL, iteration = NULL) { x <- parse_animation("wheel-out-right", duration, delay, steps, iteration) htmltools::tagAppendAttributes(ui, class = x) } #' Flash #' #' @description Animation to flash a UI element. #' #' @eval vov_params() #' #' @examples #' if (interactive()) { #' library(shiny) #' library(vov) #' #' ui <- fluidPage( #' use_vov(), #' flash( #' h1("Hello world!") #' ) #' ) #' #' server <- function(input, output, session) {} #' #' shinyApp(ui, server) #' } #' @export flash <- function(ui, duration = NULL, delay = NULL, steps = NULL, iteration = NULL) { x <- parse_animation("flash", duration, delay, steps, iteration) htmltools::tagAppendAttributes(ui, class = x) } #' Zoom in down #' #' @description Animation to zoom a UI element down. #' #' @eval vov_params() #' #' @examples #' if (interactive()) { #' library(shiny) #' library(vov) #' #' ui <- fluidPage( #' use_vov(), #' zoom_in_down( #' h1("Hello world!") #' ) #' ) #' #' server <- function(input, output, session) {} #' #' shinyApp(ui, server) #' } #' @export zoom_in_down <- function(ui, duration = NULL, delay = NULL, steps = NULL, iteration = NULL) { x <- parse_animation("zoom-in-down", duration, delay, steps, iteration) htmltools::tagAppendAttributes(ui, class = x) } #' Zoom in left #' #' @description Animation to zoom a UI element left. #' #' @eval vov_params() #' #' @examples #' if (interactive()) { #' library(shiny) #' library(vov) #' #' ui <- fluidPage( #' use_vov(), #' zoom_in_left( #' h1("Hello world!") #' ) #' ) #' #' server <- function(input, output, session) {} #' #' shinyApp(ui, server) #' } #' @export zoom_in_left <- function(ui, duration = NULL, delay = NULL, steps = NULL, iteration = NULL) { x <- parse_animation("zoom-in-left", duration, delay, steps, iteration) htmltools::tagAppendAttributes(ui, class = x) } #' Zoom in right #' #' @description Animation to zoom a UI element right. #' #' @eval vov_params() #' #' @examples #' if (interactive()) { #' library(shiny) #' library(vov) #' #' ui <- fluidPage( #' use_vov(), #' zoom_in_right( #' h1("Hello world!") #' ) #' ) #' #' server <- function(input, output, session) {} #' #' shinyApp(ui, server) #' } #' @export zoom_in_right <- function(ui, duration = NULL, delay = NULL, steps = NULL, iteration = NULL) { x <- parse_animation("zoom-in-right", duration, delay, steps, iteration) htmltools::tagAppendAttributes(ui, class = x) } #' Zoom in up #' #' @description Animation to zoom a UI element up. #' #' @eval vov_params() #' #' @examples #' if (interactive()) { #' library(shiny) #' library(vov) #' #' ui <- fluidPage( #' use_vov(), #' zoom_in_up( #' h1("Hello world!") #' ) #' ) #' #' server <- function(input, output, session) {} #' #' shinyApp(ui, server) #' } #' @export zoom_in_up <- function(ui, duration = NULL, delay = NULL, steps = NULL, iteration = NULL) { x <- parse_animation("zoom-in-up", duration, delay, steps, iteration) htmltools::tagAppendAttributes(ui, class = x) } #' Zoom in #' #' @description Animation to zoom a UI element. #' #' @eval vov_params() #' #' @examples #' if (interactive()) { #' library(shiny) #' library(vov) #' #' ui <- fluidPage( #' use_vov(), #' zoom_in( #' h1("Hello world!") #' ) #' ) #' #' server <- function(input, output, session) {} #' #' shinyApp(ui, server) #' } #' @export zoom_in <- function(ui, duration = NULL, delay = NULL, steps = NULL, iteration = NULL) { x <- parse_animation("zoom-in", duration, delay, steps, iteration) htmltools::tagAppendAttributes(ui, class = x) } #' Zoom out down #' #' @description Animation to zoom a UI element down. #' #' @eval vov_params() #' #' @examples #' if (interactive()) { #' library(shiny) #' library(vov) #' #' ui <- fluidPage( #' use_vov(), #' zoom_out_down( #' h1("Hello world!") #' ) #' ) #' #' server <- function(input, output, session) {} #' #' shinyApp(ui, server) #' } #' @export zoom_out_down <- function(ui, duration = NULL, delay = NULL, steps = NULL, iteration = NULL) { x <- parse_animation("zoom-out-down", duration, delay, steps, iteration) htmltools::tagAppendAttributes(ui, class = x) } #' Zoom out left #' #' @description Animation to zoom a UI element left. #' #' @eval vov_params() #' #' @examples #' if (interactive()) { #' library(shiny) #' library(vov) #' #' ui <- fluidPage( #' use_vov(), #' zoom_out_left( #' h1("Hello world!") #' ) #' ) #' #' server <- function(input, output, session) {} #' #' shinyApp(ui, server) #' } #' @export zoom_out_left <- function(ui, duration = NULL, delay = NULL, steps = NULL, iteration = NULL) { x <- parse_animation("zoom-out-left", duration, delay, steps, iteration) htmltools::tagAppendAttributes(ui, class = x) } #' Zoom out right #' #' @description Animation to zoom a UI element right. #' #' @eval vov_params() #' #' @examples #' if (interactive()) { #' library(shiny) #' library(vov) #' #' ui <- fluidPage( #' use_vov(), #' zoom_out_right( #' h1("Hello world!") #' ) #' ) #' #' server <- function(input, output, session) {} #' #' shinyApp(ui, server) #' } #' @export zoom_out_right <- function(ui, duration = NULL, delay = NULL, steps = NULL, iteration = NULL) { x <- parse_animation("zoom-out-right", duration, delay, steps, iteration) htmltools::tagAppendAttributes(ui, class = x) } #' Zoom out up #' #' @description Animation to zoom a UI element up. #' #' @eval vov_params() #' #' @examples #' if (interactive()) { #' library(shiny) #' library(vov) #' #' ui <- fluidPage( #' use_vov(), #' zoom_out_up( #' h1("Hello world!") #' ) #' ) #' #' server <- function(input, output, session) {} #' #' shinyApp(ui, server) #' } #' @export zoom_out_up <- function(ui, duration = NULL, delay = NULL, steps = NULL, iteration = NULL) { x <- parse_animation("zoom-out-up", duration, delay, steps, iteration) htmltools::tagAppendAttributes(ui, class = x) } #' Zoom out #' #' @description Animation to zoom a UI element. #' #' @eval vov_params() #' #' @examples #' if (interactive()) { #' library(shiny) #' library(vov) #' #' ui <- fluidPage( #' use_vov(), #' zoom_out( #' h1("Hello world!") #' ) #' ) #' #' server <- function(input, output, session) {} #' #' shinyApp(ui, server) #' } #' @export zoom_out <- function(ui, duration = NULL, delay = NULL, steps = NULL, iteration = NULL) { x <- parse_animation("zoom-out", duration, delay, steps, iteration) htmltools::tagAppendAttributes(ui, class = x) }
/scratch/gouwar.j/cran-all/cranData/vov/R/vov.R
library(shiny) library(vov) ui <- fluidPage( use_vov(), tags$head(tags$style(HTML(".form-control { text-align: center; }"))), # breaks br(), br(), fluidRow( column( width = 4, offset = 4, align = "center", uiOutput("text") ), column( br(), br(), width = 4, offset = 4, align = "center", selectInput( inputId = "animation", label = "Animation", choices = ls("package:vov")[!grepl("use_vov|run_demo", ls("package:vov"))] ) ), column( width = 4, offset = 4, align = "center", selectInput( inputId = "duration", label = "Duration", choices = c("fastest", "faster", "fast", "slow", "slower", "slowest"), selected = "fast" ), selectInput( inputId = "iteration", label = "Iteration", choices = c("1", "2", "3", "4", "5", "infinite"), selected = "1" ), sliderInput( inputId = "delay", label = "Delay", value = 0, min = 0, max = 5 ), sliderInput( inputId = "steps", label = "Steps", value = 50, min = 10, max = 50, step = 10 ) ) ) ) server <- function(input, output, session) { output$text <- renderUI({ x <- list(h1("\U0001f44b Hello world!")) lapply( X = x, FUN = input$animation, duration = input$duration, delay = input$delay, steps = input$steps, iteration = input$iteration )[[1]] }) } shinyApp(ui, server)
/scratch/gouwar.j/cran-all/cranData/vov/inst/extdata/app.R
##################### # VOWELS v. 1.2-2 # Vowel Manipulation, Normalization, and Plotting Package for R # Tyler Kendall, [email protected], 2009-2018 # cf. NORM: http://lingtools.uoregon.edu/norm/ # Info: http://blogs.uoregon.edu/vowels/ ##################### # # USAGE: source("vowels.R") # --or-- R CMD install vowels_1.2-2.tar.gz (from command line) # Then library(vowels) # Then call functions as needed # # # In all cases the input "vowels" is a data.frame of the following: # vowels<-data.frame(spkr, vtype, context_n, f1s, f2s, f3s, f1gs, f2gs, f3gs) # # The output of the normalization functions is the same, but with # attr(vowels, "norm.method") == the normalization method # attr(vowels, "no.f3s") == TRUE if the output data frame does NOT have # columns for F3 values, NA if there are F3 columns # # GENERAL FUNCTIONS # load.vowels <- function(file = NA, type='Hertz') { if (is.na(file)) file<-file.choose() vowels <- read.table(file, header=TRUE, sep="\t", quote="", comment.char="", blank.lines.skip=TRUE, fill=TRUE) attr(vowels, "unit.type")<-type vowels } label.columns <- function(vowels) { col3 <- "Context" vnames<-vector() if (!(is.null(attributes(vowels)$mean.values) | is.null(attributes(vowels)$mean.values))) col3 <- "N" vnames<-c("Speaker", "Vowel", col3, "F1", "F2", "F3", "F1.gl", "F2.gl", "F3.gl") if (!is.null(attributes(vowels)$no.f3s) | (dim(vowels)[2] < 9)){ vnames<-c("Speaker", "Vowel", col3, "F1", "F2", "F1.gl", "F2.gl") } if (!is.null(attributes(vowels)$unit.type)) { if (attributes(vowels)$unit.type=="Bark") { vnames<-c("Speaker", "Vowel", col3, "Z1", "Z2", "Z3", "Z1.gl", "Z2.gl", "Z3.gl") if (!is.null(attributes(vowels)$no.f3s) | (dim(vowels)[2] < 9)) { vnames<-c("Speaker", "Vowel", col3, "Z1", "Z2", "Z1.gl", "Z2.gl") } } else if (attributes(vowels)$unit.type=="ERB") { vnames<-c("Speaker", "Vowel", col3, "E1", "E2", "E3", "E1.gl", "E2.gl", "E3.gl") if (!is.null(attributes(vowels)$no.f3s) | (dim(vowels)[2] < 9)) { vnames<-c("Speaker", "Vowel", col3, "E1", "E2", "E1.gl", "E2.gl") } } } names(vowels)<-vnames vowels } scalevowels <- function (normed.vowels) { f3.plus <- 0 if (is.null(attributes(normed.vowels)$no.f3s)) { f3.plus <- 1 min.f3 <- min(c(normed.vowels[,6], normed.vowels[,9]), na.rm=TRUE) max.f3 <- max(c(normed.vowels[,6], normed.vowels[,9]), na.rm=TRUE) } min.f1 <- min(c(normed.vowels[,4], normed.vowels[,6+f3.plus]), na.rm=TRUE) max.f1 <- max(c(normed.vowels[,4], normed.vowels[,6+f3.plus]), na.rm=TRUE) min.f2 <- min(c(normed.vowels[,5], normed.vowels[,7+f3.plus]), na.rm=TRUE) max.f2 <- max(c(normed.vowels[,5], normed.vowels[,7+f3.plus]), na.rm=TRUE) normed.vowels[,4]<-round((500*(normed.vowels[,4] - min.f1)/(max.f1 - min.f1)) + 250, 3) normed.vowels[,6+f3.plus]<-round((500*(normed.vowels[,6+f3.plus] - min.f1)/(max.f1 - min.f1)) + 250, 3) normed.vowels[,5]<-round((1400*(normed.vowels[,5] - min.f2)/(max.f2 - min.f2)) + 850, 3) normed.vowels[,7+f3.plus]<-round((1400*(normed.vowels[,7+f3.plus] - min.f2)/(max.f2 - min.f2)) + 850, 3) if (f3.plus>0) { normed.vowels[,6]<-round((1200*(normed.vowels[,6] - min.f1)/(max.f3 - min.f3)) + 2000, 3) normed.vowels[,9]<-round((1200*(normed.vowels[,9] - min.f1)/(max.f3 - min.f3)) + 2000, 3) } attr(normed.vowels, "scaled.values")<-TRUE normed.vowels } compute.means <- function(vowels, separate=FALSE, speaker=NA) { if (!separate & !is.na(speaker)) { vals<-vowels[vowels[,1]==speaker,] } else { vals<-vowels } speakers<-unique(as.character(vals[,1])) if (!separate & (length(speakers) > 1)) { speakers<-c("AllSpkrs") } return.vals<-NA no.f3s<-FALSE if (!is.null(attributes(vowels)$no.f3s)) { no.f3s <- TRUE } for (s in speakers) { if (s == "AllSpkrs") { use.vals<-vals } else { use.vals<-vals[vals[,1]==s,] } vowel.types<-unique(use.vals[,2]) spkrs<-vector(length=length(vowel.types)) n.cols<-(length(use.vals)-3) if (n.cols > 6) n.cols <- 6 formants<-matrix(nrow=length(vowel.types), ncol=n.cols) num.of.tokens<-vector(length=length(vowel.types)) for (i in 1:length(vowel.types)) { spkrs[i]<-s if (length(speakers)==1) { spkrs[i]<-speakers[1] } else if (!is.na(speaker)) { spkrs[i]<-speaker } for (j in 4:length(use.vals)) { if (is.numeric(use.vals[,j])) { formants[i,j-3]<-round(mean(use.vals[use.vals[,2]==vowel.types[i], j], na.rm=TRUE), 3) } } num.of.tokens[i]<-length(use.vals[,2][use.vals[,2]==vowel.types[i]]) } if (is.data.frame(return.vals)) { new.vals<-data.frame(spkrs, vowel.types, num.of.tokens, formants) names(new.vals)<-c("Speaker", "Vowel", "N", names(vowels[,4:length(vowels)])) if (dim(formants)[2]==4) no.f3s<-TRUE return.vals<-rbind(return.vals, new.vals) } else { return.vals<-data.frame(spkrs, vowel.types, num.of.tokens, formants) names(return.vals)<-c("Speaker", "Vowel", "N", names(vowels[,4:length(vowels)])) if (dim(formants)[2]==4) no.f3s<-TRUE } } if (no.f3s) { attr(return.vals, "no.f3s")<-TRUE } attr(return.vals, "norm.method")<-attr(vowels, "norm.method") attr(return.vals, "norm.variant")<-attr(vowels,"norm.variant") attr(return.vals, "unit.type")<-attr(vowels,"unit.type") attr(return.vals, "mean.values")<-TRUE #return.vals<-label.columns(return.vals) return.vals } compute.sds <- function(vowels, separate=FALSE, speaker=NA) { if (!separate & !is.na(speaker)) { vals<-vowels[vowels[,1]==speaker,] } else { vals<-vowels } speakers<-unique(as.character(vals[,1])) if (!separate) { speakers<-c("AllSpkrs") } return.vals<-NA no.f3s<-FALSE if (!is.null(attributes(vowels)$no.f3s)) { no.f3s <- TRUE } for (s in speakers) { if (s == "AllSpkrs") { use.vals<-vals } else { use.vals<-vals[vals[,1]==s,] } vowel.types<-unique(use.vals[,2]) spkrs<-vector(length=length(vowel.types)) formants<-matrix(nrow=length(vowel.types), ncol=(length(use.vals)-3)) num.of.tokens<-vector(length=length(vowel.types)) for (i in 1:length(vowel.types)) { spkrs[i]<-s if (length(speakers)==1) { spkrs[i]<-speakers[1] } else if (!is.na(speaker)) { spkrs[i]<-speaker } for (j in 4:length(use.vals)) { if (is.numeric(use.vals[,j])) { formants[i,j-3]<-round(sd(use.vals[use.vals[,2]==vowel.types[i], j], na.rm=TRUE), 3) } } num.of.tokens[i]<-length(use.vals[,2][use.vals[,2]==vowel.types[i]]) } if (is.data.frame(return.vals)) { new.vals<-data.frame(spkrs, vowel.types, num.of.tokens, formants) names(new.vals)<-c("Speaker", "Vowel", "N", names(vowels[,4:length(vowels)])) if (dim(formants)[2]==4) no.f3s<-TRUE return.vals<-rbind(return.vals, new.vals) } else { return.vals<-data.frame(spkrs, vowel.types, num.of.tokens, formants) names(return.vals)<-c("Speaker", "Vowel", "N", names(vowels[,4:length(vowels)])) if (dim(formants)[2]==4) no.f3s<-TRUE } } if (no.f3s) { attr(return.vals, "no.f3s")<-TRUE } attr(return.vals, "norm.method")<-attr(vowels, "norm.method") attr(return.vals, "norm.variant")<-attr(vowels,"norm.variant") attr(return.vals, "unit.type")<-attr(vowels,"unit.type") attr(return.vals, "standard.devs")<-TRUE return.vals } compute.medians <- function(vowels, separate=FALSE, speaker=NA) { if (!separate & !is.na(speaker)) { vals<-vowels[vowels[,1]==speaker,] } else { vals<-vowels } speakers<-unique(as.character(vals[,1])) if (!separate & (length(speakers) > 1)) { speakers<-c("AllSpkrs") } return.vals<-NA no.f3s<-FALSE if (!is.null(attributes(vowels)$no.f3s)) { no.f3s <- TRUE } for (s in speakers) { if (s == "AllSpkrs") { use.vals<-vals } else { use.vals<-vals[vals[,1]==s,] } vowel.types<-unique(use.vals[,2]) spkrs<-vector(length=length(vowel.types)) n.cols<-(length(use.vals)-3) if (n.cols > 6) n.cols <- 6 formants<-matrix(nrow=length(vowel.types), ncol=n.cols) num.of.tokens<-vector(length=length(vowel.types)) for (i in 1:length(vowel.types)) { spkrs[i]<-s if (length(speakers)==1) { spkrs[i]<-speakers[1] } else if (!is.na(speaker)) { spkrs[i]<-speaker } for (j in 4:length(use.vals)) { if (is.numeric(use.vals[,j])) { formants[i,j-3]<-round(median(use.vals[use.vals[,2]==vowel.types[i], j], na.rm=TRUE), 3) } } num.of.tokens[i]<-length(use.vals[,2][use.vals[,2]==vowel.types[i]]) } if (is.data.frame(return.vals)) { new.vals<-data.frame(spkrs, vowel.types, num.of.tokens, formants) names(new.vals)<-c("Speaker", "Vowel", "N", names(vowels[,4:length(vowels)])) if (dim(formants)[2]==4) no.f3s<-TRUE return.vals<-rbind(return.vals, new.vals) } else { return.vals<-data.frame(spkrs, vowel.types, num.of.tokens, formants) names(return.vals)<-c("Speaker", "Vowel", "N", names(vowels[,4:length(vowels)])) if (dim(formants)[2]==4) no.f3s<-TRUE } } if (no.f3s) { attr(return.vals, "no.f3s")<-TRUE } attr(return.vals, "norm.method")<-attr(vowels, "norm.method") attr(return.vals, "norm.variant")<-attr(vowels,"norm.variant") attr(return.vals, "unit.type")<-attr(vowels,"unit.type") attr(return.vals, "median.values")<-TRUE #return.vals<-label.columns(return.vals) return.vals } # # CONVERSION FUNCTIONS # Based on Traunmuller (1997)'s formula # These conversion functions all take vowel dataframes in Hz convert.bark <- function(vowels) { z1s<-round((26.81/(1+1960/vowels[,4]))-0.53,3) z2s<-round((26.81/(1+1960/vowels[,5]))-0.53,3) z3s<-round((26.81/(1+1960/vowels[,6]))-0.53,3) z1.gls<-round((26.81/(1+1960/vowels[,7]))-0.53,3) z2.gls<-round((26.81/(1+1960/vowels[,8]))-0.53,3) z3.gls<-round((26.81/(1+1960/vowels[,9]))-0.53,3) return.vals<-data.frame(vowels[,1], vowels[,2], vowels[,3], z1s, z2s, z3s, z1.gls, z2.gls, z3.gls) #names(return.vals)<-c("Speaker", "Vowel", "Context", "Z1", "Z2", "Z3", "Z1 gl", "Z2 gl", "Z3 gl") attr(return.vals, "unit.type")<-"Bark" attr(return.vals, "mean.values")<-attr(vowels,"mean.values") attr(return.vals, "median.values")<-attr(vowels,"median.values") return.vals<-label.columns(return.vals) return.vals } convert.erb <- function(vowels) { e1s<-round(11.17*log((vowels[,4]+312)/(vowels[,4]+14675))+43.0,3) e2s<-round(11.17*log((vowels[,5]+312)/(vowels[,5]+14675))+43.0,3) e3s<-round(11.17*log((vowels[,6]+312)/(vowels[,6]+14675))+43.0,3) e1.gls<-round(11.17*log((vowels[,7]+312)/(vowels[,7]+14675))+43.0,3) e2.gls<-round(11.17*log((vowels[,8]+312)/(vowels[,8]+14675))+43.0,3) e3.gls<-round(11.17*log((vowels[,9]+312)/(vowels[,9]+14675))+43.0,3) return.vals<-data.frame(vowels[,1], vowels[,2], vowels[,3], e1s, e2s, e3s, e1.gls, e2.gls, e3.gls) #names(return.vals)<-c("Speaker", "Vowel", "Context", "E1", "E2", "E3", "E1 gl", "E2 gl", "E3 gl") attr(return.vals, "unit.type")<-"ERB" attr(return.vals, "mean.values")<-attr(vowels,"mean.values") attr(return.vals, "median.values")<-attr(vowels,"median.values") return.vals<-label.columns(return.vals) return.vals } # # NORMALIZATION FUNCTIONS # # Thomas' variation of Syrdal & Gopal norm.bark <- function(vowels) { # convert formant mean values to Bark bvowels<-convert.bark(vowels) if (!is.null(attributes(vowels)$unit.type)) { if (attributes(vowels)$unit.type=="Bark") { bvowels<-vowels } } z1s<-bvowels[,4] z2s<-bvowels[,5] z3s<-bvowels[,6] z1.gls<-bvowels[,7] z2.gls<-bvowels[,8] z3.gls<-bvowels[,9] # determine z3-z1, z3-z2, and z2-z1 z3.z1<-round(z3s - z1s, 3) z3.z2<-round(z3s - z2s, 3) z2.z1<-round(z2s - z1s, 3) z3.gl.z1<-round(z3.gls - z1.gls, 3) z3.gl.z2<-round(z3.gls - z2.gls, 3) z2.gl.z1<-round(z2.gls - z1.gls, 3) return.vals<-data.frame(vowels[,1], vowels[,2], vowels[,3], z3.z1, z3.z2, z2.z1, z3.gl.z1, z3.gl.z2, z2.gl.z1) names(return.vals)<-c("Speaker", "Vowel", "Context", "Z3-Z1", "Z3-Z2", "Z2-Z1", "Z3-Z1 gl", "Z3-Z2 gl", "Z2-Z1 gl") attr(return.vals, "norm.method")<-"Bark Difference" attr(return.vals, "unit.type")<-"Bark" return.vals } norm.labov <- function(vowels, G.value = NA, use.f3 = FALSE, geomean = TRUE) { if (is.na(G.value)) G.value <- 6.896874 return.vals<-NA for (speaker in as.character(unique(vowels[,1]))) { vals<-vowels[vowels[,1]==speaker,] # do Labov's Nearey-like algorithm ln.f1s <- log(vals[,4]) ln.f2s <- log(vals[,5]) ln.f1.gls <- log(vals[,7]) ln.f2.gls <- log(vals[,8]) # set all NA values to be the same as onset, basically act # like all monophthongs are diphs with glide same as onset ln.f1.gls[is.na(ln.f1.gls)]<-ln.f1s[is.na(ln.f1.gls)] ln.f2.gls[is.na(ln.f2.gls)]<-ln.f2s[is.na(ln.f2.gls)] if (use.f3) { ln.f3s <- log(vals[,6]) ln.f3.gls <- log(vals[,9]) ln.f3.gls[is.na(ln.f3.gls)]<-ln.f3s[is.na(ln.f3.gls)] grand.mean <- mean(c(ln.f1s, ln.f1.gls, ln.f2s, ln.f2.gls, ln.f3s, ln.f3.gls), na.rm=TRUE) if (geomean) grand.mean <- exp(mean(log(c(ln.f1s, ln.f1.gls, ln.f2s, ln.f2.gls, ln.f3s, ln.f3.gls)), na.rm=TRUE)) } else { grand.mean <- mean(c(ln.f1s, ln.f1.gls, ln.f2s, ln.f2.gls), na.rm=TRUE) if (geomean) grand.mean <- exp(mean(log(c(ln.f1s, ln.f1.gls, ln.f2s, ln.f2.gls)), na.rm=TRUE)) } factor <- exp(G.value - grand.mean) normed.f1s <- round(factor * vals[,4], 3) normed.f2s <- round(factor * vals[,5], 3) normed.f1.gls <- round(factor * vals[,7], 3) normed.f2.gls <- round(factor * vals[,8], 3) normed.f3s<-NA normed.f3.gls<-NA if (use.f3) { normed.f3s <- round(factor * vals[,6], 3) normed.f3.gls <- round(factor * vals[,9], 3) if (is.data.frame(return.vals)) { new.vals<-data.frame(vals[,1], vals[,2], vals[,3], normed.f1s, normed.f2s, normed.f3s, normed.f1.gls, normed.f2.gls, normed.f3.gls) names(new.vals)<-c("Speaker", "Vowel", "Context", "F1'", "F2'", "F3'", "F1' gl", "F2' gl", "F3' gl") return.vals<-rbind(return.vals, new.vals) } else { return.vals<-data.frame(vals[,1], vals[,2], vals[,3], normed.f1s, normed.f2s, normed.f3s, normed.f1.gls, normed.f2.gls, normed.f3.gls) names(return.vals)<-c("Speaker", "Vowel", "Context", "F1'", "F2'", "F3'", "F1' gl", "F2' gl", "F3' gl") } } else { if (is.data.frame(return.vals)) { new.vals<-data.frame(vals[,1], vals[,2], vals[,3], normed.f1s, normed.f2s, normed.f1.gls, normed.f2.gls) names(new.vals)<-c("Speaker", "Vowel", "Context", "F1'", "F2'", "F1' gl", "F2' gl") return.vals<-rbind(return.vals, new.vals) } else { return.vals<-data.frame(vals[,1], vals[,2], vals[,3], normed.f1s, normed.f2s, normed.f1.gls, normed.f2.gls) names(return.vals)<-c("Speaker", "Vowel", "Context", "F1'", "F2'", "F1' gl", "F2' gl") } attr(return.vals, "no.f3s")<-TRUE } } attr(return.vals, "norm.method")<-"Labov" if (G.value==6.896874) { attr(return.vals, "norm.variant")<-"Labov, w/ Telsur G" } attr(return.vals, "G.value")<-G.value return.vals } norm.lobanov <- function(vowels, f1.all.mean=NA, f2.all.mean=NA) { return.vals<-NA for (speaker in as.character(unique(vowels[,1]))) { vals<-vowels[vowels[,1]==speaker,] f1s<-vals[,4] f2s<-vals[,5] f1.gls<-vals[,7] f2.gls<-vals[,8] f1.gls[is.na(f1.gls)]<-f1s[is.na(f1.gls)] f2.gls[is.na(f2.gls)]<-f2s[is.na(f2.gls)] mean.f1 <- mean(c(f1s, f1.gls)) if (!is.na(f1.all.mean)) mean.f1<-f1.all.mean mean.f2 <- mean(c(f2s, f2.gls)) if (!is.na(f2.all.mean)) mean.f2<-f2.all.mean stdev.f1 <- sd(c(f1s, f1.gls)) stdev.f2 <- sd(c(f2s, f2.gls)) norm.f1s <- round((f1s-mean.f1)/stdev.f1, 3) norm.f2s <- round((f2s-mean.f2)/stdev.f2, 3) norm.f1.gls <- round((f1.gls-mean.f1)/stdev.f1, 3) norm.f2.gls <- round((f2.gls-mean.f2)/stdev.f2, 3) norm.f1.gls[is.na(vals[,7])]<-NA norm.f2.gls[is.na(vals[,8])]<-NA if (is.data.frame(return.vals)) { new.vals<-data.frame(vals[,1], vals[,2], vals[,3], norm.f1s, norm.f2s, norm.f1.gls, norm.f2.gls) names(new.vals)<-c("Speaker", "Vowel", "Context", "F*1", "F*2", "F*1 gl", "F*2 gl") return.vals<-rbind(return.vals, new.vals) } else { return.vals<-data.frame(vals[,1], vals[,2], vals[,3], norm.f1s, norm.f2s, norm.f1.gls, norm.f2.gls) names(return.vals)<-c("Speaker", "Vowel", "Context", "F*1", "F*2", "F*1 gl", "F*2 gl") } } attr(return.vals, "norm.method")<-"Lobanov" attr(return.vals, "no.f3s")<-TRUE return.vals } norm.nearey <- function(vowels, formant.int = FALSE, use.f3 = FALSE, all.mean = NA, all.mean.f2 = NA, all.mean.f3 = NA) { return.vals<-NA for (speaker in as.character(unique(vowels[,1]))) { vals<-vowels[vowels[,1]==speaker,] # do Nearey algorithm on the value ln.f1s <- log(vals[,4]) ln.f2s <- log(vals[,5]) ln.f1.gls <- log(vals[,7]) ln.f2.gls <- log(vals[,8]) # set all NA values to be the same as onset, basically act like # all monophthongs are diphs with glide same as onset ln.f1.gls[is.na(ln.f1.gls)]<-ln.f1s[is.na(ln.f1.gls)] ln.f2.gls[is.na(ln.f2.gls)]<-ln.f2s[is.na(ln.f2.gls)] grand.f1 <- mean(c(ln.f1s, ln.f1.gls), na.rm=TRUE) grand.f2 <- mean(c(ln.f2s, ln.f2.gls), na.rm=TRUE) ln.f3s<-vector(length=length(ln.f1s)) ln.f3.gls<-vector(length=length(ln.f1.gls)) grand.f3 <- NA if (use.f3) { ln.f3s <- log(vals[,6]) ln.f3.gls <- log(vals[,9]) ln.f3.gls[is.na(ln.f3.gls)]<-ln.f3s[is.na(ln.f3.gls)] grand.f3 <- mean(c(ln.f3s, ln.f3.gls), na.rm=TRUE) } if (!formant.int) { if (!use.f3) { grand.f1 <- mean(c(ln.f1s, ln.f1.gls, ln.f2s, ln.f2.gls), na.rm=TRUE) grand.f2 <- mean(c(ln.f1s, ln.f1.gls, ln.f2s, ln.f2.gls), na.rm=TRUE) } else { grand.f1 <- mean(c(ln.f1s, ln.f1.gls, ln.f2s, ln.f2.gls, ln.f3s, ln.f3.gls), na.rm=TRUE) grand.f2 <- mean(c(ln.f1s, ln.f1.gls, ln.f2s, ln.f2.gls, ln.f3s, ln.f3.gls), na.rm=TRUE) grand.f3 <- mean(c(ln.f1s, ln.f1.gls, ln.f2s, ln.f2.gls, ln.f3s, ln.f3.gls), na.rm=TRUE) } } if (!is.na(all.mean)) { grand.f1 <- all.mean if (!is.na(all.mean.f2)) { grand.f2 <- all.mean.f2 } else { grand.f2 <- all.mean } if (!is.na(all.mean.f3)) { grand.f3 <- all.mean.f3 } else { grand.f3 <- all.mean } } exp.ln.f1s <- round(exp(ln.f1s - grand.f1), 3) exp.ln.f2s <- round(exp(ln.f2s - grand.f2), 3) exp.ln.f1.gls <- round(exp(ln.f1.gls - grand.f1), 3) exp.ln.f2.gls <- round(exp(ln.f2.gls - grand.f2), 3) # reset NA glides to NA exp.ln.f1.gls[is.na(vals[,7])]<-NA exp.ln.f2.gls[is.na(vals[,8])]<-NA if (use.f3) { exp.ln.f3s <- round(exp(ln.f3s - grand.f3), 3) exp.ln.f3.gls <- round(exp(ln.f3.gls - grand.f3), 3) # reset NA glides to NA exp.ln.f3.gls[is.na(vals[,9])]<-NA if (is.data.frame(return.vals)) { new.vals<-data.frame(vals[,1], vals[,2], vals[,3], exp.ln.f1s, exp.ln.f2s, exp.ln.f3s, exp.ln.f1.gls, exp.ln.f2.gls, exp.ln.f3.gls) names(new.vals)<-c("Speaker", "Vowel", "Context", "F*1", "F*2", "F*3", "F*1 gl", "F*2 gl", "F*3 gl") return.vals<-rbind(return.vals, new.vals) } else { return.vals<-data.frame(vals[,1], vals[,2], vals[,3], exp.ln.f1s, exp.ln.f2s, exp.ln.f3s, exp.ln.f1.gls, exp.ln.f2.gls, exp.ln.f3.gls) names(return.vals)<-c("Speaker", "Vowel", "Context", "F*1", "F*2", "F*3", "F*1 gl", "F*2 gl", "F*3 gl") } } else { if (is.data.frame(return.vals)) { new.vals<-data.frame(vals[,1], vals[,2], vals[,3], exp.ln.f1s, exp.ln.f2s, exp.ln.f1.gls, exp.ln.f2.gls) names(new.vals)<-c("Speaker", "Vowel", "Context", "F*1", "F*2", "F*1 gl", "F*2 gl") return.vals<-rbind(return.vals, new.vals) } else { return.vals<-data.frame(vals[,1], vals[,2], vals[,3,], exp.ln.f1s, exp.ln.f2s, exp.ln.f1.gls, exp.ln.f2.gls) names(return.vals)<-c("Speaker", "Vowel", "Context", "F*1", "F*2", "F*1 gl", "F*2 gl") } attr(return.vals, "no.f3s")<-TRUE } } attr(return.vals, "norm.method")<-"Nearey" if (formant.int) { attr(return.vals, "norm.variant")<-"Nearey1" } else { attr(return.vals, "norm.variant")<-"Nearey2" } return.vals } norm.wattfabricius <- function(vowels, norm.means=FALSE, mod.WF=FALSE) { return.vals<-NA for (speaker in as.character(unique(vowels[,1]))) { vals<-vowels[vowels[,1]==speaker,] # do Watt & Fabricius algorithm # get idealized min&max F1 and F2, according to Watt & Fabricius mean.vals <- compute.means(vals) col.plus <- 0 if (dim(mean.vals)[2]>7) { col.plus<-1 } # unlike W&F (2003), we determine the corners of the vowel triangle # by choosing the vowels automatically based on position... i.f1 <- min(c(mean.vals[,4], mean.vals[,6+col.plus]), na.rm=TRUE) i.f2 <- max(c(mean.vals[,5], mean.vals[,7+col.plus]), na.rm=TRUE) ul.f1 <- i.f1 ul.f2 <- i.f1 a.f1 <- max(c(mean.vals[,4], mean.vals[,6+col.plus]), na.rm=TRUE) a.f2 <- mean(mean.vals[,5][mean.vals[,4]==a.f1 | mean.vals[,6+col.plus]==a.f1], na.rm=TRUE) if (mod.WF) { a.f2 <- (i.f2 + ul.f2)/2 } # compute S values S.f1 <- (i.f1 + a.f1 + ul.f1)/3 S.f2 <- (i.f2 + a.f2 + ul.f2)/3 # divide f1 and f2 values by S values if (norm.means) { norm.f1s <- round(mean.vals[,4]/S.f1, 3) norm.f2s <- round(mean.vals[,5]/S.f2, 3) norm.f1.gls <- round(mean.vals[,6+col.plus]/S.f1, 3) norm.f2.gls <- round(mean.vals[,7+col.plus]/S.f2, 3) if (is.data.frame(return.vals)) { new.vals <- data.frame(mean.vals[,1], mean.vals[,2], mean.vals[,3], norm.f1s, norm.f2s, norm.f1.gls, norm.f2.gls) names(new.vals) <- c("Speaker", "Vowel", "N", "F1/S(F1)", "F2/S(F2)", "F1g/S(F1g)", "F2g/S(F2g)") return.vals<-rbind(return.vals, new.vals) } else { return.vals <- data.frame(mean.vals[,1], mean.vals[,2], mean.vals[,3], norm.f1s, norm.f2s, norm.f1.gls, norm.f2.gls) names(return.vals) <- c("Speaker", "Vowel", "N", "F1/S(F1)", "F2/S(F2)", "F1g/S(F1g)", "F2g/S(F2g)") } attr(return.vals, "mean.values")<-TRUE } else { norm.f1s <- round(vals[,4]/S.f1, 3) norm.f2s <- round(vals[,5]/S.f2, 3) norm.f1.gls <- round(vals[,7]/S.f1, 3) norm.f2.gls <- round(vals[,8]/S.f2, 3) if (is.data.frame(return.vals)) { new.vals <- data.frame(vals[,1], vals[,2], vals[,3], norm.f1s, norm.f2s, norm.f1.gls, norm.f2.gls) names(new.vals) <- c("Speaker", "Vowel", "Context", "F1/S(F1)", "F2/S(F2)", "F1g/S(F1g)", "F2g/S(F2g)") return.vals<-rbind(return.vals, new.vals) } else { return.vals <- data.frame(vals[,1], vals[,2], vals[,3], norm.f1s, norm.f2s, norm.f1.gls, norm.f2.gls) names(return.vals) <- c("Speaker", "Vowel", "Context", "F1/S(F1)", "F2/S(F2)", "F1g/S(F1g)", "F2g/S(F2g)") } } } attr(return.vals, "norm.method")<-"Watt & Fabricius" if (mod.WF) { attr(return.vals, "norm.variant") <- "ModWF" } attr(return.vals, "unit.type")<-attr(vowels,"unit.type") attr(return.vals, "no.f3s")<-TRUE return.vals } # # PLOTTING FUNCTIONS # default.point.colors<- function() { c("#ff0000", "#0000ff", "#00ff00", "#ff9900", "#cd00cd", "#00cdcd", "#cdcd00", "#800000", "#008000", "#333399", "#ffff00", "#808080", "#cc99ff") } setup.point.color <- function(vowels, color = NA,color.choice=NA){ if (is.na(color)) { pl.c<-"black" } else { ind <- 1 # if coloring anything, default to speakers if (color == "vowels") ind <- 2 pl.c<-vector(length=length(vowels[,ind])) ind.types <- unique(vowels[,ind]) clrs<-default.point.colors() if (!any(is.na(color.choice))) { clrs<-color.choice } clrs<-rep(clrs, len=length(ind.types)) for (i in 1:length(ind.types)) { pl.c[vowels[,ind]==ind.types[i]]<-clrs[i] } } pl.c } setup.sizes <- function(vowels, size=NA, a.size=NA, l.size=NA) { if (!is.na(size)) { p.size<-size } else { p.size<-0.6+(1/(log(length(vowels[,1]), 10))) } if (is.na(a.size)) a.size<-1.0 if (is.na(l.size)) l.size<-a.size*0.75 c(p.size, a.size, l.size) } setup.point.shape <- function(vowels, shape = "speakers", shape.choice = NA) { ind <- 1 # default to speakers if (shape == "vowels") ind <- 2 pl.p<-vector(length=length(vowels[,ind])) ind.types <- unique(as.character(vowels[,ind])) #pnts<-c(15, 16, 17, 18, 7, 8, 6, 14) pnts<-c(16, 0, 17, 8, 9, 15, 3, 12, 18, 5) if (!is.na(shape.choice)) { pnts<-shape.choice } pnts<-rep(pnts, len=length(ind.types)) for (i in 1:length(ind.types)) { pl.p[vowels[,ind]==ind.types[i]]<-pnts[i] } pl.p } setup.axes <- function(vowels) { f3.plus <- 0 if (is.null(attributes(vowels)$no.f3s)) f3.plus <- 1 # determine scale for axes xstart <- -1000 xend <- 100000 ystart <- -1000 yend <- 100000 for (i in 1:length(vowels)) { if (xstart < max(vowels[,5], vowels[,(7+f3.plus)], na.rm=TRUE)) xstart <- max(vowels[,5], vowels[,(7+f3.plus)], na.rm=TRUE) if (xend > min(vowels[,5], vowels[,(7+f3.plus)], na.rm=TRUE)) xend <- min(vowels[,5], vowels[,(7+f3.plus)], na.rm=TRUE) if (ystart < max(vowels[,4], vowels[,(6+f3.plus)], na.rm=TRUE)) ystart <- max(vowels[,4], vowels[,(6+f3.plus)], na.rm=TRUE) if (yend > min(vowels[,4], vowels[,(6+f3.plus)], na.rm=TRUE)) yend <- min(vowels[,4], vowels[,(6+f3.plus)], na.rm=TRUE) } xunit <- (xstart-xend)/12 xstart <- xstart+xunit xend <- xend-xunit yunit <- (ystart-yend)/12 ystart <- ystart+yunit yend <- yend-yunit # Reverse axes if the values are in Bark difference if (!is.null(attributes(vowels)$norm.method)) { if (attributes(vowels)$norm.method=="Bark Difference") { xend.t<-xend xend<-xstart xstart<-xend.t yend.t<-yend yend<-ystart ystart<-yend.t } } c(xstart, xend, ystart, yend, xunit, yunit) } vowelplot <- function(vowels, speaker = NA, color = NA, color.choice = NA, shape="speakers", shape.choice = NA, size = NA, labels = "none", leg="speakers", a.size = NA, l.size = NA, title = "", subtitle = NA, xlim = NA, ylim = NA) { ltext<-NA nmethod<-"non-" if (!is.null(attributes(vowels)$norm.method)) { nmethod<-paste(attributes(vowels)$norm.method, " ", sep="") } vtext<-"Individual" if (!is.null(attributes(vowels)$mean.values)) { vtext<-"Mean" } else if (!is.null(attributes(vowels)$median.values)) { vtext<-"Median" } else if (!is.null(attributes(vowels)$standard.devs)) { vtext<-"Standard deviation of" } mtext<-paste(vtext, " vowel formant values\n", nmethod, "normalized", sep="") if (!is.na(speaker)) { vowels<-vowels[vowels[,1]==speaker,] if (labels!="none") ltext<-vowels[,2] } else if (labels=="vowels") { ltext<-vowels[,2] } else if (labels=="speakers") { ltext<-vowels[,1] } else if (labels!="none") { if (length(unique(vowels[,1]))==1) { ltext<-vowels[,2] } else { ltext<-paste(vowels[,1], vowels[,2], sep=":\n") } } spkrs<-as.character(unique(vowels[,1])) stext<-"" if (is.na(subtitle)) { if (!is.null(attributes(vowels)$norm.variant)) { stext<-paste("Variant:", attributes(vowels)$norm.variant) } else if (!is.null(attributes(vowels)$unit.type)) { if (attributes(vowels)$unit.type!="Hertz") { stext<-paste("Units:", attributes(vowels)$unit.type) } } } else if (subtitle!="") { stext<-subtitle } axes <- setup.axes(vowels) # override computation of axes limits if user specified both if (!is.na(xlim[1]) & !is.na(ylim[1])) { axes <- c(xlim[1], xlim[2], ylim[1], ylim[2], (xlim[2]-xlim[1])/12, (ylim[2]-ylim[1])/12) } pl.c <- setup.point.color(vowels, color, color.choice) pl.p <- setup.point.shape(vowels, shape, shape.choice) szs <- setup.sizes(vowels, size, a.size, l.size) p.s <- szs[1] a.s <- szs[2] l.s <- szs[3] if (title != "") mtext <- title plot(vowels[,5], vowels[,4], xlim=c(axes[1],axes[2]), ylim=c(axes[3],axes[4]), xlab=names(vowels)[5], ylab=names(vowels)[4], pch=pl.p, cex=p.s, cex.main=(a.s + 0.5), cex.axis=(a.s + 0.25), cex.lab=(a.s+0.1), main=mtext, sub=stext, col=pl.c) pl.cs<-"black" pl.ps<-unique(pl.p) if (!(is.null(attributes(vowels)$mean.values) | is.null(attributes(vowels)$median.values))) pl.ps<-unique(pl.p) if (!is.na(color) & color=="speakers") pl.cs<-unique(pl.c) if (!is.na(leg)) { if (leg == "vowels" & (shape == "vowels" | color == "vowels")) { if (shape=="speakers") pl.ps<-NA if (!is.na(color) & color=="speakers") { pl.lc<-"black" } else { pl.lc<-unique(pl.c) } legend("bottomleft", legend=unique(vowels[,2]), col=pl.lc, text.col=pl.lc, pch=pl.ps, inset=.02, cex=l.s, pt.cex=l.s) } else { if (shape=="vowels") pl.ps<-NA legend("bottomleft", legend=spkrs, col=pl.cs, text.col=pl.cs, pch=pl.ps, inset=.02, cex=l.s) } } f3.plus <- 0 if (is.null(attributes(vowels)$no.f3s)) { f3.plus <- 1 } options(warn=-1) # suppressing warnings here # (arrows create a warning when they're too short to print) arrows(vowels[,5], vowels[,4], vowels[,7+f3.plus], vowels[,6+f3.plus], angle=15, length=0.1, lwd=(p.s+0.3), col=pl.c) options(warn=0) if (!all(is.na(ltext))) { text(vowels[,5], vowels[,4], ltext, adj=c(0,1.5), cex=(2*p.s/3), col=pl.c) } } add.vowelplot <- function(vowels, speaker=NA, color=NA, color.choice=NA, shape="speakers", shape.choice = NA, size = NA, labels = "none") { ltext<-NA if (!is.na(speaker)) { vowels<-vowels[vowels[,1]==speaker,] if (labels!="none") ltext<-vowels[,2] } else if (labels=="vowels") { ltext<-vowels[,2] } else if (labels=="speakers") { ltext<-vowels[,1] } else if (labels!="none") { if (length(unique(vowels[,1]))==1) { ltext<-vowels[,2] } else { ltext<-paste(vowels[,1], vowels[,2], sep=":\n") } } spkrs<-as.character(unique(vowels[,1])) pl.c <- setup.point.color(vowels, color, color.choice) pl.p <- setup.point.shape(vowels, shape, shape.choice) szs <- setup.sizes(vowels, size) p.s <- szs[1] a.s <- szs[2] l.s <- szs[3] points(vowels[,5], vowels[,4], pch=pl.p, cex=p.s, cex.lab=(a.s+0.1), main=mtext, col=pl.c) pl.cs<-"black" pl.ps<-pl.p if (!(is.null(attributes(vowels)$mean.values) | is.null(attributes(vowels)$median.values))) pl.ps<-unique(pl.p) if (shape=="vowels") pl.ps<-NA if (!is.na(color) & color=="speakers") pl.cs<-unique(pl.c) f3.plus <- 0 if (is.null(attributes(vowels)$no.f3s)) { f3.plus <- 1 } options(warn=-1) # suppressing warnings here # (arrows create a warning when they're too short to print) arrows(vowels[,5], vowels[,4], vowels[,7+f3.plus], vowels[,6+f3.plus], angle=15, length=0.1, lwd=(p.s+0.3), col=pl.c) options(warn=0) if (!all(is.na(ltext))) { text(vowels[,5], vowels[,4], ltext, adj=c(0,1.5), cex=(2*p.s/3), col=pl.c) } } add.spread.vowelplot <- function(vowels, mean.points=FALSE, sd.mult=2, ellipsis=FALSE, speaker=NA, color=NA, color.choice=NA, shape="speakers", shape.choice = NA, size = NA, leg=FALSE, labels = "none", separate=TRUE) { if (!is.numeric(sd.mult)) { sd.mult<-as.numeric(sd.mult) } if (!is.na(speaker)) { vowels<-vowels[vowels[,1]==speaker,] } spkrs<-as.character(unique(vowels[,1])) vmns<-compute.means(vowels, separate=separate) vsds<-compute.sds(vowels, separate=separate) ltext<-NA if (!is.na(speaker) & (labels != "none")) { ltext<-vmns[,2] } else if (labels=="vowels") { ltext<-vmns[,2] } else if (labels=="speakers") { ltext<-vmns[,1] } else if (labels!="none") { if (length(unique(vmns[,1]))==1) { ltext<-vmns[,2] } else { ltext<-paste(vmns[,1], vmns[,2], sep=":\n") } } pl.c <- setup.point.color(vmns, color, color.choice) pl.p <- setup.point.shape(vmns, shape, shape.choice) szs <- setup.sizes(vmns, size) p.s <- szs[1]+0.5 a.s <- szs[2] l.s <- szs[3] if (mean.points) points(vmns[,5], vmns[,4], pch=pl.p, cex=p.s, cex.lab=(a.s+0.1), main=mtext, col=pl.c) if (ellipsis=="horizvert") { t <- seq(0,7,0.1) # if pl.c is simply "black" need to make it a long enough vec if (length(pl.c) < length(vmns[,5])) { pl.c<-rep(pl.c, length.out=length(vmns[,5])) } for (v in 1:length(vmns[,5])) { x <- vmns[v,5] + ((sd.mult*vsds[v,5])*cos(t)) y <- vmns[v,4] + ((sd.mult*vsds[v,4])*sin(t)) lines(x, y, lty=2, col=pl.c[v]) } } else if (ellipsis) { t <- seq(0,7,0.1) if (length(pl.c) < length(vmns[,5])) { pl.c<-rep(pl.c, length.out=length(vmns[,5])) } if (separate==TRUE) { for (sp in unique(vmns[,1])) { for (v in as.character(vmns[,2])) { svmns <- vmns[vmns[,1]==sp & vmns[,2]==v,] svsds <- vsds[vsds[,1]==sp & vsds[,2]==v,] svwls <- vowels[vowels[,1]==sp & vowels[,2]==v,] spl.c <- pl.c[vmns[,1]==sp & vmns[,2]==v] if (nrow(svwls) > 1) { # Find the principal components and standard devs of the distribution prcs <- prcomp(cbind(svwls[,5],svwls[,4])) if (prcs$sdev[1] >= prcs$sdev[2]) { xscale <- prcs$sdev[1] * sd.mult yscale <- prcs$sdev[2] * sd.mult column <- 1 } else { xscale <- prcs$sdev[2] * sd.mult yscale <- prcs$sdev[1] * sd.mult column <- 2 } x <- xscale*cos(t) y <- yscale*sin(t) rotatedx <- svmns[,5] + x*prcs$rotation[1,column] - y*prcs$rotation[2,column] rotatedy <- svmns[,4] + x*prcs$rotation[2,column] + y*prcs$rotation[1,column] lines(rotatedx, rotatedy, lty=2, col=spl.c) } } } } else { for (v in as.character(vmns[,2])) { if (!is.na(vsds[vsds[,2]==v,5])) { # Find the principal components and standard devs of the distribution prcs <- prcomp(cbind(vowels[vowels[,2]==v,5],vowels[vowels[,2]==v,4])) if (prcs$sdev[1] >= prcs$sdev[2]) { xscale <- prcs$sdev[1] * sd.mult yscale <- prcs$sdev[2] * sd.mult column <- 1 } else { xscale <- prcs$sdev[2] * sd.mult yscale <- prcs$sdev[1] * sd.mult column <- 2 } x <- xscale*cos(t) y <- yscale*sin(t) rotatedx <- vmns[vmns[,2]==v,5] + x*prcs$rotation[1,column] - y*prcs$rotation[2,column] rotatedy <- vmns[vmns[,2]==v,4] + x*prcs$rotation[2,column] + y*prcs$rotation[1,column] lines(rotatedx, rotatedy, lty=2, col=pl.c[which(vmns[,2]==v)]) } } } } else { arrows(vmns[,5]-(sd.mult*vsds[,5]), vmns[,4], vmns[,5]+(sd.mult*vsds[,5]), vmns[,4], length=0.1, angle=90, code=3, lty=2, col=pl.c) arrows(vmns[,5], vmns[,4]-(sd.mult*vsds[,4]), vmns[,5], vmns[,4]+(sd.mult*vsds[,4]), length=0.1, angle=90, code=3, lty=2, col=pl.c) } if (leg) legend("bottomright", legend=paste(sd.mult, " SDs", sep=""), lty=2, cex=0.8, inset=.02) if (!all(is.na(ltext))) { text(vmns[,5], vmns[,4], ltext, adj=c(0,1.5), cex=(2*p.s/3), col=pl.c) } }
/scratch/gouwar.j/cran-all/cranData/vowels/R/vowels.R
#' Computes voxelwise analysis of variance (ANOVA) tables for a Generalized Additive Model. #' #' This function computes analysis of variance tables for the fitted models after running a Generalized Additive Model (from mgcv::gam). #' The analysis will run in all voxels in the mask and will return the analysis of variance table for each voxel. #' Please check the mgcv::anova.gam documentation for further information about specific arguments used in anova.gam. Multi-model calls are disabled. #' #' @param image Input image of type 'nifti' or vector of path(s) to images. If multiple paths, the script will call mergeNifti() and merge across time. #' @param mask Input mask of type 'nifti' or path to mask. Must be a binary mask #' @param fourdOut To be passed to mergeNifti, This is the path and file name without the suffix to save the fourd file. Default (NULL) means script won't write out 4D image. #' @param formula Must be a formula passed to gam() #' @param subjData Dataframe containing all the covariates used for the analysis #' @param dispersion To be passed to mgcv::anova.gam, Defaults to NULL. Dispersion Parameter, not normally used. #' @param freq To be passed to mgcv::anova.gam, Defaults to FALSE. Frequentist or Bayesian approximations for p-values #' @param mc.preschedule Argument to be passed to mclapply, whether or not to preschedule the jobs. More info in parallel::mclapply #' @param ncores Number of cores to use #' @param ... Additional arguments passed to gam() #' #' @return Returns list of models fitted to each voxel over the masked images passed to function. #' #' @export #' @examples #' image <- oro.nifti::nifti(img = array(1:200, dim =c(2,2,2,25))) #' mask <- oro.nifti::nifti(img = array(0:1, dim = c(2,2,2,1))) #' set.seed(1) #' covs <- data.frame(x = runif(25), y=runif(25)) #' fm1 <- "~ s(x) + y" #' models <- anovagamVoxel(image=image, mask=mask, #' formula=fm1, subjData=covs, ncores = 1) anovagamVoxel <- function(image, mask , fourdOut = NULL, formula, subjData, dispersion = NULL, freq = FALSE, mc.preschedule = TRUE, ncores = 1, ...) { if (missing(image)) { stop("image is missing")} if (missing(mask)) { stop("mask is missing")} if (missing(formula)) { stop("formula is missing")} if (missing(subjData)) { stop("subjData is missing")} if (class(formula) != "character") { stop("formula class must be character")} if (class(image) == "character" & length(image) == 1) { image <- oro.nifti::readNIfTI(fname=image) } else if (class(image) == "character" & length(image) > 1) { image <- mergeNiftis(inputPaths = image, direction = "t", outfile <- fourdOut) } if (class(mask) == "character" & length(mask) == 1) { mask <- oro.nifti::readNIfTI(fname=mask) } imageMat <- ts2matrix(image, mask) rm(image) rm(mask) gc() print("Created time series to matrix") voxNames <- names(imageMat) m <- parallel::mclapply(voxNames, FUN = listFormula, formula, mc.cores = ncores) imageMat <- cbind(imageMat, subjData) print("Created formula list") timeIn <- proc.time() print("Running test ANOVA") model <- mgcv::gam(m[[1]], data=imageMat, ...) model <- mgcv::anova.gam(model, dispersion = dispersion, freq = freq) print("Running parallel ANOVAs") model <- parallel::mclapply(m, FUN = function(x, data, dispersion, freq, ...) { foo <- mgcv::gam(x, data=data, ...) foo <- mgcv::anova.gam(foo, dispersion = dispersion, freq = freq) return(list(anovaPTable = foo$pTerms.table, anovaSTable = foo$s.table)) }, data=imageMat, dispersion, freq, ..., mc.preschedule = mc.preschedule, mc.cores = ncores) timeOut <- proc.time() - timeIn print(timeOut[3]) print("Parallel ANOVAs Ran") return(model) }
/scratch/gouwar.j/cran-all/cranData/voxel/R/anovagamVoxel.R
#' Computes voxelwise analysis of variance (ANOVA) tables for a Generalized Additive Mixed Effects Model. #' #' This function computes analysis of variance tables for the fitted Generalized Additive Mixed Effects (from gamm4::gamm4) models. #' The analysis will run in all voxels in the specified mask and will return a list with the ANOVA table at each voxel. #' Please check the mgcv::anova.gam documentation for further information about specific arguments used in anova.gam. Multi-model calls are disabled. #' #' #' @param image Input image of type 'nifti' or vector of path(s) to images. If multiple paths, the script will call mergeNifti() and merge across time. #' @param mask Input mask of type 'nifti' or path to mask. Must be a binary. #' @param fourdOut To be passed to mergeNifti, This is the output path to write out the fourd file. Do not include a suffix (i.e. .nii.gz). Default (NULL) means script won't write out 4D image. #' @param formula Must be a formula passed to gamm4() #' @param randomFormula Random effects formula passed to gamm4() #' @param subjData Dataframe containing all the covariates used for the analysis #' @param dispersion To be passed to mgcv::anova.gam, Defaults to NULL. Dispersion Parameter, not normally used. #' @param freq To be passed to mgcv::anova.gam, Defaults to FALSE. Frequentist or Bayesian approximations for p-values #' @param mc.preschedule To be passed to mclapply, whether or not to preschedule the jobs. More info in parallel::mclapply #' @param ncores Number of cores to use #' @param ... Additional arguments passed to gamm4() #' #' @return Returns list of models fitted to each voxel over the masked images passed to function. #' @export #' #' @examples #' #' #' image <- oro.nifti::nifti(img = array(1:1600, dim =c(4,4,4,25))) #' mask <- oro.nifti::nifti(img = array(data = c(rep(0,15), rep(1,1)), #' dim = c(4,4,4,1))) #' set.seed(1) #' covs <- data.frame(x = runif(25), y=runif(25), id = rep(1:5,5)) #' f1 <- "~ s(x) + y" #' randomFormula <- "~(1|id)" #' models <- anovagammVoxel(image, mask, formula = f1, #' randomFormula = randomFormula, #' subjData = covs, ncores = 1, REML=TRUE) anovagammVoxel <- function(image, mask , fourdOut = NULL, formula, randomFormula, subjData, dispersion = NULL, freq = FALSE, mc.preschedule = TRUE, ncores =1, ...) { if (missing(image)) { stop("image is missing")} if (missing(mask)) { stop("mask is missing")} if (missing(formula)) { stop("formula is missing")} if (missing(subjData)) { stop("subjData is missing")} if (missing(randomFormula)) { stop("randomFormula is missing")} if (class(formula) != "character") { stop("formula class must be character")} if (class(image) == "character" & length(image) == 1) { image <- oro.nifti::readNIfTI(fname=image) } else if (class(image) == "character" & length(image) > 1) { image <- mergeNiftis(inputPaths = image, direction = "t", outfile <- fourdOut) } if (class(mask) == "character" & length(mask) == 1) { mask <- oro.nifti::readNIfTI(fname=mask) } imageMat <- ts2matrix(image, mask) print("Created time series to matrix") rm(image) rm(mask) gc() voxNames <- names(imageMat) m <- parallel::mclapply(voxNames, FUN = listFormula, formula, mc.cores = ncores) gc() print("Created formula list") imageMat <- cbind(imageMat, subjData) random <- stats::as.formula(randomFormula, env = environment()) timeIn <- proc.time() print("Running test ANOVA") model <- gamm4::gamm4(m[[1]], data=imageMat, random = random, ...) model <- mgcv::anova.gam(model$gam, dispersion = dispersion, freq = freq) gc() print("Running parallel ANOVAs") model <- parallel::mclapply(m, FUN = function(x, data, random, dispersion, freq, ...) { foo <- gamm4::gamm4(x, data=data, random=random, ...) foo <- mgcv::anova.gam(foo$gam, dispersion = dispersion, freq = freq) return(list(anovaPTable = foo$pTerms.table, anovaSTable = foo$s.table)) }, data=imageMat,random=random, dispersion, freq, ...,mc.preschedule=mc.preschedule, mc.cores = ncores) timeOut <- proc.time() - timeIn print(timeOut[3]) print("Parallel ANOVAs Ran") return(model) }
/scratch/gouwar.j/cran-all/cranData/voxel/R/anovagammVoxel.R
#' Computes voxelwise analysis of variance (ANOVA) tables for a Linear Model. #' #' This function computes analysis of variance tables for the fitted models after running a Linear Model using the stats::lm() function. #' The analysis will run in all voxels in the mask and will return the analysis of variance table for each voxel. #' Please check the stats documentation for further information about specific arguments used in stats::anova.lm(). Multi-model calls are disabled. #' #' @param image Input image of type 'nifti' or vector of path(s) to images. If multiple paths, the script will all mergeNifti() and merge across time. #' @param mask Input mask of type 'nifti' or path to mask. Must be a binary mask #' @param fourdOut To be passed to mergeNifti, This is the path and file name without the suffix to save the fourd file. Default (NULL) means script won't write out 4D image. #' @param formula Must be a formula passed to lm() #' @param subjData Dataframe containing all the covariates used for the analysis #' @param mc.preschedule Argument to be passed to mclapply, whether or not to preschedule the jobs. More info in parallel::mclapply #' @param ncores Number of cores to use #' @param ... Additional arguments passed to lm() #' #' @return Returns list of models fitted to each voxel over the masked images passed to function. #' #' @export #' @examples #' image <- oro.nifti::nifti(img = array(1:1600, dim =c(4,4,4,25))) #' mask <- oro.nifti::nifti(img = array(0:1, dim = c(4,4,4,1))) #' set.seed(1) #' covs <- data.frame(x = runif(25), y=runif(25)) #' fm1 <- "~ x + y" #' models <- anovalmVoxel(image=image, mask=mask, #' formula=fm1, subjData=covs, ncores = 1) anovalmVoxel <- function(image, mask , fourdOut = NULL, formula, subjData, mc.preschedule = TRUE, ncores = 1, ...) { if (missing(image)) { stop("image is missing")} if (missing(mask)) { stop("mask is missing")} if (missing(formula)) { stop("formula is missing")} if (missing(subjData)) { stop("subjData is missing")} if (class(formula) != "character") { stop("formula class must be character")} if (class(image) == "character" & length(image) == 1) { image <- oro.nifti::readNIfTI(fname=image) } else if (class(image) == "character" & length(image) > 1) { image <- mergeNiftis(inputPaths = image, direction = "t", outfile <- fourdOut) } if (class(mask) == "character" & length(mask) == 1) { mask <- oro.nifti::readNIfTI(fname=mask) } imageMat <- ts2matrix(image, mask) voxNames <- names(imageMat) rm(image) rm(mask) gc() print("Created time series to matrix") m <- parallel::mclapply(voxNames, FUN = listFormula, formula, mc.cores = ncores) imageMat <- cbind(imageMat, subjData) print("Created formula list") timeIn <- proc.time() print("Running test ANOVA") model <- stats::lm(m[[1]], data=imageMat, ...) model <- stats::anova(model) print("Running parallel ANOVAs") model <- parallel::mclapply(m, FUN = function(x, data, ...) { foo <- stats::lm(x, data=data, ...) return(stats::anova(foo)) }, data=imageMat, ..., mc.preschedule = mc.preschedule, mc.cores = ncores) timeOut <- proc.time() - timeIn print(timeOut[3]) print("Parallel ANOVAs Ran") return(model) }
/scratch/gouwar.j/cran-all/cranData/voxel/R/anovalmVoxel.R
#' Computes voxelwise analysis of variance (ANOVA) tables for a Linear Mixed Effects Model. #' #' This function computes analysis of variance tables for the fitted models after running a Linear Mixed Effect Model using the lmerTest() function and the anova function in that package. #' The analysis will run in all voxels in the mask and will return the analysis of variance table for each voxel. #' Please check the lmerTest documentation for further information about specific arguments used in anova.lmerModLmerTest. Multi-model calls are disabled. #' #' #' #' @param image Input image of type 'nifti' or vector of path(s) to images. If multiple paths, the script will call mergeNifti() and merge across time. #' @param mask Input mask of type 'nifti' or path to mask. Must be a binary mask #' @param fourdOut To be passed to mergeNifti, This is the path and file name without the suffix to save the fourd file. Default (NULL) means script won't write out 4D image. #' @param formula Must be a formula passed to lmer() #' @param subjData Dataframe containing all the covariates used for the analysis #' @param ddf Which approximation of DDF to be used. To be passed to anova.lmerModLmerTest. Defaults to "Satterthwaite" #' @param type Type of hypothesis to be test (defined from SAS terminology). Defaults to 3. To be passed to anova.lmerModLmerTest #' @param mc.preschedule Argument to be passed to mclapply, whether or not to preschedule the jobs. More info in parallel::mclapply #' @param ncores Number of cores to use #' @param ... Additional arguments passed to lmer() #' #' @return Returns list of models fitted to each voxel over the masked images passed to function. #' @export #' @import lmerTest #' @importFrom stats anova #' #' @examples #' #' #' image <- oro.nifti::nifti(img = array(1:1600, dim =c(4,4,4,25))) #' mask <- oro.nifti::nifti(img = array(c(rep(0,15), rep(1,1)), dim = c(4,4,4,1))) #' set.seed(1) #' covs <- data.frame(x = runif(25), y = runif(25), id = rep(1:5,5)) #' fm1 <- "~ x + y + (1|id)" #' models <- anovalmerVoxel(image, mask, formula = fm1, subjData = covs, ncores = 1, REML=TRUE) #' anovalmerVoxel <- function(image, mask , fourdOut = NULL, formula, subjData, ddf="Satterthwaite", type=3, mc.preschedule = TRUE, ncores = 1, ...) { if (missing(image)) { stop("image is missing")} if (missing(mask)) { stop("mask is missing")} if (missing(formula)) { stop("formula is missing")} if (missing(subjData)) { stop("subjData is missing")} if (class(formula) != "character") { stop("formula class must be character")} if (class(image) == "character" & length(image) == 1) { image <- oro.nifti::readNIfTI(fname=image) } else if (class(image) == "character" & length(image) > 1) { image <- mergeNiftis(inputPaths = image, direction = "t", outfile <- fourdOut) } if (class(mask) == "character" & length(mask) == 1) { mask <- oro.nifti::readNIfTI(fname=mask) } imageMat <- ts2matrix(image, mask) voxNames <- as.character(names(imageMat)) rm(image) rm(mask) gc() print("Created time series to matrix") m <- parallel::mclapply(voxNames, FUN = listFormula, formula, mc.cores = ncores) rm(formula) gc() imageMat <- cbind(imageMat, subjData) print("Created formula list") timeIn <- proc.time() print("Running test ANOVA") foo <- base::do.call(lmerTest::lmer, list(formula = m[[1]], data=imageMat, ...)) model <- anova(foo, ddf=ddf, type=type) print("Running parallel ANOVAs") model <- parallel::mclapply(m, FUN = function(x, data, ddf, type, ...) { foo <- base::do.call(lmerTest::lmer, list(formula = x, data=data, ...)) return(anova(foo, ddf=ddf, type=type)) }, data=imageMat,ddf=ddf,type=type, ..., mc.preschedule = mc.preschedule , mc.cores = ncores) timeOut <- proc.time() - timeIn print(timeOut[3]) print("Parallel ANOVAs Ran") return(model) }
/scratch/gouwar.j/cran-all/cranData/voxel/R/anovalmerVoxel.R
#' Run a Generalized Additive Model on the mean intensity over a region of interest #' #' This function is able to run a Generalized Additive Model (GAM) using the mgcv package. #' All clusters must be labeled with integers in the mask passed as an argument. #' #' @param image Input image of type 'nifti' or vector of path(s) to images. If multiple paths, the script will call mergeNiftis() and merge across time. #' @param mask Input mask of type 'nifti' or path to mask. All clusters must be labeled with integers in the mask passed as an argument #' @param fourdOut To be passed to mergeNifti, This is the path and file name without the suffix to save the fourd file. Default (NULL) means script won't write out 4D image. #' @param formula Must be a formula passed to gam() #' @param subjData Dataframe containing all the covariates used for the analysis #' @param mc.preschedule Argument to be passed to mclapply, whether or not to preschedule the jobs. More info in parallel::mclapply #' @param ncores Number of cores to use for the analysis #' @param ... Additional arguments passed to gam() #' #' @return Returns list of models fitted to the mean voxel intensity over region of interest. #' #' @export #' @examples #' image <- oro.nifti::nifti(img = array(1:1600, dim =c(4,4,4,25))) #' mask <- oro.nifti::nifti(img = array(1:4, dim = c(4,4,4,1))) #' set.seed(1) #' covs <- data.frame(x = runif(25)) #' fm1 <- "~ s(x)" #' models <- gamCluster(image=image, mask=mask, #' formula=fm1, subjData=covs, ncores = 1, method="REML") gamCluster <- function(image, mask , fourdOut = NULL, formula, subjData, mc.preschedule = TRUE, ncores = 1, ...) { if (missing(image)) { stop("image is missing")} if (missing(mask)) { stop("mask is missing")} if (missing(formula)) { stop("formula is missing")} if (missing(subjData)) { stop("subjData is missing")} if (class(formula) != "character") { stop("formula class must be character")} if (class(image) == "character" & length(image) == 1) { image <- oro.nifti::readNIfTI(fname=image) } else if (class(image) == "character" & length(image) > 1) { image <- mergeNiftis(inputPaths = image, direction = "t", outfile <- fourdOut) } if (class(mask) == "character" & length(mask) == 1) { mask <- oro.nifti::readNIfTI(fname=mask) } imageMat <- ts2meanCluster(image, mask) voxNames <- names(imageMat) rm(image) rm(mask) gc() print("Created meanCluster Matrix") m <- parallel::mclapply(voxNames, FUN = listFormula, formula, mc.cores = ncores) imageMat <- cbind(imageMat, subjData) print("Created formula list") timeIn<-proc.time() print("Running test model") model <- mgcv::gam(m[[1]], data=imageMat, ...) print("Running parallel models") model <- parallel::mclapply(m, FUN = function(x, data, ...) { mgcv::gam(x, data=data, ...) }, data=imageMat, ..., mc.preschedule = mc.preschedule, mc.cores = ncores) timeOut <- proc.time() - timeIn print(timeOut[3]) print("Parallel Models Ran") return(model) }
/scratch/gouwar.j/cran-all/cranData/voxel/R/gamCluster.R
#' Wrapper to run a Generalized Additive model on a NIfTI image and output parametric maps #' #' This function is able to run a Generalized Additive Model (GAM) using the mgcv package. #' The analysis will run in all voxels in in the mask and will return parametric and smooth coefficients. #' The function will create parametric maps according to the model selected. #' The function will return a p-map, t-map, z-map, p-adjusted-map for parametric terms and p-map, z-map, p-adjusted-map for smooth terms. #' You can select which type of p-value correction you want done on the map. #' #' @param image Input image of type 'nifti' or vector of path(s) to images. If multiple paths, the script will call mergeNifti() and merge across time. #' @param mask Input mask of type 'nifti' or path to mask. Must be a binary mask #' @param fourdOut To be passed to mergeNifti, This is the path and file name without the suffix to save the fourd file. Default (NULL) means script won't write out 4D image. #' @param formula Must be a formula passed to gam() #' @param subjData Dataframe containing all the covariates used for the analysis #' @param mc.preschedule Argument to be passed to mclapply, whether or not to preschedule the jobs. More info in parallel::mclapply #' @param ncores Number of cores to use #' @param method which method of correction for multiple comparisons (default is none) #' @param residual If set to TRUE then residuals maps will be returned along parametric maps #' @param outDir Path to the folder where to output parametric maps (Default is Null, only change if you want to write maps out) #' @param ... Additional arguments passed to gam() #' #' @return Parametric maps of the fitted models #' #' @export #' @examples #' image <- oro.nifti::nifti(img = array(1:1600, dim =c(4,4,4,25))) #' mask <- oro.nifti::nifti(img = array(0:1, dim = c(4,4,4,1))) #' set.seed(1) #' covs <- data.frame(x = runif(25), y = rnorm(25)) #' fm1 <- "~ x + s(y)" #' Maps <- gamNIfTI(image=image, mask=mask, #' formula=fm1, subjData=covs, ncores = 1, method="fdr") gamNIfTI <- function(image, mask , fourdOut = NULL, formula, subjData, mc.preschedule = TRUE, ncores = 1, method="none", residual=FALSE, outDir = NULL, ...) { if (missing(image)) { stop("image is missing")} if (missing(mask)) { stop("mask is missing")} if (missing(formula)) { stop("formula is missing")} if (missing(subjData)) { stop("subjData is missing")} if (class(formula) != "character") { stop("formula class must be character")} if (residual) { models <- rgamParam(image, mask , fourdOut = fourdOut, formula = formula, subjData = subjData, mc.preschedule = mc.preschedule, ncores = ncores, ...) print("Creating residual and parametric maps") return(rparMap(parameters = models, image = image, mask = mask, method = method, ncores = ncores, mc.preschedule = mc.preschedule, outDir = outDir)) } else { models <- vgamParam(image, mask , fourdOut = fourdOut, formula = formula, subjData = subjData, mc.preschedule = mc.preschedule, ncores = ncores, ...) print("Creating parametric maps") return(parMap(parameters = models, mask = mask, method=method, outDir = outDir)) } }
/scratch/gouwar.j/cran-all/cranData/voxel/R/gamNIfTI.R
#' Generate FSL Randomise call for a GAM Model #' #' #' This function is able to generate all the necessary files to run randomise with a GAM Model #' This script will write out all design and contrast files #' This function will run a f-test to compare a full and reduced model (a model with and without spline) #' #' #' @param image Input path of 'nifti' image or vector of path(s) to images. If multiple paths, the script will all mergeNiftis() and merge across time. #' @param maskPath to mask. Must be a binary mask #' @param formulaFull Must be the formula of the full model (i.e. "~s(age,k=5)+sex+mprage_antsCT_vol_TBV") #' @param formulaRed Must be the formula of the reduced model (i.e. "~sex+mprage_antsCT_vol_TBV") #' @param subjData Dataframe containing all the covariates used for the analysis #' @param outDir output directory for randomise #' @param nsim Number of simulations #' @param thresh significance threshold #' @param run FALSE will only print randomise command but won't it #' #' @return Return randomise command #' @export #' #' @examples #' \dontrun{ #' #' subjData = mgcv::gamSim(1,n=400,dist="normal",scale=2) #' OutDirRoot="Output Directory" #' maskName="Path to mask" #' imagePath="Path to output" #' covsFormula="~s(age,k=5)+sex+mprage_antsCT_vol_TBV" #' redFormula="~sex+mprage_antsCT_vol_TBV" #' #' gamRandomise(image = imagePath, maskPath = maskName, formulaFull = covsFormula, #' formulaRed = redFormula, subjData = subjData, outDir = OutDirRoot) #' #' } #' gamRandomise <- function(image, maskPath = NULL, formulaFull, formulaRed, subjData, outDir, nsim = 500, thresh = 0.01, run = FALSE) { if (missing(image)) { stop("image is missing")} if (missing(formulaFull)) { stop("formulaFull is missing")} if (missing(formulaRed)) { stop("formulaRed is missing")} if (missing(subjData)) { stop("subjData is missing")} if (missing(outDir)) { stop("outDir is missing")} if (class(formulaFull) != "character") { stop("formula class must be character")} if (class(formulaRed) != "character") { stop("formula class must be character")} if (class(image) == "character" & length(image) == 1) { mergednifti <- image } else if (class(image) == "character" & length(image) > 1) { mergednifti = file.path(outDir, 'fourd') image <- mergeNiftis(inputPaths = image, direction = "t", outfile = mergednifti) mergednifti <- file.path(outDir, 'fourd.nii.gz') } rm(image) subjData$dummy <- stats::rnorm(dim(subjData)[1]) # model matrices X = mgcv::model.matrix.gam(mgcv::gam(stats::update.formula(formulaFull, "dummy ~ .") , data=subjData)) Xred = mgcv::model.matrix.gam(mgcv::gam(stats::update.formula(formulaRed, "dummy ~ .") , data=subjData)) ## DESIGN AND CONTRASTS ## # design file n = nrow(X) p = ncol(X) p2 = p - ncol(Xred) matfile = file.path(outDir, 'design.mat') cat('/NumWaves\t', ncol(X), '\n/NumPoints\t', nrow(X), '\n/PPheights\t', paste(apply(X, 2, function(x) abs(diff(range(x))) ), collapse='\t'), '\n\n/Matrix\n', sep='', file=matfile) utils::write.table(X, append=TRUE, file=matfile, row.names=FALSE, col.names=FALSE) # contrast file confile1 = file.path(outDir, 'design.con') # for f-test cons = matrix(0, nrow=p2, ncol=ncol(X)) cons[ cbind(1:(p2), which(! colnames(X) %in% colnames(Xred) ) ) ] = 1 cat('/ContrastName1\t temp\n/ContrastName2\t\n/NumWaves\t', ncol(X), '\n/NumPoints\t', nrow(cons), '\n/PPheights\t', paste(rep(1,ncol(cons)), collapse='\t'), '\n/RequiredEffect\t1\t1\n\n/Matrix\n', sep='', file=confile1) utils::write.table(cons, append=TRUE, file=confile1, row.names=FALSE, col.names=FALSE) # fts file ftsfile = file.path(outDir, 'design.fts') fts = matrix(1, nrow=1, ncol=nrow(cons)) # ftest of all contrasts cat('/NumWaves\t', nrow(cons), '\n/NumContrasts\t', 1, '\n\n/Matrix\n', sep='', file=ftsfile) utils::write.table(fts, append=TRUE, file=ftsfile, row.names=FALSE, col.names=FALSE) # t distribution is two tailed, F is one tailed. -x outputs voxelwise statistics -N outputs null distribution text files # F-test ##Change mergenifti if(!is.null(maskPath)){ fcmd = paste('randomise -i', mergednifti, '-m', maskPath, '-o', file.path(outDir, 'randomise'), '-d', matfile, '-t', confile1, '-f', ftsfile, '--fonly -F', stats::qf( (1-thresh),df1=p2, df2=(n-p) ), '-x -N -n', nsim, '--uncorrp' ) } else { fcmd = paste('randomise -i', mergednifti, '-o', file.path(outDir, 'randomise'), '-d', matfile, '-t', confile1, '-f', ftsfile, '--fonly -F', stats::qf( (1-thresh),df1=p2, df2=(n-p) ), '-x -N -n', nsim, '--uncorrp' ) } if(run){ system(fcmd) } print(fcmd) }
/scratch/gouwar.j/cran-all/cranData/voxel/R/gamRandomise.R
#' Run a Generalized Additive Model on all voxels of a NIfTI image within a mask. #' #' This function is able to run a Generalized Additive Model (GAM) using the mgcv package. #' The analysis will run in all voxels in in the mask and will return the model fit for each voxel. #' #' @param image Input image of type 'nifti' or vector of path(s) to images. If multiple paths, the script will call mergeNifti() and merge across time. #' @param mask Input mask of type 'nifti' or path to mask. Must be a binary mask #' @param fourdOut To be passed to mergeNifti, This is the path and file name without the suffix to save the fourd file. Default (NULL) means script won't write out 4D image. #' @param formula Must be a formula passed to gam() #' @param subjData Dataframe containing all the covariates used for the analysis #' @param mc.preschedule Argument to be passed to mclapply, whether or not to preschedule the jobs. More info in parallel::mclapply #' @param ncores Number of cores to use #' @param ... Additional arguments passed to gam() #' #' @return List of models fitted to each voxel over the masked images passed to function. #' @keywords internal #' @export #' @examples #' image <- oro.nifti::nifti(img = array(1:1600, dim =c(4,4,4,25))) #' mask <- oro.nifti::nifti(img = array(0:1, dim = c(4,4,4,1))) #' set.seed(1) #' covs <- data.frame(x = runif(25)) #' fm1 <- "~ s(x)" #' models <- gamVoxel(image=image, mask=mask, #' formula=fm1, subjData=covs, ncores = 1) gamVoxel <- function(image, mask , fourdOut = NULL, formula, subjData, mc.preschedule = TRUE, ncores = 1, ...) { if (missing(image)) { stop("image is missing")} if (missing(mask)) { stop("mask is missing")} if (missing(formula)) { stop("formula is missing")} if (missing(subjData)) { stop("subjData is missing")} if (class(formula) != "character") { stop("formula class must be character")} if (class(image) == "character" & length(image) == 1) { image <- oro.nifti::readNIfTI(fname=image) } else if (class(image) == "character" & length(image) > 1) { image <- mergeNiftis(inputPaths = image, direction = "t", outfile <- fourdOut) } if (class(mask) == "character" & length(mask) == 1) { mask <- oro.nifti::readNIfTI(fname=mask) } imageMat <- ts2matrix(image, mask) rm(image) rm(mask) gc() print("Created time series to matrix") voxNames <- names(imageMat) m <- parallel::mclapply(voxNames, FUN = listFormula, formula, mc.cores = ncores) imageMat <- cbind(imageMat, subjData) print("Created formula list") timeIn <- proc.time() print("Running test model") model <- mgcv::gam(m[[1]], data=imageMat, ...) print("Running parallel models") model <- parallel::mclapply(m, FUN = function(x, data, ...) { mgcv::gam(x, data=data, ...) }, data=imageMat, ..., mc.preschedule = mc.preschedule, mc.cores = ncores) timeOut <- proc.time() - timeIn print(timeOut[3]) print("Parallel Models Ran") return(model) }
/scratch/gouwar.j/cran-all/cranData/voxel/R/gamVoxel.R
#' Run a Generalized Additive Mixed Effects Model on the mean intensity over a region of interest #' #' This function is able to run a Generalized Additive Mixed Effects Model (GAMM) using the gamm4() function. #' All clusters or Regions of Interest must be labeled with integers in the mask passed as an argument. #' #' #' @param image Input image of type 'nifti' or vector of path(s) to images. If multiple paths, the script will call mergeNifti() and merge across time. #' @param mask Input mask of type 'nifti' or path to mask. All clusters must be labeled with integers in the mask passed as an argument #' @param fourdOut To be passed to mergeNifti, This is the path and file name without the suffix to save the fourd file. Default (NULL) means script won't write out 4D image. #' @param formula Must be a formula passed to gamm4() #' @param randomFormula Random effects formula passed to gamm4() #' @param subjData Dataframe containing all the covariates used for the analysis #' @param mc.preschedule Argument to be passed to mclapply, whether or not to preschedule the jobs. More info in parallel::mclapply #' @param ncores Number of cores to use for the analysis #' @param ... Additional arguments passed to gamm4() #' #' #' @return Returns list of models fitted to the mean voxel intensity a region or interest. #' #' @export #' @examples #' #' #' image <- oro.nifti::nifti(img = array(1:1600, dim =c(4,4,4,25))) #' mask <- oro.nifti::nifti(img = array(c(rep(0,14),1,2), dim = c(4,4,4,1))) #' set.seed(1) #' covs <- data.frame(x = runif(25), id = rep(1:5,5)) #' fm1 <- "~ s(x)" #' randomFormula <- "~(1|id)" #' models <- gammCluster(image, mask, formula = fm1, #' randomFormula = randomFormula, subjData = covs, ncores = 1, REML=TRUE) #' gammCluster <- function(image, mask , fourdOut = NULL, formula, randomFormula, subjData, mc.preschedule = TRUE, ncores =1, ...) { if (missing(image)) { stop("image is missing")} if (missing(mask)) { stop("mask is missing")} if (missing(formula)) { stop("formula is missing")} if (missing(subjData)) { stop("subjData is missing")} if (missing(randomFormula)) { stop("randomFormula is missing")} if (class(formula) != "character") { stop("formula class must be character")} if (class(randomFormula) != "character") { stop("randomFormula class must be character")} if (class(image) == "character" & length(image) == 1) { image <- oro.nifti::readNIfTI(fname=image) } else if (class(image) == "character" & length(image) > 1) { image <- mergeNiftis(inputPaths = image, direction = "t", outfile <- fourdOut) } if (class(mask) == "character" & length(mask) == 1) { mask <- oro.nifti::readNIfTI(fname=mask) } imageMat <- ts2meanCluster(image, mask) print("Created meanCluster Matrix") rm(image) rm(mask) gc() voxNames <- names(imageMat) m <- parallel::mclapply(voxNames, FUN = listFormula, formula, mc.cores = 1) gc() print("Created formula list") imageMat <- cbind(imageMat, subjData) random <- stats::as.formula(randomFormula, env = environment()) timeIn <- proc.time() print("Running test model") model <- gamm4::gamm4(m[[1]], data=imageMat, random=random, ...) print("Running parallel models") model <- parallel::mclapply(m, FUN = function(x, data, random, ...) { gamm4::gamm4(x, data=data, random=random, ...) }, data=imageMat,random=random, ..., mc.preschedule = mc.preschedule, mc.cores = ncores) timeOut <- proc.time() - timeIn print(timeOut[3]) print("Parallel Models Ran") return(model) }
/scratch/gouwar.j/cran-all/cranData/voxel/R/gammCluster.R
#' Wrapper to run a Generalized Additive Mixed Effects model on an Nifti and output a parametric map #' #' This function is able to run a Generalized Additive Model (GAMM) using the gamm4() function. #' The analysis will run in all voxels within the mask and will return parametric and smooth coefficients. #' The function will create parametric maps according to the model selected. #' The function will return a p-map, t-map, z-map, p-adjusted-map for parametric terms and p-map, z-map, p-adjusted-map for smooth terms. #' You can select which type of p-value correction you want done on the map #' #' @param image Input image of type 'nifti' or vector of path(s) to images. If multiple paths, the script will call mergeNifti() and merge across time. #' @param mask Input mask of type 'nifti' or path to mask. Must be a binary mask #' @param fourdOut To be passed to mergeNifti, This is the path and file name without the suffix to save the fourd file. Default (NULL) means script won't write out 4D image. #' @param formula Must be a formula passed to gamm4() #' @param randomFormula Random effects formula passed to gamm4() #' @param subjData Dataframe containing all the covariates used for the analysis #' @param mc.preschedule Argument to be passed to mclapply, whether or not to preschedule the jobs. More info in parallel::mclapply #' @param ncores Number of cores to use #' @param method which method of correction for multiple comparisons (default is none) #' @param residual If set to TRUE then residuals maps will be returned along parametric maps #' @param outDir Path to the folder where to output parametric maps (Default is Null, only change if you want to write maps out) #' @param ... Additional arguments passed to gamm4() #' #' @return Returns Parametric maps of the fitted models over the NIfTI image #' #' @export #' @examples #' #' image <- oro.nifti::nifti(img = array(rnorm(1600, sd=10), dim =c(4,4,4,25))) #' mask <- oro.nifti::nifti(img = array(c(rep(0,14), rep(1,2)), dim = c(4,4,4,1))) #' set.seed(1) #' covs <- data.frame(x = runif(25), y = runif(25), id = rep(1:5,5)) #' fm1 <- "~ s(x) + s(y)" #' randomFormula <- "~(1|id)" #' Maps <- gammNIfTI(image, mask, formula = fm1, #' randomFormula = randomFormula, subjData = covs, ncores = 1, #' method="fdr", REML=TRUE) #' #' gammNIfTI <- function (image, mask, fourdOut = NULL, formula, randomFormula, subjData, mc.preschedule = TRUE, ncores = 1, method = "none", residual=FALSE, outDir = NULL, ...) { if (missing(image)) { stop("image is missing") } if (missing(mask)) { stop("mask is missing") } if (missing(formula)) { stop("formula is missing") } if (missing(subjData)) { stop("subjData is missing") } if (missing(randomFormula)) { stop("randomFormula is missing") } if (class(formula) != "character") { stop("formula class must be character") } if (class(randomFormula) != "character") { stop("randomFormula class must be character") } if (residual) { models <- rgamm4Param(image, mask, fourdOut = fourdOut, formula = formula, randomFormula = randomFormula, subjData = subjData, mc.preschedule = mc.preschedule, ncores = ncores, ...) print("Creating residual and parametric maps") return(rparMap(parameters = models, image = image, mask = mask, method = method, ncores = ncores, mc.preschedule = mc.preschedule, outDir = outDir)) } else { models <- vgamm4Param(image, mask, fourdOut = fourdOut, formula = formula, randomFormula = randomFormula, subjData = subjData, mc.preschedule = mc.preschedule, ncores = ncores, ...) print("Creating parametric maps") return(parMap(parameters = models, mask = mask, method = method, outDir = outDir)) } }
/scratch/gouwar.j/cran-all/cranData/voxel/R/gammNIfTI.R
#' Run a Generalized Additive Mixed Effects Model on all voxels of a NIfTI image within a mask. #' #' This function is able to run a Generalized Mixed Effects Model (GAMM) using the gamm4() function. #' The analysis will run in all voxels within the mask and will return the model fit for each voxel. #' #' #' @param image Input image of type 'nifti' or vector of path(s) to images. If multiple paths, the script will call mergeNifti() and merge across time. #' @param mask Input mask of type 'nifti' or path to mask. Must be a binary mask #' @param fourdOut To be passed to mergeNifti, This is the path and file name without the suffix to save the fourd file. Default (NULL) means script won't write out 4D image. #' @param formula Must be a formula passed to gamm4() #' @param randomFormula Random effects formula passed to gamm4() #' @param subjData Dataframe containing all the covariates used for the analysis #' @param mc.preschedule Argument to be passed to mclapply, whether or not to preschedule the jobs. More info in parallel::mclapply #' @param ncores Number of cores to use #' @param ... Additional arguments passed to gamm4() #' #' @return Returns list of models fitted to each voxel over the masked images passed to function. #' @keywords internal #' @export #' #' @examples #' #' #' image <- oro.nifti::nifti(img = array(1:1600, dim =c(4,4,4,25))) #' mask <- oro.nifti::nifti(img = array(c(rep(0,14),1), dim = c(4,4,4,1))) #' set.seed(1) #' covs <- data.frame(x = runif(25), id = rep(1:5,5)) #' fm1 <- "~ s(x)" #' randomFormula <- "~(1|id)" #' models <- gammVoxel(image = image , mask = mask, formula = fm1, randomFormula = randomFormula, #' subjData = covs, ncores = 1, REML=TRUE) #' gammVoxel <- function(image, mask , fourdOut = NULL, formula, randomFormula, subjData, mc.preschedule = TRUE, ncores =1, ...) { if (missing(image)) { stop("image is missing")} if (missing(mask)) { stop("mask is missing")} if (missing(formula)) { stop("formula is missing")} if (missing(subjData)) { stop("subjData is missing")} if (missing(randomFormula)) { stop("randomFormula is missing")} if (class(formula) != "character") { stop("formula class must be character")} if (class(randomFormula) != "character") { stop("randomFormula class must be character")} if (class(image) == "character" & length(image) == 1) { image <- oro.nifti::readNIfTI(fname=image) } else if (class(image) == "character" & length(image) > 1) { image <- mergeNiftis(inputPaths = image, direction = "t", outfile <- fourdOut) } if (class(mask) == "character" & length(mask) == 1) { mask <- oro.nifti::readNIfTI(fname=mask) } imageMat <- ts2matrix(image, mask) print("Created time series to matrix") rm(image) rm(mask) gc() voxNames <- names(imageMat) m <- parallel::mclapply(voxNames, FUN = listFormula, formula, mc.cores = ncores) gc() print("Created formula list") imageMat <- cbind(imageMat, subjData) random <- stats::as.formula(randomFormula, env = environment()) timeIn <- proc.time() print("Running test model") model <- gamm4::gamm4(m[[1]], data=imageMat, random = random, ...) gc() print("Running parallel models") model <- parallel::mclapply(m, FUN = function(x, data, random, ...) { gamm4::gamm4(x, data=data, random=random, ...) }, data=imageMat,random=random, ...,mc.preschedule=mc.preschedule, mc.cores = ncores) timeOut <- proc.time() - timeIn print(timeOut[3]) print("Parallel Models Ran") return(model) }
/scratch/gouwar.j/cran-all/cranData/voxel/R/gammVoxel.R
#' Create list of Formulas for each voxel #' #' This function is internal. #' This function creates list of formulas that will be passed for analysis. #' @param x Index of voxels to be analyzed #' @param formula covariates to be included in the analysis #' @keywords internal #' @export #' @examples #' #' #' x <- 1 #' fm1 <- "~ x1" #' formula <- listFormula(x, formula = fm1) listFormula <- function(x, formula) { stats::as.formula(paste(x, formula, sep=""), env = parent.frame(n=3)) }
/scratch/gouwar.j/cran-all/cranData/voxel/R/listFormula.R
#' Run a Linear Model on the mean intensity over a region of interest #' #' This function is able to run a Linear Model using the stats package. #' All clusters must be labeled with integers in the mask passed as an argument. #' #' @param image Input image of type 'nifti' or vector of path(s) to images. If multiple paths, the script will call mergeNifti() and merge across time. #' @param mask Input mask of type 'nifti' or path to mask. All clusters must be labeled with integers in the mask passed as an argument #' @param fourdOut To be passed to mergeNifti. This is the path and file name without the suffix to save the fourd file. Default (NULL) means script won't write out 4D image. #' @param formula Must be a formula passed to lm() #' @param subjData Dataframe containing all the covariates used for the analysis #' @param mc.preschedule Argument to be passed to mclapply, whether or not to preschedule the jobs. More info in parallel::mclapply #' @param ncores Number of cores to use #' @param ... Additional arguments passed to lm() #' #' @return Returns list of models fitted to the mean voxel intensity a region or interest. #' #' @export #' @examples #' image <- oro.nifti::nifti(img = array(1:1600, dim =c(4,4,4,25))) #' mask <- oro.nifti::nifti(img = array(1:4, dim = c(4,4,4,1))) #' set.seed(1) #' covs <- data.frame(x = runif(25)) #' fm1 <- "~ x" #' models <- lmCluster(image=image, mask=mask, #' formula=fm1, subjData=covs, ncores = 1) lmCluster <- function(image, mask , fourdOut = NULL, formula, subjData, mc.preschedule = TRUE, ncores = 1, ...) { if (missing(image)) { stop("image is missing")} if (missing(mask)) { stop("mask is missing")} if (missing(formula)) { stop("formula is missing")} if (missing(subjData)) { stop("subjData is missing")} if (class(formula) != "character") { stop("formula class must be character")} if (class(image) == "character" & length(image) == 1) { image <- oro.nifti::readNIfTI(fname=image) } else if (class(image) == "character" & length(image) > 1) { image <- mergeNiftis(inputPaths = image, direction = "t", outfile <- fourdOut) } if (class(mask) == "character" & length(mask) == 1) { mask <- oro.nifti::readNIfTI(fname=mask) } imageMat <- ts2meanCluster(image, mask) voxNames <- names(imageMat) rm(image) rm(mask) gc() print("Created meanCluster Matrix") m <- parallel::mclapply(voxNames, FUN = listFormula, formula, mc.cores = ncores) imageMat <- cbind(imageMat, subjData) print("Created formula list") timeIn <- proc.time() print("Running test model") model <- stats::lm(m[[1]], data=imageMat, ...) print("Running parallel models") model <- parallel::mclapply(m, FUN = function(x, data, ...) { stats::lm(x, data=data, ...) }, data=imageMat, ...,mc.preschedule = mc.preschedule, mc.cores = ncores) timeOut <- proc.time() - timeIn print(timeOut[3]) print("Parallel Models Ran") return(model) }
/scratch/gouwar.j/cran-all/cranData/voxel/R/lmCluster.R
#' Wrapper to run a model on a NIfTI image and output parametric maps #' #' This function is able to run a Linear Model using the stats package. #' The analysis will run in all voxels in in the mask and will return parametric coefficients. #' The function will create parametric maps according to the model selected. #' The function will return a p-map, t-map, z-map, p-adjusted-map for parametric terms and p-map, z-map, p-adjusted-map for smooth terms. #' You can select which type of p-value correction you want done on the map. #' #' @param image Input image of type 'nifti' or vector of path(s) to images. If multiple paths, the script will call mergeNifti() and merge across time. #' @param mask Input mask of type 'nifti' or path to mask. Must be a binary mask #' @param fourdOut To be passed to mergeNifti, This is the path and file name without the suffix to save the fourd file. Default (NULL) means script won't write out 4D image. #' @param formula Must be a formula passed to lm() #' @param subjData Dataframe containing all the covariates used for the analysis #' @param mc.preschedule Argument to be passed to mclapply, whether or not to preschedule the jobs. More info in parallel::mclapply #' @param ncores Number of cores to use #' @param method which method of correction for multiple comparisons (default is none) #' @param residual If set to TRUE then residuals maps will be returned along parametric maps #' @param outDir Path to the folder where to output parametric maps (Default is Null, only change if you want to write maps out) #' @param ... Additional arguments passed to lm() #' #' @return Return parametric maps of the fitted models #' #' @export #' @examples #' image <- oro.nifti::nifti(img = array(1:1600, dim =c(4,4,4,25))) #' mask <- oro.nifti::nifti(img = array(0:1, dim = c(4,4,4,1))) #' set.seed(1) #' covs <- data.frame(x = runif(25), y = runif(25)) #' fm1 <- "~ x + y" #' Maps <- lmNIfTI(image=image, mask=mask, #' formula=fm1, subjData=covs, ncores = 1, method="fdr") lmNIfTI <- function(image, mask , fourdOut = NULL, formula, subjData, mc.preschedule = TRUE, ncores = 1, method="none", residual=FALSE, outDir = NULL, ...) { if (missing(image)) { stop("image is missing")} if (missing(mask)) { stop("mask is missing")} if (missing(formula)) { stop("formula is missing")} if (missing(subjData)) { stop("subjData is missing")} if (class(formula) != "character") { stop("formula class must be character")} if (residual) { models <- rlmParam(image, mask , fourdOut = fourdOut, formula = formula, subjData = subjData, mc.preschedule = mc.preschedule, ncores = ncores, ...) print("Creating residual and parametric maps") return(rparMap(parameters = models, image = image, mask = mask, method = method, ncores = ncores, mc.preschedule = mc.preschedule, outDir = outDir)) } else { models <- vlmParam(image, mask , fourdOut = fourdOut, formula = formula, subjData = subjData, mc.preschedule = mc.preschedule, ncores = ncores, ...) print("Creating parametric maps") return(parMap(parameters = models, mask = mask, method=method, outDir = outDir)) } }
/scratch/gouwar.j/cran-all/cranData/voxel/R/lmNIfTI.R
#' Run a Linear Model on all voxels of a NIfTI image within a mask. #' #' This function is able to run a Linear Model using the stats package. #' The analysis will run in all voxels in in the mask and will return the model fit for each voxel. #' #' @param image Input image of type 'nifti' or vector of path(s) to images. If multiple paths, the script will all mergeNifti() and merge across time. #' @param mask Input mask of type 'nifti' or path to mask. Must be a binary mask #' @param fourdOut To be passed to mergeNifti, This is the path and file name without the suffix to save the fourd file. Default (NULL) means script won't write out 4D image. #' @param formula Must be a formula passed to lm() #' @param subjData Dataframe containing all the covariates used for the analysis #' @param mc.preschedule Argument to be passed to mclapply, whether or not to preschedule the jobs. More info in parallel::mclapply #' @param ncores Number of cores to use #' @param ... Additional arguments passed to lm() #' #' @return Returns list of models fitted to each voxel over the masked images passed to function. #' @keywords internal #' #' @export #' @examples #' image <- oro.nifti::nifti(img = array(1:1600, dim =c(4,4,4,25))) #' mask <- oro.nifti::nifti(img = array(0:1, dim = c(4,4,4,1))) #' set.seed(1) #' covs <- data.frame(x = runif(25)) #' fm1 <- "~ x" #' models <- lmVoxel(image=image, mask=mask, #' formula=fm1, subjData=covs, ncores = 1) lmVoxel <- function(image, mask , fourdOut = NULL, formula, subjData, mc.preschedule = TRUE, ncores = 1, ...) { if (missing(image)) { stop("image is missing")} if (missing(mask)) { stop("mask is missing")} if (missing(formula)) { stop("formula is missing")} if (missing(subjData)) { stop("subjData is missing")} if (class(formula) != "character") { stop("formula class must be character")} if (class(image) == "character" & length(image) == 1) { image <- oro.nifti::readNIfTI(fname=image) } else if (class(image) == "character" & length(image) > 1) { image <- mergeNiftis(inputPaths = image, direction = "t", outfile <- fourdOut) } if (class(mask) == "character" & length(mask) == 1) { mask <- oro.nifti::readNIfTI(fname=mask) } imageMat <- ts2matrix(image, mask) voxNames <- names(imageMat) rm(image) rm(mask) gc() print("Created time series to matrix") m <- parallel::mclapply(voxNames, FUN = listFormula, formula, mc.cores = ncores) imageMat <- cbind(imageMat, subjData) print("Created formula list") timeIn <- proc.time() print("Running test model") model <- stats::lm(m[[1]], data=imageMat, ...) print("Running parallel models") model <- parallel::mclapply(m, FUN = function(x, data, ...) { stats::lm(x, data=data, ...) }, data=imageMat, ..., mc.preschedule = mc.preschedule, mc.cores = ncores) timeOut <- proc.time() - timeIn print(timeOut[3]) print("Parallel Models Ran") return(model) }
/scratch/gouwar.j/cran-all/cranData/voxel/R/lmVoxel.R
#' Run a Linear Mixed Effects Model on the mean intensity over a region of interest #' #' This function is able to run a LME using the lmer() function. #' All clusters or region of interest must be labeled with integers in the mask passed as an argument. #' The function relies on lmerTest to create p-values using the Satterthwaite Approximation. #' #' #' @param image Input image of type 'nifti' or vector of path(s) to images. If multiple paths, the script will call mergeNifti() and merge across time. #' @param mask Input mask of type 'nifti' or path to mask. All clusters must be labeled with integers in the mask passed as an argument #' @param fourdOut To be passed to mergeNifti, This is the path and file name without the suffix to save the fourd file. Default (NULL) means script won't write out 4D image. #' @param formula Must be a formula passed to lmer() #' @param subjData Dataframe containing all the covariates used for the analysis #' @param mc.preschedule Argument to be passed to mclapply, whether or not to preschedule the jobs. More info in parallel::mclapply #' @param ncores Number of cores to use #' @param ... Additional arguments passed to lmer() #' @export #' #' @return Returns list of models fitted to the mean voxel intensity a region or interest. #' #' @examples #' #' #' image <- oro.nifti::nifti(img = array(1:1600, dim =c(4,4,4,25))) #' mask <- oro.nifti::nifti(img = array(c(rep(0,14),1,2), dim = c(4,4,4,1))) #' set.seed(1) #' covs <- data.frame(x = runif(25), id = rep(1:5,5)) #' fm1 <- "~ x + (1|id)" #' models <- lmerCluster(image, mask, formula = fm1, subjData = covs, ncores = 1, REML=TRUE) #' lmerCluster <- function(image, mask , fourdOut = NULL, formula, subjData, mc.preschedule = TRUE, ncores = 1, ...) { if (missing(image)) { stop("image is missing")} if (missing(mask)) { stop("mask is missing")} if (missing(formula)) { stop("formula is missing")} if (missing(subjData)) { stop("subjData is missing")} if (class(formula) != "character") { stop("formula class must be character")} if (class(image) == "character" & length(image) == 1) { image <- oro.nifti::readNIfTI(fname=image) } else if (class(image) == "character" & length(image) > 1) { image <- mergeNiftis(inputPaths = image, direction = "t", outfile <- fourdOut) } if (class(mask) == "character" & length(mask) == 1) { mask <- oro.nifti::readNIfTI(fname=mask) } imageMat <- ts2meanCluster(image, mask) voxNames <- names(imageMat) rm(image) rm(mask) gc() print("Created meanCluster Matrix") m <- parallel::mclapply(voxNames, FUN = listFormula, formula, mc.cores = ncores) imageMat <- cbind(imageMat, subjData) print("Created formula list") timeIn <- proc.time() print("Running test model") model <- base::do.call(lmerTest::lmer, list(formula=m[[1]], data=imageMat, ...)) print("Running parallel models") model <- parallel::mclapply(m, FUN = function(x, data, ...) { base::do.call(lmerTest::lmer, list(formula=x, data=data, ...)) }, data=imageMat, ..., mc.preschedule = mc.preschedule , mc.cores = ncores) timeOut <- proc.time() - timeIn print(timeOut[3]) print("Parallel Models Ran") return(model) }
/scratch/gouwar.j/cran-all/cranData/voxel/R/lmerCluster.R
#' Run a Linear Mixed Effects Model on a NIfTI image and output a parametric maps #' #' This function is able to run a Linear Mixed Effect Model using the lmer() function. #' The function relies on lmerTest to create p-values using the Satterthwaite Approximation. #' The analysis will run in all voxels in in the mask and will return parametric coefficients. #' The function will create parametric maps according to the model selected. #' The function will return a p-map, t-map, z-map, p-adjusted-map for parametric terms and p-map, z-map, p-adjusted-map for smooth terms. #' You can select which type of p-value correction you want done on the map. #' #' @param image Input image of type 'nifti' or vector of path(s) to images. If multiple paths, the script will call mergeNifti() and merge across time. #' @param mask Input mask of type 'nifti' or path to mask. Must be a binary mask #' @param fourdOut To be passed to mergeNifti, This is the path and file name without the suffix to save the fourd file. Default (NULL) means script won't write out 4D image. #' @param formula Must be a formula passed to lmer() #' @param subjData Dataframe containing all the covariates used for the analysis #' @param mc.preschedule Argument to be passed to mclapply, whether or not to preschedule the jobs. More info in parallel::mclapply #' @param ncores Number of cores to use #' @param method which method of correction for multiple comparisons (default is none) #' @param residual If set to TRUE then residuals maps will be returned along parametric maps #' @param outDir Path to the folder where to output parametric maps (Default is Null, only change if you want to write maps out) #' @param ... Additional arguments passed to lmer() #' #' @return Returns parametric maps of the fitted models #' @export #' #' #' @examples #' #' #' image <- oro.nifti::nifti(img = array(1:1600, dim =c(4,4,4,25))) #' mask <- oro.nifti::nifti(img = array(c(rep(0,14),1,1), dim = c(4,4,4,1))) #' set.seed(1) #' covs <- data.frame(x = runif(25), id = rep(1:5,5)) #' fm1 <- "~ x + (1|id)" #' Maps <- lmerNIfTI(image, mask, formula = fm1, subjData = covs, method="fdr", ncores = 1) #' lmerNIfTI <- function(image, mask , fourdOut = NULL, formula, subjData, mc.preschedule = TRUE, ncores = 1, method="none", residual=FALSE, outDir = NULL, ...) { if (missing(image)) { stop("image is missing")} if (missing(mask)) { stop("mask is missing")} if (missing(formula)) { stop("formula is missing")} if (missing(subjData)) { stop("subjData is missing")} if (class(formula) != "character") { stop("formula class must be character")} if (residual) { models <- rlmerParam(image, mask, fourdOut = fourdOut, formula = formula, subjData = subjData, mc.preschedule = mc.preschedule, ncores = ncores, ...) print("Creating residual and parametric maps") return(rparMap(parameters = models, image = image, mask = mask, method = method, ncores = ncores, mc.preschedule = mc.preschedule, outDir = outDir)) } else { models <- vlmerParam(image, mask , fourdOut = fourdOut, formula = formula, subjData = subjData, mc.preschedule = mc.preschedule, ncores = ncores, ...) print("Creating parametric maps") return(parMap(parameters = models, mask = mask, method=method, outDir = outDir)) } }
/scratch/gouwar.j/cran-all/cranData/voxel/R/lmerNIfTI.R
#' Run a Linear Mixed Effects Model on all voxels of a NIfTI image within a mask. #' #' This function is able to run a Linear Mixed Effect Model using the lmer() function. #' The analysis will run in all voxels in in the mask and will return parametric coefficients at each voxel #' The function relies on lmerTest to create p-values using the Satterthwaite Approximation. #' #' #' @param image Input image of type 'nifti' or vector of path(s) to images. If multiple paths, the script will call mergeNifti() and merge across time. #' @param mask Input mask of type 'nifti' or path to mask. Must be a binary mask #' @param fourdOut To be passed to mergeNifti, This is the path and file name without the suffix to save the fourd file. Default (NULL) means script won't write out 4D image. #' @param formula Must be a formula passed to lmer() #' @param subjData Dataframe containing all the covariates used for the analysis #' @param mc.preschedule Argument to be passed to mclapply, whether or not to preschedule the jobs. More info in parallel::mclapply #' @param ncores Number of cores to use #' @param ... Additional arguments passed to lmer() #' #' @return returns list of models fitted to each voxel over the masked images passed to function. #' @keywords internal #' @export #' #' #' #' @examples #' \dontrun{ #' #' image <- oro.nifti::nifti(img = array(1:1600, dim =c(4,4,4,25))) #' mask <- oro.nifti::nifti(img = array(0:1, dim = c(4,4,4,1))) #' set.seed(1) #' covs <- data.frame(x = runif(25), id = rep(1:5,5)) #' fm1 <- "~ x + (1|id)" #' models <- lmerVoxel(image, mask, formula = fm1, subjData = covs, ncores = 1, REML=T) #' } lmerVoxel <- function(image, mask , fourdOut = NULL, formula = NULL, subjData, mc.preschedule = TRUE, ncores = 1, ...) { if (missing(image)) { stop("image is missing")} if (missing(mask)) { stop("mask is missing")} if (missing(formula)) { stop("formula is missing")} if (missing(subjData)) { stop("subjData is missing")} if (class(formula) != "character") { stop("formula class must be character")} if (class(image) == "character" & length(image) == 1) { image <- oro.nifti::readNIfTI(fname=image) } else if (class(image) == "character" & length(image) > 1) { image <- mergeNiftis(inputPaths = image, direction = "t", outfile <- fourdOut) } if (class(mask) == "character" & length(mask) == 1) { mask <- oro.nifti::readNIfTI(fname=mask) } imageMat <- ts2matrix(image, mask) voxNames <- as.character(names(imageMat)) rm(image) rm(mask) gc() print("Created time series to matrix") m <- parallel::mclapply(voxNames, FUN = listFormula, formula, mc.cores = ncores) rm(formula) gc() imageMat <- cbind(imageMat, subjData) print("Created formula list") timeIn <- proc.time() print("Running test model") model <- lmerTest::lmer(m[[1]], data=imageMat, ...) print("Running parallel models") model <- parallel::mclapply(m, FUN = function(x, data, ...) { base::do.call(lmerTest::lmer, list(formula = x, data=data, ...)) }, data=imageMat, ..., mc.preschedule = mc.preschedule , mc.cores = ncores) timeOut <- proc.time() - timeIn print(timeOut[3]) print("Parallel Models Ran") return(model) }
/scratch/gouwar.j/cran-all/cranData/voxel/R/lmerVoxel.R
#' Merge NIfTI Images across specified direction #' #' This function merges nifti images together in a specified direction. #' #' @param inputPaths This is a vector of input filenames (character) #' @param direction This is the direction you want to merge your image over, x, y, z, or t #' @param outfile This is the path and file name to save the Nifti file without the suffix, passed to writeNIfTI #' @param ncores Number of cores to be used for this operation #' @param ... Additional arguments passed to readNIfTI #' @return Returns a merged NIfTI image #' @keywords internal #' @export mergeNiftis <- function(inputPaths, direction = c("x","y","z","t"), outfile = NULL, ncores = 1,...) { if (missing(inputPaths)) { stop("inputPaths is missing")} if (class(inputPaths) != "character") { stop("inputPaths is not a character vector of paths)")} if (length(inputPaths) < 2) { stop("Input Paths has less than two paths")} images <- parallel::mclapply(inputPaths, FUN = function(x) { gc() foo <- oro.nifti::readNIfTI(fname=x,...) return(list([email protected], foo@datatype)) },..., mc.cores = ncores, mc.preschedule = F) datatype <- unique(unlist((parallel::mclapply(images, FUN = function(x) { gc() return(x[[2]]) }, mc.cores=ncores, mc.preschedule = F)))) if (length(unique(datatype)) != 1) { stop("Images have different datatypes, cannot merge") } dim <- as.vector(parallel::mclapply(images, FUN = function(x) { dim(x[[1]]) }, mc.cores=ncores, mc.preschedule = T)) if (length(unique(dim)[[1]]) != length(dim(images[[1]][[1]]))) { stop("Images have different number of dimentions, cannot merge") } if (any(unique(dim)[[1]] != dim(images[[1]][[1]]))) { stop("Images have different dimentions, cannot merge") } if (length(unique(dim)[[1]]) == 4) { if (direction == "t") { timeIndex <- length(images) * dim(images[[1]][[1]])[4] mergedArray <- array(data=NA, dim=c(dim(images[[1]][[1]])[1:3], timeIndex)) ImageL <- dim(images[[1]][[1]])[4] for (i in 1:length(images)) { mergedArray[,,,(1 + (i - 1)*ImageL ):((i)*ImageL)] <- images[[i]][[1]] } rm(images) mergedNifti <- oro.nifti::nifti(img = mergedArray, datatype = datatype) rm(mergedArray) gc() } if (direction == "x") { timeIndex <- length(images) * dim(images[[1]][[1]])[1] mergedArray <- array(data=NA, dim=c( timeIndex, dim(images[[1]][[1]])[2:4])) ImageL <- dim(images[[1]][[1]])[1] for (i in 1:length(images)) { mergedArray[(1 + (i - 1)*ImageL ):((i)*ImageL),,,] <- images[[i]][[1]] } rm(images) mergedNifti <- oro.nifti::nifti(img = mergedArray, datatype = datatype) rm(mergedArray) gc() } if (direction == "y") { timeIndex <- length(images) * dim(images[[1]][[1]])[2] mergedArray <- array(data=NA, dim=c(dim(images[[1]][[1]])[1], timeIndex, dim(images[[1]][[1]])[3:4])) ImageL <- dim(images[[1]][[1]])[2] for (i in 1:length(images)) { mergedArray[,(1 + (i - 1)*ImageL ):((i)*ImageL),,] <- images[[i]][[1]] } rm(images) mergedNifti <- oro.nifti::nifti(img = mergedArray, datatype = datatype) rm(mergedArray) gc() } if (direction == "z") { timeIndex <- length(images) * dim(images[[1]][[1]])[3] mergedArray <- array(data=NA, dim=c(dim(images[[1]][[1]])[1:2], timeIndex, dim(images[[1]][[1]])[4])) ImageL <- dim(images[[1]][[1]])[3] for (i in 1:length(images)) { mergedArray[,,(1 + (i - 1)*ImageL ):((i)*ImageL),] <- images[[i]][[1]] } rm(images) mergedNifti <- oro.nifti::nifti(img = mergedArray, datatype = datatype) rm(mergedArray) gc() } } if (length(unique(dim)[[1]]) == 3) { if (direction == "t") { timeIndex <- length(images) mergedArray <- array(data=NA, dim=c(dim(images[[1]][[1]])[1:3], timeIndex)) ImageL <- 1 for (i in 1:length(images)) { mergedArray[,,,(1 + (i - 1)*ImageL ):((i)*ImageL)] <- images[[i]][[1]] } rm(images) mergedNifti <- oro.nifti::nifti(img = mergedArray, datatype = datatype) rm(mergedArray) gc() } if (direction == "x") { timeIndex <- length(images) * dim(images[[1]][[1]])[1] mergedArray <- array(data=NA, dim=c( timeIndex, dim(images[[1]][[1]])[2:3])) ImageL <- dim(images[[1]][[1]])[1] for (i in 1:length(images)) { mergedArray[(1 + (i - 1)*ImageL ):((i)*ImageL),,] <- images[[i]][[1]] } rm(images) mergedNifti <- oro.nifti::nifti(img = mergedArray, datatype = datatype) rm(mergedArray) gc() } if (direction == "y") { timeIndex <- length(images) * dim(images[[1]][[1]])[2] mergedArray <- array(data=NA, dim=c(dim(images[[1]][[1]])[1], timeIndex, dim(images[[1]][[1]])[3])) ImageL <- dim(images[[1]][[1]])[2] for (i in 1:length(images)) { mergedArray[,(1 + (i - 1)*ImageL ):((i)*ImageL),] <- images[[i]][[1]] } rm(images) mergedNifti <- oro.nifti::nifti(img = mergedArray, datatype = datatype) rm(mergedArray) gc() } if (direction == "z") { timeIndex <- length(images) * dim(images[[1]][[1]])[3] mergedArray <- array(data=NA, dim=c(dim(images[[1]][[1]])[1:2], timeIndex)) ImageL <- dim(images[[1]][[1]])[3] for (i in 1:length(images)) { mergedArray[,,(1 + (i - 1)*ImageL ):((i)*ImageL)] <- images[[i]][[1]] } rm(images) mergedNifti <- oro.nifti::nifti(img = mergedArray, datatype = datatype) rm(mergedArray) gc() } } if (length(unique(dim)[[1]]) == 2) { if (direction == "t") { stop("Cannot merge a 2D image in the time; chose one of -xyz") } if (direction == "x") { timeIndex <- length(images) * dim(images[[1]][[1]])[1] mergedArray <- array(data=NA, dim=c( timeIndex, dim(images[[1]][[1]])[2])) ImageL <- dim(images[[1]][[1]])[1] for (i in 1:length(images)) { mergedArray[(1 + (i - 1)*ImageL ):((i)*ImageL),] <- images[[i]][[1]] } rm(images) mergedNifti <- oro.nifti::nifti(img = mergedArray, datatype = datatype) rm(mergedArray) gc() } if (direction == "y") { timeIndex <- length(images) * dim(images[[1]][[1]])[2] mergedArray <- array(data=NA, dim=c(dim(images[[1]][[1]])[1], timeIndex)) ImageL <- dim(images[[1]][[1]])[2] for (i in 1:length(images)) { mergedArray[,(1 + (i - 1)*ImageL ):((i)*ImageL)] <- images[[i]][[1]] } rm(images) mergedNifti <- oro.nifti::nifti(img = mergedArray, datatype = datatype) rm(mergedArray) gc() } if (direction == "z") { timeIndex <- length(images) mergedArray <- array(data=NA, dim=c(dim(images[[1]][[1]])[1:2], timeIndex)) ImageL <- 1 for (i in 1:length(images)) { mergedArray[,,(1 + (i - 1)*ImageL ):((i)*ImageL)] <- images[[i]][[1]] } rm(images) mergedNifti <- oro.nifti::nifti(img = mergedArray, datatype = datatype) rm(mergedArray) gc() } } if (!base::is.null(outfile)) { oro.nifti::writeNIfTI(mergedNifti, filename=outfile) } return(mergedNifti) }
/scratch/gouwar.j/cran-all/cranData/voxel/R/mergeNiftis.R
#' Create parametric maps #' #' This function create parametric maps according from model parametric tables or analysis of variance tables. #' The function will return a p-map, t-map, signed z-map, p-adjusted-map for parametric terms and p-map, z-map, p-adjusted-map for smooth terms. #' Additionally the function will return a p-map, F-map, p-to-z-map, and p-adjusted-map if the input is ANOVA. #' You can select which type of p-value correction you want done on the map. The z-maps are signed just like FSL. #' #' @param parameters list of parametric and smooth table coefficients or ANOVA (like the output from vlmParam, vgamParam, anovalmVoxel) #' @param mask Input mask of type 'nifti' or path to one. Must be a binary mask or a character. Must match the mask passed to one of vlmParam, vgamParam, vgamm4Param, vlmerParam #' @param method which method of correction for multiple comparisons (default is none) #' @param outDir Path to the folder where to output parametric maps (Default is Null, only change if you want to write maps out) #' #' @return Return parametric maps of the fitted models #' #' @export #' @examples #' image <- oro.nifti::nifti(img = array(1:1600, dim =c(4,4,4,25))) #' mask <- oro.nifti::nifti(img = array(0:1, dim = c(4,4,4,1))) #' set.seed(1) #' covs <- data.frame(x = runif(25), y = runif(25)) #' fm1 <- "~ x + y" #' models <- vlmParam(image=image, mask=mask, #' formula=fm1, subjData=covs, ncores = 1) #' Maps <- parMap(models, mask, method="fdr") parMap <- function(parameters, mask, method="none", outDir = NULL) { if (missing(parameters)) { stop("parameters is missing")} if (missing(mask)) { stop("mask is missing")} ParameterMaps <- list(NA) names(ParameterMaps) <- "temp" if (class(mask) == "character" & length(mask) == 1) { mask <- oro.nifti::readNIfTI(fname=mask) } if (class(parameters[[1]])[1] == "anova") { if (dim(parameters[[1]])[2] == 5) { print("Working with anova.lm object") for (j in 1:(dim(parameters[[1]])[1] - 1)) { pOut<-matrix(NA,nrow=length(parameters),ncol=1) FOut<-matrix(NA,nrow=length(parameters),ncol=1) zOut<-matrix(NA,nrow=length(parameters),ncol=1) variable <- rownames(parameters[[1]])[j] pvalIndex <- which(colnames(parameters[[1]]) == "Pr(>F)") FvalIndex <- which(colnames(parameters[[1]]) == "F value") for( i in 1:length(parameters)){ pOut[i,1]<- parameters[[i]][which(rownames(parameters[[i]]) == variable),pvalIndex] FOut[i,1]<- parameters[[i]][which(rownames(parameters[[i]]) == variable),FvalIndex] zOut[i,1]<- stats::qnorm(parameters[[i]][which(rownames(parameters[[i]]) == variable),pvalIndex] / 2, lower.tail=F) } pOutImage<-mask zOutImage<-mask FOutImage<-mask [email protected][[email protected]]<-pOut [email protected][[email protected]]<-zOut [email protected][[email protected]]<-FOut pAdjustedOutImage<-mask pAdjustedOut <- stats::p.adjust(pOut, method=method) [email protected][[email protected]]<-pAdjustedOut var <- gsub("\\(", "", variable) var <- gsub("\\)", "", var) var <- gsub("\\*","and",var) var <- gsub(":","and",var) tempNames <- names(ParameterMaps) ParameterMaps <- c(ParameterMaps, list(pOutImage), list(FOutImage), list(zOutImage), list(pAdjustedOutImage)) names(ParameterMaps) <- c(tempNames, paste0(var,"_pAnovaMap"), paste0(var,"_FAnovaMap"), paste0(var, "_zAnovaMap"), paste0(var, "_MultipleComp_pAnovaAdjusted_",method,"_Map")) } } else if (dim(parameters[[1]])[2] == 6) { print("Working with anova.merModLmerTest object") for (j in 1:(dim(parameters[[1]])[1])) { pOut<-matrix(NA,nrow=length(parameters),ncol=1) FOut<-matrix(NA,nrow=length(parameters),ncol=1) zOut<-matrix(NA,nrow=length(parameters),ncol=1) variable <- rownames(parameters[[1]])[j] pvalIndex <- which(colnames(parameters[[1]]) == "Pr(>F)") FvalIndex <- which(colnames(parameters[[1]]) == "F.value") for( i in 1:length(parameters)){ FOut[i,1]<- parameters[[i]][which(rownames(parameters[[i]]) == variable),FvalIndex] pOut[i,1]<- stats::pf(FOut[i,1], parameters[[i]]$NumDF[which(rownames(parameters[[i]]) == variable)], parameters[[i]]$DenDF[which(rownames(parameters[[i]]) == variable)], lower.tail = F) zOut[i,1]<- stats::qnorm(parameters[[i]][which(rownames(parameters[[i]]) == variable),pvalIndex] / 2, lower.tail=F) } pOutImage<-mask zOutImage<-mask FOutImage<-mask [email protected][[email protected]]<-pOut [email protected][[email protected]]<-zOut [email protected][[email protected]]<-FOut pAdjustedOutImage<-mask pAdjustedOut <- stats::p.adjust(pOut, method=method) [email protected][[email protected]]<-pAdjustedOut var <- gsub("\\(", "", variable) var <- gsub("\\)", "", var) var <- gsub("\\*","and",var) var <- gsub(":","and",var) tempNames <- names(ParameterMaps) ParameterMaps <- c(ParameterMaps, list(pOutImage), list(FOutImage), list(zOutImage), list(pAdjustedOutImage)) names(ParameterMaps) <- c(tempNames, paste0(var,"_pAnovaMap"), paste0(var,"_FAnovaMap"), paste0(var, "_zAnovaMap"), paste0(var, "_MultipleComp_pAnovaAdjusted_",method,"_Map")) } } } if (!is.null(names(parameters[[1]]))) { if (length(names(parameters[[1]])) == 2) { if (all(names(parameters[[1]]) == c("anovaPTable","anovaSTable"))) { print("Working with anova.gam object") if (!is.null(parameters[[1]]$anovaPTable)) { for (j in 1:(dim(parameters[[1]]$anovaPTable)[1])) { pOut<-matrix(NA,nrow=length(parameters),ncol=1) FOut<-matrix(NA,nrow=length(parameters),ncol=1) zOut<-matrix(NA,nrow=length(parameters),ncol=1) variable <- rownames(parameters[[1]]$anovaPTable)[j] pvalIndex <- which(colnames(parameters[[1]]$anovaPTable) == "p-value") FvalIndex <- which(colnames(parameters[[1]]$anovaPTable) == "F") for( i in 1:length(parameters)){ pOut[i,1]<- parameters[[i]]$anovaPTable[which(rownames(parameters[[i]]$anovaPTable) == variable),pvalIndex] FOut[i,1]<- parameters[[i]]$anovaPTable[which(rownames(parameters[[i]]$anovaPTable) == variable),FvalIndex] zOut[i,1]<- stats::qnorm(parameters[[i]]$anovaPTable[which(rownames(parameters[[i]]$anovaPTable) == variable),pvalIndex] / 2, lower.tail=F) } pOutImage<-mask zOutImage<-mask FOutImage<-mask [email protected][[email protected]]<-pOut [email protected][[email protected]]<-zOut [email protected][[email protected]]<-FOut pAdjustedOutImage<-mask pAdjustedOut <- stats::p.adjust(pOut, method=method) [email protected][[email protected]]<-pAdjustedOut var <- gsub("\\(", "", variable) var <- gsub("\\)", "", var) var <- gsub("\\*","and",var) var <- gsub(":","and",var) tempNames <- names(ParameterMaps) ParameterMaps <- c(ParameterMaps, list(pOutImage), list(FOutImage), list(zOutImage), list(pAdjustedOutImage)) names(ParameterMaps) <- c(tempNames, paste0(var,"_pAnovaMap"), paste0(var,"_FAnovaMap"), paste0(var, "_zAnovaMap"), paste0(var, "_MultipleComp_pAnovaAdjusted_",method,"_Map")) } } if (!is.null(parameters[[1]]$anovaSTable)) { for (j in 1:(dim(parameters[[1]]$anovaSTable)[1])) { pOut<-matrix(NA,nrow=length(parameters),ncol=1) FOut<-matrix(NA,nrow=length(parameters),ncol=1) zOut<-matrix(NA,nrow=length(parameters),ncol=1) variable <- rownames(parameters[[1]]$anovaSTable)[j] pvalIndex <- which(colnames(parameters[[1]]$anovaSTable) == "p-value") FvalIndex <- which(colnames(parameters[[1]]$anovaSTable) == "F") for( i in 1:length(parameters)){ pOut[i,1]<- parameters[[i]]$anovaSTable[which(rownames(parameters[[i]]$anovaSTable) == variable),pvalIndex] FOut[i,1]<- parameters[[i]]$anovaSTable[which(rownames(parameters[[i]]$anovaSTable) == variable),FvalIndex] zOut[i,1]<- stats::qnorm(parameters[[i]]$anovaSTable[which(rownames(parameters[[i]]$anovaSTable) == variable),pvalIndex] / 2, lower.tail=F) } pOutImage<-mask zOutImage<-mask FOutImage<-mask [email protected][[email protected]]<-pOut [email protected][[email protected]]<-zOut [email protected][[email protected]]<-FOut pAdjustedOutImage<-mask pAdjustedOut <- stats::p.adjust(pOut, method=method) [email protected][[email protected]]<-pAdjustedOut var <- gsub("\\(", "", variable) var <- gsub("\\)", "", var) var <- gsub("\\*","and",var) var <- gsub(":","and",var) tempNames <- names(ParameterMaps) ParameterMaps <- c(ParameterMaps, list(pOutImage), list(FOutImage), list(zOutImage), list(pAdjustedOutImage)) names(ParameterMaps) <- c(tempNames, paste0(var,"_pAnovaMap"), paste0(var,"_FAnovaMap"), paste0(var, "_zAnovaMap"), paste0(var, "_MultipleComp_pAnovaAdjusted_",method,"_Map")) } } } } } if (length(parameters[[1]]) == 2) { if (!all(names(parameters[[1]]) == c("anovaPTable","anovaSTable"))) { print("Working with output of gam object") if (!is.null(dim(parameters[[1]][[1]]))) { for (j in 1:dim(parameters[[1]][[1]])[1]) { pOut<-matrix(NA,nrow=length(parameters),ncol=1) tOut<-matrix(NA,nrow=length(parameters),ncol=1) zOut<-matrix(NA,nrow=length(parameters),ncol=1) variable <- rownames(parameters[[1]][[1]])[j] pvalIndex <- which(colnames(parameters[[1]][[1]]) == "Pr(>|t|)") tvalIndex <- which(colnames(parameters[[1]][[1]]) == "t value") for( i in 1:length(parameters)){ pOut[i,1]<- parameters[[i]][[1]][which(rownames(parameters[[i]][[1]]) == variable),pvalIndex] tOut[i,1]<- parameters[[i]][[1]][which(rownames(parameters[[i]][[1]]) == variable),tvalIndex] zOut[i,1]<- sign(tOut[i,1])*stats::qnorm(parameters[[i]][[1]][which(rownames(parameters[[i]][[1]]) == variable),pvalIndex] / 2, lower.tail=F) } pOutImage<-mask pAdjustedOutImage<-mask zOutImage<-mask tOutImage<-mask pAdjustedOut <- stats::p.adjust(pOut, method=method) [email protected][[email protected]]<-pOut [email protected][[email protected]]<-pAdjustedOut [email protected][[email protected]]<-zOut [email protected][[email protected]]<-tOut var <- gsub("\\(", "", variable) var <- gsub("\\)", "", var) var <- gsub("\\*","and",var) var <- gsub(":","and",var) tempNames <- names(ParameterMaps) ParameterMaps <- c(ParameterMaps, list(pOutImage), list(tOutImage), list(zOutImage), list(pAdjustedOutImage)) names(ParameterMaps) <- c(tempNames, paste0(var,"_pMap"), paste0(var,"_tMap"), paste0(var, "_zMap"), paste0(var, "_multipleComp_pAdjusted_",method,"_Map")) } } if (!is.null(dim(parameters[[1]][[2]]))) { for (j in 1:dim(parameters[[1]][[2]])[1]) { pOut<-matrix(NA,nrow=length(parameters),ncol=1) zOut<-matrix(NA,nrow=length(parameters),ncol=1) variable <- rownames(parameters[[1]][[2]])[j] pvalIndex <- which(colnames(parameters[[1]][[2]]) == "p-value") for(i in 1:length(parameters)){ pOut[i,1]<- parameters[[i]][[2]][which(rownames(parameters[[i]][[2]]) == variable),pvalIndex] zOut[i,1]<- stats::qnorm(parameters[[i]][[2]][which(rownames(parameters[[i]][[2]]) == variable),pvalIndex] / 2, lower.tail=F) } pOutImage<-mask [email protected][[email protected]==1]<-pOut zOutImage<-mask [email protected][[email protected]==1]<-zOut pAdjustedOutImage<-mask pAdjustedOut <- stats::p.adjust(pOut, method=method) [email protected][[email protected]]<-pAdjustedOut var <- gsub("\\(", "", variable) var <- gsub("\\)", "", var) var <- gsub(",", "", var) var <- gsub("=", "", var) tempNames <- names(ParameterMaps) ParameterMaps <- c(ParameterMaps, list(pOutImage), list(zOutImage), list(pAdjustedOutImage)) names(ParameterMaps) <- c(tempNames, paste0(var,"_pMap"), paste0(var, "_zMap"), paste0(var, "_multipleComp_pAdjusted_",method,"_Map")) } } } } if (length(colnames(parameters[[1]])) == 4) { if (all(colnames(parameters[[1]]) == c("Estimate","Std. Error","t value","Pr(>|t|)"))) { print("Working with output from lm model") for (j in 1:dim(parameters[[1]])[1]) { pOut<-matrix(NA,nrow=length(parameters),ncol=1) tOut<-matrix(NA,nrow=length(parameters),ncol=1) zOut<-matrix(NA,nrow=length(parameters),ncol=1) variable <- rownames(parameters[[1]])[j] pvalIndex <- which(colnames(parameters[[1]]) == "Pr(>|t|)") tvalIndex <- which(colnames(parameters[[1]]) == "t value") for( i in 1:length(parameters)){ pOut[i,1]<- parameters[[i]][which(rownames(parameters[[i]]) == variable),pvalIndex] tOut[i,1]<- parameters[[i]][which(rownames(parameters[[i]]) == variable),tvalIndex] zOut[i,1]<- sign(tOut[i,1])*stats::qnorm(parameters[[i]][which(rownames(parameters[[i]]) == variable),pvalIndex] / 2, lower.tail=F) } pOutImage<-mask zOutImage<-mask tOutImage<-mask [email protected][[email protected]]<-pOut [email protected][[email protected]]<-zOut [email protected][[email protected]]<-tOut pAdjustedOutImage<-mask pAdjustedOut <- stats::p.adjust(pOut, method=method) [email protected][[email protected]]<-pAdjustedOut var <- gsub("\\(", "", variable) var <- gsub("\\)", "", var) var <- gsub("\\*","and",var) var <- gsub(":","and",var) tempNames <- names(ParameterMaps) ParameterMaps <- c(ParameterMaps, list(pOutImage), list(tOutImage), list(zOutImage), list(pAdjustedOutImage)) names(ParameterMaps) <- c(tempNames, paste0(var,"_pMap"), paste0(var,"_tMap"), paste0(var, "_zMap"), paste0(var, "_multipleComp_pAdjusted_",method,"_Map")) } } } if (length(colnames(parameters[[1]])) == 5) { if (all(colnames(parameters[[1]]) == c("Estimate","Std. Error","df","t value","Pr(>|t|)"))) { print("Working with output from lmerTest model") for (j in 1:dim(parameters[[1]])[1]) { pOut<-matrix(NA,nrow=length(parameters),ncol=1) tOut<-matrix(NA,nrow=length(parameters),ncol=1) zOut<-matrix(NA,nrow=length(parameters),ncol=1) variable <- rownames(parameters[[1]])[j] pvalIndex <- which(colnames(parameters[[1]]) == "Pr(>|t|)") tvalIndex <- which(colnames(parameters[[1]]) == "t value") for( i in 1:length(parameters)){ tOut[i,1]<- parameters[[i]][which(rownames(parameters[[i]]) == variable),tvalIndex] pOut[i,1]<- stats::pt(abs(tOut[i,1]), parameters[[i]][which(rownames(parameters[[i]]) == variable), which(colnames(parameters[[1]]) == "df")], lower.tail=F)*2 zOut[i,1]<- sign(tOut[i,1])*stats::qnorm(parameters[[i]][which(rownames(parameters[[i]]) == variable),pvalIndex] / 2, lower.tail=F) } pOutImage<-mask zOutImage<-mask tOutImage<-mask [email protected][[email protected]]<-pOut [email protected][[email protected]]<-zOut [email protected][[email protected]]<-tOut pAdjustedOutImage<-mask pAdjustedOut <- stats::p.adjust(pOut, method=method) [email protected][[email protected]]<-pAdjustedOut var <- gsub("\\(", "", variable) var <- gsub("\\)", "", var) var <- gsub("\\*","and",var) var <- gsub(":","and",var) tempNames <- names(ParameterMaps) ParameterMaps <- c(ParameterMaps, list(pOutImage), list(tOutImage), list(zOutImage), list(pAdjustedOutImage)) names(ParameterMaps) <- c(tempNames, paste0(var,"_pMap"), paste0(var,"_tMap"), paste0(var, "_zMap"), paste0(var, "_multipleComp_pAdjusted_",method,"_Map")) } } } ParameterMaps <- ParameterMaps[-1] if (length(ParameterMaps) == 0) { stop("Input object not recognized") } if (!is.null(outDir)) { dirPath <- base::paste(strsplit(outDir, "/")[[1]][1:(length(strsplit(outDir, "/")[[1]]))], collapse = "/") print(base::paste("Checking if", dirPath ,"Exists")) if (!dir.exists(dirPath)) { print("Directory is missing, creating it now") dir.create(dirPath) } for (i in 1:length(names(ParameterMaps))) { outPath <- base::paste(outDir, names(ParameterMaps)[i], sep = "/") oro.nifti::writeNIfTI(ParameterMaps[[i]], filename = outPath, gzipped = T) } } return(ParameterMaps) }
/scratch/gouwar.j/cran-all/cranData/voxel/R/parMap.R
#' GAM plotting using ggplot2 #' #' @family Plotting #' @param gamFit fitted gam model as produced by mgcv::gam() #' @param smooth.cov (character) name of smooth term to be plotted #' @param groupCovs (character) name of group variable to plot by, if NULL (default) then there are no groups in plot #' @param orderedAsFactor if TRUE then the model is refitted with ordered variables as factors. #' @param rawOrFitted If FALSE (default) then only smooth terms are plotted; if rawOrFitted = "raw" then raw values are plotted against smooth; if rawOrFitted = "fitted" then fitted values are plotted against smooth #' @param plotCI if TRUE (default) upper and lower confidence intervals are added at 2 standard errors above and below the mean #' #' @return Returns a ggplot object that can be visualized using the print() function #' #' @export #' #' @examples #' #' data <- data.frame(x = rep(1:20, 2), group = rep(1:2, each = 20)) #' set.seed(1) #' data$y <- (data$x^2)*data$group*3 + rnorm(40, sd = 200) #' data$group <- ordered(data$group) #' #' gam <- mgcv::gam(y ~ s(x) + group, data=data) #' #' plot1 <- plotGAM(gamFit = gam, smooth.cov = "x", groupCovs = NULL, #' rawOrFitted = "raw", plotCI=TRUE, orderedAsFactor = FALSE) #' gam <- mgcv::gam(y ~ s(x) + group + s(x, by=group), data=data) #' plot2 <- plotGAM(gamFit = gam, smooth.cov = "x", groupCovs = "group", #' rawOrFitted = "raw", orderedAsFactor = FALSE) plotGAM <- function(gamFit, smooth.cov , groupCovs = NULL, orderedAsFactor = T, rawOrFitted = F, plotCI = T) { if (missing(gamFit)) { stop("gamFit is missing")} if (missing(smooth.cov)) { stop("smooth.cov is missing")} if (class(smooth.cov) != "character") { stop("smooth.cov must be a character")} if (class(groupCovs) != "character" & (!is.null(groupCovs))) { stop("groupCovs must be a character")} if (!(rawOrFitted == F | rawOrFitted == "raw" | rawOrFitted == "fitted")) { stop("Wrong input for rawOrFitted") } fit <- fitted <- group <- se.fit <- NULL if (base::class(gamFit)[1] != "gam") { stop("gamFit is not a object of type gam") } if (base::is.null(groupCovs)) { gam <- gamFit temp.data <- gam$model old.formula <- gam$formula old.covariates <- base::as.character(old.formula)[3] old.covariates <- base::gsub(" ", "", old.covariates) main.smooth <- base::paste0("s(", smooth.cov) interaction.smooth <- base::paste0("s(", smooth.cov, ",by=") if (!base::grepl(pattern = main.smooth, old.covariates, fixed=T)) { base::stop("smooth.cov is not included in formula for original model fit") } if (base::grepl(pattern = interaction.smooth, old.covariates, fixed=T)) { base::stop("smooth.cov has an interaction term in original model fit, pass groupCovs as an argument") } plot.df = base::data.frame( x = base::seq(min(temp.data[smooth.cov]), max(temp.data[smooth.cov]), length.out=200)) base::names(plot.df) <- smooth.cov for (i in base::names(temp.data)[-1]) { if (i != smooth.cov) { if (base::any(base::class(temp.data[i][,1])[1] == c("numeric", "integer","boolean"))) { plot.df[, base::dim(plot.df)[2] + 1] <- base::mean(temp.data[i][,1]) base::names(plot.df)[base::dim(plot.df)[2]] <- i } else if (base::any(base::class(temp.data[i][,1])[1] == c("character", "factor","ordered"))) { plot.df[, base::dim(plot.df)[2] + 1] <- temp.data[i][1,1] base::names(plot.df)[base::dim(plot.df)[2]] <- i } else { stop(base::paste("Unrecognized data type for",i,"please refit cluster model with different datatype")) } } } for (i in 1:dim(plot.df)[2]) { if (class(plot.df[,i])[1] == "ordered" | class(plot.df[,i])[1] == "factor") { warning("There are one or more factors in the model fit, please consider plotting by group since plot might be unprecise") } } plot.df = base::cbind(plot.df, base::as.data.frame(mgcv::predict.gam(gam, plot.df, se.fit = TRUE))) if (plotCI) { plot <- (ggplot2::ggplot(data=plot.df, ggplot2::aes(x=plot.df[,1])) + ggplot2::geom_line(ggplot2::aes(y=fit), size=1) + ggplot2::geom_ribbon(data=plot.df, ggplot2::aes(ymax = fit+1.96*se.fit, ymin = fit-1.96*se.fit, linetype=NA), alpha = .2) + ggplot2::ggtitle(base::paste0(base::as.character(old.formula)[2], " vs. s(",smooth.cov,")")) + ggplot2::ylab(base::paste0("Predicted ", base::as.character(old.formula)[2])) + ggplot2::xlab(base::paste0("s(",smooth.cov,")")) + ggplot2::theme_bw()) } else { plot <- (ggplot2::ggplot(data=plot.df, ggplot2::aes(x=plot.df[,1])) + ggplot2::geom_line(ggplot2::aes(y=fit), size=1) + ggplot2::ggtitle(base::paste0(base::as.character(old.formula)[2], " vs. s(",smooth.cov,")")) + ggplot2::ylab(base::paste0("Predicted ", base::as.character(old.formula)[2])) + ggplot2::xlab(base::paste0("s(",smooth.cov,")")) + ggplot2::theme_bw()) } if (rawOrFitted == "raw") { plot <- plot + ggplot2::geom_point(data = temp.data, ggplot2::aes(x=purrr::as_vector(temp.data[smooth.cov]), y=temp.data[,1])) base::return(plot) } else if (rawOrFitted == "fitted") { temp.data$fitted <- gam$fitted.values plot <- plot + ggplot2::geom_point(data = temp.data, ggplot2::aes(x=purrr::as_vector(temp.data[smooth.cov]), y=fitted)) base::return(plot) } else { base::return(plot) } } else if (base::is.character(groupCovs)) { gam <- gamFit temp.data <- gam$model old.formula <- gam$formula old.covariates <- base::as.character(old.formula)[3] old.covariates <- base::gsub(" ", "", old.covariates) main.smooth <- base::paste0("s(", smooth.cov) interaction.smooth <- base::paste0("s(", smooth.cov, ",by=") if(regexpr(groupCovs, as.character(old.covariates))[1] == 1) { old.covariates <- paste0("+", old.covariates) } main.group <- base::paste0("+", groupCovs) if (!base::grepl(pattern = main.group, old.covariates, fixed=T)) { base::stop("Error groupCovs is not included as a main effect in original model, include in original fit") } temp.fm <- strsplit(old.covariates, split='+', fixed = T)[[1]] for (i in 1:length(temp.fm)) { if (grepl(main.smooth, temp.fm[i], fixed=T)) { temp.term <- strsplit(temp.fm[i], split=',', fixed = T)[[1]] if (length(temp.term) > 1) { for (j in 2:length(temp.term)) { if (grepl('=',temp.term[j])) { if(grepl('by',temp.term[j])) { order <- 1:length(temp.term) order <- setdiff(order, j) if (all(order == 1)) { order <- c(1,2) temp.term <- temp.term[order] } else { order <- c(order, NA) order <- order[c(1, length(order), 2:(length(order) - 1))] order[2] <- j temp.term <- temp.term[order] temp.term <- gsub(pattern=")", replacement = "", x = temp.term) temp.term[length(temp.term)]<- paste0(temp.term[length(temp.term)], ")") } } } else { base::stop("spline containing smooth.cov has more than one variable, refit with only one") } } } temp.fm[i] <- toString(temp.term) } } old.covariates <- paste0(temp.fm, collapse="+") old.covariates <- base::gsub(" ", "", old.covariates) if (!base::grepl(pattern = main.smooth, old.covariates, fixed=T) & base::class(temp.data[groupCovs][,1])[1] == "ordered") { base::stop("smooth.cov is not included in formula for original model fit, model might be incorrectly parametrized") } else if (!base::grepl(pattern = interaction.smooth, old.covariates, fixed=T)) { base::warning("smooth.cov has no interaction term in original model fit") foo <- base::seq(min(temp.data[smooth.cov]), max(temp.data[smooth.cov]), length.out=200) plot.df = base::data.frame( x = rep(foo, nlevels(as.factor(temp.data[groupCovs][,1])))) base::names(plot.df) <- smooth.cov plot.df$temp <- rep(levels(as.factor(temp.data[groupCovs][,1])), each = 200) base::names(plot.df)[2] <- groupCovs for (i in base::names(temp.data)[-1]) { if (!(i == smooth.cov | i == groupCovs)) { if (base::any(base::class(temp.data[i][,1])[1] == c("numeric", "integer","boolean"))) { plot.df[, base::dim(plot.df)[2] + 1] <- base::mean(temp.data[i][,1]) base::names(plot.df)[base::dim(plot.df)[2]] <- i } else if (base::any(base::class(temp.data[i][,1])[1] == c("character", "factor","ordered"))) { plot.df[, base::dim(plot.df)[2] + 1] <- temp.data[i][1,1] base::names(plot.df)[base::dim(plot.df)[2]] <- i } else { stop(base::paste("Unrecognized data type for",i,"please refit cluster model with different datatype")) } } } plot.df = base::cbind(plot.df, base::as.data.frame(mgcv::predict.gam(gam, plot.df, se.fit = TRUE))) plot.df$group <- plot.df[,2] if (plotCI) { plot <- (ggplot2::ggplot(data=plot.df, ggplot2::aes(x=plot.df[,1])) + ggplot2::geom_line(ggplot2::aes(y=fit, col=factor(group)), size=1) + ggplot2::geom_ribbon(data=plot.df, ggplot2::aes(ymax = fit+1.96*se.fit, ymin = fit-1.96*se.fit, col=factor(group), linetype=NA), alpha = .2) + ggplot2::ggtitle(base::paste0(base::as.character(old.formula)[2], " vs. s(",smooth.cov,")")) + ggplot2::ylab(base::paste0("Predicted ", base::as.character(old.formula)[2])) + ggplot2::xlab(base::paste0("s(",smooth.cov,")")) + ggplot2::scale_colour_discrete(name = groupCovs) + ggplot2::theme_bw()) } else { plot <- (ggplot2::ggplot(data=plot.df, ggplot2::aes(x=plot.df[,1])) + ggplot2::geom_line(ggplot2::aes(y=fit, col=factor(group)), size=1) + ggplot2::ggtitle(base::paste0(base::as.character(old.formula)[2], " vs. s(",smooth.cov,")")) + ggplot2::ylab(base::paste0("Predicted ", base::as.character(old.formula)[2])) + ggplot2::xlab(base::paste0("s(",smooth.cov,")")) + ggplot2::scale_colour_discrete(name = groupCovs) + ggplot2::theme_bw()) } if (rawOrFitted == "raw") { plot <- plot + ggplot2::geom_point(data = temp.data, ggplot2::aes(x=purrr::as_vector(temp.data[smooth.cov]), y=temp.data[,1], col=temp.data[groupCovs][,1])) base::return(plot) } else if (rawOrFitted == "fitted") { temp.data$fitted <- gam$fitted.values plot <- plot + ggplot2::geom_point(data = temp.data, ggplot2::aes(x=purrr::as_vector(temp.data[smooth.cov]), y=fitted, col=temp.data[groupCovs][,1])) base::return(plot) } else { base::return(plot) } } else { main.group <- base::paste0("+", groupCovs) if (!base::grepl(pattern = main.group, old.covariates, fixed=T)) { base::stop("groupCovs is not included as main effect in original model, please include in original fit") } if (base::class(temp.data[groupCovs][,1])[1] == "ordered" & orderedAsFactor) { base::warning("groupCovs is an ordered variable in original fit, reffiting model with groupCovs as a factor") temp.data[groupCovs] <- as.factor(as.character(temp.data[groupCovs][,1])) textCall <- gam$call temp.fm.updated <- strsplit(old.covariates, split='+', fixed = T)[[1]] index.Main <- setdiff(grep(pattern = main.smooth, x = temp.fm.updated, fixed = T), grep(pattern = interaction.smooth, x = temp.fm.updated, fixed = T)) temp.fm.updated <- temp.fm[-index.Main] updatedCovs <- paste0(temp.fm.updated, collapse="+") updatedCovs <- base::gsub(" ", "", updatedCovs) updatedformula <- stats::as.formula(paste(old.formula[2], old.formula[1], updatedCovs)) new.data <- temp.data gam <- stats::update(gam, formula = updatedformula, data = new.data) } temp.data <- gam$model old.formula <- gam$formula old.covariates <- base::as.character(old.formula)[3] old.covariates <- base::gsub(" ", "", old.covariates) main.smooth <- base::paste0("s(", smooth.cov, ")") interaction.smooth <- base::paste0("s(", smooth.cov, ",by=") foo <- base::seq(min(temp.data[smooth.cov]), max(temp.data[smooth.cov]), length.out=200) plot.df = base::data.frame( x = rep(foo, nlevels(temp.data[groupCovs][,1]))) base::names(plot.df) <- smooth.cov plot.df$temp <- rep(levels(temp.data[groupCovs][,1]), each = 200) base::names(plot.df)[2] <- groupCovs for (i in base::names(temp.data)[-1]) { if (!(i == smooth.cov | i == groupCovs)) { if (base::any(base::class(temp.data[i][,1])[1] == c("numeric", "integer","boolean"))) { plot.df[, base::dim(plot.df)[2] + 1] <- base::mean(temp.data[i][,1]) base::names(plot.df)[base::dim(plot.df)[2]] <- i } else if (base::any(base::class(temp.data[i][,1])[1] == c("character", "factor","ordered"))) { plot.df[, base::dim(plot.df)[2] + 1] <- temp.data[i][1,1] base::names(plot.df)[base::dim(plot.df)[2]] <- i } else { stop(base::paste("Unrecognized data type for",i,"please refit cluster model with different datatype")) } } } plot.df = base::cbind(plot.df, base::as.data.frame(mgcv::predict.gam(gam, plot.df, se.fit = TRUE))) plot.df$group <- plot.df[,2] if (plotCI) { plot <- (ggplot2::ggplot(data=plot.df, ggplot2::aes(x=plot.df[,1])) + ggplot2::geom_line(ggplot2::aes(y=fit, col=factor(group)), size=1) + ggplot2::geom_ribbon(data=plot.df, ggplot2::aes(ymax = fit+1.96*se.fit, ymin = fit-1.96*se.fit, col=factor(group), linetype=NA), alpha = .2) + ggplot2::ggtitle(base::paste0(base::as.character(old.formula)[2], " vs. s(",smooth.cov,")")) + ggplot2::ylab(base::paste0("Predicted ", base::as.character(old.formula)[2])) + ggplot2::xlab(base::paste0("s(",smooth.cov,")")) + ggplot2::scale_colour_discrete(name = groupCovs) + ggplot2::theme_bw()) } else { plot <- (ggplot2::ggplot(data=plot.df, ggplot2::aes(x=plot.df[,1])) + ggplot2::geom_line(ggplot2::aes(y=fit, col=factor(group)), size=1) + ggplot2::ggtitle(base::paste0(base::as.character(old.formula)[2], " vs. s(",smooth.cov,")")) + ggplot2::ylab(base::paste0("Predicted ", base::as.character(old.formula)[2])) + ggplot2::xlab(base::paste0("s(",smooth.cov,")")) + ggplot2::scale_colour_discrete(name = groupCovs) + ggplot2::theme_bw()) } if (rawOrFitted == "raw") { plot <- plot + ggplot2::geom_point(data = temp.data, ggplot2::aes(x= purrr::as_vector(temp.data[smooth.cov]), y=temp.data[,1], col=temp.data[groupCovs][,1])) base::return(plot) } else if (rawOrFitted == "fitted") { temp.data$fitted <- gam$fitted.values plot <- plot + ggplot2::geom_point(data = temp.data, ggplot2::aes(x= purrr::as_vector(temp.data[smooth.cov]), y=fitted, col=temp.data[groupCovs][,1])) base::return(plot) } else { base::return(plot) } } } else { stop("groupCovs is not a character or null please correct") } }
/scratch/gouwar.j/cran-all/cranData/voxel/R/plotGAM.R
#' GAMM plotting using ggplot2 #' #' @family Plotting #' @param gammFit fitted gam model as produced by gamm4::gamm() #' @param smooth.cov (character) name of smooth term to be plotted #' @param groupCovs (character) name of group variable to plot by, if NULL (default) then there are no groups in plot #' @param orderedAsFactor Disabled #' @param rawOrFitted If FALSE (default) then only smooth terms are plotted; if rawOrFitted = "raw" then raw values are plotted against smooth; if rawOrFitted = "fitted" then fitted values are plotted against smooth #' @param plotCI if TRUE (default) upper and lower confidence intervals are added at 2 standard errors above and below the mean #' @param grouping (character) Name of variable that you want to use as the group argument in ggplot2::aes(), useful for better visualization of longitudinal data, (default is NULL) #' #' @return Returns a ggplot object that can be visualized using the print() function #' #' @export #' #' @examples #' #' set.seed(1) #' data <- data.frame(x = (seq(.25,25, .25) +rnorm(100)), group = rep(1:2, 5), z=rnorm(100), #' index.rnorm = rep(rnorm(50, sd = 50), 2), index.var = rep(1:50, 2)) #' data$y <- (data$x)*data$group*10 + rnorm(100, sd = 700) + data$index.rnorm + data$z #' data$group <- ordered(data$group) #' #' #' gamm <- gamm4::gamm4(y ~ + s(x) + s(x, by=group) + z + group, data=data, random = ~ (1|index.var)) #' #' #' plot <- plotGAMM(gammFit <- gamm, smooth.cov <- "x", groupCovs = "group", #' plotCI <- T, rawOrFitted = "raw", grouping = "index.var") #' #' plot2 <- plotGAMM(gammFit <- gamm, smooth.cov <- "x", groupCovs = "group", #' plotCI <- T, rawOrFitted = "fitted", grouping = "index.var") plotGAMM <- function(gammFit, smooth.cov , groupCovs = NULL, orderedAsFactor = F, rawOrFitted = F, plotCI = T, grouping = NULL) { if (missing(gammFit)) { stop("gammFit is missing")} if (missing(smooth.cov)) { stop("smooth.cov is missing")} if (class(smooth.cov) != "character") { stop("smooth.cov must be a character")} if (class(groupCovs) != "character" & (!is.null(groupCovs))) { stop("groupCovs must be a character")} if (!(rawOrFitted == F | rawOrFitted == "raw" | rawOrFitted == "fitted")) { stop("Wrong input for rawOrFitted") } fit <- fitted <- group <- se.fit <- NULL if (!(base::class(gammFit$gam) == "gam" & base::class(gammFit$mer) == "lmerMod")) { stop("gamFit is not a object created by gamm4()") } if (base::is.character(rawOrFitted)) { if (((rawOrFitted == "raw") & base::is.null(grouping))) { base::warning("grouping variable is missing will plot raw values as points rather than trajectories") } else if (((rawOrFitted == "fitted") & base::is.null(grouping))) { base::warning("grouping variable is missing will plot fitted values as points rather than trajectories") } } if (base::is.null(rawOrFitted) & !(is.null(grouping))) { warning("Ignoring grouping variable and defaulting to no raw or fitted values in plot") } if (base::is.null(groupCovs)) { gam <- gammFit$gam temp.data <- gam$model if (is.character(grouping)) { if (!any(names(temp.data) == grouping) ) { stop("grouping variable is not in model fit, please update model arguments") } } if (is.character(grouping)) { temp.data[grouping] <- as.factor(temp.data[grouping][,1]) } old.formula <- gam$formula old.covariates <- base::as.character(old.formula)[3] old.covariates <- base::gsub(" ", "", old.covariates) main.smooth <- base::paste0("s(", smooth.cov) interaction.smooth <- base::paste0("s(", smooth.cov, ",by=") if (!base::grepl(pattern = main.smooth, old.covariates, fixed=T)) { base::stop("smooth.cov is not included in formula for original model fit") } if (base::grepl(pattern = interaction.smooth, old.covariates, fixed=T)) { base::stop("smooth.cov has an interaction term in original model fit, pass groupCovs as an argument") } plot.df = base::data.frame( x = base::seq(min(temp.data[smooth.cov]), max(temp.data[smooth.cov]), length.out=200)) base::names(plot.df) <- smooth.cov for (i in names(gam$var.summary)) { if (i != smooth.cov) { if (base::any(base::class(temp.data[i][,1])[1] == c("numeric", "integer","boolean"))) { plot.df[, base::dim(plot.df)[2] + 1] <- base::mean(temp.data[i][,1]) base::names(plot.df)[base::dim(plot.df)[2]] <- i } else if (base::any(base::class(temp.data[i][,1])[1] == c("character", "factor","ordered"))) { plot.df[, base::dim(plot.df)[2] + 1] <- temp.data[i][1,1] base::names(plot.df)[base::dim(plot.df)[2]] <- i } else { stop(base::paste("Unrecognized data type for",i,"please refit cluster model with different datatype")) } } } for (i in 1:dim(plot.df)[2]) { if (class(plot.df[,i])[1] == "ordered" | class(plot.df[,i])[1] == "factor") { warning("There are one or more factors in the model fit, please consider plotting by group since plot might be unprecise") } } plot.df = base::cbind(plot.df, base::as.data.frame(mgcv::predict.gam(gam, plot.df, se.fit = TRUE))) if (plotCI) { plot <- (ggplot2::ggplot(data=plot.df, ggplot2::aes(x=plot.df[,1])) + ggplot2::geom_line(ggplot2::aes(y=fit), size=1) + ggplot2::geom_ribbon(data=plot.df, ggplot2::aes(ymax = fit+1.96*se.fit, ymin = fit-1.96*se.fit, linetype=NA), alpha = .2) + ggplot2::ggtitle(base::paste0(base::as.character(old.formula)[2], " vs. s(",smooth.cov,")")) + ggplot2::ylab(base::paste0("Predicted ", base::as.character(old.formula)[2])) + ggplot2::xlab(base::paste0("s(",smooth.cov,")")) + ggplot2::theme_bw()) } else { plot <- (ggplot2::ggplot(data=plot.df, ggplot2::aes(x=plot.df[,1])) + ggplot2::geom_line(ggplot2::aes(y=fit), size=1) + ggplot2::ggtitle(base::paste0(base::as.character(old.formula)[2], " vs. s(",smooth.cov,")")) + ggplot2::ylab(base::paste0("Predicted ", base::as.character(old.formula)[2])) + ggplot2::xlab(base::paste0("s(",smooth.cov,")")) + ggplot2::theme_bw()) } if (base::is.character(rawOrFitted)) { if (rawOrFitted == "raw" & base::is.null(grouping)) { plot <- plot + ggplot2::geom_point(data = temp.data, ggplot2::aes(x = purrr::as_vector(temp.data[smooth.cov]), y=temp.data[,1])) base::return(plot) } else if (rawOrFitted == "fitted" & base::is.null(grouping)) { temp.data$fitted <- gam$fitted.values plot <- plot + ggplot2::geom_point(data = temp.data, ggplot2::aes(x = purrr::as_vector(temp.data[smooth.cov]), y=fitted)) base::return(plot) } else if (rawOrFitted == "raw" & base::is.character(grouping)) { plot <- plot + ggplot2::geom_line(data = temp.data, ggplot2::aes(x = purrr::as_vector(temp.data[smooth.cov]), y=temp.data[,1], group=factor(temp.data[grouping][,1])), alpha=.2) base::return(plot) } else if (rawOrFitted == "fitted" & base::is.character(grouping)) { temp.data$fitted <- gam$fitted.values plot <- plot + ggplot2::geom_line(data = temp.data, ggplot2::aes(x = purrr::as_vector(temp.data[smooth.cov]), y=fitted, group=factor(temp.data[grouping][,1])), alpha=.2) base::return(plot) } } else { base::return(plot) } } else if (base::is.character(groupCovs)) { gam <- gammFit$gam temp.data <- gam$model if (is.character(grouping)) { if (!any(names(temp.data) == grouping) ) { stop("grouping variable is not in model fit, please update model arguments") } } if (is.character(grouping)) { temp.data[grouping] <- as.factor(temp.data[grouping][,1]) } old.formula <- gam$formula old.covariates <- base::as.character(old.formula)[3] old.covariates <- base::gsub(" ", "", old.covariates) main.smooth <- base::paste0("s(", smooth.cov) interaction.smooth <- base::paste0("s(", smooth.cov, ",by=") if(regexpr(groupCovs, as.character(old.covariates))[1] == 1) { old.covariates <- paste0("+", old.covariates) } main.group <- base::paste0("+", groupCovs) if (!base::grepl(pattern = main.group, old.covariates, fixed=T)) { base::stop("Error groupCovs is not included as a main effect in original model, include in original fit") } temp.fm <- strsplit(old.covariates, split='+', fixed = T)[[1]] for (i in 1:length(temp.fm)) { if (grepl(main.smooth, temp.fm[i], fixed=T)) { temp.term <- strsplit(temp.fm[i], split=',', fixed = T)[[1]] if (length(temp.term) > 1) { for (j in 2:length(temp.term)) { if (grepl('=',temp.term[j])) { if(grepl('by',temp.term[j])) { order <- 1:length(temp.term) order <- setdiff(order, j) if (all(order == 1)) { order <- c(1,2) temp.term <- temp.term[order] } else { order <- c(order, NA) order <- order[c(1, length(order), 2:(length(order) - 1))] order[2] <- j temp.term <- temp.term[order] temp.term <- gsub(pattern=")", replacement = "", x = temp.term) temp.term[length(temp.term)]<- paste0(temp.term[length(temp.term)], ")") } } } else { base::stop("spline containing smooth.cov has more than one variable, refit with only one") } } } temp.fm[i] <- toString(temp.term) } } old.covariates <- paste0(temp.fm, collapse="+") old.covariates <- base::gsub(" ", "", old.covariates) if (!base::grepl(pattern = main.smooth, old.covariates, fixed=T) & base::class(temp.data[groupCovs][,1])[1] == "ordered") { base::stop("smooth.cov is not included in formula for original model fit, model might be incorrectly parametrized") } else if (!base::grepl(pattern = interaction.smooth, old.covariates, fixed=T)) { base::warning("smooth.cov has no interaction term in original model fit") foo <- base::seq(min(temp.data[smooth.cov]), max(temp.data[smooth.cov]), length.out=200) plot.df = base::data.frame( x = rep(foo, nlevels(as.factor(temp.data[groupCovs][,1])))) base::names(plot.df) <- smooth.cov plot.df$temp <- rep(levels(as.factor(temp.data[groupCovs][,1])), each = 200) base::names(plot.df)[2] <- groupCovs for (i in names(gam$var.summary)) { if (!(i == smooth.cov | i == groupCovs)) { if (base::any(base::class(temp.data[i][,1])[1] == c("numeric", "integer","boolean"))) { plot.df[, base::dim(plot.df)[2] + 1] <- base::mean(temp.data[i][,1]) base::names(plot.df)[base::dim(plot.df)[2]] <- i } else if (base::any(base::class(temp.data[i][,1])[1] == c("character", "factor","ordered"))) { plot.df[, base::dim(plot.df)[2] + 1] <- temp.data[i][1,1] base::names(plot.df)[base::dim(plot.df)[2]] <- i } else { stop(base::paste("Unrecognized data type for",i,"please refit cluster model with different datatype")) } } } plot.df = base::cbind(plot.df, base::as.data.frame(mgcv::predict.gam(gam, plot.df, se.fit = TRUE))) plot.df$group <- plot.df[,2] if (plotCI) { plot <- (ggplot2::ggplot(data=plot.df, ggplot2::aes(x=plot.df[,1])) + ggplot2::geom_line(ggplot2::aes(y=fit, col=factor(group)), size=1) + ggplot2::geom_ribbon(data=plot.df, ggplot2::aes(ymax = fit+1.96*se.fit, ymin = fit-1.96*se.fit, col=factor(group), linetype=NA), alpha = .2) + ggplot2::ggtitle(base::paste0(base::as.character(old.formula)[2], " vs. s(",smooth.cov,")")) + ggplot2::ylab(base::paste0("Predicted ", base::as.character(old.formula)[2])) + ggplot2::xlab(base::paste0("s(",smooth.cov,")")) + ggplot2::scale_colour_discrete(name = groupCovs) + ggplot2::theme_bw()) } else { plot <- (ggplot2::ggplot(data=plot.df, ggplot2::aes(x=plot.df[,1])) + ggplot2::geom_line(ggplot2::aes(y=fit, col=factor(group)), size=1) + ggplot2::ggtitle(base::paste0(base::as.character(old.formula)[2], " vs. s(",smooth.cov,")")) + ggplot2::ylab(base::paste0("Predicted ", base::as.character(old.formula)[2])) + ggplot2::xlab(base::paste0("s(",smooth.cov,")")) + ggplot2::scale_colour_discrete(name = groupCovs) + ggplot2::theme_bw()) } if (base::is.character(rawOrFitted)) { if (rawOrFitted == "raw" & base::is.null(grouping)) { plot <- plot + ggplot2::geom_point(data = temp.data, ggplot2::aes(x = purrr::as_vector(temp.data[smooth.cov]), y=temp.data[,1], col=factor(temp.data[groupCovs][,1]))) base::return(plot) } else if (rawOrFitted == "fitted" & base::is.null(grouping)) { temp.data$fitted <- gam$fitted.values plot <- plot + ggplot2::geom_point(data = temp.data, ggplot2::aes(x = purrr::as_vector(temp.data[smooth.cov]), y=fitted, col=factor(temp.data[groupCovs][,1]))) base::return(plot) } else if (rawOrFitted == "raw" & base::is.character(grouping)) { plot <- plot + ggplot2::geom_line(data = temp.data, ggplot2::aes(x = purrr::as_vector(temp.data[smooth.cov]), y=temp.data[,1], group=factor(temp.data[grouping][,1]), col=factor(temp.data[groupCovs][,1])), alpha=.4) base::return(plot) } else if (rawOrFitted == "fitted" & base::is.character(grouping)) { temp.data$fitted <- gam$fitted.values plot <- plot + ggplot2::geom_line(data = temp.data, ggplot2::aes(x = purrr::as_vector(temp.data[smooth.cov]), y=fitted, group=factor(temp.data[grouping][,1]), col=factor(temp.data[groupCovs][,1])), alpha=.4) base::return(plot) } } else { base::return(plot) } } else { main.group <- base::paste0("+", groupCovs) if (!base::grepl(pattern = main.group, old.covariates, fixed=T)) { base::stop("groupCovs is not included as main effect in original model, please include in original fit") } orderedAsFactor <- F if (base::class(temp.data[groupCovs][,1])[1] == "ordered" & orderedAsFactor) { base::warning("groupCovs is an ordered variable in original fit, reffiting model with groupCovs as a factor") temp.data[groupCovs] <- as.factor(as.character(temp.data[groupCovs][,1])) textCall <- gam$call updatedCovs <- base::gsub(main.smooth, replacement = "", old.covariates, fixed = T) updatedformula <- stats::as.formula(paste(old.formula[2], old.formula[1], updatedCovs)) new.data <- temp.data gam <- stats::update(gam, formula = updatedformula, data = new.data) } temp.data <- gam$model old.formula <- gam$formula old.covariates <- base::as.character(old.formula)[3] old.covariates <- base::gsub(" ", "", old.covariates) main.smooth <- base::paste0("s(", smooth.cov, ")") interaction.smooth <- base::paste0("s(", smooth.cov, ",by=") foo <- base::seq(min(temp.data[smooth.cov]), max(temp.data[smooth.cov]), length.out=200) plot.df = base::data.frame( x = rep(foo, nlevels(temp.data[groupCovs][,1]))) base::names(plot.df) <- smooth.cov plot.df$temp <- rep(levels(temp.data[groupCovs][,1]), each = 200) base::names(plot.df)[2] <- groupCovs for (i in names(gam$var.summary)) { if (!(i == smooth.cov | i == groupCovs)) { if (base::any(base::class(temp.data[i][,1])[1] == c("numeric", "integer","boolean"))) { plot.df[, base::dim(plot.df)[2] + 1] <- base::mean(temp.data[i][,1]) base::names(plot.df)[base::dim(plot.df)[2]] <- i } else if (base::any(base::class(temp.data[i][,1])[1] == c("character", "factor","ordered"))) { plot.df[, base::dim(plot.df)[2] + 1] <- temp.data[i][1,1] base::names(plot.df)[base::dim(plot.df)[2]] <- i } else { stop(base::paste("Unrecognized data type for",i,"please refit cluster model with different datatype")) } } } plot.df = base::cbind(plot.df, base::as.data.frame(mgcv::predict.gam(gam, plot.df, se.fit = TRUE))) plot.df$group <- plot.df[,2] if (plotCI) { plot <- (ggplot2::ggplot(data=plot.df, ggplot2::aes(x=plot.df[,1])) + ggplot2::geom_line(ggplot2::aes(y=fit, col=factor(group)), size=1) + ggplot2::geom_ribbon(data=plot.df, ggplot2::aes(ymax = fit+1.96*se.fit, ymin = fit-1.96*se.fit, col=factor(group), linetype=NA), alpha = .2) + ggplot2::ggtitle(base::paste0(base::as.character(old.formula)[2], " vs. s(",smooth.cov,")")) + ggplot2::ylab(base::paste0("Predicted ", base::as.character(old.formula)[2])) + ggplot2::xlab(base::paste0("s(",smooth.cov,")")) + ggplot2::scale_colour_discrete(name = groupCovs) + ggplot2::theme_bw()) } else { plot <- (ggplot2::ggplot(data=plot.df, ggplot2::aes(x=plot.df[,1])) + ggplot2::geom_line(ggplot2::aes(y=fit, col=factor(group)), size=1) + ggplot2::ggtitle(base::paste0(base::as.character(old.formula)[2], " vs. s(",smooth.cov,")")) + ggplot2::ylab(base::paste0("Predicted ", base::as.character(old.formula)[2])) + ggplot2::xlab(base::paste0("s(",smooth.cov,")")) + ggplot2::scale_colour_discrete(name = groupCovs) + ggplot2::theme_bw()) } if (base::is.character(rawOrFitted)) { if (rawOrFitted == "raw" & base::is.null(grouping)) { plot <- plot + ggplot2::geom_point(data = temp.data, ggplot2::aes(x = purrr::as_vector(temp.data[smooth.cov]), y=temp.data[,1], col=factor(temp.data[groupCovs][,1]))) base::return(plot) } else if (rawOrFitted == "fitted" & base::is.null(grouping)) { temp.data$fitted <- gam$fitted.values plot <- plot + ggplot2::geom_point(data = temp.data, ggplot2::aes(x = purrr::as_vector(temp.data[smooth.cov]), y=fitted, col=factor(temp.data[groupCovs][,1]))) base::return(plot) } else if (rawOrFitted == "raw" & base::is.character(grouping)) { plot <- plot + ggplot2::geom_line(data = temp.data, ggplot2::aes(x = purrr::as_vector(temp.data[smooth.cov]), y=temp.data[,1], group=factor(temp.data[grouping][,1]), col=factor(temp.data[groupCovs][,1])), alpha=.4) base::return(plot) } else if (rawOrFitted == "fitted" & base::is.character(grouping)) { temp.data$fitted <- gam$fitted.values plot <- plot + ggplot2::geom_line(data = temp.data, ggplot2::aes(x = purrr::as_vector(temp.data[smooth.cov]), y=fitted, group=factor(temp.data[grouping][,1]), col=factor(temp.data[groupCovs][,1])), alpha=.4) base::return(plot) } } else { base::return(plot) } } } else { stop("groupCovs is not a character or null please correct") } }
/scratch/gouwar.j/cran-all/cranData/voxel/R/plotGAMM.R
#' Run a Generalized Additive Model on all voxels of a NIfTI image and return coefficients and residuals #' #' This function is able to run a Generalized Additive Model (GAM) using the mgcv package. #' The analysis will run in all voxels in in the mask and will return parametric and smooth coefficients. #' #' @param image Input image of type 'nifti' or vector of path(s) to images. If multiple paths, the script will all mergeNifti() and merge across time. #' @param mask Input mask of type 'nifti' or path to mask. Must be a binary mask #' @param fourdOut To be passed to mergeNifti, This is the path and file name without the suffix to save the fourd file. Default (NULL) means script won't write out 4D image. #' @param formula Must be a formula passed to gam() #' @param subjData Dataframe containing all the covariates used for the analysis #' @param mc.preschedule Argument to be passed to mclapply, whether or not to preschedule the jobs. More info in parallel::mclapply #' @param ncores Number of cores to use #' @param ... Additional arguments passed to gam() #' #' @return Return list of parametric and spline coefficients (include standard errors and p-values) fitted to each voxel over the masked images passed to function. #' @keywords internal #' @export #' @examples #' image <- oro.nifti::nifti(img = array(1:1600, dim =c(4,4,4,25))) #' mask <- oro.nifti::nifti(img = array(0:1, dim = c(4,4,4,1))) #' set.seed(1) #' covs <- data.frame(x = runif(25)) #' fm1 <- "~ s(x)" #' models <- rgamParam(image=image, mask=mask, #' formula=fm1, subjData=covs, ncores = 1, method="REML") rgamParam <- function(image, mask , fourdOut = NULL, formula, subjData, mc.preschedule = TRUE, ncores = 1, ...) { if (missing(image)) { stop("image is missing")} if (missing(mask)) { stop("mask is missing")} if (missing(formula)) { stop("formula is missing")} if (missing(subjData)) { stop("subjData is missing")} if (class(formula) != "character") { stop("formula class must be character")} if (class(image) == "character" & length(image) == 1) { image <- oro.nifti::readNIfTI(fname=image) } else if (class(image) == "character" & length(image) > 1) { image <- mergeNiftis(inputPaths = image, direction = "t", outfile = fourdOut) } if (class(mask) == "character" & length(mask) == 1) { mask <- oro.nifti::readNIfTI(fname=mask) } imageMat <- ts2matrix(image, mask) rm(image) rm(mask) gc() print("Created time series to matrix") voxNames <- names(imageMat) m <- parallel::mclapply(voxNames, FUN = listFormula, formula, mc.cores = ncores) imageMat <- cbind(imageMat, subjData) print("Created formula list") timeIn <- proc.time() print("Running test model") model <- mgcv::gam(m[[1]], data=imageMat, ...) print("Running parallel models") model <- parallel::mclapply(m, FUN = function(x, data, ...) { foo <- mgcv::gam(x, data=data, ...) foo2 <- foo$residuals foo <- mgcv::summary.gam(foo) return(list(list(par.coeff = foo$p.table, smooth.coeff = foo$s.table), foo2)) }, data=imageMat, ..., mc.preschedule = mc.preschedule , mc.cores = ncores) timeOut <- proc.time() - timeIn print(timeOut[3]) print("Parallel Models Ran") return(model) }
/scratch/gouwar.j/cran-all/cranData/voxel/R/rgamParam.R
#' Run a Generalized Additive Mixed Effects Model on all voxels of a NIfTI image return coefficients and residuals #' #' This function is able to run a Generalized Mixed Effects Model (GAMM) using the gamm4() function. #' The analysis will run in all voxels in in the mask and will return parametric and smooth coefficients. #' #' #' @param image Input image of type 'nifti' or vector of path(s) to images. If multiple paths, the script will all mergeNifti() and merge across time. #' @param mask Input mask of type 'nifti' or path to mask. Must be a binary mask #' @param fourdOut To be passed to mergeNifti, This is the path and file name without the suffix to save the fourd file. Default (NULL) means script won't write out 4D image. #' @param formula Must be a formula passed to gamm4() #' @param randomFormula Random effects formula passed to gamm4() #' @param subjData Dataframe containing all the covariates used for the analysis #' @param mc.preschedule Argument to be passed to mclapply, whether or not to preschedule the jobs. More info in parallel::mclapply #' @param ncores Number of cores to use #' @param ... Additional arguments passed to gamm4() #' #' @return Return list of parametric and spline coefficients (include standard errors and p-values) fitted to each voxel over the masked images passed to function. #' @keywords internal #' @export #' #' @examples #' #' #' image <- oro.nifti::nifti(img = array(1:1600, dim =c(4,4,4,25))) #' mask <- oro.nifti::nifti(img = array(c(rep(0,15), 1), dim = c(4,4,4,1))) #' set.seed(1) #' covs <- data.frame(x = runif(25), y = runif(25), id = rep(1:5,5)) #' fm1 <- "~ s(x) + s(y)" #' randomFormula <- "~(1|id)" #' models <- rgamm4Param(image, mask, formula = fm1, #' randomFormula = randomFormula, subjData = covs, ncores = 1, REML=TRUE) #' rgamm4Param <- function(image, mask , fourdOut = NULL, formula, randomFormula, subjData, mc.preschedule = TRUE, ncores =1, ...) { if (missing(image)) { stop("image is missing")} if (missing(mask)) { stop("mask is missing")} if (missing(formula)) { stop("formula is missing")} if (missing(subjData)) { stop("subjData is missing")} if (missing(randomFormula)) { stop("randomFormula is missing")} if (class(formula) != "character") { stop("formula class must be character")} if (class(randomFormula) != "character") { stop("randomFormula class must be character")} if (class(image) == "character" & length(image) == 1) { image <- oro.nifti::readNIfTI(fname=image) } else if (class(image) == "character" & length(image) > 1) { image <- mergeNiftis(inputPaths = image, direction = "t", outfile = fourdOut) } if (class(mask) == "character" & length(mask) == 1) { mask <- oro.nifti::readNIfTI(fname=mask) } imageMat <- ts2matrix(image, mask) print("Created time series to matrix") rm(image) rm(mask) gc() voxNames <- names(imageMat) m <- parallel::mclapply(voxNames, FUN = listFormula, formula, mc.cores = ncores) gc() print("Created formula list") timeIn <- proc.time() imageMat <- cbind(imageMat, subjData) random <- stats::as.formula(randomFormula, env = environment()) print("Running test model") model <- gamm4::gamm4(m[[1]], data=imageMat, random = random, ...) print("Running parallel models") model <- parallel::mclapply(m, FUN = function(x, data, random, ...) { foo <- gamm4::gamm4(x, data=data, random=random, ...)$gam foo2 <- foo$residuals foo <- mgcv::summary.gam(foo) return(list(list(par.coeff = foo$p.table, smooth.coeff = foo$s.table), foo2)) }, data=imageMat,random=random, ..., mc.preschedule = mc.preschedule, mc.cores = ncores) timeOut <- proc.time() - timeIn print(timeOut[3]) print("Parallel Models Ran") return(model) }
/scratch/gouwar.j/cran-all/cranData/voxel/R/rgamm4Param.R
#' Run a Linear Model on all voxels of a NIfTI and return parametric coefficients and residuals #' #' #' This function is able to run a Linear Model using the stats package. #' The analysis will run in all voxels in in the mask and will and will return parametric coefficients at each voxel. #' #' @param image Input image of type 'nifti' or vector of path(s) to images. If multiple paths, the script will all mergeNifti() and merge across time. #' @param mask Input mask of type 'nifti' or path to mask. Must be a binary mask #' @param fourdOut To be passed to mergeNifti, This is the path and file name without the suffix to save the fourd file. Default (NULL) means script won't write out 4D image. #' @param formula Must be a formula passed to lm() #' @param subjData Dataframe containing all the covariates used for the analysis #' @param mc.preschedule Argument to be passed to mclapply, whether or not to preschedule the jobs. More info in parallel::mclapply #' @param ncores Number of cores to use #' @param ... Additional arguments passed to lm() #' #' @return Return list of parametric and spline coefficients (include standard errors and p-values) fitted to each voxel over the masked images passed to function. #' @keywords internal #' @export #' @examples #' image <- oro.nifti::nifti(img = array(1:1600, dim =c(4,4,4,25))) #' mask <- oro.nifti::nifti(img = array(0:1, dim = c(4,4,4,1))) #' set.seed(1) #' covs <- data.frame(x = runif(25), y = runif(25)) #' fm1 <- "~ x + y" #' models <- rlmParam(image=image, mask=mask, formula=fm1, subjData=covs, ncores = 1) rlmParam <- function(image, mask , fourdOut = NULL, formula, subjData, mc.preschedule = TRUE, ncores = 1, ...) { if (missing(image)) { stop("image is missing")} if (missing(mask)) { stop("mask is missing")} if (missing(formula)) { stop("formula is missing")} if (missing(subjData)) { stop("subjData is missing")} if (class(formula) != "character") { stop("formula class must be character")} if (class(image) == "character" & length(image) == 1) { image <- oro.nifti::readNIfTI(fname=image) } else if (class(image) == "character" & length(image) > 1) { image <- mergeNiftis(inputPaths = image, direction = "t", outfile = fourdOut) } if (class(mask) == "character" & length(mask) == 1) { mask <- oro.nifti::readNIfTI(fname=mask) } imageMat <- ts2matrix(image, mask) voxNames <- names(imageMat) #rm(image) #rm(mask) gc() print("Created time series to matrix") m <- parallel::mclapply(voxNames, FUN = listFormula, formula, mc.cores = ncores) imageMat <- cbind(imageMat, subjData) print("Created formula list") timeIn <- proc.time() print("Running test model") model <- stats::lm(m[[1]], data=imageMat, ...) print("Running parallel models") model <- parallel::mclapply(m, FUN = function(x, data, ...) { foo <- stats::summary.lm(stats::lm(x, data=data, ...)) foo2 <- stats::lm(x, data=data, ...)$residuals return(list(foo$coefficients, foo2)) }, data=imageMat, ..., mc.preschedule = mc.preschedule, mc.cores = ncores) timeOut <- proc.time() - timeIn print(timeOut[3]) print("Parallel Models Ran") return(model) }
/scratch/gouwar.j/cran-all/cranData/voxel/R/rlmParam.R
#' Run a Linear Mixed Effects Model on all voxels of a NIfTI image and return parametric coefficients and residuals #' #' #' This function is able to run a Linear Mixed Effect Model using the lmer() function. #' The analysis will run in all voxels in in the mask and will return the model fit for each voxel. #' The function relies on lmerTest to create p-values using the Satterthwaite Approximation. #' #' #' @param image Input image of type 'nifti' or vector of path(s) to images. If multiple paths, the script will all mergeNifti() and merge across time. #' @param mask Input mask of type 'nifti' or path to mask. Must be a binary mask #' @param fourdOut To be passed to mergeNifti, This is the path and file name without the suffix to save the fourd file. Default (NULL) means script won't write out 4D image. #' @param formula Must be a formula passed to lmer() #' @param subjData Dataframe containing all the covariates used for the analysis #' @param mc.preschedule Argument to be passed to mclapply, whether or not to preschedule the jobs. More info in parallel::mclapply #' @param ncores Number of cores to use #' @param ... Additional arguments passed to lmer() #' #' @keywords internal #' @return Return list of parametric and spline coefficients (include standard errors and p-values) fitted to each voxel over the masked images passed to function. #' @export #' #' #' #' @examples #' #' #' image <- oro.nifti::nifti(img = array(1:1600, dim =c(4,4,4,25))) #' mask <- oro.nifti::nifti(img = array(c(rep(0,15),1), dim = c(4,4,4,1))) #' set.seed(1) #' covs <- data.frame(x = runif(25), id = rep(1:5,5)) #' fm1 <- "~ x + (1|id)" #' models <- rlmerParam(image, mask, formula = fm1, subjData = covs, ncores = 1) #' rlmerParam <- function(image, mask , fourdOut = NULL, formula, subjData, mc.preschedule = TRUE, ncores = 1, ...) { if (missing(image)) { stop("image is missing")} if (missing(mask)) { stop("mask is missing")} if (missing(formula)) { stop("formula is missing")} if (missing(subjData)) { stop("subjData is missing")} if (class(formula) != "character") { stop("formula class must be character")} if (class(image) == "character" & length(image) == 1) { image <- oro.nifti::readNIfTI(fname=image) } else if (class(image) == "character" & length(image) > 1) { image <- mergeNiftis(inputPaths = image, direction = "t", outfile = fourdOut) } if (class(mask) == "character" & length(mask) == 1) { mask <- oro.nifti::readNIfTI(fname=mask) } imageMat <- ts2matrix(image, mask) voxNames <- as.character(names(imageMat)) rm(image) rm(mask) gc() print("Created time series to matrix") m <- parallel::mclapply(voxNames, FUN = listFormula, formula, mc.cores = ncores) print("Created formula list") timeIn <- proc.time() imageMat <- cbind(imageMat, subjData) print("Running test model") model <- base::do.call(lmerTest::lmer, list(formula = m[[1]], data=imageMat, ...)) print("Running parallel models") model <- parallel::mclapply(m, FUN = function(x, data, ...) { foo <- base::do.call(lmerTest::lmer, list(formula = x, data=data, ...)) return(list(summary(foo)$coefficients, summary(foo)$residuals)) }, data=imageMat, ..., mc.preschedule = mc.preschedule, mc.cores = ncores) timeOut <- proc.time() - timeIn print(timeOut[3]) print("Parallel Models Ran") return(model) }
/scratch/gouwar.j/cran-all/cranData/voxel/R/rlmerParam.R
#' Create parametric maps and residuals #' #' This function create parametric maps according from model parametric tables or analysis of variance tables. #' The function will return a p-map, t-map, signed z-map, p-adjusted-map for parametric terms and p-map, z-map, p-adjusted-map for smooth terms. #' Additionally the function will return a p-map, F-map, p-to-z-map, and p-adjusted-map if the input is ANOVA. #' This function will return a residual map that can be used for cluster correction #' You can select which type of p-value correction you want done on the map. The z-maps are signed just like FSL. #' #' @param parameters list of parametric and smooth table coefficients or ANOVA (like the output from vlmParam, vgamParam, anovalmVoxel) #' @param image Input image of type 'nifti' or vector of path(s) to images. If multiple paths, the script will all mergeNifti() and merge across time. #' @param mask Input mask of type 'nifti' or path to one. Must be a binary mask or a character. Must match the mask passed to one of vlmParam, vgamParam, vgamm4Param, vlmerParam #' @param method which method of correction for multiple comparisons (default is none) #' @param ncores Number of cores to use #' @param mc.preschedule Argument to be passed to mclapply, whether or not to preschedule the jobs. More info in parallel::mclapply #' @param outDir Path to the folder where to output parametric maps (Default is Null, only change if you want to write maps out) #' #' @return Return parametric maps of the fitted models #' @keywords internal #' #' @export #' @examples #' image <- oro.nifti::nifti(img = array(1:1600, dim =c(4,4,4,25))) #' mask <- oro.nifti::nifti(img = array(0:1, dim = c(4,4,4,1))) #' set.seed(1) #' covs <- data.frame(x = runif(25), y = runif(25)) #' fm1 <- "~ x + y" #' models <- rlmParam(image=image, mask=mask, #' formula=fm1, subjData=covs, ncores = 1) #' Maps <- rparMap(models, image, mask, method="fdr", ncores = 1, mc.preschedule=TRUE) rparMap <- function(parameters, image, mask, method, ncores, mc.preschedule, outDir = NULL) { #Generate tsresiduals residualList <- parallel::mclapply(parameters, function(x) { return(x[[2]]) }, mc.cores = ncores) #Generate tsresiduals residualMat <- parallel::mcmapply(function(x) { return(x) }, residualList, mc.cores = ncores, SIMPLIFY = TRUE) rm(residualList) gc() #Save only parameter tables under models parameters <- parallel::mclapply(parameters, function(x) { return(x[[1]]) }, mc.cores = ncores) ### Create output residualMask <- mask residualMask <- [email protected] #remove image in for memorize optimization purposes dataTypeIn <- oro.nifti::datatype(image) dimPixIn <- oro.nifti::pixdim(image) rm(image) gc() seq <- 1:dim(residualMat)[1] #generate 4d residual image residuals <- parallel::mcmapply(function(x) { residualMask[[email protected]==1] <- residualMat[x,] return(residualMask) }, seq, SIMPLIFY = "array", mc.cores = ncores, mc.preschedule= mc.preschedule) #Write it out residualNii <- oro.nifti::nifti(residuals, datatype=dataTypeIn, pixdim=dimPixIn) rm(residuals) gc() ParameterMaps <- parMap(parameters, mask, method=method) ParameterMaps$residuals <- residualNii rm(parameters) gc() if (!is.null(outDir)) { dirPath <- base::paste(strsplit(outDir, "/")[[1]][1:(length(strsplit(outDir, "/")[[1]]))], collapse = "/") print(base::paste("Checking if", dirPath ,"Exists")) if (!dir.exists(dirPath)) { print("Directory is missing, creating it now") dir.create(dirPath) } for (i in 1:length(names(ParameterMaps))) { outPath <- base::paste(outDir, names(ParameterMaps)[i], sep = "/") oro.nifti::writeNIfTI(ParameterMaps[[i]], filename = outPath, gzipped = T) } } }
/scratch/gouwar.j/cran-all/cranData/voxel/R/rparMap.R
#' Timeseries to Matrix #' #' This function is able to mask a 4-Dimensional image and create a matrix from it. #' Each column represents the same voxel in the xyz array while the rows represent the t-dimension. #' @param image Input image of type 'nifti' #' @param mask Input mask of type 'nifti'. Must be a binary mask #' @keywords internal #' @export #' @examples #' #' #' image <- oro.nifti::nifti(img = array(1:64, dim =c(4,4,4,5))) #' mask <- oro.nifti::nifti(img = array(0:1, dim = c(4,4,4))) #' matrix <- ts2matrix(image, mask) ts2matrix <- function(image, mask) { if (missing(image)) { stop("image is missing")} if (missing(mask)) { stop("mask is missing")} label <- sort(as.numeric(unique(matrix([email protected])))) if (length(label) == 2 && label[1] == 0 && label[2] == 1) { if (length(dim([email protected])) == 3 | dim([email protected])[4] == 1) { vector <- [email protected][[email protected] == 1] gc() return(vector) } else { temp <- matrix([email protected])[[email protected] == 1] dim(temp) <- c(sum([email protected]), dim([email protected])[length(dim([email protected]))]) temp <- t(temp) temp <- as.data.frame(temp) names <- base::lapply(1:dim(temp)[2], function(x) { return(paste0("voxel",x))}) names(temp) <- names gc() return(temp) } } else { gc() stop("Mask Image is not Binary") } }
/scratch/gouwar.j/cran-all/cranData/voxel/R/ts2matrix.R
#' Timeseries to Mean Cluster #' #' This function is able to output the mean voxel intensity over a cluster. #' Each column represents a cluster and the rows represent the t-dimension. #' @param image Input image of type 'nifti' #' @param mask Input mask of type 'nifti'. Must have different clusters labeled as integers. #' @keywords internal #' @export #' @examples #' #' #' image <- oro.nifti::nifti(img = array(1:320, dim =c(4,4,4,5))) #' mask <- oro.nifti::nifti(img = array(0:15, dim = c(4,4,4,1))) #' matrix <- ts2meanCluster(image, mask) ts2meanCluster <- function(image, mask) { if (missing(image)) { stop("image is missing")} if (missing(mask)) { stop("mask is missing")} label <- sort(as.numeric(unique(matrix([email protected])))) label <- label[label != 0] if (!all.equal(round(label), round(label))) { stop("Cluster Mask must have integer labels") } if (!all.equal(dim([email protected])[1:3], dim([email protected])[1:3])) { stop("Image and Mask have different dimentions") } matrix <- matrix(NA, nrow = dim([email protected])[length(dim([email protected]))], ncol=max(label)) for (i in label) { temp <- matrix([email protected])[[email protected] == i] dim(temp) <- c(sum([email protected] == i), dim([email protected])[length(dim([email protected]))]) temp <- t(temp) matrix[,i] <- rowMeans(temp) } matrix <- as.data.frame(matrix) names <- base::lapply(1:dim(matrix)[2], function(x) { return(paste0("cluster",x))}) names(matrix) <- names gc() keep.NonNA <- base::rep(TRUE, dim(matrix)[2]) for (i in 1:dim(matrix)[2]) { if (all(is.na(matrix[,i]))) { keep.NonNA[i] <- FALSE } } matrix <- matrix[,keep.NonNA] return(matrix) }
/scratch/gouwar.j/cran-all/cranData/voxel/R/ts2meanCluster.R
#' Run a Generalized Additive Model on all voxels of a NIfTI image within a mask and return parametric and smooth coefficients tables #' #' This function is able to run a Generalized Additive Model (GAM) using the mgcv package. #' The analysis will run in all voxels in in the mask and will return parametric and smooth coefficients. #' #' @param image Input image of type 'nifti' or vector of path(s) to images. If multiple paths, the script will all mergeNifti() and merge across time. #' @param mask Input mask of type 'nifti' or path to mask. Must be a binary mask #' @param fourdOut To be passed to mergeNifti, This is the path and file name without the suffix to save the fourd file. Default (NULL) means script won't write out 4D image. #' @param formula Must be a formula passed to gam() #' @param subjData Dataframe containing all the covariates used for the analysis #' @param mc.preschedule Argument to be passed to mclapply, whether or not to preschedule the jobs. More info in parallel::mclapply #' @param ncores Number of cores to use #' @param ... Additional arguments passed to gam() #' #' @return Return list of parametric and spline coefficients (include standard errors and p-values) fitted to each voxel over the masked images passed to function. #' @keywords internal #' @export #' @examples #' image <- oro.nifti::nifti(img = array(1:1600, dim =c(4,4,4,25))) #' mask <- oro.nifti::nifti(img = array(0:1, dim = c(4,4,4,1))) #' set.seed(1) #' covs <- data.frame(x = runif(25)) #' fm1 <- "~ s(x)" #' models <- vgamParam(image=image, mask=mask, #' formula=fm1, subjData=covs, ncores = 1, method="REML") vgamParam <- function(image, mask , fourdOut = NULL, formula, subjData, mc.preschedule = TRUE, ncores = 1, ...) { if (missing(image)) { stop("image is missing")} if (missing(mask)) { stop("mask is missing")} if (missing(formula)) { stop("formula is missing")} if (missing(subjData)) { stop("subjData is missing")} if (class(formula) != "character") { stop("formula class must be character")} if (class(image) == "character" & length(image) == 1) { image <- oro.nifti::readNIfTI(fname=image) } else if (class(image) == "character" & length(image) > 1) { image <- mergeNiftis(inputPaths = image, direction = "t", outfile = fourdOut) } if (class(mask) == "character" & length(mask) == 1) { mask <- oro.nifti::readNIfTI(fname=mask) } imageMat <- ts2matrix(image, mask) rm(image) rm(mask) gc() print("Created time series to matrix") voxNames <- names(imageMat) m <- parallel::mclapply(voxNames, FUN = listFormula, formula, mc.cores = ncores) imageMat <- cbind(imageMat, subjData) print("Created formula list") timeIn <- proc.time() print("Running test model") model <- mgcv::gam(m[[1]], data=imageMat, ...) print("Running parallel models") model <- parallel::mclapply(m, FUN = function(x, data, ...) { foo <- mgcv::summary.gam(mgcv::gam(x, data=data, ...)) return(list(par.coeff = foo$p.table, smooth.coeff = foo$s.table)) }, data=imageMat, ..., mc.preschedule = mc.preschedule , mc.cores = ncores) timeOut <- proc.time() - timeIn print(timeOut[3]) print("Parallel Models Ran") return(model) }
/scratch/gouwar.j/cran-all/cranData/voxel/R/vgamParam.R
#' Run a Generalized Additive Mixed Effects Model on all voxels of a NIfTI image and return parametric and smooth coefficients #' #' This function is able to run a Generalized Mixed Effects Model (GAMM) using the gamm4() function. #' The analysis will run in all voxels in in the mask and will return parametric and smooth coefficients. #' #' #' @param image Input image of type 'nifti' or vector of path(s) to images. If multiple paths, the script will all mergeNifti() and merge across time. #' @param mask Input mask of type 'nifti' or path to mask. Must be a binary mask #' @param fourdOut To be passed to mergeNifti, This is the path and file name without the suffix to save the fourd file. Default (NULL) means script won't write out 4D image. #' @param formula Must be a formula passed to gamm4() #' @param randomFormula Random effects formula passed to gamm4() #' @param subjData Dataframe containing all the covariates used for the analysis #' @param mc.preschedule Argument to be passed to mclapply, whether or not to preschedule the jobs. More info in parallel::mclapply #' @param ncores Number of cores to use #' @param ... Additional arguments passed to gamm4() #' #' @return Return list of parametric and spline coefficients (include standard errors and p-values) fitted to each voxel over the masked images passed to function. #' @keywords internal #' @export #' #' @examples #' #' #' image <- oro.nifti::nifti(img = array(1:1600, dim =c(4,4,4,25))) #' mask <- oro.nifti::nifti(img = array(c(rep(0,15), 1), dim = c(4,4,4,1))) #' set.seed(1) #' covs <- data.frame(x = runif(25), y = runif(25), id = rep(1:5,5)) #' fm1 <- "~ s(x) + s(y)" #' randomFormula <- "~(1|id)" #' models <- vgamm4Param(image, mask, formula = fm1, #' randomFormula = randomFormula, subjData = covs, ncores = 1, REML=TRUE) #' vgamm4Param <- function(image, mask , fourdOut = NULL, formula, randomFormula, subjData, mc.preschedule = TRUE, ncores =1, ...) { if (missing(image)) { stop("image is missing")} if (missing(mask)) { stop("mask is missing")} if (missing(formula)) { stop("formula is missing")} if (missing(subjData)) { stop("subjData is missing")} if (missing(randomFormula)) { stop("randomFormula is missing")} if (class(formula) != "character") { stop("formula class must be character")} if (class(randomFormula) != "character") { stop("randomFormula class must be character")} if (class(image) == "character" & length(image) == 1) { image <- oro.nifti::readNIfTI(fname=image) } else if (class(image) == "character" & length(image) > 1) { image <- mergeNiftis(inputPaths = image, direction = "t", outfile = fourdOut) } if (class(mask) == "character" & length(mask) == 1) { mask <- oro.nifti::readNIfTI(fname=mask) } imageMat <- ts2matrix(image, mask) print("Created time series to matrix") rm(image) rm(mask) gc() voxNames <- names(imageMat) m <- parallel::mclapply(voxNames, FUN = listFormula, formula, mc.cores = ncores) gc() print("Created formula list") timeIn <- proc.time() imageMat <- cbind(imageMat, subjData) random <- stats::as.formula(randomFormula, env = environment()) print("Running test model") model <- gamm4::gamm4(m[[1]], data=imageMat, random = random, ...) print("Running parallel models") model <- parallel::mclapply(m, FUN = function(x, data, random, ...) { foo <- mgcv::summary.gam(gamm4::gamm4(x, data=data, random=random, ...)$gam) return(list(par.coeff = foo$p.table, smooth.coeff = foo$s.table)) }, data=imageMat,random=random, ..., mc.preschedule = mc.preschedule, mc.cores = ncores) timeOut <- proc.time() - timeIn print(timeOut[3]) print("Parallel Models Ran") return(model) }
/scratch/gouwar.j/cran-all/cranData/voxel/R/vgamm4Param.R
#' Run a Linear Model on all voxels of a NIfTI image within a mask and and return parametric coefficients tables #' #' #' This function is able to run a Linear Model using the stats package. #' The analysis will run in all voxels in in the mask and will and will return parametric coefficients at each voxel. #' #' @param image Input image of type 'nifti' or vector of path(s) to images. If multiple paths, the script will all mergeNifti() and merge across time. #' @param mask Input mask of type 'nifti' or path to mask. Must be a binary mask #' @param fourdOut To be passed to mergeNifti, This is the path and file name without the suffix to save the fourd file. Default (NULL) means script won't write out 4D image. #' @param formula Must be a formula passed to lm() #' @param subjData Dataframe containing all the covariates used for the analysis #' @param mc.preschedule Argument to be passed to mclapply, whether or not to preschedule the jobs. More info in parallel::mclapply #' @param ncores Number of cores to use #' @param ... Additional arguments passed to lm() #' #' @return Return list of parametric and spline coefficients (include standard errors and p-values) fitted to each voxel over the masked images passed to function. #' @keywords internal #' @export #' @examples #' image <- oro.nifti::nifti(img = array(1:1600, dim =c(4,4,4,25))) #' mask <- oro.nifti::nifti(img = array(0:1, dim = c(4,4,4,1))) #' set.seed(1) #' covs <- data.frame(x = runif(25), y = runif(25)) #' fm1 <- "~ x + y" #' models <- vlmParam(image=image, mask=mask, formula=fm1, subjData=covs, ncores = 1) vlmParam <- function(image, mask , fourdOut = NULL, formula, subjData, mc.preschedule = TRUE, ncores = 1, ...) { if (missing(image)) { stop("image is missing")} if (missing(mask)) { stop("mask is missing")} if (missing(formula)) { stop("formula is missing")} if (missing(subjData)) { stop("subjData is missing")} if (class(formula) != "character") { stop("formula class must be character")} if (class(image) == "character" & length(image) == 1) { image <- oro.nifti::readNIfTI(fname=image) } else if (class(image) == "character" & length(image) > 1) { image <- mergeNiftis(inputPaths = image, direction = "t", outfile = fourdOut) } if (class(mask) == "character" & length(mask) == 1) { mask <- oro.nifti::readNIfTI(fname=mask) } imageMat <- ts2matrix(image, mask) voxNames <- names(imageMat) rm(image) rm(mask) gc() print("Created time series to matrix") m <- parallel::mclapply(voxNames, FUN = listFormula, formula, mc.cores = ncores) imageMat <- cbind(imageMat, subjData) print("Created formula list") timeIn <- proc.time() print("Running test model") model <- stats::lm(m[[1]], data=imageMat, ...) print("Running parallel models") model <- parallel::mclapply(m, FUN = function(x, data, ...) { foo <- stats::summary.lm(stats::lm(x, data=data, ...)) return(foo$coefficients) }, data=imageMat, ..., mc.preschedule = mc.preschedule, mc.cores = ncores) timeOut <- proc.time() - timeIn print(timeOut[3]) print("Parallel Models Ran") return(model) }
/scratch/gouwar.j/cran-all/cranData/voxel/R/vlmParam.R