R/functions2.R

Defines functions classif_gen arraycorr_gen gencorr myread.data hist_pdf freq.map.radial create.df cor2d

Documented in arraycorr_gen classif_gen cor2d create.df freq.map.radial gencorr hist_pdf myread.data

#' Correlation Between Two Array Slices
#'
#' this function finds the correlation between two matrices along pre-specified locations
#'
#' @param mats An array of dimension (m1 x m2 x 2), where m1 x m2 is the image size which contains the base and tip
#' @param ind.mat A matrix of size (m1 x m2) that indicates the regions where to compute the correlations betwee base and tip.
#' Typically generated by freq.map.radial().
#'
#' @return  a correlation (between 0 and 1)
#' @export
#' @author Carlos Llosa-Vite, \email{llosacarlos2@@gmail.com}
#' @author Geoffrey Z. Thompson
cor2d <- function(mats,ind.mat){
  #cleaned by cl, original by gzt
  tip <- (mats[2, , ]) * ind.mat
  base <- (mats[1, , ]) * ind.mat

  base.vec <- as.numeric(base[base != 0])
  tip.vec <- as.numeric(tip[tip != 0])

  return(cor(x = base.vec, y = tip.vec))
}


#' Generating correlations from all read data
#'
#' this function finds the correlations between base and tip along all the knifes, image repetitions, and desired frequencies.
#'
#' This function creates a data frame which has columns containing some quantity (usually correlation) calculated for every pair
#' of aligned images on a base and a tip.
#'
#' @param data list of arrays where each elements is an array corresponding to all the data from a single knife, typically generated by myread.data
#' @param cuts numeric vector of cut points for specifying frequency ranges over which we would like to calculate correlations.
#' For example, if 5-10 and 10-20 frequency ranges are desired, set cuts as c(5,10,20).
#' @param freqs This is an alternative to specifying cuts (note that you should only specify one or the other). Suppose that you wished to calculate
#'  correlations for the 5-10 and 20-30 frequency ranges, but not 10-20. Then you could use this argument by passing a matrix with two columns and a
#'   number of rows equal to the number of frequency ranges you want to perform calculations for. The first column indicates the lower number in the
#'   frequency range, and the second column specifies the upper number in the frequency range.
#' @param freq_mult This argument is the multiplier that tells you the at a given row or column index. This changes depending on the image
#' magnification.
#' @param map_func This argument is a function that takes in three arguments: freqs, freq\_mult, and image.dimensions, and produces a 3-D array
#' where, along the third dimension, each element is a matrix of zeros and ones specifying the cells in a given image that are relevant for
#' calculations at a given frequency range. Each of these matrices will be passed to func to specify the cells from a specific frequency range.
#' The default function used here will likely not need to change.
#' @param verb true or false, indicating if you want progress details
#' @return  data frame with the correlations along all frequencies, sample pairs
#' @export
#' @author Carlos Llosa-Vite, \email{llosacarlos2@@gmail.com}
#' @author Geoffrey Z. Thompson
create.df <- function(data,
                      cuts,
                      freqs,
                      freq_mult = 1.775,
                      map_func = freq.map.radial,
                      verb = verb)  {
  ## cleaned by cll 23/09/21, now I ignore all the "corclass" and "adjust"
  # original by gzt
  imgs <- 1:unname(dim(data[[1]])[4])
  d <- unname(dim(data[[1]])[2:3])
  if (is.numeric(cuts))
  {
    freqs <- cbind(cuts[1:(length(cuts)-1)],cuts[2:length(cuts)])
  }
  if (!is.matrix(freqs) & !is.numeric(cuts))
  {
    print("Warnings: Must supply either cuts or freqs")
    break()
  }
  freqnames <- apply(freqs,1,paste,collapse = "-")
  if(verb){
    cat("Finding correlations along the frequency bands ",freqnames, "and with a resolution of",freq_mult,"\n")
  }
  ## create the index matrices
  freq_map <-
    map_func(freqs = freqs,
             freq_mult = freq_mult,
             image.dimensions = d)

  knife.no <- names(data)
  img.no <- dim(data[[1]])[4]
  nonmatch_names <- character()
  match_vec <-  c(rep(TRUE, length(knife.no) * img.no),
                  rep(FALSE,length(knife.no) * (length(knife.no) - 1) * img.no)   )

  ##correlation matrix to store vectors of correlations at different frequency ranges
  cormat <-
    matrix(nrow = length(knife.no) ^ 2 * img.no,
           ncol = nrow(freqs))


  ## top loop to go through the frequency ranges
  for (i in 1:nrow(freqs))
  {
    cat("generating correlations along the frequency band ",freqnames[i],": ")
    ## inner loops to go through the surface pairs

    ## calculate match correlations
    match_cor <- numeric()
    for (j in 1:length(data))
    {
      temp <-
        apply(
          X = data[[j]],
          MARGIN = 4,
          FUN = cor2d,
          ind.mat = freq_map[, , i]
        )
      match_cor <- c(match_cor, temp)
    }
    cat( "Finished: Matches ")

    ## calculate nonmatch correlations
    nonmatch_cor <- numeric()
    for (j in 1:length(data))
    {
      for (k in 1:length(data))
      {
        if (j != k)
        {
          if (i == 1)
          {
            new.names <-
              rep(paste(knife.no[j], knife.no[k], sep = ":"), times = img.no)
            nonmatch_names <- c(nonmatch_names, new.names)
          }
          nonmatch_array <- array(dim = dim(data[[j]]))
          nonmatch_array[1, , , ] <- data[[j]][1, , , ]
          nonmatch_array[2, , , ] <- data[[k]][2, , , ]
          temp <-
            apply(
              X = nonmatch_array,
              MARGIN = 4,
              FUN = cor2d,
              ind.mat = freq_map[, , i]
            )
          nonmatch_cor <- c(nonmatch_cor, temp)
        }
      }
    }
    cat( "and Non-Matches \n")

    ## properly name the correlations which have just been calculated for frequency range i
    names(match_cor) <-
      paste(rep(knife.no, each = img.no),
            rep(knife.no, each = img.no),
            sep = ":")
    names(nonmatch_cor) <- nonmatch_names

    ## store the i-th frequency range correlations as the i-th column of cormat
    cormat[, i] <- c(match_cor, nonmatch_cor)
    rownames(cormat) <- c(names(match_cor), names(nonmatch_cor))

  }

  colnames(cormat) <- freqnames
  cordf <- as.data.frame(cormat, row.names = 1:nrow(cormat))
  cordf$knife <- row.names(cormat)
  cordf$img <- rep(imgs, times = length(knife.no) ^ 2)
  #set up match
  match_vec[match_vec == TRUE ] <- "match"
  match_vec[match_vec == FALSE] <- "nonmatch"
  match_vec <- as.factor(match_vec)
  levels(match_vec) = c('match','nonmatch')
  cordf$match <- match_vec

  return(cordf)

}



