<p>As it turns out, pseudotime algorithms are exceedingly difficult to parallelize. Pseudotime does not scale linearly to a subset of data compared to the full dataset, and as such a course-grained approach to parallelizing pseudotime calculations on random bins of the data, followed by bin merging, does not work. These values will never converge on the actual full-dataset solution.</p>

<p>I put in a pretty good effort trying to parallelize slingshot, but with no success. I realize my code may be of limited utility without more explanation, but I'm not putting more time into this. FWIW:</p>

<p>This code:</p>

<ol>
<li>Finds computationally optimal bin size for slingshot based on a number of genes and features</li>
<li>Randomly splits the SingleCellExperiment object into that number of bins and runs slingshot on each bin</li>
<li>Orients each bin so that a cell with a pseudotime of 1 in the first bin is similar to a pseudotime of 1 in every bin. Pseudotime can get flipped depending on the sampled subset.</li>
<li>Merges all bins into a single matrix so each cell has a assigned pseudotime based on randomly sampled bins.</li>
<li>Repeats steps #2 to #5 with a different random seed for binning every time.</li>
<li>Measures convergence towards actual solution at three pseudotime values, where convergence is defined as correlation of cell indices along the trajectory.</li>
</ol>

<p>I abandoned the project after observing that more iterations to not change the convergence towards the actual solution. While pseudotime values close to 0 recapitulated the actual solution quite well, pseudotime values towards 100 failed to correlate at all with the actual solution. There was no convergence with more iterations.</p>

<p>Maybe this will be helpful to somebody, which is why I'm posting.</p>

<pre><code># Parallel Iterative Sampling with Slingshot
# pissshot is a course-grained estimator of the actual slingshot solution, and iteratively converges towards the actual solution
# pissshot randomly partitions cells in a large database into bins, bin size is determined by finding the computationally optimal number of cells
# pissshot is run independently on each bin, pseudotime vectors are aligned across all bins, and then all bins are merged
# pissshot repeats this process and the average of pseudotime assignments for each cell is taken at the end of each iteration. 
# The convergence of the blingshot model at the end of each iteration is calculated by running slingshot on a small sample of adjacent cells at a random pseudotime interval and measuring correlation with the predicted model
# When satisfactory convergence is reached, blingshot returns a singlecellobject, just as slingshot would

