R/distr_rxns_within_plates.R

Defines functions .distr_rxns_within_plates

#' @import data.table

.distr_rxns_within_plates <- function(rxns,plate.layout) {
  n.plates <- max(rxns[,plate])

  # Create a list of matrices that represent the qPCR plates
  plates <- list(plate.layout)[rep(1,n.plates)]


  # Spatially distribute reactions within each plate

  # Initialize row and column fields in the rxns data.table
  set(rxns,i=NULL,j=c("row","column"),value=0L)

  message("Distributing reactions within plates")
  pb.2 <- txtProgressBar()

  for(rxn in split(rxns[,.(biol.repl,dilution,tech.repl,.N),
                        by=.(plate,target,sample,rxn.type)][order(-N)],
                   by=c("plate","target","sample","rxn.type"))) {
    rxn[,N:=NULL]
    n.rxns <- nrow(rxn)
    plate <- rxn[,plate][1]

    # Assign each reaction group to a free line within its corresponding plate
    rxn[,c("row","column"):=
          .fit_in_matrix_cells(n=n.rxns,
                               m=plates[[..plate]],
                               free.value=FALSE,
                               occupied.value=TRUE)]


    # Get the newly assigned wells from data frames and put them in their corresponding
    # positions in the plate matrix

    # Matrix cell assignment by matrix (see ?Extract for information)
    plates[[plate]][cbind(rxn[,row],
                          rxn[,column])] <- TRUE


    # Put the plate coordinates in the original rxns data.table
    rxns[rxn,
         c("row","column"):=.(i.row,i.column),
         on=.(plate,target,sample,rxn.type,biol.repl,dilution,tech.repl)]

    setTxtProgressBar(pb=pb.2,value=nrow(rxns[row!=0L & column!=0L])/nrow(rxns))
  }

  close(pb.2)
  message("")

  setorder(rxns,plate,row,column)

  set(x=rxns,i=NULL,j=c("row","column"),
      value=list(as.factor(rownames(plate.layout)[rxns[,row]]),
                 as.factor(colnames(plate.layout)[rxns[,column]])))

  set(x=rxns,i=NULL,j="column",
      value=factor(rxns[,column],
                   levels=stringr::str_sort(levels(rxns[,column]),
                                            numeric=TRUE)))

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