######################################################################
######################################################################
######################################################################
######################################################################


#' Create regions where to find correlations based on frequency bands, image size, and magnification
#'
#' This function creates a matrix of indicator variables specifying which cells in the 512 by 1023 matrix should be used in the calculation of the
#' correlation for a given frequency range. I would suggest writing an entire matrix from this function to a csv file to get a handle on what it's
#' doing.
#'
#' @param freqs This is an alternative to specifying cuts (note that you should only specify one or the other). Suppose that you wished to calculate
#'  correlations for the 5-10 and 20-30 frequency ranges, but not 10-20. Then you could use this argument by passing a matrix with two columns and a
#'   number of rows equal to the number of frequency ranges you want to perform calculations for. The first column indicates the lower number in the
#'   frequency range, and the second column specifies the upper number in the frequency range.
#' @param freq_mult This argument is the multiplier that tells you the at a given row or column index. This changes depending on the image
#' magnification.
#' @param image.dimensions Image dimensions (not neccesarity 512 x 1023)
#' @return matrix of indicator variables
#' @examples
#' freqs <- freq.ranges(cuts = c(5,10,20))
#' ind.mats <- freq.map.radial(freqs = freqs, freq_mult = 1.775, image.dimensions = c(512,1023))
#' dim(ind.mats)
#' ind.mats[c(502:512), c(506:518),1]
#' @export
#' @author Geoffrey Thompson
#' @author Geoffrey Z. Thompson
freq.map.radial <- function(freqs, freq_mult, image.dimensions){
  d <- image.dimensions
  ind.array <- array(data = NA, dim = c(d[1], d[2], nrow(freqs)))

  colseq <-
    c(seq(
      from = d[1] - 1,
      to = 0,
      by = -1
    ), seq(from = 1, to = d[1] - 1, by = 1))
  rowseq <- (d[1] - 1):0

  colfreq <- freq_mult * colseq
  rowfreq <- freq_mult * rowseq
  freq.array <- array(data = NA, dim = c(d[1], d[2], 2))
  freq.array[, , 1] <-
    matrix(rep(rowfreq, times = d[2]), ncol = d[2], byrow = FALSE)
  freq.array[, , 2] <-
    matrix(rep(colfreq, times = d[1]), ncol = d[2], byrow = TRUE)

  ## temp is a matrix of max frequency values
  radius.func <- function(xy)
  {
    sqrt(xy[1] ^ 2 + xy[2] ^ 2)
  }

  radial.freq <- apply(freq.array, MARGIN = c(1, 2), FUN = radius.func)
  for (i in 1:nrow(freqs))
  {
    ind.array[, , i] <-
      1 * (radial.freq >= freqs[i, 1] & radial.freq < freqs[i, 2])
  }


  return(ind.array)
}