pissshot &lt;- function(sce, num_iterations = 20){
    cat("Running blingshot on", dim(sce)[2],"cells and",dim(sce)[1],"features\n")
    cat("  Step 1/5: Finding computationally optimal increment sizes\n   ")
#    increment_size &lt;- FindOptimalIncrementSize(sce)
    increment_size &lt;- 688
    num_increments &lt;- ceiling(dim(sce)[2]/increment_size)-1
    cat("\n  ...Increment size of",increment_size,"cells is computationally optimal\n")
    cat("  Step 2/5: Course-grained pseudotime assignment across",num_increments,"increments")
    ps &lt;- list()
    convergenceArr &lt;- c()
    for(iteration in seq(from=1,to=num_iterations,by=1)){
        cat("\n   ... iteration",iteration,"...\n")
        cat("         randomly assigning cells to",num_increments,"bins\n         0%.")
        bins &lt;- PartitionBins(sce, increment_size = increment_size, seed = 7*iteration)
        cat("100%\n         running slingshot on each bin\n         0%")
        cell_pseudotimes &lt;- c()
        for(b in seq(from=1,to=length(bins),by=1)){
            bin_with_pseudotime &lt;- suppressMessages(slingshot(bins[[b]]))
            # Find right cell and left cell in pseudotime array (cell with highest/lowest pseudotime values)
            pcells &lt;- as.data.frame(colData(bin_with_pseudotime)<span class="math-container">$slingPseudotime_1)
            rownames(pcells) &lt;- colnames(bin_with_pseudotime)
            pcells &lt;- data.frame(lapply(pcells, function(x) as.numeric(as.character(x))), check.names = F, row.names = rownames(pcells))
            pcells.sorted &lt;- pcells[order(-pcells[,1]), , drop = FALSE]
            right_cell_ID &lt;- rownames(pcells.sorted)[dim(pcells.sorted)[1]]
            left_cell_ID &lt;- rownames(pcells.sorted)[1]
            right_cell_pos &lt;- match(right_cell_ID,colnames(bins[[b]]))
            left_cell_pos &lt;- match(left_cell_ID,colnames(bins[[b]]))
            right_cell_logcounts &lt;- assays(bins[[b]])$</span>logcounts[,right_cell_pos]
            left_cell_logcounts &lt;- assays(bins[[b]])<span class="math-container">$logcounts[,left_cell_pos]
            if(b==1&amp;&amp;iteration==1){
                ref_right_cell_logcounts &lt;- right_cell_logcounts
                ref_left_cell_logcounts &lt;- left_cell_logcounts
            }
            # Figure out whether this pseudotime in this bin has flipped relative to reference (first bin), and if so, flip pseudotime values
            cor_opposite_ends &lt;- mean(cor(right_cell_logcounts,ref_left_cell_logcounts),cor(left_cell_logcounts,ref_right_cell_logcounts))
            cor_same_ends &lt;- mean(cor(right_cell_logcounts,ref_right_cell_logcounts),cor(left_cell_logcounts,ref_left_cell_logcounts))
            flipped &lt;- FALSE
            if(cor_opposite_ends &gt; cor_same_ends){
                flipped &lt;- TRUE
            }
            if(flipped==TRUE){
                # find max pseudotime in colData(bin_with_pseudotime)$slingPseudotime
                # Recalculate pseudotime in bin_with_pseudotime as max-value
                pseudotimes &lt;- colData(bin_with_pseudotime)$slingPseudotime_1
                colData(bin_with_pseudotime)$slingPseudotime_1 &lt;- max(pseudotimes)-pseudotimes 
            }
            cells_with_pseudotime &lt;- as.data.frame(colData(bin_with_pseudotime)$</span>slingPseudotime_1,colnames(bin_with_pseudotime))
            cell_pseudotimes &lt;- rbind(cell_pseudotimes, cells_with_pseudotime)
            cat(".")
        }
        cat("100%\n")

        ps[[iteration]] &lt;- cell_pseudotimes[order(row.names(cell_pseudotimes)), , drop = FALSE]

        pss &lt;- data.frame(ps)
        if(iteration&gt;1){
            convergence10 &lt;- measureConvergence(pss, sce = sce, ptime = 10, increment_size = increment_size)
            convergence50 &lt;- measureConvergence(pss, sce = sce, ptime = 50, increment_size = increment_size)
            convergence99 &lt;- measureConvergence(pss, sce = sce, ptime = 99, increment_size = increment_size)
            cat("   convergence at 10:",convergence10,"... at 50:",convergence50,"...at 100:",convergence99,"\n")
            convergenceArr &lt;- rbind(convergenceArr,c(iteration,convergence10,convergence50,convergence99))
        }
        # Iterate until the model converges towards the actual slingshot solution, within an indicated fraction (i.e. convergence = 0.02)
        # The convergence measure compares how similar the model is to the actual slingshot solution, i.e. a convergence of 0.02 means that cell pseudotime values are within 2% of the actual solution
        # Assess this by selecting a pseudotime at random, analyzing the following increment_size cells, and comparing accuracy of pseudotime measurement across that trajectory with the composite of the course-grained analysis

        # need to study how convergence changes over pseudotime
    }

    # remove cells with really high standard deviations

    return(pss)
#    return(convergenceArr)
}


