R/distr_rxns_in_plates.R

Defines functions .distr_rxns_in_plates

#' @import data.table

.distr_rxns_in_plates <- function(rxns,plate.layout) {
  n.plates <- 1L
  plate.size <- sum(plate.layout==FALSE,na.rm=TRUE)
  n.unused.wells <- plate.size

  rxns[,plate:=0L]

  genes <- unique(rxns[,target])

  # Determine how many plates and which plate each reaction will go into
  message("Distributing reactions to plates")
  pb.1 <- txtProgressBar()

  for(gene in seq_len(length(genes))) {
    if(sum(nrow(rxns[target==genes[gene]]) <= n.unused.wells) > 0) {
      # If the gene can fit completely in ANY plate (current or previous ones)

      plate.to.add.to <- min(which(nrow(rxns[target==genes[gene]]) <= n.unused.wells))

      rxns[target==genes[gene],
           plate:=plate.to.add.to][]
      n.unused.wells[plate.to.add.to] <- n.unused.wells[plate.to.add.to] - nrow(rxns[target==genes[gene]])

    } else {
      # If the total remaining reactions CANNOT fit in the total remaining unused wells
      # A new plate will be started

      if(nrow(rxns[plate==0]) >= sum(n.unused.wells)) {
        n.plates <- n.plates + 1L
        n.unused.wells <- c(n.unused.wells,plate.size)
        rxns[target==genes[gene],
             plate:=n.plates][]
        n.unused.wells[length(n.unused.wells)] <- n.unused.wells[length(n.unused.wells)] - nrow(rxns[target==genes[gene]])

      } else {
        # If the total remaining reactions CAN fit in the total remaining unused wells
        # They will be distributed to them appropriately

        for(rxn in split(rxns[target==genes[gene]],
                         by=c("sample","rxn.type","biol.repl","dilution"))) {

          # These are used in a join, in order to fill the plate field in the main data.table
          rxns[rxn,
               plate:=which(n.unused.wells==max(n.unused.wells))[1],
               on=.(sample,rxn.type,target,biol.repl,dilution)][]

          # Update the number of unused wells in each plate
          n.unused.wells[which(n.unused.wells==max(n.unused.wells))[1]] <-
            n.unused.wells[which(n.unused.wells==max(n.unused.wells))[1]] -
            nrow(rxn)

        }
      }
    }

    setTxtProgressBar(pb=pb.1,value=nrow(rxns[plate!=0L])/nrow(rxns))

  }

  close(pb.1)
  message("")

  setorder(rxns,plate,target,sample,rxn.type)

  return(rxns)
}
dimitriskokoretsis/qpcrR documentation built on May 29, 2022, 10:11 p.m.