#' Create correlation histograms
#'
#' This function will save a pdf file of correlation histograms, with one frequency band per page
#'
#' @param cordf data frame of correlations, as created by create.df
#' @param filename Name of pdf file to be saved, includying directory
#' @param bns histogram bins
#' @param data.name name of data, will appear in the histograms
#' @return won't return anything, will just save the pdf
#' @export
#' @author Geoffrey Thompson
#' @import ggplot2
hist_pdf <- function(cordf,filename, bns, data.name) {
  nms <- strsplit(colnames(cordf), split = "-")
  keep <- character()
  for(i in 1:length(nms))
  {
    if(length(nms[[i]]) == 2)
    {
      keep[i] <- colnames(cordf[i])
    }
  }

  pdf(paste(filename))
  for(i in 1:length(keep))
  {
    newdata <- cordf[,colnames(cordf) %in% keep[i] | !(colnames(cordf) %in% keep)]
    print(head(newdata))
    p <- ggplot() +
      geom_histogram(mapping = aes(x = newdata[newdata$match == "nonmatch",1], y = ..count.., colour = "1", fill = "1"), bins = bns, alpha = 0.5) +
      geom_histogram(mapping = aes(x = newdata[newdata$match == "match",1], y = ..count.., colour = "2", fill = "2"), bins = bns, alpha = 0.5) +
      ggtitle(paste(paste("Correlations for Frequency Range", colnames(newdata)[1]), data.name, sep = "\n")) +
      geom_hline(yintercept = 0, colour = "grey", size = 0.5) +
      xlab(paste("Correlation")) +
      xlim(c(-1,1)) +
      scale_colour_manual(labels = c("nonmatch", "match"), values = c(rgb(1,0,0,0.5), rgb(0,0,1,0.5))) +
      scale_fill_manual(labels = c("nonmatch", "match"), values = c(rgb(1,0,0,0.5), rgb(0,0,1,0.5))) +
      labs(col = "Match vs Nonmatch", fill = "Match vs Nonmatch") +
      theme_light()
    p
    print(p)
  }
  dev.off()
}



