Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
Expand Up @@ -350,6 +350,17 @@ Changes:
stores and reloads its running sum. The terms are added in the same order and rounded the same way, so results
are bitwise unchanged. A normal-prior `lr` fit (100,000 rows, 13,000 columns, 18 million values; `"auto"`, Newton)
takes 11.0 s instead of 12.3 s on 1 thread and 10.8 s instead of 12.2 s on 4; Laplace fits are unchanged
54. `convertToCyclopsData()` from data frames needs much less memory beyond its input: it reads the covariate vectors
in place instead of copying them (into `integer64` vectors and again into C++), and sorts unsorted `lr` and `pr`
covariates through a permutation instead of a sorted copy. With 26 million covariate values (100,000 rows,
20,000 covariates) the process peak fell from 1.96 GB to 0.82 GB for covariates sorted by `covariateId` and
`rowId`, and from 2.57 GB to 1.04 GB for covariates sorted by `rowId`. The batches of an `Andromeda` table are read
in place too. The data, and so every fit, are the same as before
55. `convertToCyclopsData()` takes `lr` and `pr` covariates as a sparse matrix (`dgCMatrix`, `lgCMatrix` or
`ngCMatrix`, one row per outcome row, column `j` the covariate with id `j`), read in place without a data frame of
its entries; the data equal those of that data frame. With 26 million binary values (100,000 rows, 20,000 columns),
converting took 0.08 GB beyond the matrix and 0.3 s, against 0.28 GB and 0.7 s through a data frame of the entries
(1.25 GB and 3.6 s before item 54)

Cyclops v3.8.0
==============
Expand Down
34 changes: 25 additions & 9 deletions R/DataManagement.R
Original file line number Diff line number Diff line change
Expand Up @@ -719,6 +719,24 @@ appendSqlCyclopsData <- function(object,
}

#' @importFrom bit64 as.integer64 is.integer64
# Ids as the loader reads them in place (no copies): integer, integer64 and double vectors read as bit64::as.integer64()
# reads them. Other types (e.g. character), and doubles that overflow int64 (so that bit64 warns), go through bit64 here
.idsForLoading <- function(x) {
if ((!is.numeric(x) && !bit64::is.integer64(x)) || .anyIdOverflow(x)) {
x <- bit64::as.integer64(x)
}
x
}

# Values as the loader reads them in place: integer, logical and double vectors (an integer64 vector by its doubles, as
# before). Other types go through the conversion the loader's argument used to make (Rcpp's, with its errors)
.valuesForLoading <- function(x) {
if (!is.null(x) && !typeof(x) %in% c("double", "integer", "logical")) {
x <- .asLoaderDoubles(x)
}
x
}