measureConvergence &lt;- function(mat, sce = sce, ptime = 45, increment_size = 500){
    # this line is throwing an error
    mat[,"avg"] &lt;- apply(mat[,1:dim(mat)[2]],1,mean)
    mat &lt;- mat[order(mat[,"avg"]), , drop = FALSE]
    # select a random pseudotime increment
    mat &lt;- mat[mat[, "avg"] &gt; ptime,]
    mat &lt;- mat[1:increment_size,]
    cell_IDs &lt;- rownames(mat)
    # pull out this list of cell_IDs from the sce object and run slingshot
    sce2 &lt;- suppressMessages(slingshot(sce[,cell_IDs]))
    cpcells &lt;- as.data.frame(colData(sce2)$slingPseudotime_1)
    rownames(cpcells) &lt;- colnames(sce2)
    cpcells &lt;- data.frame(lapply(cpcells, function(x) as.numeric(as.character(x))), check.names = F, row.names = rownames(cpcells))
    # sort cpcells by increasing pseudotime
    cpcells &lt;- cpcells[order(cpcells[,1]), , drop = FALSE]
    ordered_cells &lt;- cbind(rownames(mat),rownames(cpcells))
    # get the index of each cell in the dataframe, run a correlation on how well the indices line up
    cell_indices &lt;- c()
    for(cell in cell_IDs){
        new_indices &lt;- c(which(ordered_cells[,1] == cell), which(ordered_cells[,2] == cell))
        cell_indices &lt;- rbind(cell_indices,new_indices)
    }
    convergence_measure &lt;- cor(cell_indices[,1],cell_indices[,2])
    plot(cell_indices[,1],cell_indices[,2])
    return(convergence_measure)
}

PartitionBins &lt;- function(sce, increment_size = 500, seed = 123){
    bins &lt;- c()
    while(dim(sce)[2]&gt;=increment_size){
        if(dim(sce)[2]&lt;increment_size*2){
            bins &lt;- c(bins, sce)
            sce &lt;- sce[,1]
        }
        else{
            set.seed(seed)
            train_ind &lt;- sample(seq_len(ncol(sce)), size = increment_size)
            bins &lt;- c(bins, sce[,train_ind])
            sce &lt;- sce[,-train_ind]
            cat(".")
        }
    }
    return(bins)
}

FindOptimalIncrementSize &lt;- function(sce){
    # Find the computationally optimal increment_size for grainy alignments using 5 increment points (100, 500, 1000, 2500)
    res &lt;- c(100,250,500,750,1000,1500,2500,5000)
    runtimes &lt;- c()
    for(i in res){
        runtimes &lt;- c(runtimes, suppressMessages(system.time(slingshot(sce[,0:i])))["elapsed"])
    }
    mat &lt;- as.data.frame(t(rbind(res,runtimes)))
    c &lt;- summary(lm(mat<span class="math-container">$runtimes ~ poly(mat$</span>res, 2, raw=TRUE)))$coefficients[,"Estimate"]
    predicted_runtimes &lt;- c()
    for(i in seq(from=100, to=5000, by=1)){
        predicted_runtime &lt;- (c[1] + c[2]*i + c[3]*i^2)*(dim(sce)[2]/i)
        predicted_runtimes &lt;- rbind(predicted_runtimes,c(i,predicted_runtime))
        cat(".")
    }
    increment_size &lt;- predicted_runtimes[which.min(predicted_runtimes[,2]),1]
    return(increment_size)
}
</code></pre>

CC BY-SA 4.0
2020-01-19T14:24:33.303Z
2020-01-19T14:24:33.303Z
zdebruine
<p>There is a <a href="https://www.nature.com/articles/s41587-019-0071-9" rel="nofollow noreferrer">recent publication</a> that compares methods for trajectory inference. In <a href="https://www.nature.com/articles/s41587-019-0071-9/figures/2" rel="nofollow noreferrer">Figure 2</a> in terms of scalability <a href="https://doi.org/10.1101/208819" rel="nofollow noreferrer">PAGA</a>, PAGA Tree and Component 1 get the highest rating. The authors <a href="https://dynverse.org/users/3-user-guide/2-guidelines/" rel="nofollow noreferrer">offer a shiny app</a> to help select the best method for your dataset.</p>

CC BY-SA 4.0
2020-07-01T00:51:16.427Z
2020-07-01T00:51:16.427Z
Tapper
<p>What algorithms for linear Pseudotime trajectory construction (diffusion-based) are the most scalable to large datasets?</p>

<p>I'm currently using Slingshot based on the recommendation in this manuscript: <a href="https://www.biorxiv.org/content/biorxiv/early/2018/03/05/276907.full.pdf" rel="nofollow noreferrer">https://www.biorxiv.org/content/biorxiv/early/2018/03/05/276907.full.pdf</a></p>

<p>Slingshot is nice and easy to use, but it turns out it is terrible at scaling to big datasets. </p>