#' Read FFT data in Excel form
#'
#' The raw data for each image exists as a 512 by 1023 matrix (say) stored in an excel file (one file per image). This function
#' loops through the files in the specified folder/directory and stores the image matrices for each knife as a 4-D array which is one element
#' of a list. The array dimensions correspond to 1) Base/Tip 2) Image matrix rows 3) #' Image matrix columns 4) Image number.
#'
#' @param img.no number of (usually) overlapping images
#' @param sample.names This is another character vector where each element is a string corresponding to the knives we wish to include.
#' In the image.names example, the element of this vector corresponding to knife T01 would be T01.
#' @param base.names names of the base images. Usually if operator A did it is A_FFT
#' @param tip.names  usually the same name as the base, but might change.
#' @param base.directory The file path for where the bases are located
#' @param tip.directory typically the same as base.directory
#' @param surface Typically  c("Base", "Tip"), but this might change. For instance they might be  c("base", "tip") instead
#' @param verb show progress? True or False
#' @param stopmiss  should the function stop when there is missing data?
#' @return list of arrays, one for each knife, with all the read data across base x tip and image repetitions
#' @export
#' @author Carlos Llosa
#' @author Geoffrey Z. Thompson
#' @import readxl
myread.data <- function(img.no,
                        sample.names,
                        base.names,
                        tip.names = base.names,
                        base.directory,
                        tip.directory = base.directory,
                        surface = c("Base", "Tip"),
                        verb = T,
                        stopmiss = T){
  ## created by cl on 09/17/21
  ## newer version, the older was hard to read and didn't give info about the errors

 # if(substring(base.directory,nchar(base.directory))!="/") base.directory <- paste0(base.directory,"/")
#  if(substring(tip.directory,nchar(tip.directory))!="/") tip.directory <- paste0(tip.directory,"/")

  #1: samples (or knifes) indicators in sample.names
  #2: overlapping image names in image.names
  image.names <- paste0("0",1:img.no)
  if(img.no>9) image.names[10:img.no] <- substring(image.names[10:img.no] ,2)
  #3: FFT dimensions in image.dimensions
  dir.base <- paste0(base.directory,paste(sample.names[1],surface[1],image.names[1],base.names,sep="-"),".xlsx")
  dim.base <- try(suppressMessages(    read_excel(dir.base, col_names = F,progress=F)  ),silent = T)
  dir.tip  <- paste0(tip.directory,paste(sample.names[1],surface[2],image.names[1],tip.names,sep="-"),".xlsx")
  dim.tip  <- try(suppressMessages(    read_excel(dir.tip , col_names = F,progress=F)  ),silent = T)
  if(class(dim.base)[1] == "try-error"){
    stop("directory for the first base does not exist or is corrupted: \n",dir.base)
  } else if(class(dim.tip)[1] == "try-error"){
    stop("directory for the first tip does not exist or is corrupted: \n",dir.tip)
  } else if(!all(dim(dim.base) == dim(dim.tip))){
    stop("dimensions of the first base:",dim(dim.base),"does not match dimensions of the first tip:",dim(dim.tip))
  } else{
    image.dimensions <- dim(dim.base)
    if(verb) cat("dimension of first base and tip are:",image.dimensions,"\n")
  }

  #this is a dummy array that will later contain all the info, here I create the names
  B1dim <- c("surface"=2,"FFT_row"=image.dimensions[1],"FFT_col"=image.dimensions[2],"images"=img.no)
  B1 <- array(-1,B1dim)
  #start new.klist (which will contain all the data). Each list element has a copy of B1, which correspons to one knife.
  new.klist <- lapply(1:length(sample.names),function(x)B1)
  names(new.klist) <- sample.names

  #store all elements in new.klist
  for(i in 1:length(sample.names)){
    smp <- sample.names[i]
    if(verb) cat("################## \n started reading data for sample",smp,"\n")
    for(j in 1:img.no){
      img <- image.names[j]
      #read base and tips for the ith sample, jth image
      if(verb) cat("reading base-tip for image",j)
      dir.base <- paste0(base.directory,paste(smp,surface[1],img,base.names,sep="-"),".xlsx")
      dat.base <- try(suppressMessages( read_excel(dir.base, col_names = F,progress=F)  ),silent = T)
      dir.tip  <- paste0(tip.directory,paste(smp,surface[2],img,tip.names,sep="-"),".xlsx")
      dat.tip  <- try(suppressMessages( read_excel(dir.tip , col_names = F,progress=F)  ),silent = T)
      #check if there is any problems
      if(class(dat.base)[1] == "try-error"){
        cat("\nbase directory for image",img,", sample",smp," does not exist or is corrupted: \n",dir.base,"\n")
        if(stopmiss) stop("\n ERROR: ")
      } else if(class(dat.tip)[1] == "try-error"){
        cat( "\ntip directory for image",img,", sample",smp," does not exist or is corrupted: \n", dir.tip,"\n")
        if(stopmiss) stop("\n ERROR: ")
      } else if(!all(apply(cbind(dim(dat.base),dim(dat.base),image.dimensions),1,var) == 0)){
        stop("\nERROR: base-tip dimensions for image",img,"sample",smp,"dont match\n")
      } else{
        new.klist[[i]][1,,,j] <- as.matrix(dat.base)
        new.klist[[i]][2,,,j] <- as.matrix(dat.tip)
        if(verb) cat('--read! \n')
      }
    }
    if(any(new.klist[[i]]<0))
      cat("WARNING: The FFTs corresponding to ",img,"contains negative FFT \n")
    cat("Finished!\n\n")
  }

  return(new.klist)
}