#' @keywords internal
loadNewSqlCyclopsDataMultipleX <- function(object,
covariateId, # Vector
Expand All @@ -729,7 +747,8 @@ loadNewSqlCyclopsDataMultipleX <- function(object,
checkSorting = FALSE,
checkCovariateIds = FALSE,
checkCovariateBounds = FALSE,
forceSparse = FALSE) {
forceSparse = FALSE,
order = NULL) { # order: a permutation that sorts the ids, read through

if (!isInitialized(object)) stop("Object is no longer or improperly initialized.")

Expand All @@ -750,13 +769,9 @@ loadNewSqlCyclopsDataMultipleX <- function(object,
stop("Not yet implemented")
}

if (!bit64::is.integer64(covariateId)) {
covariateId <- bit64::as.integer64(covariateId)
}

if (!bit64::is.integer64(rowId)) {
rowId <- bit64::as.integer64(rowId)
}
covariateId <- .idsForLoading(covariateId)
rowId <- .idsForLoading(rowId)
covariateValue <- .valuesForLoading(covariateValue)

index <- .loadCyclopsDataMultipleX(object,
covariateId,
Expand All @@ -765,7 +780,8 @@ loadNewSqlCyclopsDataMultipleX <- function(object,
checkCovariateIds,
checkCovariateBounds,
append,
forceSparse)
forceSparse,
order)

if (!missing(name)) {
if (is.null(object$coefficientNames)) {
Expand Down
96 changes: 88 additions & 8 deletions R/NewDataConversion.R
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,8 @@ isSorted <- function(data, columnNames, ascending = rep(TRUE, length(columnNames
#' \code{convertToCyclopsData} loads data from two data frames or ffdf objects, and inserts it into a Cyclops data object.
#'
#' @param outcomes A data frame or ffdf object containing the outcomes with predefined columns (see below).
#' @param covariates A data frame or ffdf object containing the covariates with predefined columns (see below).
#' @param covariates A data frame or ffdf object containing the covariates with predefined columns (see below),
#' or, for \code{"lr"} and \code{"pr"} models with data-frame outcomes, a sparse matrix (see below).
#' @param modelType Cyclops model type. Current supported types are "pr", "cpr", lr", "clr", "cox", "cox_counting"
#' or "plr" (pooled logistic regression; see Details)
#' @param addIntercept Add an intercept to the model?
Expand Down Expand Up @@ -97,6 +98,14 @@ isSorted <- function(data, columnNames, ascending = rep(TRUE, length(columnNames
#' \verb{covariateValue} \tab(real) \tab The value of the specified covariate \cr
#' }
#'
#' For \code{"lr"} and \code{"pr"} models the covariates can instead be a sparse matrix from the \pkg{Matrix}
#' package (a \code{dgCMatrix}, \code{lgCMatrix} or \code{ngCMatrix}) with one row per row of \code{outcomes}:
#' row \code{r} holds the covariates of \code{outcomes$rowId[r]}, and column \code{j} is the covariate with
#' \code{covariateId} \code{j}, named by \code{colnames()} if the matrix has them. The matrix is read in place,
#' without a data frame of its entries; columns without non-zero entries are left out, as covariates without rows
#' in a data frame are. The data equal those of the data frame with \code{rowId = outcomes$rowId[x@i + 1]},
#' \code{covariateId} the column number and \code{covariateValue = x@x}.
#'
#' These columns are expected in the timeEffectMap object:
#' \tabular{lll}{
#' \verb{covariateId} \tab(integer) \tab A numeric identifier of the covariates that have time-varying effects on the outcome \cr
Expand Down Expand Up @@ -191,6 +200,10 @@ convertToCyclopsData.data.frame <- function(outcomes,
if (!is.null(checkSorting))
warning("The 'checkSorting' argument has been deprecated. Sorting is now always checked")

# covariates as a sparse matrix (lr and pr): row r belongs to outcomes row r, column j is covariate j; the matrix is
# read in place, without a data frame of its entries
sparseCovariates <- .isSparseCovariateMatrix(covariates, outcomes, modelType)

if (modelType == "plr") {
return(.convertToPooledCyclopsData(outcomes, covariates, timeBasis, timeEffectMap, addIntercept,
checkRowIds, normalize, quiet, floatingPoint, link))
Expand All @@ -214,23 +227,30 @@ convertToCyclopsData.data.frame <- function(outcomes,

if (modelType == "lr" | modelType == "pr") {
outcomes$stratumId <- NULL
covariates$stratumId <- NULL
if (!sparseCovariates) covariates$stratumId <- NULL
}
if ((modelType == "cox" | modelType == "cox_time" | modelType == "fgr" | modelType == "cox_counting") & !"stratumId" %in% colnames(outcomes)) {
outcomes$stratumId <- 0
covariates$stratumId <- 0
}

covariateOrder <- NULL # lr and pr: the permutation that sorts the covariates, if they were not sorted
if (modelType == "lr" | modelType == "pr") {
if (!isSorted(outcomes, c("rowId"))) {
if (!quiet)
writeLines("Sorting outcomes by rowId")
outcomes <- outcomes[order(outcomes$rowId),]
rowOrder <- order(outcomes$rowId)
outcomes <- outcomes[rowOrder,]
if (sparseCovariates) covariates <- covariates[rowOrder, , drop = FALSE] # rows follow their outcomes
}
if (!isSorted(covariates, c("covariateId", "rowId"))) {
if (!sparseCovariates && !isSorted(covariates, c("covariateId", "rowId"))) {
if (!quiet)
writeLines("Sorting covariates by covariateId and rowId")
covariates <- covariates[order(covariates$covariateId, covariates$rowId),]
# the permutation only, read through when loading (a sorted copy of the covariates and order()'s work
# took about 40 bytes per covariate value); order() and a sorted copy where .sortOrder() does not decide
covariateOrder <- .sortOrder(covariates$covariateId, covariates$rowId)
if (is.null(covariateOrder))
covariates <- covariates[order(covariates$covariateId, covariates$rowId),]
}
}

Expand Down Expand Up @@ -301,7 +321,12 @@ convertToCyclopsData.data.frame <- function(outcomes,
}
}

if (checkRowIds) {
# (.allIn() decides most cases without match()'s vectors as long as the covariates; NA: not decided there)
if (!sparseCovariates && checkRowIds && !isTRUE(.allIn(covariates$rowId, outcomes$rowId))) {
if (!is.null(covariateOrder)) { # sorted, as before
covariates <- covariates[covariateOrder, ]
covariateOrder <- NULL
}
mapping <- match(covariates$rowId,outcomes$rowId)
if (any(is.na(mapping))) {
if (!quiet)
Expand Down Expand Up @@ -339,12 +364,27 @@ convertToCyclopsData.data.frame <- function(outcomes,
loadNewSqlCyclopsDataX(dataPtr, 0, NULL, NULL, name = "(Intercept)")
}

covarNames <- unique(covariates$covariateId)
if (sparseCovariates) {
covarNames <- .loadSparseCovariateMatrix(dataPtr, covariates, outcomes$rowId)
} else {
# the covariates are sorted by covariateId first, so its distinct values are the starts of its runs (no hash table
# as long as the covariates); unique() if they are not
starts <- .runStarts(covariates$covariateId, covariateOrder)
covarNames <- if (is.null(starts)) {
unique(if (is.null(covariateOrder)) covariates$covariateId else covariates$covariateId[covariateOrder])
} else if (is.null(covariateOrder)) {
covariates$covariateId[starts]
} else {
covariates$covariateId[covariateOrder[starts]]
}
rm(starts)
loadNewSqlCyclopsDataMultipleX(object = dataPtr,
covariateId = covariates$covariateId,
rowId = covariates$rowId,
covariateValue = covariates$covariateValue,
name = covarNames)
name = covarNames,
order = covariateOrder)
}

if (modelType == "cox_time" && !is.null(timeEffectMap)) {
if (!all(timeEffectMap$covariateId %in% covarNames)) stop("Invalid covariateId for time effects.")
Expand Down Expand Up @@ -615,6 +655,46 @@ convertToCyclopsData.tbl_dbi <- function(outcomes,
return(dataPtr)
}

# Whether covariates is a sparse matrix of covariates (checked: lr or pr, one row per outcome); FALSE for a data frame.
# A dgCMatrix, lgCMatrix or ngCMatrix is read in place; other Matrix classes are refused rather than copied
.isSparseCovariateMatrix <- function(covariates, outcomes, modelType) {
if (!methods::is(covariates, "Matrix")) {
return(FALSE)
}
if (!class(covariates)[1] %in% c("dgCMatrix", "lgCMatrix", "ngCMatrix")) {
stop("Sparse matrix covariates must be a dgCMatrix, lgCMatrix or ngCMatrix (column-compressed and general), ",
"e.g. methods::as(methods::as(x, \"generalMatrix\"), \"CsparseMatrix\")", call. = FALSE)
}
if (!modelType %in% c("lr", "pr")) {
stop("Sparse matrix covariates are supported for modelType \"lr\" and \"pr\"; ",
"give the covariates as a data frame for other models", call. = FALSE)
}
if (nrow(covariates) != nrow(outcomes)) {
stop("A sparse covariate matrix needs one row per outcome row: ", nrow(covariates), " rows for ",
nrow(outcomes), " outcomes", call. = FALSE)
}
TRUE
}

# Loads the columns of a sparse covariate matrix whose row r belongs to rowIds[r]: column j has covariate id j, and is
# named by colnames() if the matrix has them (else by its id). Columns without non-zero entries are left out, as
# covariates without rows in a data frame. Returns the names of the columns loaded
.loadSparseCovariateMatrix <- function(dataPtr, covariates, rowIds) {
p <- covariates@p
kept <- which(diff(p) > 0)
if (length(kept) == 0) {
return(character(0))
}
index <- .loadCyclopsDataColumns(dataPtr, p, covariates@i, if (methods::.hasSlot(covariates, "x")) covariates@x else NULL,
.idsForLoading(rowIds), seq_len(ncol(covariates)), FALSE)
names <- if (is.null(colnames(covariates))) as.character(kept) else colnames(covariates)[kept]
if (is.null(dataPtr$coefficientNames)) {
dataPtr$coefficientNames <- as.character(c())
}
dataPtr$coefficientNames[index + seq_along(names)] <- names
names
}

# timeBasis and link are for plr models only
.checkPooledArguments <- function(modelType, timeBasis, link) {
if (!is.null(timeBasis) || !identical(link, "logit")) {
Expand Down
28 changes: 26 additions & 2 deletions R/RcppExports.R
Original file line number Diff line number Diff line change
Expand Up @@ -207,6 +207,22 @@ listGPUDevices <- function() {
.Call(`_Cyclops_isSortedVectorList`, vectorList, ascending)
}

.runStarts <- function(x, order = NULL) {
.Call(`_Cyclops_runStarts`, x, order)
}

.anyIdOverflow <- function(x) {
.Call(`_Cyclops_anyIdOverflow`, x)
}

.allIn <- function(x, table) {
.Call(`_Cyclops_allIn`, x, table)
}

.sortOrder <- function(first, second) {
.Call(`_Cyclops_sortOrder`, first, second)
}

.isRcppPtrNull <- function(x) {
.Call(`_Cyclops_isRcppPtrNull`, x)
}
Expand Down Expand Up @@ -400,8 +416,16 @@ getStartTimeVector <- function(object) {
invisible(.Call(`_Cyclops_cyclopsLoadDataPooledRows`, x, implicitRows, rowsPerSubject, interval, event, rowWeight, rowOffset, subjectOffset, basis, intervals, timeCovariateId, timeBasisColumn, cloglog))
}

.loadCyclopsDataMultipleX <- function(x, covariateId, rowId, covariateValue, checkCovariateIds, checkCovariateBounds, append, forceSparse) {
.Call(`_Cyclops_cyclopsLoadDataMultipleX`, x, covariateId, rowId, covariateValue, checkCovariateIds, checkCovariateBounds, append, forceSparse)
.loadCyclopsDataMultipleX <- function(x, covariateId, rowId, covariateValue, checkCovariateIds, checkCovariateBounds, append, forceSparse, order) {
.Call(`_Cyclops_cyclopsLoadDataMultipleX`, x, covariateId, rowId, covariateValue, checkCovariateIds, checkCovariateBounds, append, forceSparse, order)
}

.loadCyclopsDataColumns <- function(x, p, i, values, rowIds, columnIds, forceSparse) {
.Call(`_Cyclops_cyclopsLoadDataColumns`, x, p, i, values, rowIds, columnIds, forceSparse)
}

.asLoaderDoubles <- function(x) {
.Call(`_Cyclops_cyclopsAsLoaderDoubles`, x)
}

.loadCyclopsDataX <- function(x, bitCovariateId, rowId, covariateValue, replace, append, forceSparse) {
Expand Down
11 changes: 10 additions & 1 deletion man/convertToCyclopsData.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading
Loading