<p>For 2000 highest variable genes and a random sampling of a variable number of cells in my ~80% sparse expression matrix I get the following computation times in R (96 GB RAM):</p>

<pre><code>#cells / Time (min)
100 / 0.7
1000 / 4.3
2000 / 12.3
5000 / 71.1
</code></pre>

<p>At this rate it would take nearly 1.5 days to process 200,000 cells and 4.5 months to process 2 million cells based on 2,000 HVG.</p>

<p>I feel like Slingshot is limited by a fundamentally unnecessary comparison of diffusion for all cells against all cells, rather than preclustering and then finer resolution of pseudotime across cluster edges.</p>

<p>What algorithms are better, but still implement a similar realization of pseudotime ordering?  I just need a single linear trajectory.</p>

CC BY-SA 4.0
2020-01-17T13:47:16.523Z
Well, in the absence of any comments, and being unable to find any scalable solution, I am now writing a function to granularly order cells at low resolution, then incrementally resolve high-resolution ordering. All using slingshot. Will post up when done.
zdebruine
CC BY-SA 4.0
2020-01-17T14:57:22.757Z
Thank you! That would be appreciated!
terdon
<scrnaseq><r>
Most scalable pseudotime ordering algorithm
# Most scalable pseudotime ordering algorithm

(Asked by: username_0 on 2020-01-16)

What algorithms for linear Pseudotime trajectory construction (diffusion-based) are the most scalable to large datasets?
I'm currently using Slingshot based on the recommendation in this manuscript: https://www.biorxiv.org/content/biorxiv/early/2018/03/05/276907.full.pdf
Slingshot is nice and easy to use, but it turns out it is terrible at scaling to big datasets. 
For 2000 highest variable genes and a random sampling of a variable number of cells in my ~80% sparse expression matrix I get the following computation times in R (96 GB RAM):
#cells / Time (min)
100 / 0.7
1000 / 4.3
2000 / 12.3
5000 / 71.1

At this rate it would take nearly 1.5 days to process 200,000 cells and 4.5 months to process 2 million cells based on 2,000 HVG.
I feel like Slingshot is limited by a fundamentally unnecessary comparison of diffusion for all cells against all cells, rather than preclustering and then finer resolution of pseudotime across cluster edges.
What algorithms are better, but still implement a similar realization of pseudotime ordering?  I just need a single linear trajectory.

**Tags:** scrnaseq, r
> **Comments:**
> **username_0**: Well, in the absence of any comments, and being unable to find any scalable solution, I am now writing a function to granularly order cells at low resolution, then incrementally resolve high-resolution ordering. All using slingshot. Will post up when done.  
> **username_1**: Thank you! That would be appreciated!  

---

## 2 answers

### Answer by username_0 on 2020-01-19. Score: 1 | Accepted answer

As it turns out, pseudotime algorithms are exceedingly difficult to parallelize. Pseudotime does not scale linearly to a subset of data compared to the full dataset, and as such a course-grained approach to parallelizing pseudotime calculations on random bins of the data, followed by bin merging, does not work. These values will never converge on the actual full-dataset solution.
I put in a pretty good effort trying to parallelize slingshot, but with no success. I realize my code may be of limited utility without more explanation, but I'm not putting more time into this. FWIW:
This code:

Finds computationally optimal bin size for slingshot based on a number of genes and features
Randomly splits the SingleCellExperiment object into that number of bins and runs slingshot on each bin
Orients each bin so that a cell with a pseudotime of 1 in the first bin is similar to a pseudotime of 1 in every bin. Pseudotime can get flipped depending on the sampled subset.
Merges all bins into a single matrix so each cell has a assigned pseudotime based on randomly sampled bins.
Repeats steps #2 to #5 with a different random seed for binning every time.
Measures convergence towards actual solution at three pseudotime values, where convergence is defined as correlation of cell indices along the trajectory.