#' Generate correlations from raw FFT data
#'
#' This function reads the data from myread.data, saves it with create.df and creates histograms with hist_pdf
#'
#' @param img.no number of (usually) overlapping images
#' @param sample.names This is another character vector where each element is a string corresponding to the knives we wish to include.
#' In the image.names example, the element of this vector corresponding to knife T01 would be T01.
#' @param base.names names of the base images. Usually if operator A did it is A_FFT
#' @param tip.names  usually the same name as the base, but might change.
#' @param base.directory The file path for where the bases are located
#' @param tip.directory typically the same as base.directory
#' @param surface Typically  c("Base", "Tip"), but this might change. For instance they might be  c("base", "tip") instead
#' @param verb show progress? True or False
#' @param stopmiss  should the function stop when there is missing data?
#' @param cuts numeric vector of cut points for specifying frequency ranges over which we would like to calculate correlations.
#' For example, if 5-10 and 10-20 frequency ranges are desired, set cuts as c(5,10,20).
#' @param freqs This is an alternative to specifying cuts (note that you should only specify one or the other). Suppose that you wished to calculate
#'  correlations for the 5-10 and 20-30 frequency ranges, but not 10-20. Then you could use this argument by passing a matrix with two columns and a
#'   number of rows equal to the number of frequency ranges you want to perform calculations for. The first column indicates the lower number in the
#'   frequency range, and the second column specifies the upper number in the frequency range.
#' @param freq_mult This argument is the multiplier that tells you the at a given row or column index. This changes depending on the image
#' magnification.
#' @param map_func This argument is a function that takes in three arguments: freqs, freq\_mult, and image.dimensions, and produces a 3-D array
#' where, along the third dimension, each element is a matrix of zeros and ones specifying the cells in a given image that are relevant for
#' calculations at a given frequency range. Each of these matrices will be passed to func to specify the cells from a specific frequency range.
#' The default function used here will likely not need to change.
#' @param corr_csvloc location for csv files of correlations
#' @param corr_pdfloc location for pdf file of correlation histograms
#' @return correlations along all images, pairs and frequencies, will also save pdf and csv correlation files.
#' @export
#' @author Carlos Llosa
#' @author Geoffrey Z. Thompson
gencorr <- function(img.no,
                    sample.names,
                    base.names,
                    tip.names = base.names,
                    base.directory,
                    tip.directory = base.directory,
                    surface = c("Base", "Tip"),
                    verb = T,
                    stopmiss = T,
                    cuts=NA,
                    freqs,
                    freq_mult = 1.775,
                    map_func = freq.map.radial,
                    corr_csvloc = NULL,
                    corr_pdfloc = NULL){
  klist <- myread.data(
    img.no = img.no,
    sample.names = sample.names,
    base.names = base.names,
    tip.names = tip.names,
    base.directory = base.directory,
    tip.directory = tip.directory,
    surface = surface,
    verb = verb,
    stopmiss = stopmiss)
  #if(klist == 0 ) return(0)

  if(verb) cat("Finished reading data, now creating correlations \n")

  cordf <- create.df(data=klist,
                     cuts=cuts,
                     freqs=freqs,
                     freq_mult = freq_mult,
                     map_func = map_func,
                     verb = verb)



  cat("Finished creating correlations! \n")
  if(!is.null(corr_csvloc)){
    write.csv( cordf,corr_csvloc)
    cat("Finished saving csv correlation file \n")
  }
  if(!is.null(corr_pdfloc)){
    nam <- paste("(base,tip) = ( ",base.names,",",tip.names,")")
    hist_pdf(cordf = cordf, filename = corr_pdfloc, bns = 50, data.name = nam)
    cat("Finished saving pdf correlation file \n")
  }




}