I abandoned the project after observing that more iterations to not change the convergence towards the actual solution. While pseudotime values close to 0 recapitulated the actual solution quite well, pseudotime values towards 100 failed to correlate at all with the actual solution. There was no convergence with more iterations.
Maybe this will be helpful to somebody, which is why I'm posting.
# Parallel Iterative Sampling with Slingshot
# pissshot is a course-grained estimator of the actual slingshot solution, and iteratively converges towards the actual solution
# pissshot randomly partitions cells in a large database into bins, bin size is determined by finding the computationally optimal number of cells
# pissshot is run independently on each bin, pseudotime vectors are aligned across all bins, and then all bins are merged
# pissshot repeats this process and the average of pseudotime assignments for each cell is taken at the end of each iteration. 
# The convergence of the blingshot model at the end of each iteration is calculated by running slingshot on a small sample of adjacent cells at a random pseudotime interval and measuring correlation with the predicted model
# When satisfactory convergence is reached, blingshot returns a singlecellobject, just as slingshot would

pissshot <- function(sce, num_iterations = 20){
    cat("Running blingshot on", dim(sce)[2],"cells and",dim(sce)[1],"features\n")
    cat("  Step 1/5: Finding computationally optimal increment sizes\n   ")
#    increment_size <- FindOptimalIncrementSize(sce)
    increment_size <- 688
    num_increments <- ceiling(dim(sce)[2]/increment_size)-1
    cat("\n  ...Increment size of",increment_size,"cells is computationally optimal\n")
    cat("  Step 2/5: Course-grained pseudotime assignment across",num_increments,"increments")
    ps <- list()
    convergenceArr <- c()
    for(iteration in seq(from=1,to=num_iterations,by=1)){
        cat("\n   ... iteration",iteration,"...\n")
        cat("         randomly assigning cells to",num_increments,"bins\n         0%.")
        bins <- PartitionBins(sce, increment_size = increment_size, seed = 7*iteration)
        cat("100%\n         running slingshot on each bin\n         0%")
        cell_pseudotimes <- c()
        for(b in seq(from=1,to=length(bins),by=1)){
            bin_with_pseudotime <- suppressMessages(slingshot(bins[[b]]))
            # Find right cell and left cell in pseudotime array (cell with highest/lowest pseudotime values)
            pcells <- as.data.frame(colData(bin_with_pseudotime)$slingPseudotime_1)
            rownames(pcells) <- colnames(bin_with_pseudotime)
            pcells <- data.frame(lapply(pcells, function(x) as.numeric(as.character(x))), check.names = F, row.names = rownames(pcells))
            pcells.sorted <- pcells[order(-pcells[,1]), , drop = FALSE]
            right_cell_ID <- rownames(pcells.sorted)[dim(pcells.sorted)[1]]
            left_cell_ID <- rownames(pcells.sorted)[1]
            right_cell_pos <- match(right_cell_ID,colnames(bins[[b]]))
            left_cell_pos <- match(left_cell_ID,colnames(bins[[b]]))
            right_cell_logcounts <- assays(bins[[b]])$logcounts[,right_cell_pos]
            left_cell_logcounts <- assays(bins[[b]])$logcounts[,left_cell_pos]
            if(b==1&&iteration==1){
                ref_right_cell_logcounts <- right_cell_logcounts
                ref_left_cell_logcounts <- left_cell_logcounts
            }
            # Figure out whether this pseudotime in this bin has flipped relative to reference (first bin), and if so, flip pseudotime values
            cor_opposite_ends <- mean(cor(right_cell_logcounts,ref_left_cell_logcounts),cor(left_cell_logcounts,ref_right_cell_logcounts))
            cor_same_ends <- mean(cor(right_cell_logcounts,ref_right_cell_logcounts),cor(left_cell_logcounts,ref_left_cell_logcounts))
            flipped <- FALSE
            if(cor_opposite_ends > cor_same_ends){
                flipped <- TRUE
            }
            if(flipped==TRUE){
                # find max pseudotime in colData(bin_with_pseudotime)$slingPseudotime
                # Recalculate pseudotime in bin_with_pseudotime as max-value
                pseudotimes <- colData(bin_with_pseudotime)$slingPseudotime_1
                colData(bin_with_pseudotime)$slingPseudotime_1 <- max(pseudotimes)-pseudotimes 
            }
            cells_with_pseudotime <- as.data.frame(colData(bin_with_pseudotime)$slingPseudotime_1,colnames(bin_with_pseudotime))
            cell_pseudotimes <- rbind(cell_pseudotimes, cells_with_pseudotime)
            cat(".")
        }
        cat("100%\n")

        ps[[iteration]] <- cell_pseudotimes[order(row.names(cell_pseudotimes)), , drop = FALSE]

        pss <- data.frame(ps)
        if(iteration>1){
            convergence10 <- measureConvergence(pss, sce = sce, ptime = 10, increment_size = increment_size)
            convergence50 <- measureConvergence(pss, sce = sce, ptime = 50, increment_size = increment_size)
            convergence99 <- measureConvergence(pss, sce = sce, ptime = 99, increment_size = increment_size)
            cat("   convergence at 10:",convergence10,"... at 50:",convergence50,"...at 100:",convergence99,"\n")
            convergenceArr <- rbind(convergenceArr,c(iteration,convergence10,convergence50,convergence99))
        }
        # Iterate until the model converges towards the actual slingshot solution, within an indicated fraction (i.e. convergence = 0.02)
        # The convergence measure compares how similar the model is to the actual slingshot solution, i.e. a convergence of 0.02 means that cell pseudotime values are within 2% of the actual solution
        # Assess this by selecting a pseudotime at random, analyzing the following increment_size cells, and comparing accuracy of pseudotime measurement across that trajectory with the composite of the course-grained analysis

        # need to study how convergence changes over pseudotime
    }

    # remove cells with really high standard deviations

    return(pss)
#    return(convergenceArr)
}


measureConvergence <- function(mat, sce = sce, ptime = 45, increment_size = 500){
    # this line is throwing an error
    mat[,"avg"] <- apply(mat[,1:dim(mat)[2]],1,mean)
    mat <- mat[order(mat[,"avg"]), , drop = FALSE]
    # select a random pseudotime increment
    mat <- mat[mat[, "avg"] > ptime,]
    mat <- mat[1:increment_size,]
    cell_IDs <- rownames(mat)
    # pull out this list of cell_IDs from the sce object and run slingshot
    sce2 <- suppressMessages(slingshot(sce[,cell_IDs]))
    cpcells <- as.data.frame(colData(sce2)$slingPseudotime_1)
    rownames(cpcells) <- colnames(sce2)
    cpcells <- data.frame(lapply(cpcells, function(x) as.numeric(as.character(x))), check.names = F, row.names = rownames(cpcells))
    # sort cpcells by increasing pseudotime
    cpcells <- cpcells[order(cpcells[,1]), , drop = FALSE]
    ordered_cells <- cbind(rownames(mat),rownames(cpcells))
    # get the index of each cell in the dataframe, run a correlation on how well the indices line up
    cell_indices <- c()
    for(cell in cell_IDs){
        new_indices <- c(which(ordered_cells[,1] == cell), which(ordered_cells[,2] == cell))
        cell_indices <- rbind(cell_indices,new_indices)
    }
    convergence_measure <- cor(cell_indices[,1],cell_indices[,2])
    plot(cell_indices[,1],cell_indices[,2])
    return(convergence_measure)
}

PartitionBins <- function(sce, increment_size = 500, seed = 123){
    bins <- c()
    while(dim(sce)[2]>=increment_size){
        if(dim(sce)[2]$runtimes ~ poly(mat$res, 2, raw=TRUE)))$coefficients[,"Estimate"]
    predicted_runtimes <- c()
    for(i in seq(from=100, to=5000, by=1)){
        predicted_runtime <- (c[1] + c[2]*i + c[3]*i^2)*(dim(sce)[2]/i)
        predicted_runtimes <- rbind(predicted_runtimes,c(i,predicted_runtime))
        cat(".")
    }
    increment_size <- predicted_runtimes[which.min(predicted_runtimes[,2]),1]
    return(increment_size)
}


---

### Answer by username_2 on 2020-07-01. Score: 1

There is a [recent publication](https://www.nature.com/articles/s41587-019-0071-9) that compares methods for trajectory inference. In [Figure 2](https://www.nature.com/articles/s41587-019-0071-9/figures/2) in terms of scalability [PAGA](https://doi.org/10.1101/208819), PAGA Tree and Component 1 get the highest rating. The authors [offer a shiny app](https://dynverse.org/users/3-user-guide/2-guidelines/) to help select the best method for your dataset.


---