#' Generate array of fisher-z transformed correlations from raw csv correlations
#'
#' This function reads the raw correlations csv files and returns an array with p x q x n , where p is the frequencies, q is the images, and n is the sample size
#'
#' Given a csv file for correlations (corrloc) and a set of frequencies (freq) will return the 3-way array
#'  (corrs), where ith slice (indicated in the 3d array mode) contains the ith matrix feature
#'
#' @param corrloc location of rds correlation file, typically generated from create.df or gencorr
#' @param freqs frequencies that are desired to have in the array
#' @return a list with 1) 3-way array of correlations, with frequencies in rows, images, in columns, and
#' repetitions in the third dimension, 2) the matching of the correlations and 3) the knife pair for the correlation
#' @export
#' @author Carlos Llosa
#' @author Geoffrey Z. Thompson
arraycorr_gen <- function(corrloc,freqs){
  # Given a csv file for correlations (corrloc) and a set of frequencies (freq)
  #
  corrsdat <- read.csv(corrloc)
  freqs <- cbind(freqs[1:(length(freqs)-1)],freqs[2:length(freqs)])
  freqs <- paste0("X",apply(freqs,1,paste,collapse = "."))
  nimg <- max(corrsdat$img)
  corrs <- as.matrix(corrsdat[,colnames(corrsdat) %in% freqs])
  dim(corrs) <- c(nimg,nrow(corrs)/nimg,ncol(corrs))
  corrs <- atanh(aperm(corrs,c(3,1,2)))
  matches <- matrix(corrsdat$match,nimg)[1,]
  kpair <- matrix(corrsdat$knife,nimg)[1,]
  return(list(corrs= corrs,matches = matches,kpair = kpair))
}



#' classify a set of correlations based on a training and a testing path
#'
#' this function will take the path of the training and testing sets, and classify
#'
#'
#' @param corrloc_train directory of the training set
#' @param corrloc_test directory of the testing set (to classify)
#' @param prob_loc location where one wants to save the probabilities (includying file name)
#' @param boxplot_loc location where one wants to save the probabilities boxplots (includying file name)
#' @param freqs frequencies to be used in the training/testing
#' @param df degrees of freedom in the matrix-t distribution that will be used
#' @param verb T or F indicating whether one wants to see progress
#'
#' @return a list with 1) posterior probabilities of match 2) the boxplot 3) parameters used in the training and 4) ML fits
#' @export
#' @author Carlos Llosa-Vite
#' @author Geoffrey Z. Thompson
#' @import MixMatrix
#' @import ggplot2
classif_gen <- function(corrloc_train,
                        corrloc_test,
                        prob_loc = NULL,
                        boxplot_loc= NULL,
                        freqs = c(5,10,20),
                        df = 5,
                        verb = T){

  # obtain features from the correlation csv files
  arrcorr_train <- arraycorr_gen(corrloc_train,freqs)
  arrcorr_test  <- arraycorr_gen(corrloc_test ,freqs)

  # fit models to the matches and non-matches
  fit_match    <- MLmatrixt_ar1(arrcorr_train$corrs[,,arrcorr_train$matches == "match"],df = df)
  fit_nonmatch <- MLmatrixt_ar1(arrcorr_train$corrs[,,arrcorr_train$matches == "nonmatch"],df = df)
  if(verb) cat("training data on n =",sum(arrcorr_train$matches == "match"),"matches and n =",sum(arrcorr_train$matches == "nonmatch"),"nonmatches\n")

  #generate posterior log-odd
  logodds <- dmatrixt(  arrcorr_test$corrs,df = df,mean = fit_match$mean   ,U = fit_match$U   , V = fit_match$V   , log = T) -
    dmatrixt(arrcorr_test$corrs,df = df,mean = fit_nonmatch$mean,U = fit_nonmatch$U, V = fit_nonmatch$V, log = T)
  if(verb) cat("testing data on n =",sum(arrcorr_test$matches == "match"),"matches and n =",sum(arrcorr_test$matches == "nonmatch"),"nonmatches\n")

  #write logits and information
  toret <- data.frame("logitprobs"=logodds,"match" = arrcorr_test$matches,"kpair"=arrcorr_test$kpair)
  toret$probs <- exp(logodds)/(1+exp(logodds))
  if(!is.null(prob_loc)){
    write.csv(toret,file = prob_loc)
    if(verb) cat("probabilities successfully saved \n")
  }


  ### Plotting


  sci <- function(l){
    if(l == 0.5) return(0.5)
    # turn in to character string in scientific notation, and remove the first 1
    l <- sub('.', '', format(l, scientific = TRUE))
    # turn the 'e+' into plotmath format
    gsub("e", "10^", l)
  }
  fancy_scientific <- function(l) {
    l2 <- rep(0,length(l))
    for(i in 1:length(l)){
      if(l[i]<=0.5){
        l2[i] <- sci(l[i])
      } else {
        l2[i] <- paste0("1-",sci(1-l[i]))
      }
    }
    parse(text=l2)
  }

  toret$probs <- exp(logodds)/(1+exp(logodds))
  ybreaks <- c(10^-(10:1),0.5,1-10^-(1:10))
  ybreaks <- ybreaks[(ybreaks <  max(toret$probs)) & (ybreaks >  min(toret$probs)) ]
  p1 <- ggplot(data = toret, aes(x = match, y = probs)) +
    labs(x = "match",y = "posterior probability of match") +
    theme_bw() +   geom_boxplot() +
    geom_hline(yintercept=0.5)+
    coord_trans(y="logit")+
    scale_y_continuous(breaks=ybreaks,labels=fancy_scientific,
                       minor_breaks = ybreaks)
  if(!is.null(prob_loc)){
    ggsave(boxplot_loc,p1,width = 4,height = 4)
    if(verb) cat("boxplot successfully saved \n")
  }
  toret <- list(probs = toret,
                plot = p1,
                pars = c(freqs=paste(freqs,collapse = "-"),df=df),
                fits = list("match"=fit_match,"nonmatch"=fit_nonmatch)
                )
  return(toret)
}
carlos-llosa/topologymatcheR documentation built on Dec. 19, 2021, 1:52 p.m.