content
stringlengths
0
14.9M
filename
stringlengths
44
136
#' Convert an STL file to an x3p file #' #' STL (STereo Lithographic) files describe 3d objects as mesh objects. Here, we assume that the 3d object consists of a 3d surface on the top of a rectangular, equi-spaced 2d grid. #' We further assume, that each node of the STL file describes the x-y location of an actual measurement. These measurements are then converted into the surface matrix of an x3p object. #' The resolution is derived from the distance between consecutive x and y nodes. #' @param stl STL file object or path to the file #' @return x3p object #' @importFrom rgl readSTL #' @export #' @examples #' \dontrun{ #' # the website https://touchterrain.geol.iastate.edu/ allows a download #' # of a 3d printable terrain model. For an example we suggest to download a file from there. #' gc <- rgl::readSTL("<PATH TO STL FILE>", plot=FALSE) #' x3p <- stl_to_x3p(gc) #' } stl_to_x3p <- function(stl) { if (is.character(stl)) { stl <- rgl::readSTL(stl, plot = FALSE) } stopifnot(is.matrix(stl), ncol(stl)==3) x <- y <- value <- NULL stl_df <- data.frame(stl) names(stl_df) <- c("x", "y", "value") stl_df <- stl_df %>% group_by(x, y) %>% summarize(value = max(value)) x3p <- stl_df %>% df_to_x3p() x3p }
/scratch/gouwar.j/cran-all/cranData/x3ptools/R/stl_to_x3p.R
#' Read (or convert) from TMD file to x3p #' #' TMD files are used in telemetry, specifically, they are a native format used #' by GelSight to store 3d topographic surface scans. #' #' The algorithm is based on GelSight's MatLab routine `readtmd.m` published as #' part of the Github repository #' [`gelsightinc/gsmatlab`](https://github.com/gelsightinc/gsmatlab) #' @param tmd_path path to TMD file #' @param yaml_path path to corresponding yaml file with meta information. #' If set to `NA` (default), path of the the tmd file will be tried. If set to NULL, #' meta file will be ignored. #' @param verbose boolean #' @return x3p file of the scan. Some rudimentary information will be filled in, #' information of scanning process, and parameter settings need to be added manually. #' @importFrom assertthat assert_that #' @importFrom yaml read_yaml #' @export #' @examples #' #x3p <- tmd_to_x3p("~/Downloads/Sc04.Pl044.Ma4.SB.An80.Pb.DirFo.SizL.tmd") # #' #x3p <- tmd_to_x3p("~/Downloads/Sc04.Pl044.Ma4.SB.An80.Pb.DirFo.SizL.tmd", #' # yaml_path="~/Downloads/scan.yaml") # tmd_to_x3p <- function(tmd_path, yaml_path = NA, verbose=TRUE) { assert_that(file.exists(tmd_path)) # do we care about the yaml meta information? if (!is.null(yaml_path)) { if (is.na(yaml_path)) { # we don't know name, so try the path of the tmd file directory <- dirname(tmd_path) yaml <- dir(directory, pattern="\\.yaml$", full.names=TRUE, recursive = FALSE) if (length(yaml) != 1) { # warning or error? if (length(yaml) == 0) stop(simpleError(message = sprintf("No yaml file with meta information found in '%s'; set yaml_path=NULL to ignore meta information.", directory))) if (length(yaml) > 1) stop(simpleError(message = sprintf("Multiple yaml files found in directory '%s':\n %s\nAvoid ambiguity by setting yaml_path.", directory, paste(basename(yaml), sep="\n", collapse="\n ")))) } # yaml_path <- yaml[1] # can't be reached } yaml_file <- yaml::read_yaml(yaml_path) if (verbose) message(sprintf("Reading meta information from file '%s'.", basename(yaml_path))) } con <- file(tmd_path,"rb") header <- readBin(con, character(), n=1L, size=32) assert_that(header == 'Binary TrueMap Data File v2.0\r\n') comment <- readBin(con, character(), size=1, n=1L) # % Read number of columns cols <- readBin(con, integer(), size=4, n=1L) # % Read number of rows rows <- readBin(con, integer(), size=4, n=1L) # # % Length of axes # for the field of view (FOV) # browser() data.lengthx <- readBin(con, numeric(), size=4, n=1, endian="little") data.lengthy <- readBin(con, numeric(), size=4, n=1, endian="little") # # % Offsets data.offsetx <- readBin(con, numeric(), size=4, n=1, endian="little") data.offsety <- readBin(con, numeric(), size=4, n=1, endian="little") # # surface matrix data.mmpp = data.lengthx / cols # mm per pixel resolution hmbuf <- readBin(con, numeric(), size=4, n=rows*cols) close(con) x3p <- list() class(x3p) <- "x3p" # need the class early on if (is.null(x3p$matrix.info)) { x3p$matrix.info <- list(MatrixDimension = list(SizeX = cols, SizeY = rows, SizeZ = 1)) } x3p[["surface.matrix"]] <- t(matrix(hmbuf, rows, cols,byrow = TRUE)) if (is.null(x3p$header.info)) { x3p$header.info <- list( sizeX = cols, sizeY = rows, incrementX = data.mmpp, incrementY = data.mmpp ) } if (is.null(x3p$general.info)) { logo <- x3p_read(system.file("csafe-logo.x3p", package="x3ptools")) x3p$general.info <- logo$general.info x3p <- x3p %>% x3p_modify_xml("^Creator$", "N/A") if (is.null(yaml_path)) { # we don't want any meta info - i.e. only ensure structure is there # browser() x3p <- x3p %>% x3p_modify_xml("^Date$", "N/A") x3p <- x3p %>% x3p_modify_xml("CalibrationDate", "N/A") x3p <- x3p %>% x3p_modify_xml("ProbingSystem.Type", "N/A") x3p <- x3p %>% x3p_modify_xml("Comment", sprintf("Converted from TMD file using x3ptools %s", packageVersion("x3ptools"))) } else { # check that we have the correct yaml file if (yaml_file$activeheightmap != basename(tmd_path)) { warning(sprintf("Meta info in %s might not be correct for the scan. Heightmap info specifies scan '%s'. Did you rename the scan?", basename(yaml_path), yaml_file$activeheightmap)) } x3p <- x3p_yaml_info(x3p, yaml_file) } } x3p } # internal helper function # the code will likely only work for GelSight instruments. #' @importFrom utils packageVersion x3p_yaml_info <- function(x3p, yaml_file) { # browser() meta <- data.frame( Date = yaml_file$createdon, Instrument.Manufacturer = "GelSight", Instrument.Model = yaml_file$device$devicetype, Instrument.Serial = yaml_file$device$serialnumber, Instrument.Version = "v1", CalibrationDate = yaml_file$calibration$date, ProbingSystem.Type = paste0(yaml_file$metadata$appname," ", yaml_file$metadata$appversion, ", Gel: ", yaml_file$metadata$gelid, ", Use Count: ", yaml_file$metadata$gelusecount), ProbingSystem.Identification = yaml_file$metadata$sdkversion ) i <- 1 x3p <- x3p %>% x3p_modify_xml("^Date", meta$Date[i]) %>% x3p_modify_xml("Instrument.Manufacturer", meta$Instrument.Manufacturer[i]) %>% x3p_modify_xml("Instrument.Model", meta$Instrument.Model[i]) %>% x3p_modify_xml("Instrument.Serial", meta$Instrument.Serial[i]) %>% x3p_modify_xml("Instrument.Version", meta$Instrument.Version[i]) %>% x3p_modify_xml("CalibrationDate", meta$CalibrationDate[i]) %>% x3p_modify_xml("ProbingSystem.Type", meta$ProbingSystem.Type[i]) %>% x3p_modify_xml("ProbingSystem.Identification", meta$ProbingSystem.Identification[i]) x3p <- x3p %>% x3p_modify_xml("Comment", sprintf("Converted from TMD file using x3ptools %s", packageVersion("x3ptools"))) x3p }
/scratch/gouwar.j/cran-all/cranData/x3ptools/R/tmd_to_x3p.R
#' Pipe operator #' #' See \code{magrittr::\link[magrittr:pipe]{\%>\%}} for details. #' #' @name %>% #' @rdname pipe #' @keywords internal #' @export #' @importFrom magrittr %>% #' @usage lhs \%>\% rhs #' @param lhs A value or the magrittr placeholder. #' @param rhs A function call using the magrittr semantics. #' @return The result of calling `rhs(lhs)`. NULL
/scratch/gouwar.j/cran-all/cranData/x3ptools/R/utils-pipe.R
#' Write an x3p object to a file #' #' @param x3p x3p object #' @param file path to where the file should be written #' @param size integer. The number of bytes per element in the surface matrix used for creating the binary file. Use size = 4 for 32 bit IEEE 754 floating point numbers and size = 8 for 64 bit IEEE 754 floating point number (default). #' @param quiet suppress messages #' @param create_dir boolean. create directory for saving file, if necessary. Posts a message in case a directory is created. #' @importFrom digest digest #' @importFrom xml2 read_xml #' @importFrom utils as.relistable relist zip #' @importFrom graphics par plot #' @importFrom grDevices dev.off #' @export #' @examples #' logo <- x3p_read(system.file("csafe-logo.x3p", package="x3ptools")) #' # write a copy of the file into a temporary file #' x3p_write(logo, file = tempfile(fileext="x3p")) x3p_write <- function(x3p, file, size = 8, quiet = F, create_dir = T) { a1 <- read_xml(system.file("templateXML.xml", package = "x3ptools")) a1list <- as_list(a1, ns = xml_ns(a1)) tmp <- as.relistable(a1list) # structure needed for compiling xml_document # check that file can be written directory <- dirname(file) if (!dir.exists(directory)) { if (create_dir) { message("Creating directory '", directory, "'") dir.create(directory, recursive = TRUE) } else { stop("directory '", directory,"' does not exist. Set `create_dir` to TRUE to create it during the file export.") } } # check that size is 4 or 8 stopifnot(size %in% c(4, 8)) feature.info <- x3p$feature.info general.info <- x3p$general.info header.info <- x3p$header.info matrix.info <- x3p$matrix.info other.info <- x3p$other.info if (is.null(general.info)) { if (!quiet) message("general info not specified, using template") general.info <- as_list(xml_child(a1, search = "Record2")) } if (is.null(feature.info)) { if (!quiet) message("feature info not specified, using template") feature.info <- as_list(xml_child(a1, search = "Record1")) } if (is.null(matrix.info)) { if (!quiet) message("matrix info not specified, using template") matrix.info <- as_list(xml_child(a1, search = "Record3")) } # now overwrite template with relevant information: feature.info$Axes$CX$Increment <- list(header.info$incrementX) feature.info$Axes$CY$Increment <- list(header.info$incrementY) feature.info$Axes$CZ$Increment <- list(1) matrix.info$MatrixDimension$SizeX <- list(header.info$sizeX) matrix.info$MatrixDimension$SizeY <- list(header.info$sizeY) matrix.info$MatrixDimension$SizeZ <- list(1) # Storing the Working Dir path orig.path <- getwd() # include on.exit call to prevent surprises on.exit(setwd(orig.path)) # Figure out where the file should go fileDir <- normalizePath(dirname(file)) fileName <- basename(file) # Creating Temp directory and switch to directory tmpDir <- tempdir() tmpx3pfolder <- tempfile(pattern = "folder", tmpdir = tmpDir) setwd(tmpDir) # Set up file structure dir.create(tmpx3pfolder) setwd(tmpx3pfolder) dir.create("bindata") # Assigning values to the Record 1 part of the XML a1list[[1]]$Record2 <- general.info # Updating the Records in list for: main.xml. a1list[[1]]$Record3 <- matrix.info binPath <- file.path("bindata", "data.bin") a1list[[1]]$Record3$DataLink$PointDataLink <- list(binPath) a1list[[1]]$Record1 <- feature.info a1list[[1]]$Other <- other.info # Writing the Surface Matrix as a Binary file writeBin(as.vector((x3p$surface.matrix)), con = binPath, size = size) # Generating the MD% check sum chksum <- digest("bindata/data.bin", algo = "md5", serialize = FALSE, file = TRUE) a1list[[1]]$Record3$DataLink$MD5ChecksumPointData <- list(chksum) # if the mask exists, write it as a png file if (exists("mask", x3p)) { grDevices::png( file = "bindata/mask.png", width = x3p$header.info$sizeX, height = x3p$header.info$sizeY, units = "px", bg = "transparent" ) graphics::par(mar = c(0, 0, 0, 0)) plot(x3p$mask) dev.off() } if (size == 4) a1list[[1]]$Record1$Axes$CZ$DataType[[1]] <- "F" if (size == 8) a1list[[1]]$Record1$Axes$CZ$DataType[[1]] <- "D" # Assigning values to Record 4 in main.xml a1list[[1]]$Record4$ChecksumFile <- list("md5checksum.hex") # Convert to xml # final.xml.list<- relist(unlist(a1list), skeleton = tmp) #tmp structure used for writing the xml file final.xml.list <- a1list a1xml <- as_xml_document(list(structure(list(final.xml.list)))) # xml_attrs(a1xml)<- xml_attrs(a1) # Write the Main xml file write_xml(a1xml, "main.xml") # HH unfortunate solution: get namespace reference back in front of the root tag of the resulting xml: main <- readLines("main.xml") main <- gsub("^<ISO5436_2", "<p:ISO5436_2", main) main <- gsub("^</ISO5436_2", "</p:ISO5436_2", main) writeLines(main, "main.xml") # HH: only get the checksum once we are done changing the main.xml # Writing the md5checksum.hex with checksum for the main.xml main.chksum <- digest("main.xml", algo = "md5", serialize = FALSE, file = TRUE) write(main.chksum, "md5checksum.hex") # Write the x3p file and reset path # create zipped file in the specified location # zip(zipfile = file.path(fileDir, fileName), files = dir()) zip( zipfile = file.path(fileDir, fileName), files = dir(), flags = ifelse(quiet, "-r9Xq", "-r9X") ) # not necessary to delete the temporary folder # setwd("..") # unlink(tmpx3pfolder,recursive = TRUE) setwd(orig.path) } #' @rdname x3p_write #' @export write_x3p <- function(x3p, file, size = 8, quiet = F) { x3p_write(x3p = x3p, file = file, size = size, quiet = quiet) }
/scratch/gouwar.j/cran-all/cranData/x3ptools/R/write_x3p.R
#' Add a layer to the mask #' #' Add a region a mask. The region is specfied as TRUE values in a matrix of the same dimensions as the existing mask. In case no mask exists, one is created. #' @param x3p x3p object #' @param mask logical matrix of the same dimension as the surface matrix. Values of TRUE are assumed to be added in the mask, values of FALSE are being ignored. #' @param color name or hex value of color #' @param annotation character value describing the region #' @return x3p object with changed mask #' @export x3p_add_mask_layer <- function(x3p, mask, color = "red", annotation = "") { stopifnot("x3p" %in% class(x3p)) if (!exists("mask", x3p)) x3p <- x3p_add_mask(x3p, mask) # need to check that mask has the correct dimensions stopifnot(dim(mask) == dim(x3p$mask)) x3p$mask[mask] <- color # add color and annotation to the xml file x3p <- x3p_add_annotation(x3p, color, annotation) x3p }
/scratch/gouwar.j/cran-all/cranData/x3ptools/R/x3p_add_mask_layer.R
#' Average an x3p object #' #' Calculate blockwise summary statistics on the surface matrix of an x3p. #' If the x3p object has a mask, the mode of the mask value #' @param x3p x3p object #' @param b positive integer value, block size #' @param f function aggregate function #' @param ... parameters passed on to function f. Make sure to use na.rm = T as needed. #' @export #' @importFrom dplyr group_by summarize ungroup add_tally #' @examples #' logo <- x3p_read(system.file("csafe-logo.x3p", package="x3ptools")) #' small <- x3p_average(logo) x3p_average <- function(x3p, b = 10, f = mean, ...) { stopifnot("x3p" %in% class(x3p)) x <- y <- value <- NULL # pass R CMD CHECK mask <- mask_n <- NULL df <- x3p_to_df(x3p) scale <- x3p_get_scale(x3p) df$x <- round(df$x/scale,0) df$y <- round(df$y/scale,0) # round x and y to block size df$x <- df$x %/% b df$y <- df$y %/% b # browser() if(!is.null(x3p$mask)) { df <- ungroup(add_tally(group_by(df, x, y, mask), name="mask_n")) df <- summarize(group_by(df, x, y), value = f(value, ...), mask = mask[which.max(mask_n)] # in case of ties, take the first ) # if(!is.null(x3p$matrix.info$Mask$Annotations)) { # browser() # colors <- x3p_mask_legend(x3p) # annotations <- data.frame( # mask_low = tolower(colors), # annotation = names(colors) # ) # df <- left_join( # mutate(df, mask_low=tolower(mask)), # annotations, # by="mask_low" # ) # df <- select(df, -mask_low) # } } else { df <- summarize(group_by(df, x, y), value = f(value, ...) ) } # scale x and y back df$x <- df$x * scale * b df$y <- df$y * scale * b df_to_x3p(df) }
/scratch/gouwar.j/cran-all/cranData/x3ptools/R/x3p_average.R
#' Add colored stripes of the surface gradient to the mask of an x3p object #' #' Apply gradient-based color shading to the mask of a 3d topographic surface. #' Gradients are determined empirically based on sequentical row- (or column-)wise #' differences of surface values. #' The `direction` parameter determines the direction of differencing. #' If direction is "vertical", columns in the surface matrix are #' differenced to identify whether 'vertical' stripes exist. #' @param x3p object containing a 3d topographic surface #' @param direction in which the stripes are created: `vertical` or `horizontal`. #' @param colors vector of colors #' @param freqs vector of values corresponding to color frequency (turned into quantiles of the differenced values) #' @return x3p object with mask colored by discretized surface gradient #' @export #' @examples #' data(wire) #' x3p <- wire #' if (interactive()) x3p_image(x3p, size = c(400, 400), zoom=0.8) #' x3p_with <- x3p_bin_stripes(x3p, direction="vertical") #' x3p_with <- x3p_bin_stripes(x3p, direction="vertical", #' colors=c("#b12819","#ffffff","#134D6B"), freqs=c(0, 0.3, 0.7, 1)) #' if (interactive()) x3p_image(x3p_with, size = c(400, 400), zoom=0.8) #' #' data(lea) #' if (interactive()) { #' lea %>% x3p_bin_stripes() %>% x3p_image() # default stripes #' #' # three colors only #' lea %>% x3p_bin_stripes( #' colors=c("#b12819","#ffffff","#134D6B"), #' freqs=c(0, 0.3, 0.7, 1)) %>% x3p_image() #' } x3p_bin_stripes <- function(x3p, direction = "vertical", colors = rev(c("#b12819", "#d7301f","#e16457","#ffffff","#5186a2","#175d82", "#134D6B")), freqs = c(0, 0.05, 0.1, 0.3,0.7, 0.9, 0.95, 1)) { stopifnot("x3p" %in% class(x3p)) stopifnot(length(freqs) >= 3) # we need at least min, max and one other value. stopifnot(length(colors) == length(freqs) -1) stopifnot(direction %in% c("vertical", "horizontal")) freqs <- sort(freqs) # just to prevent any strange things x3p_diff <- x3p dims <- dim(x3p_diff$surface.matrix) if (direction=="horizontal") { x3p_diff$surface.matrix <- x3p_diff$surface.matrix[,-1]-x3p_diff$surface.matrix[,-dims[2]] x3p_diff$header.info$sizeY <- x3p_diff$header.info$sizeY-1 } if (direction=="vertical") { x3p_diff$surface.matrix <- x3p_diff$surface.matrix[-1,]-x3p_diff$surface.matrix[-dims[1],] x3p_diff$header.info$sizeX <- x3p_diff$header.info$sizeX-1 } rescaled <- scales::rescale(x3p_diff$surface.matrix) qus = quantile(rescaled, freqs, na.rm=TRUE) # hexes <- scales::gradient_n_pal(colors, qus)(rescaled) hexes <- cut(rescaled, breaks=qus, labels=colors) if (direction=="horizontal") { stripes <- matrix(hexes, byrow = FALSE, nrow = dims[1]) stripes <- cbind(stripes, NA) } if (direction=="vertical") { stripes <- matrix(hexes, byrow = FALSE, ncol = dims[2]) stripes <- rbind(stripes, NA) } x3p <- x3p %>% x3p_add_mask(mask = as.raster(t(stripes))) #x3p_image(x3p_diff, size = dim(x3p_diff$surface.matrix)/5, zoom=0.8) x3p }
/scratch/gouwar.j/cran-all/cranData/x3ptools/R/x3p_bin_strips.R
#' Crop an x3p object to a specified width and height #' #' Cuts out a rectangle of size width x height from the location (x, y) of an x3p object. #' x and y specify the bottom right corner of the rectangle. #' In case the dimensions of the surface matrix do not allow for the full dimensions of the rectangle cutout the dimensions are adjusted accordingly. #' @param x3p x3p object #' @param x integer, location (in pixels) of the leftmost side of the rectangle, #' @param y integer, location (in pixels) of the leftmost side of the rectangle, #' @param width integer, width (in pixels) of the rectangle, #' @param height integer, height (in pixels) of the rectangle, #' @export #' @examples #' logo <- x3p_read(system.file("csafe-logo.x3p", package="x3ptools")) #' # crop the x3p file to just the CSAFE logo #' logo_only <- x3p_crop(logo, x=20, y=50, width = 255 ,height =310) #' logo_only <- x3p_crop(logo, x=20, y=50, width = 255 ,height =510) #' # x3p_image(logo_only, size=c(500,500), zoom = 1) x3p_crop <- function(x3p, x=1, y=1, width=128, height=128) { # check that x, x+width, y, y+height are inside the matrix y3p <- x3p dims <- dim(y3p$surface.matrix) xidx <- x+0:(width-1) yidx <- sort(dims[2] - (y+0:(height-1)))+1 # dimension checks: xidx <- xidx[(xidx > 0) & (xidx <= dims[1])] yidx <- yidx[(yidx > 0) & (yidx <= dims[2])] # warn in case dimensions are not what was specified by user: if ((length(xidx) != width) | (length(yidx) != height)) { warning(sprintf("Specified dimension are adjusted to fit within range of the surface matrix: %d x %d", length(xidx), length(yidx))) } stopifnot(length(xidx) > 0, length(yidx) > 0) # there should be something left over after adjusting y3p$surface.matrix <- y3p$surface.matrix[xidx, yidx] y3p$header.info$sizeY <- height y3p$header.info$sizeX <- width y3p$matrix.info$MatrixDimension$SizeX[[1]] <- y3p$header.info$sizeX y3p$matrix.info$MatrixDimension$SizeY[[1]] <- y3p$header.info$sizeY y3p$general.info$Comment <- paste(trimws(y3p$general.info$Comment), "; cropped from location (", x, ",", y,")") if (!is.null(y3p$mask)) { # matrix with flipped x and y dimensions y3p$mask <- y3p$mask[yidx, xidx] } y3p }
/scratch/gouwar.j/cran-all/cranData/x3ptools/R/x3p_crop.R
#' Extract values from a surface matrix based on a mask #' #' If a mask is present, a subset of the surface matrix is extracted based on specified value(s). #' @param x3p x3p object #' @param mask_vals vector of mask value(s) #' @return x3p object #' @export #' @examples #' logo <- x3p_read(system.file("csafe-logo.x3p", package="x3ptools")) #' # add a mask #' logo <- x3p_add_mask(logo) #' mask <- t(logo$surface.matrix==median(logo$surface.matrix)) #' logo <- x3p_add_mask_layer(logo, mask, color = "red", annotation = "median") #' x3p_extract(logo, "#cd7f32") #' # x3p_image(logo, size=c(500,500), zoom = 1) x3p_extract <- function(x3p, mask_vals) { if (is.null(x3p$mask)) return(x3p) idx <- which(!(t(as.matrix(x3p$mask)) %in% mask_vals)) x3p$surface.matrix[idx] <- NA x3p }
/scratch/gouwar.j/cran-all/cranData/x3ptools/R/x3p_extract.R
#' Interactively select a line on the active rgl device #' #' In the active rgl device select a line on the 3d surface by clicking on start and end-point (order matters). These points define the beginning and end of a line segment. #' The line segment is drawn on the mask of the x3p object. #' The line object is returned as part of the x3p object, if `line_result` is set to `TRUE` #' @param x3p x3p file #' @param col character value of the selection color #' @param update boolean value, whether the rgl window should be updated to show the selected circle #' @param line_result enhance result by a data frame of the line: NULL for no, "raw" for data frame of original x and y (in the mask) and #' projected x onto the line, "equi-spaced" (default) returns a data frame with equispaced x values after fitting a loess smooth to the raw values. #' Note that variable x indicates the direction from first click (x=0) to #' the second click (max x). #' @param multiply integer value, factor to multiply surface values. Only applied if update is true. Defaults to 5, #' @param linewidth line width of the extracted line. Defaults to 1. #' @return x3p file with identified line in the mask. Depending on the setting of `line_result` #' additional information on the line is attached as a data frame. #' @export #' @importFrom dplyr arrange between filter mutate rename #' @examples #' \dontrun{ #' if (interactive) { #' x3p <- x3p_read(system.file("sample-land.x3p", package="x3ptools")) #' x3p %>% image_x3p(size=dim(x3p$surface.matrix), multiply=1, zoom=.3) #' x3p <- x3p_extract_profile(x3p, update=TRUE, col="#FFFFFF") #' x3p$line_df %>% #' ggplot(aes(x = x, y = value)) + geom_line() #' #' x3p$line_df$y <- 1 #' sigs <- bulletxtrctr::cc_get_signature(ccdata = x3p$line_df, #' grooves = list(groove=range(x3p$line_df$x)), span1 = 0.75, span2 = 0.03) #' sigs %>% #' ggplot(aes(x = x)) + #' geom_line(aes(y = raw_sig), colour = "grey50") + #' geom_line(aes(y = sig), size = 1) + #' theme_bw() #' }} x3p_extract_profile <- function(x3p, col = "#FF0000", update=TRUE, line_result= "equi-spaced", multiply = 5, linewidth = 1) { cat("Select start point and endpoint on the surface ...\n") stopifnot("x3p" %in% class(x3p)) ids <- rgl::ids3d() if (nrow(ids) == 0) { size <- dim(x3p$surface.matrix) size[2] <- round(500/size[1]*size[2]) size[1] <- 500 x3p %>% x3p_image(size = size, zoom=0.8) } rgl::rgl.bringtotop() # initialize values orig_x <- orig_y <- `p-x.m` <- `p-x.n` <- value <- NULL multiply <- multiply surface <- x3p$surface.matrix z <- multiply * surface yidx <- ncol(z):1 y <- x3p$header.info$incrementY * yidx x <- x3p$header.info$incrementX * (1:nrow(x3p$surface.matrix)) xidx <- rep(x, length(y)) yidx <- rep(y, each=length(x)) selected <- identify3d(xidx, yidx ,z, n=2, buttons=c("left", "middle")) # browser() coord1 <- xidx[selected] coord2 <- yidx[selected] X <- c(coord1[1], coord2[1]) Y <- c(coord1[2], coord2[2]) m <- Y-X dm <- sqrt(sum(m^2)) # length of Y-X m <- m/dm n <- c(m[2],-m[1]) # normal vector to m if (is.null(x3p$mask)) x3p <- x3p %>% x3p_add_mask() # x3p_df <- x3p_to_df(x3p) x3p_df <- x3p_df %>% mutate( `p-x.n` = (x - X[1])*n[1] + (y - X[2])*n[2], `p-x.m` = (x - X[1])*m[1] + (y - X[2])*m[2] ) eps <- x3p %>% x3p_get_scale() * linewidth/2 on_line <- abs(x3p_df$`p-x.n`)< eps & dplyr::between(x3p_df$`p-x.m`, 0, dm) x3p_df$mask[on_line] <- col tmp <- x3p_df %>% df_to_x3p() # if (is.null(x3p$mask)) x3p <- x3p %>% x3p_add_mask() # browser() x3p$mask <- tmp$mask # browser() if (update) { rgl::rgl.bringtotop() clear3d() # remove the active scene surface3d(x, y, z, col = as.vector(x3p$mask), back = "fill") # x3p %>% image_x3p(update=TRUE) } if (!is.null(line_result)) { line_df <- x3p_df %>% filter(abs(`p-x.n`)<eps, between(`p-x.m`, 0, dm)) %>% rename( orig_x = x, orig_y = y, x = `p-x.m`, y = `p-x.n` ) %>% select(x, y, orig_x, orig_y, value) %>% arrange(x) if (line_result == "raw") { line <- line_df } if (line_result == "equi-spaced") { #ps <- sequence_points(0, Y-X, by=x3p %>% x3p_get_scale()) scale <- x3p %>% x3p_get_scale() line_df <- line_df %>% mutate( x = round(x/scale), y = round(y/scale) ) line <- line_df %>% group_by(x) %>% summarize( value = median(value, na.rm=TRUE), orig_x = median(orig_x), orig_y = median(orig_y), y = 0, n = n()) %>% mutate(x = x*scale) } attributes(line)$click <- list(start=X, end=Y) x3p$line <- line } x3p }
/scratch/gouwar.j/cran-all/cranData/x3ptools/R/x3p_extract_profile.R
#' Extract profiles from surface using multiple segments #' #' The 3d topographic surface is split into multiple segments of width `width` (in pixels) #' using an overlap of 10% between segments. For each segment, a line is extracted (with `x3p_extract_profile`). #' Line segments are projected onto the mask of the initial x3p object and exported as a `lines` attribute. #' @param x3p object #' @param width segment width #' @param col color #' @param linewidth integer value specifying the width for the profile #' @param verbose logical #' @return x3p object with added `lines` attribute. #' @importFrom dplyr mutate left_join select desc add_tally ungroup n #' @importFrom purrr pmap map map_dbl pmap_df #' @importFrom tidyr unnest #' @export #' @examples #' logo <- x3p_read(system.file("csafe-logo.x3p", package="x3ptools")) #' logo <- x3p_m_to_mum(logo) #' if(interactive()) #' x3p_extract_profile_segments(logo, 850, col="#ffffff", linewidth=5) x3p_extract_profile_segments <- function(x3p, width, col="#FF0000", linewidth=11, verbose = TRUE) { # pass R CMD CHECK x <- y <- height <- value <- orig_x <- orig_y <- piece <- NULL mask.x <- mask.y <- line <- offset_x <- value_adjust <- NULL offset_y <- NULL # how many pieces do we need assuming we use 10% for overlap? dims <- dim(x3p$surface.matrix) w10 <- round(.1*width) w90 <- width - w10 orig_scale <- x3p$header.info$incrementY x3p$header.info$incrementY <- 1 x3p$header.info$incrementX <- 1 if (verbose) { message(sprintf("Setting up %d pieces ...", dims[1] %/% w90 + 1)) } dframe <- data.frame(x = seq(1, dims[1], by = w90), y = 1, width = width, height=dims[2]-1) dframe <- dframe %>% mutate( width = ifelse(x+width > dims[1], dims[1]-x, width) ) dframe <- dframe %>% mutate( x3p = purrr::pmap(list(x, y, width, height), .f = function(x, y, width, height) { x3p_crop(x3p, x,y,width,height)}) ) if (verbose) { message("done\nExtract profiles for each piece ...\n") } dframe <- dframe %>% mutate( x3p = x3p %>% purrr::map(.f = function(x) { x %>% x3ptools::x3p_image() x <- x %>% x3p_extract_profile(linewidth=linewidth) }) ) if (verbose) { message("done\nIncorporate into mask ...\n") } dframe <- dframe %>% mutate( line = x3p %>% purrr::map(.f = function(x) x$line) ) masklines <- dframe %>% select(-x3p) %>% rename(offset_x = x, offset_y = y) %>% mutate(piece = 1:n()) %>% tidyr::unnest(col=line) masklines$mask <- col masklines <- masklines %>% mutate( x = round(orig_x + offset_x), y = round(orig_y + offset_y) ) %>% select(x, y, mask) %>% unique() if (is.null(x3p$mask)) x3p <- x3p %>% x3p_add_mask() x3p_df <- x3p %>% x3p_to_df() # masklines %>% anti_join(x3p_df, by=c("x", "y")) x3p_df <- x3p_df %>% left_join(masklines, by=c("x", "y")) x3p_df <- x3p_df %>% mutate( mask = ifelse(is.na(mask.y), mask.x, mask.y) ) %>% select(-mask.x, -mask.y) if (verbose) { message("done\nCombine profiles into one ...\n") } # check the `value` values of overlapping pieces and adjust consecutive pieces for any systematic # differences in `value` dframe <- dframe %>% mutate( value_first10 = x3p %>% purrr::map_dbl(.f = function(x) { x$line %>% filter(x <= w10) %>% summarize(value = mean(value, na.rm=TRUE)) %>% pull(1) }), value_last10 = x3p %>% purrr::map_dbl(.f = function(x) { x$line %>% filter(x > w90) %>% summarize(value = mean(value, na.rm=TRUE)) %>% pull(1) }) ) idx <-1:nrow(dframe) dframe$value_adjust <- 0 if (length(idx) > 1) { idx_last <- c(NA, 1:(nrow(dframe)-1)) dframe$value_adjust <- dframe$value_last10[idx_last]-dframe$value_first10[idx] dframe$value_adjust[1] <- 0 dframe$value_adjust <- cumsum(dframe$value_adjust) } lines <- dframe %>% select(-x3p) %>% rename(offset_x = x, offset_y = y) %>% mutate(piece = 1:n()) %>% tidyr::unnest(col=line) %>% mutate( value = value + value_adjust, x = orig_x+offset_x ) # lines %>% ggplot(aes(x = orig_x+offset_x, y = value)) + geom_point(aes(colour=factor(piece))) if (verbose) { message("done") } x3p_df <- x3p_df %>% arrange(x,desc(y)) mask <- matrix(x3p_df$mask, nrow = dims[2]) x3p$mask <- as.raster(mask) x3p$header.info$incrementY <- orig_scale x3p$header.info$incrementX <- orig_scale x3p$lines <- lines %>% mutate( x = x * orig_scale, y = y * orig_scale, orig_x = orig_x+offset_x, orig_y = orig_y+offset_y) %>% select(x, y, value, orig_x, orig_y, piece) x3p }
/scratch/gouwar.j/cran-all/cranData/x3ptools/R/x3p_extract_profile_segments.R
#' Flip the x coordinate of an x3p file #' #' Flip the surface matrix of an x3p file along the x axis. #' @param x3p x3p object #' @return x3p object in which the x coordinate is reversed. #' @export #' @examples #' logo <- x3p_read(system.file("csafe-logo.x3p", package="x3ptools")) #' dim(logo$surface.matrix) #' \dontrun{ #' x3p_image(logo) #' } #' # flip the y-axis for the old ISO standard: #' logoflip <- x3p_flip_x(logo) #' dim(logoflip$surface.matrix) #' \dontrun{ #' x3p_image(logoflip) #' } x3p_flip_x <- function(x3p) { x3p_transpose(rotate_x3p(x3p, angle = 90)) } #' @rdname x3p_flip_x #' @export x_flip_x3p <- x3p_flip_x
/scratch/gouwar.j/cran-all/cranData/x3ptools/R/x3p_flip_x.R
#' Flip the y coordinate of an x3p image #' #' One of the major changes between the previous two ISO standards is the #' way the y axis is defined in a scan. The entry (0,0) used to refer to the top left corner of a scan, now it refers to the #' bottom right corner, which means that all legacy x3p files have to flip their y axis in order to #' conform to the newest ISO norm. #' @param x3p x3p object #' @return x3p object in which the y coordinate is reversed. #' @export #' @examples #' logo <- x3p_read(system.file("csafe-logo.x3p", package="x3ptools")) #' dim(logo$surface.matrix) #' \dontrun{ #' x3p_image(logo) #' } #' # flip the y-axis for the old ISO standard: #' logoflip <- x3p_flip_y(logo) #' dim(logoflip$surface.matrix) #' \dontrun{ #' x3p_image(logoflip) #' } x3p_flip_y <- function(x3p) { rotate_x3p(x3p_transpose(x3p), angle = 90) } #' @rdname x3p_flip_y #' @export y_flip_x3p <- x3p_flip_y
/scratch/gouwar.j/cran-all/cranData/x3ptools/R/x3p_flip_y.R
#' Get legend for mask colors #' #' Retrieve color definitions and annotations from the mask. If available, results in a named vector of colors. #' @param x3p x3p object with a mask #' @return named vector of colors, names show annotations. In case no annotations exist NULL is returned. #' @export #' @examples #' x3p <- x3p_read(system.file("sample-land.x3p", package="x3ptools")) #' x3p_mask_legend(x3p) # annotations and color hex definitions x3p_mask_legend <- function(x3p) { stopifnot("x3p" %in% class(x3p)) # no x3p object if (is.null(x3p$mask)) return(NULL) if (length(suppressWarnings(x3p_show_xml(x3p, "Annotations"))) == 0) return(NULL) annotations <- unlist(x3p$matrix.info$Mask$Annotations) colors <- unlist(lapply(x3p$matrix.info$Mask$Annotations, attributes)) names(colors) <- annotations background <- list() elements <- x3p_show_xml(x3p,"*") element_bg <- grep("Background", names(elements), value=TRUE) if (length(element_bg) > 0) background <- x3p_show_xml(x3p, element_bg[1]) if (length(background) > 0) { colors <- c(background[[1]], colors) names(colors)[1] <- "well expressed striae" } colors } #' Display legend in active rgl object #' #' Display the legend for colors and annotations in the active rgl window. In case no rgl window is opened, a new window displaying the x3p file (using default sizes and zoom) opens. #' @param x3p x3p object with a mask #' @param colors named character vector of colors (in hex format by default), names contain annotations #' @export #' @examples #' x3p <- x3p_read(system.file("sample-land.x3p", package="x3ptools")) #' \dontrun{ #' # run when rgl can open window on the device #' x3p_image(x3p) #' x3p_add_legend(x3p) # add legend #' } x3p_add_legend <- function(x3p, colors = NULL) { stopifnot("x3p" %in% class(x3p)) # no x3p object # stopifnot(length(rgl.dev.list()) > 0) if (is.null(colors)) colors <- x3p_mask_legend(x3p) stopifnot("No colors to add to legend"=!is.null(colors)) ids <- rgl::ids3d() if (nrow(ids) == 0) { x3p_image(x3p) } if (!is.null(colors)) { legend3d("bottomright", legend = names(colors), pch = 15, col = colors, cex = 1, pt.cex = 2, inset = c(0.02) ) } } #' Lighten active rgl object #' #' Make the currently active rgl object lighter. Adds a light source. Up to eight light sources can be added. Alternatively, any rgl light source can be added (see `light3d`). #' @export #' @examples #' x3p <- x3p_read(system.file("sample-land.x3p", package="x3ptools")) #' \dontrun{ #' x3p_image(x3p) # run when rgl can open window on the device #' x3p_lighter() # add a light source #' } x3p_lighter <- function() { stopifnot(length(rgl.dev.list()) > 0) # stopifnot("x3p" %in% class(x3p)) # no x3p object light3d(diffuse = "gray20", specular = "gray20") } #' Darken active rgl object #' #' Makes the currently active rgl object darker by removing a light source. Once all light sources are removed the object can not be any darker. #' @export #' @examples #' x3p <- x3p_read(system.file("sample-land.x3p", package="x3ptools")) #' \dontrun{ #' x3p_image(x3p) # run when rgl can open window on the device #' x3p_darker() # remove a light source #' } x3p_darker <- function() { stopifnot(length(rgl.dev.list()) > 0) # stopifnot("x3p" %in% class(x3p)) # no x3p object pop3d("lights") }
/scratch/gouwar.j/cran-all/cranData/x3ptools/R/x3p_mask_legend.R
#' Draw a quantile region on the mask #' #' For each x value of the surface matrix add a region to the mask of an x3p object corresponding to the area between two specified #' quantiles. #' @param x3p x3p object #' @param quantiles vector of quantiles between which surface matrix values are included in the mask #' @param color name or hex value of color #' @param annotation character value describing the region #' @return x3p object with changed mask #' @importFrom stats quantile #' @export x3p_mask_quantile <- function(x3p, quantiles = c(0.25, 0.75), color = "red", annotation = "quantile-region") { stopifnot("x3p" %in% class(x3p)) if (!exists("mask", x3p)) x3p <- x3p_add_mask(x3p) if (length(quantiles) == 1) quantiles <- c(quantiles, 1 - quantiles) tA <- apply(x3p$surface.matrix, 1, FUN = function(x) { qu <- quantile(x, na.rm = TRUE, probs = quantiles) (x >= qu[1]) & (x <= qu[2]) }) x3p$mask[tA] <- color # add color and annotation to the xml file x3p <- x3p_add_annotation(x3p, color, annotation) x3p }
/scratch/gouwar.j/cran-all/cranData/x3ptools/R/x3p_mask_quantile.R
#' Read data from an x-y-z file #' #' @param dat path to the x-y-z file #' @param delim character determining delimiter #' @param col_names logical value - does the first line of the file contain the column names? Default is set to FALSE. #' @return x3p object #' @importFrom readr read_delim #' @export x3p_read_dat <- function(dat, delim = " ", col_names = FALSE) { stopifnot(file.exists(dat)) datfile <- readr::read_delim(dat, delim = delim, col_names = col_names) # browser() stopifnot(dim(datfile)[2] == 3) # we need to have exactly 3 columns names(datfile) <- c("x", "y", "value") datfile$value <- as.numeric(datfile$value) x3p <- df_to_x3p(datfile) plux <- gsub(".dat$", ".plux", dat) if (file.exists(plux)) { x3p$general.info <- x3p_read_plux(plux) } else { warning(sprintf("no matching plux file found for %s", dat)) } x3p } #' Read information from plux file #' #' plux files are zip containers of 3d topographic scans in a format proprietary to Sensofar™. #' One of the files in the container is the file `index.xml` which contains meta-information on the instrument, scan settings, date, and creator. #' This information is added to the x3p meta-information. #' @param plux path to plux file #' @return xml of general information as stored in the plux file #' @export x3p_read_plux <- function(plux) { # browser() mydir <- tempdir() result <- unzip(plux, exdir = mydir) index <- read_xml(grep("index.xml", result, value = TRUE)) index_info <- xml_children(xml_children(index)) ## Convert to a list index_names <- sapply(index_info, xml_name) index_values <- sapply(index_info, xml_text) a1 <- read_xml(system.file("templateXML.xml", package = "x3ptools")) general.info <- as_list(xml_child(a1, search = "Record2")) general.info$Date[[1]] <- index_values[grep("DATE", index_names)] general.info$Creator[[1]] <- index_values[grep("AUTHOR", index_names)] general.info$Instrument$Manufacturer[[1]] <- "Sensofar" general.info$Instrument$Model[[1]] <- gsub("Device", "", grep("Device", index_values, value = TRUE)) general.info$ProbingSystem$Type[[1]] <- gsub("Technique", "", grep("Technique", index_values, value = TRUE)) general.info$ProbingSystem$Identification[[1]] <- gsub("Objective", "", grep("Objective", index_values, value = TRUE)) general.info }
/scratch/gouwar.j/cran-all/cranData/x3ptools/R/x3p_read_dat.R
#' Rotate an x3p object #' #' Rotate the surface matrix and mask of an x3p object. Also adjust meta information. #' @param x3p x3p object #' @param angle rotate counter-clockwise by angle in degrees. #' @importFrom imager as.cimg pad rotate_xy #' @importFrom dplyr near #' @export #' @examples #' \dontrun{ #' logo <- x3p_read(system.file("csafe-logo.x3p", package = "x3ptools")) #' color_logo <- png::readPNG(system.file("csafe-color.png", package="x3ptools")) #' logoplus <- x3p_add_mask(logo, as.raster(color_logo)) #' dim(logoplus$surface.matrix) #' dim(logoplus$mask) #' x3p_image(logoplus, multiply=50, size = c(741, 419),zoom = 0.5) #' #' logoplus60 <- x3p_rotate(x3p = logoplus, angle = 60) #' dim(logoplus60$surface.matrix) #' dim(logoplus60$mask) #' x3p_image(logoplus60, multiply=50, size = c(741, 419),zoom = 0.75) #' } x3p_rotate <- function(x3p, angle = 90) { stopifnot(is.numeric(angle)) # Make sure that all angles are in [0, 360) angle <- angle %% 360 if (near(angle, 0)) { return(x3p) } ### Change NAs to background x3p_shift <- x3p$surface.matrix # NA_val <- -(x3p$surface.matrix %>% # c() %>% # summary() %>% # .[c("Min.", "Max.")] %>% # abs() %>% # max() %>% # ceiling()) NA_val <- min(x3p$surface.matrix, na.rm=TRUE) - .1*diff(range(x3p$surface.matrix, na.rm=TRUE)) x3p_shift[is.na(x3p$surface.matrix)] <- NA_val ### Change to raster # # x3p_raster <- t(x3p_shift) %>% # # as.raster( # # max = max(x3p$surface.matrix, na.rm=TRUE), # # xmx = (x3p$header.info$sizeX - 1) * x3p$header.info$incrementX, # # ymx = (x3p$header.info$sizeY - 1) * x3p$header.info$incrementY) # x3p_raster <- t(x3p_shift) %>% # raster(xmx = (x3p$header.info$sizeX - 1) * x3p$header.info$incrementX, ymx = (x3p$header.info$sizeY - 1) * x3p$header.info$incrementY) ### Change to cimg x3p_cimg <- as.cimg(x3p_shift) ### Compute diagonal length diag_len <- sqrt(nrow(x3p_cimg)^2 + ncol(x3p_cimg)^2) ### Pad the original cimg object x3p_cimg_pad <- x3p_cimg %>% pad(nPix = diag_len, axes = "xy", pos = -1, val = NA_val) %>% pad(nPix = diag_len - nrow(x3p_cimg), axes = "x", pos = 1, val = NA_val) %>% pad(nPix = diag_len - ncol(x3p_cimg), axes = "y", pos = 1, val = NA_val) ### Rotate at padding center ### interpolation maintain the original scaling x3p_cimg_pad_rotate <- x3p_cimg_pad %>% rotate_xy(-angle, diag_len, diag_len, interpolation = 0L, boundary_conditions = 1L) ### Change cimg object to matrix x3p_matrix_pad_rotate <- x3p_cimg_pad_rotate %>% as.matrix() x3p_matrix_pad_rotate[near(x3p_matrix_pad_rotate, NA_val)] <- NA ### Remove extra NA space after padding na_matrix <- x3p_matrix_pad_rotate %>% is.na() na_row <- rowSums(na_matrix) == (ncol(na_matrix)) na_col <- colSums(na_matrix) == (nrow(na_matrix)) x3p_matrix_pad_rotate <- x3p_matrix_pad_rotate[!na_row, !na_col] ### Copy x3p object x3p_pad_rotate <- x3p ### Change details of x3p object x3p_pad_rotate$header.info$sizeX <- nrow(x3p_matrix_pad_rotate) x3p_pad_rotate$header.info$sizeY <- ncol(x3p_matrix_pad_rotate) x3p_pad_rotate$matrix.info$MatrixDimension$SizeX <- list(nrow(x3p_matrix_pad_rotate)) x3p_pad_rotate$matrix.info$MatrixDimension$SizeY <- list(ncol(x3p_matrix_pad_rotate)) x3p_pad_rotate$surface.matrix <- x3p_matrix_pad_rotate if (!is.null(x3p$mask)) { ### Change to cimg # x3p_mask_cimg <- x3p$mask %>% # raster::as.matrix() %>% # t() %>% # as.raster() %>% # as.cimg() x3p_mask_cimg <- as.cimg(x3p$mask) ### Compute diagonal length diag_len <- sqrt(nrow(x3p_mask_cimg)^2 + ncol(x3p_mask_cimg)^2) ### Pad the original cimg object NA_val <- "black" x3p_mask_cimg_pad <- x3p_mask_cimg %>% pad(nPix = diag_len, axes = "xy", pos = -1, val = NA_val) %>% pad(nPix = diag_len - nrow(x3p_mask_cimg), axes = "x", pos = 1, val = NA_val) %>% pad(nPix = diag_len - ncol(x3p_mask_cimg), axes = "y", pos = 1, val = NA_val) ### Rotate at padding center ### interpolation maintain the original scaling x3p_mask_cimg_pad_rotate <- x3p_mask_cimg_pad %>% rotate_xy(-angle, diag_len, diag_len, interpolation = 0L, boundary_conditions = 1L) ### Change cimg object to raster x3p_mask_raster_pad_rotate <- x3p_mask_cimg_pad_rotate %>% as.raster() x3p_mask_raster_pad_rotate[x3p_mask_raster_pad_rotate == "#000000"] <- NA ### Remove extra NA space after padding x3p_mask_raster_pad_rotate <- x3p_mask_raster_pad_rotate[!na_col, !na_row] %>% toupper() # x3p_add_mask(x3p_pad_rotate, x3p_mask_raster_pad_rotate) x3p_pad_rotate$mask <- x3p_mask_raster_pad_rotate } return(x3p_pad_rotate) } #' @rdname x3p_rotate #' @export rotate_x3p <- x3p_rotate
/scratch/gouwar.j/cran-all/cranData/x3ptools/R/x3p_rotate.R
#' Draw rectangle on the mask of an x3p file using rgl #' #' Interactive selection of rectangular area on the mask of an x3p object. Once the function runs, the active rgl window is brought to the front. #' Select the window with a click, then use click & drag to select a rectangular area. On release, this area is marked in the mask and (if update is TRUE) appears in the selection color in the active rgl window. #' @param x3p x3p file #' @param col character value of the selection color #' @param update boolean value, whether the rgl window should be updated to show the selected rectangle #' @return x3p file with selection in mask #' @export #' @examples #' \dontrun{ #' if (interactive) { #' if (!file.exists("fadul1-1.x3p")) { #' url <- "https://tsapps.nist.gov/NRBTD/Studies/CartridgeMeasurement/DownloadMeasurement" #' file <- "2d9cc51f-6f66-40a0-973a-a9292dbee36d" #' download.file(file.path(url, file), destfile="fadul1-1.x3p") #' } #' x3p <- x3p_read("fadul1-1.x3p") #' x3p_image(x3p, size=c(500,500), zoom=.8) #' x3p <- x3p_select(x3p, update=TRUE, col="#FF0000") #' #' logo <- x3p_read(system.file("csafe-logo.x3p", package="x3ptools")) #' x3p_image(logo, size=c(500,500), zoom = 1) #' x3p_select(logo, update=TRUE, col="#00FF00") #' }} x3p_select <- function(x3p, col = "#FF0000", update=TRUE) { # browser() stopifnot("x3p" %in% class(x3p)) ids <- rgl::ids3d() if (nrow(ids) == 0) { size <- dim(x3p$surface.matrix) size[2] <- round(500/size[1]*size[2]) size[1] <- 500 x3p %>% x3p_image(size = size, zoom=0.8) } rgl::rgl.bringtotop() cat("select rectangular area (by click and drag) or click to stop\n") f <- select3d() multiply <- 5 surface <- x3p$surface.matrix z <- multiply * surface yidx <- ncol(z):1 y <- x3p$header.info$incrementY * yidx x <- x3p$header.info$incrementX * (1:nrow(x3p$surface.matrix)) selected <- f(rep(x, length(y)), rep(y, each=length(x)) ,z) if (is.null(x3p$mask)) x3p <- x3p %>% x3p_add_mask() # x3p$mask[matrix(selected, nrow = dim(x3p$mask)[1], byrow=TRUE)] <- col if (update) { # browser() pop3d() # remove the active scene surface3d(x, y, z, col = as.vector(x3p$mask), back = "fill") # x3p %>% image_x3p(update=TRUE) } x3p } #' Interactive selection of region of interest #' #' #' @param x3p x3p file #' @param col character value of the selection color #' @param mad scalar #' @param type only "plane" is implemented at the moment #' @param update boolean value, whether the rgl window should be updated to show the selected rectangle #' @return x3p file with updated mask #' @importFrom stats predict #' @importFrom MASS rlm #' @export #' @examples #' \dontrun{ #' if (interactive) { #' if (!file.exists("fadul1-1.x3p")) { #' url <- "https://tsapps.nist.gov/NRBTD/Studies/CartridgeMeasurement/DownloadMeasurement" #' file <- "2d9cc51f-6f66-40a0-973a-a9292dbee36d" #' download.file(file.path(url, file), destfile="fadul1-1.x3p") #' } #' x3p <- x3p_read("fadul1-1.x3p") #' x3p_image(x3p, size=c(500,500), zoom=.8) #' x3p <- x3p_fuzzyselect(x3p, update=TRUE, col="#FF0000") #' #' logo <- x3p_read(system.file("csafe-logo.x3p", package="x3ptools")) #' x3p_image(logo, size=c(500,500), zoom = 1) #' x3p_fuzzyselect(logo, update=TRUE, col="#00FF00") #' }} x3p_fuzzyselect <- function(x3p, col="#FF0000", mad=5, type="plane", update=TRUE) { ids <- rgl::ids3d() if (nrow(ids) == 0) { size <- dim(x3p$surface.matrix) size[2] <- round(500/size[1]*size[2]) size[1] <- 500 x3p_image(x3p, size = size, zoom=0.8) } rgl::rgl.bringtotop() mask <- NULL stop <- FALSE cat("select rectangular area or click to stop\n") while(!stop) { tab1 <- table(as.vector(x3p$mask)) x3p <- x3p_select(x3p, col=col) tab2 <- table(as.vector(x3p$mask)) stop <- identical(tab1, tab2) if (stop) { cat("exiting selection.") return(x3p) } x3p_df <- x3p_to_df(x3p) # x3p_df %>% count(mask) if (type== "plane") { filtered_region <- dplyr::filter(x3p_df, mask == col) m1 <- MASS::rlm(value ~ x + y, data = filtered_region) cat("... adding similar cases \n") x3p_df$p1 <- predict(m1, newdata = x3p_df) x3p_df$r1 <- abs(x3p_df$value - x3p_df$p1) #x3p_df <- x3p_df %>% filter(r1 < 1*max(abs(m1$residuals))) x3p_df$mask[which(x3p_df$r1 < mad*max(.Machine$double.eps, mad(m1$residuals)))] = col } if (type == "distance") { # idea: color in all pixels } # convert back to x3p x3p <- df_to_x3p(x3p_df) if (update) { rgl::pop3d() # browser() surface <- x3p$surface.matrix z <- 5 * surface yidx <- ncol(z):1 y <- x3p$header.info$incrementY * yidx x <- x3p$header.info$incrementX * (1:nrow(x3p$surface.matrix)) rgl::surface3d(x, y, z, col = x3p_df$mask, back = "fill") } cat("select a rectangular area on the active rgl device or click on white space to stop ...\n") } cat("exiting selection.") x3p } #' Select a circle area on the surface of an x3p file using rgl #' #' In the active rgl window select a circle on the scan's surface by clicking on three points along the circumference. #' Make sure that x3p file and the rgl window match. If no rgl window is active, an rgl window opens with the scan. #' @param x3p x3p file #' @param col character value of the selection color #' @param update boolean value, whether the rgl window should be updated to show the selected circle #' @return x3p file with selected circle in mask #' @export #' @importFrom pracma circlefit #' @examples #' \dontrun{ #' if (interactive) { #' if (!file.exists("fadul1-1.x3p")) { #' url <- "https://tsapps.nist.gov/NRBTD/Studies/CartridgeMeasurement/DownloadMeasurement" #' file <- "2d9cc51f-6f66-40a0-973a-a9292dbee36d" #' download.file(file.path(url, file), destfile="fadul1-1.x3p") #' } #' x3p <- x3p_read("fadul1-1.x3p") #' x3p_image(x3p, size=c(500,500), zoom=.8) #' x3p <- x3p_circle_select(x3p, update=TRUE, col="#FF0000") #' #' logo <- x3p_read(system.file("csafe-logo.x3p", package="x3ptools")) #' x3p_image(logo, size=c(500,500), zoom = 1) #' x3p_circle_select(logo, update=TRUE, col="#00FF00") #' }} x3p_circle_select <- function(x3p, col = "#FF0000", update=TRUE) { cat("Select 3 points on the circumference of the circle you want to mark.\n") stopifnot("x3p" %in% class(x3p)) ids <- rgl::ids3d() if (nrow(ids) == 0) { size <- dim(x3p$surface.matrix) size[2] <- round(500/size[1]*size[2]) size[1] <- 500 x3p %>% x3p_image(size = size, zoom=0.8) } rgl::rgl.bringtotop() multiply <- 5 surface <- x3p$surface.matrix z <- multiply * surface yidx <- ncol(z):1 y <- x3p$header.info$incrementY * yidx x <- x3p$header.info$incrementX * (1:nrow(x3p$surface.matrix)) xidx <- rep(x, length(y)) yidx <- rep(y, each=length(x)) selected <- identify3d(xidx, yidx ,z, n=3, buttons=c("left", "middle")) res <- pracma::circlefit(xidx[selected], yidx[selected]) # first two values are circle center in x and y, # third value is radius names(res) <- c("midx", "midy", "radius") # browser() if (is.null(x3p$mask)) x3p <- x3p %>% x3p_add_mask() # x3p_df <- x3p_to_df(x3p) incircle <- (x3p_df$x-res["midx"])^2 + (x3p_df$y-res["midy"])^2 < res["radius"]^2 # x3p_df$mask[incircle] <- col # x3p <- x3p_df %>% df_to_x3p() x3p$mask[matrix(incircle, nrow = dim(x3p$mask)[1], byrow=TRUE)] <- col # browser() if (update) { rgl::rgl.bringtotop() clear3d() # remove the active scene surface3d(x, y, z, col = as.vector(x3p$mask), back = "fill") # x3p %>% image_x3p(update=TRUE) } x3p }
/scratch/gouwar.j/cran-all/cranData/x3ptools/R/x3p_select.R
#' Shade the mask of an x3p object to reflect its surface profile #' #' Apply color shading to the mask of a 3d topographic surface. #' @param x3p object containing a 3d topographic surface #' @param colors vector of colors #' @param freqs vector of values corresponding to color frequency (turned into quantiles of the differenced values) #' @return x3p object with color-shaded mask #' @export #' @examples #' \dontrun{ #' data(wire) #' x3p <- wire #' x3p_image(x3p, size = c(400, 400), zoom=0.8) #' x3p_with <- x3p %>% x3p_shade_mask() #' x3p_image(x3p_with, size = c(400, 400), zoom=0.8) #' #' data(lea) #' lea %>% x3p_shade_mask() %>% x3p_image() #' lea %>% x3p_shade_mask(freqs = c(0, 0.05, 0.1, 0.3,0.7, 0.9, 0.95, 1)) %>% x3p_image() #' } x3p_shade_mask <- function(x3p, colors = rev(c("#b12819", "#d7301f","#e16457","#ffffff","#5186a2","#175d82", "#134D6B")), freqs = c(0, 0.05, 0.25, 0.45, 0.55, 0.75, 0.95, 1)) { stopifnot("x3p" %in% class(x3p)) stopifnot(length(freqs) >= 3) # we need at least min, max and one other value. stopifnot(length(colors) == length(freqs) -1) freqs <- sort(freqs) # just to prevent any strange things rescaled <- scales::rescale(x3p$surface.matrix) qus = quantile(rescaled, freqs, na.rm=TRUE) # hexes <- scales::gradient_n_pal(colors, qus)(rescaled) hexes <- cut(rescaled, breaks=qus, labels=colors) dims <- dim(x3p$surface.matrix) stripes <- matrix(hexes, byrow = FALSE, nrow = dims[1]) x3p <- x3p %>% x3p_add_mask(mask = as.raster(t(stripes))) #x3p_image(x3p_diff, size = dim(x3p_diff$surface.matrix)/5, zoom=0.8) x3p }
/scratch/gouwar.j/cran-all/cranData/x3ptools/R/x3p_shade_mask.R
#' Transpose an x3p object #' #' Transpose the surface matrix of an x3p object. Also adjust meta information. #' @param x3p x3p object #' @export #' @examples #' logo <- x3p_read(system.file("csafe-logo.x3p", package="x3ptools")) #' dim(logo$surface.matrix) #' \dontrun{ #' x3p_image(logo) #' } #' # transpose the image #' logotp <- x3p_transpose(logo) #' dim(logotp$surface.matrix) #' \dontrun{ #' x3p_image(logotp) #' } x3p_transpose <- function(x3p) { stopifnot("x3p" %in% class(x3p)) x3p$surface.matrix <- t(x3p$surface.matrix) size <- x3p$header.info$sizeX x3p$header.info$sizeX <- x3p$header.info$sizeY x3p$header.info$sizeY <- size inc <- x3p$header.info$incrementX x3p$header.info$incrementX <- x3p$header.info$incrementY x3p$header.info$incrementY <- inc x3p$matrix.info$MatrixDimension$SizeX[[1]] <- x3p$header.info$sizeX x3p$matrix.info$MatrixDimension$SizeY[[1]] <- x3p$header.info$sizeY if (!is.null(x3p$mask)) x3p$mask <- as.raster(t(as.matrix(x3p$mask))) x3p } #' @rdname x3p_transpose #' @export transpose_x3p <- function(x3p) { x3p_transpose(x3p) }
/scratch/gouwar.j/cran-all/cranData/x3ptools/R/x3p_transpose.R
#' Trim rows and columns with missing values only from an x3p #' #' Trims rows and columns from the edges of a surface matrix that contain missing values only. #' @param x3p x3p object #' @param ratio ratio between zero and one, indicating the percent of values that need to be missing in each row and column, for the row or column to be removed #' @return x3p object of the same or smaller dimension where missing values are removed from the boundaries #' @export #' @examples #' logo <- x3p_read(system.file("csafe-logo.x3p", package="x3ptools")) #' logo$surface.matrix[logo$surface.matrix == median(logo$surface.matrix)] <- NA #' x3p_trim_na(logo) # reduced to dimension: 668 by 268 x3p_trim_na <- function(x3p, ratio = 1) { xmin <- 1 ymin <- 1 xmax <- dim(x3p$surface.matrix)[1] ymax <- dim(x3p$surface.matrix)[2] stopifnot(ratio > 0, ratio <= 1) rows <- apply(x3p$surface.matrix, MARGIN=1, FUN=function(x) sum(is.na(x))) idx <- which(rows == dim(x3p$surface.matrix)[2] * ratio) if (length(idx) > 0) { if (idx[1] == 1) xmin <- max(which(idx==1:length(idx))) +1 if (idx[length(idx)] == dim(x3p$surface.matrix)[1]) xmax <- idx[min(which(idx==(dim(x3p$surface.matrix)[1] - rev(seq_along(idx))+1)))]-1 } cols <- apply(x3p$surface.matrix, MARGIN=2, FUN=function(x) sum(is.na(x))) idx <- which(cols == dim(x3p$surface.matrix)[1] * ratio) if (length(idx) > 0) { if (idx[1] == 1) ymin <- max(which(idx==1:length(idx))) +1 if (idx[length(idx)] == dim(x3p$surface.matrix)[2]) ymax <- idx[min(which(idx==(dim(x3p$surface.matrix)[2] - rev(seq_along(idx))+1)))]-1 } # browser() x3p %>% x3p_crop(x = xmin, y = dim(x3p$surface.matrix)[2]-ymax+1, width = xmax-xmin+1, height = ymax-ymin+1) }
/scratch/gouwar.j/cran-all/cranData/x3ptools/R/x3p_trim_na.R
/scratch/gouwar.j/cran-all/cranData/x3ptools/inst/extdata/stl-file.R
library(rgl) x3p <- read_x3p("inst/pyramid.x3p") z <- x3p$surface.matrix open3d() surface3d(x=(1:5), y = (1:5), z = x3p$surface.matrix) writeSTL("inst/pyramid.stl")
/scratch/gouwar.j/cran-all/cranData/x3ptools/inst/pyramid-stl-x3p.R
Kfoldcv_xllim = function(yapp,tapp,func,verb=1,Kfold=10,B=10,...){ ## func must be a function with func(cov.train,resp.train,cov.test,resp.test,...) and returns a prediction value n = nrow(yapp) l = ncol(tapp) pred = list() for (b in 1:B){ if (verb) print(paste0("Repetition ",b,"/",B)) pred[[b]] = matrix(0,nrow=n,ncol=l) fold <- createFolds_xllim(1:n,k=Kfold) for (i in 1:length(fold)){ if (verb) print(paste0("Fold ",i,"/",length(fold))) yapp.train = yapp[-fold[[i]],] yapp.test = yapp[fold[[i]],] tapp.train = tapp[-fold[[i]],] tapp.test = tapp[fold[[i]],] pred[[b]][fold[[i]],] = func(tapp.train,yapp.train,tapp.test,yapp.test,...) } } return(pred) }
/scratch/gouwar.j/cran-all/cranData/xLLiM/R/Kfoldcv_xllim.R
Maximization_hybrid = function(tapp,yapp,r,u,phi,muw,Sw,mahalt,mahaly,cstr,verb){ if(verb>=1) print(' M'); if(verb>=3) print(' k='); K = ncol(r); D = nrow(yapp);N=ncol(yapp) Lt = nrow(tapp) Lw = ifelse(is.null(muw),0,nrow(muw)) L=Lt+Lw; th = list() ph = list() th$c=matrix(NaN,nrow=L,ncol=K) th$Gamma=array(0,dim=c(L,L,K)); if(Lw>0) {th$c[(Lt+1):L,]=cstr$cw; #% LwxK th$Gamma[(Lt+1):L,(Lt+1):L,]=cstr$Gammaw;} #% LwxLwxK} ph$pi=rep(NaN,K); th$A=array(NaN,dim=c(D,L,K)); th$b=matrix(NaN,nrow=D,ncol=K); th$Sigma= array(NaN,dim=c(D,D,K)); rk_bar=rep(0,K); for (k in 1:K){ if(verb>=3) print(k); # % Posteriors' sums rk=r[,k]; #% 1xN rk_bar[k]=sum(rk); #% 1x1 uk=u[,k]; #% 1xN rk_tilde = rk * uk; rk_bar_tilde = sum(rk_tilde); if(Lt>0) { if(verb>=3) {print('c');} #% Compute optimal mean ctk if(is.null(cstr$ct)) {th$c[1:Lt,k]=rowSums(sweep(tapp,2, rk_tilde,"*"))/rk_bar_tilde;}# % Ltx1 else {th$c[1:Lt,k]=cstr$ct[,k];} #% Compute optimal covariance matrix Gammatk if(verb>=3) {print('Gt');} diffGamma= sweep(sweep(tapp,1,th$c[1:Lt,k],"-"),2,sqrt(rk_tilde),"*"); #% LtxN if( is.null(cstr$Gammat) || (length(cstr$Gammat)==1 & cstr$Gammat=='*')) # | ou ||? # %%%% Full Gammat {th$Gamma[1:Lt,1:Lt,k]=tcrossprod(diffGamma)/rk_bar[k]; #% DxD }#th$Gamma[1:Lt,1:Lt,k]=th$Gamma[1:Lt,1:Lt,k]; else { if( !is.character(cstr$Gammat)) #%%%% Fixed Gammat {th$Gamma[1:Lt,1:Lt,k]=cstr$Gammat[,,k]; } else { if(cstr$Gammat[1]=='d' | cstr$Gammat[1]=='i') #% Diagonal terms {gamma2=rowSums(diffGamma^2)/rk_bar[k]; #%Ltx1 if(cstr$Gammat[1]=='d') #%%% Diagonal Gamma {th$Gamma[1:Lt,1:Lt,k]=diag(gamma2);} #% LtxLt else #%%% Isotropic Gamma {th$Gamma[1:Lt,1:Lt,k]=mean(gamma2)*diag(Lt);} #% LtxLt } else {if(cstr$Gammat[1]=='v') #%%%% Full Gamma {th$Gamma[1:Lt,1:Lt,k]=tcrossprod(diffGamma)/rk_bar[k];} #% LtxLt else {# cstr$Gammat, stop(' ERROR: invalid constraint on Gamma.'); } } } } } #% Compute optimal weight pik ph$pi[k]=rk_bar[k]/N; #% 1x1 if(Lw>0) {x=rbind(tapp,muw[,,k]); #% LxN Skx=rbind(cbind(matrix(0,Lt,Lt),matrix(0,Lt,Lw)),cbind(matrix(0,Lw,Lt),Sw[,,k])); }#% LxL else {x=tapp; #% LtxN Skx=matrix(0,Lt,Lt);} #%LtxLt if(verb>=3) {print('A');} if(is.null(cstr$b)) {# % Compute weighted means of y and x yk_bar=rowSums(sweep(yapp,2,rk_tilde,"*"))/rk_bar_tilde; #% Dx1 if(L>0) xk_bar= rowSums(sweep(x,2, rk_tilde,"*"))/rk_bar_tilde #% Lx1 else {xk_bar=NULL;} } else {yk_bar=cstr$b[,k]; xk_bar=rep(0,L); th$b[,k]=cstr$b[,k]; } #% Compute weighted, mean centered y and x weights=sqrt(rk_tilde)/sqrt(rk_bar[k]); #% 1xN y_stark=sweep(yapp,1,yk_bar,"-"); #% DxN #col or row? y_stark= sweep(y_stark,2,weights,"*"); #% DxN #col or row? if(L>0) { x_stark=sweep(x,1,xk_bar,"-"); #% LxN x_stark= sweep(x_stark,2,weights,"*"); #% LxN } else {x_stark=NULL;} # % Robustly compute optimal transformation matrix Ak # warning off MATLAB:nearlySingularMatrix; if(!all(Skx==0)) {if(N>=L & det(Skx+tcrossprod(x_stark))>10^(-8)) {th$A[,,k]=tcrossprod(y_stark,x_stark)%*%solve(Skx+tcrossprod(x_stark));} #% DxL else {th$A[,,k]=tcrossprod(y_stark,x_stark)%*%ginv(Skx+tcrossprod(x_stark));} #%DxL } else {if(!all(x_stark==0)) {if(N>=L & det(tcrossprod(x_stark))>10^(-8)) {th$A[,,k]=tcrossprod(y_stark,x_stark)%*% solve(tcrossprod(x_stark));} #% DxL else {if(N<L && det(crossprod(x_stark))>10^(-8)) {th$A[,,k]=y_stark %*% solve(crossprod(x_stark)) %*% t(x_stark);} #% DxL else {if(verb>=3) print('p') th$A[,,k]=y_stark %*% ginv(x_stark);} #% DxL }} else {#% Correspond to null variance in cluster k or L=0: if(verb>=1 & L>0) print('null var\n'); th$A[,,k]=0; # % DxL } } if(verb>=3)print('b'); # % Intermediate variable wk=y-Ak*x if(L>0) {wk=yapp-th$A[,,k]%*%x;} #% DxN #attention au reshape? else {wk=yapp;} #% Compute optimal transformation vector bk if(is.null(cstr$b)) th$b[,k]=rowSums(sweep(wk,2,rk_tilde,"*"))/rk_bar_tilde; #% Dx1 #col ou row? if(verb>=3) print('S'); #% Compute optimal covariance matrix Sigmak if(Lw>0) { Awk=th$A[,(Lt+1):L,k]; Swk=Sw[,,k]; ASAwk=Awk%*%tcrossprod(Swk,Awk);} else ASAwk=0; diffSigma=sweep(sweep(wk,1,th$b[,k],"-"),2,sqrt(rk_tilde),"*"); #%DxN if (cstr$Sigma %in% c("","*")) {#%%%% Full Sigma th$Sigma[,,k]=tcrossprod(diffSigma)/rk_bar[k]; #% DxD th$Sigma[,,k]=th$Sigma[,,k]+ASAwk; } else { if(!is.character(cstr$Sigma)) #%%%% Fixed Sigma {th$Sigma=cstr$Sigma;} else { if(cstr$Sigma[1]=='d' || cstr$Sigma[1]=='i') #% Diagonal terms {sigma2=rowSums(diffSigma^2)/rk_bar[k]; #%Dx1 if(cstr$Sigma[1]=='d') {#%%% Diagonal Sigma th$Sigma[,,k]=diag(sigma2,ncol=D,nrow=D); #% DxD if (is.null(dim(ASAwk))) {th$Sigma[,,k]=th$Sigma[,,k] + diag(ASAwk,ncol=D,nrow=D)} else {th$Sigma[,,k]=th$Sigma[,,k]+diag(diag(ASAwk));} } else {#%%% Isotropic Sigma th$Sigma[,,k]=mean(sigma2)*diag(D); #% DxD if (is.null(dim(ASAwk))) {th$Sigma[,,k]=th$Sigma[,,k]+sum(diag(ASAwk,ncol=D,nrow=D))/D*diag(D);} else {th$Sigma[,,k]=th$Sigma[,,k]+sum(diag(ASAwk))/D*diag(D);} } } else { cstr$Sigma ; stop(' ERROR: invalid constraint on Sigma.');} } } #% Avoid numerical problems on covariances: if(verb>=3) print('n'); if(! is.finite(sum(th$Gamma[1:Lt,1:Lt,k]))) {th$Gamma[1:Lt,1:Lt,k]=0;} th$Gamma[1:Lt,1:Lt,k]=th$Gamma[1:Lt,1:Lt,k]+1e-8*diag(Lt); if(! is.finite(sum(th$Sigma[,,k]))) {th$Sigma[,,k]=0;} th$Sigma[,,k]=th$Sigma[,,k]+1e-8*diag(D); if(verb>=3) print(','); # % Compute phi.alpha % if(!is.null(mahalt) && !is.null(mahaly)) { ph$alpha[k] = inv_digamma((digamma(phi$alpha[k] + (D+Lt)/2) - (1/rk_bar[k]) * sum( rk * log(1 + (1/2) * (mahaly[,k] + mahalt[,k]))))); ## potentielle erreur?passage difficile if(verb>=3) print(paste("K",k,"-> alpha=",ph$alpha[k]));} else {ph$alpha = phi$alpha;} } if(verb>=3) print('end'); if (cstr$Sigma=="*") {#%%% Equality constraint on Sigma th$Sigma=sweep(th$Sigma ,3,rk_bar,"*"); th$Sigma=array(apply(th$Sigma,c(1,2),mean),dim=c(D,D,K)) } if( !is.null(cstr$Gammat) && cstr$Gammat=='v') {#%%% Equal volume constraint on Gamma detG=rep(0,K); for (k in 1:K){ if (D==1) {detG[k]=th$Gamma[1:Lt,1:Lt,k]} else {detG[k]=det(th$Gamma[1:Lt,1:Lt,k]);} #% 1x1 th$Gamma[1:Lt,1:Lt,k] = th$Gamma[1:Lt,1:Lt,k] / detG[k] } th$Gamma[1:Lt,1:Lt,]=sum(detG^(1/Lt)*ph$pi)*th$Gamma[1:Lt,1:Lt,]; } if(is.character(cstr$Gammat) && !is.null(cstr$Gammat) && cstr$Gammat[length(cstr$Gammat)]=='*') {#%%% Equality constraint on Gammat for (k in 1:K){ th$Gamma[1:Lt,1:Lt,k]=th$Gamma[1:Lt,1:Lt,k]%*%diag(rk_bar); th$Gamma[1:Lt,1:Lt,k]=matrix(1,Lt,Lt) * sum(th$Gamma[1:Lt,1:Lt,k])/N; } } if( ! is.character(cstr$pi) || is.null(cstr$pi)) {if(! is.null(cstr$pi)) {ph$pi=cstr$pi;}} else { if (!is.null(cstr$pi) && cstr$pi[1]=='*') {ph$pi=1/K*rep(1,K);} else {stop(' ERROR: invalid constraint on pi.');} } return(list(ph=ph,th=th)) }
/scratch/gouwar.j/cran-all/cranData/xLLiM/R/Maximization_hybrid.R
bllim = function(tapp,yapp,in_K,in_r=NULL,ninit=20,maxiter=100,verb=0,in_theta=NULL,plot=TRUE){ # %%%%%%%% General EM Algorithm for Block diagonal gaussian Locally Linear Mapping %%%%%%%%% # %%% Author: ED, MG, EP (April 2017) - [email protected] %%% # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% # %%%% Input %%%% # %- t (LtxN) % Training latent variables # %- y (DxN) % Training observed variables # %- in_K (int) % Initial number of components # % <Optional> # %- Lw (int) % Dimensionality of hidden components (default 0) # %- maxiter (int) % Maximum number of iterations (default 100) # %- in_theta (struct) % Initial parameters (default NULL) # % | same structure as output theta # %- in_r (NxK) % Initial assignments (default NULL) # %- cstr (struct) % Constraints on parameters theta (default NULL,'') # % - cstr$ct % fixed value (LtxK) or ''=uncons. # % - cstr$cw % fixed value (LwxK) or ''=fixed to 0 # % - cstr$Gammat % fixed value (LtxLtxK) or ''=uncons. # % | or {'','d','i'}{'','*','v'} [1] # % - cstr$Gammaw % fixed value (LwxLwxK) or ''=fixed to I # % - cstr$pi % fixed value (1xK) or ''=uncons. or '*'=equal # % - cstr$A % fixed value (DxL) or ''=uncons. # % - cstr$b % fixed value (DxK) or ''=uncons. # % - cstr$Sigma % fixed value (DxDxK) or ''=uncons. # % | or {'','d','i'}{'','*'} [1] # %- verb {0,1,2} % Verbosity (default 1) # %%%% Output %%%% # %- theta (struct) % Estimated parameters (L=Lt+Lw) # % - theta.c (LxK) % Gaussian means of X # % - theta.Gamma (LxLxK) % Gaussian covariances of X # % - theta.pi (1xK) % Gaussian weights of X # % - theta.A (DxLxK) % Affine transformation matrices # % - theta.b (DxK) % Affine transformation vectors # % - theta.Sigma (DxDxK) % Error covariances # %- r (NxK) % Posterior probabilities p(z_n=k|x_n,y_n;theta) # %%% [1] 'd'=diag., 'i'=iso., '*'=equal for all k, 'v'=equal det. for all k # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if (ncol(tapp) != ncol(yapp)) {stop("Observations must be in columns and variables in rows")} # % ==========================EM initialization============================== L <- nrow(tapp) D <- nrow(yapp) ; N = ncol(yapp); if (is.null(in_r)){ ## Step 1 A) if (verb) {print("Initialization ... ")} ## we perform 10 initialisations of the model ## with diagonal Sigma and keep the best initialisation to r = emgm(as.matrix(rbind(tapp, yapp)), init=in_K, 1000, verb=0) LLinit = sapply(1:ninit,function(it){ while (min(table(r$label)) < 2){ r = emgm(as.matrix(rbind(tapp, yapp)), init=in_K, 1000, verb=0) } modInit = gllim(as.matrix(tapp),as.matrix(yapp),in_K=in_K,in_r=r,cstr=list(Sigma="d"),verb=0,maxiter = 5,in_theta=in_theta) return(list(r=r,LLinit=modInit$LLf)) }) ## we select the model maximizing the logliklihood among the 10 models ## this model will be used in step 2 r = LLinit[1,][[which.max(unlist(LLinit[2,]))]] } else {r=in_r} ## Step 1 B) ## using the best initialisation selected in step 1 "r" ## we rerun the model estimation "modInit" ## "modInit" is a glimm model with diagonale matrices cstr=list(Sigma="d") modInit = gllim(as.matrix(tapp),as.matrix(yapp),in_K=in_K,in_r=r,cstr=list(Sigma="d"),verb=0,maxiter = maxiter,in_theta=in_theta) ## save modInit for further FinalModInit <- modInit ## STEP 2 INITIALIZATION Sigma_k ## construct the collection of block diagonal matrices for Sigma_k ## to get a first estimation of Sigma_k for k in 1,...,K ## based on the classification of observations obtained (modInit) ## STEP 2 A) we extract the classification of individuals (drosophiles) based on the modInit affecIndModInit = sapply(1:N,function(i)which.max(modInit$r[i,])) ## STEP 2 B) we compute full sigma_k (the covariance associated to the noise) ## for each group of individuals listKfullSigma = lapply(1:in_K,function(dum){ tmp = cov(t(yapp[,affecIndModInit == dum, drop = FALSE])) - matrix(modInit$A[,,dum], ncol = L)%*%modInit$Gamma[,,dum]%*%t(matrix(modInit$A[,,dum],ncol = L)) return(tmp ) }) ## List of K matrices with full matrix ## optional plot of estimated matrix Sigma ## lapply(listKfullSigma,image.plot) ## lapply(listKfullSigma,hist) if (verb) {print("Building model collection ... ")} ## STEP 2 C) we threshold each Sigma_k from Sigma_k full to diagonal ## partsSparseSig is a list of size K of matrix (N_struc x D) that contain in each row a partition ## of variables obtained by threshold of the matrix Sigma_k partsSparseSig = lapply(listKfullSigma,function(x) do.call(rbind,thresholdAbsSPath2(cov2cor(x))$partitionList)) ## We clean each matrix to suprress extra complex models partsSparseSig = lapply(partsSparseSig,function(x) as.matrix(x[(nrow(x)-min(sapply(partsSparseSig,nrow))+1):nrow(x),])) ## STEP 3 : Compute Glimm-shock model ## it initizalizes the count of the number of model it = 0 ## LL will contain the log-likelihood for each partition of Sigma_k ## (ED) for each model or for each partition of Sigma_k ? Pour moi le dernier veut dire qu'on a un vecteur de taille K LL = rep(0,nrow(partsSparseSig[[1]])) ## nbpar will contain the total number of parameters for each partition of Sigma_k nbpar = rep(0,nrow(partsSparseSig[[1]])) ## save the number of obs in each cluster, used for cleaning after effectifs = matrix(0,nrow=in_K,ncol=nrow(partsSparseSig[[1]])) ## save the size of the largest clique for each partition Pg = matrix(0,nrow=in_K,ncol=nrow(partsSparseSig[[1]])) ## Collect the corresponding estimated glimm model with shock modelSparSig <- list() ## Collect the corresponding partition used to estimate glimm model with shock strucSig <- list() if (verb) {print("Running BLLiM ... ")} ## this loop estimate a gllim model with each possible partition of (Sigma_k), from the more simple (each matrix is diagonal) to the more complex (each matrix is full) ## indPart index the partition of variables describing the structure of sigma if (verb) {pb <- progress_bar$new(total = nrow(partsSparseSig[[1]]))} for (indPart in 1:nrow(partsSparseSig[[1]])){ # if (verb) print(paste0("Model ",indPart)) if (verb) {pb$tick()} ## strucSig is a list of size K (for each groups of individuals) ## containing the partition of variables associated to cluster k ## given by thresholding of sigma_k strucSig[[indPart]] = lapply(1:in_K,function(dum) partsSparseSig[[dum]][indPart,]) ## estimation of parameters taking into account ## the variable to predict as.matrix(tapp) ## the covariables as.matrix(yapp) ## K number of clusters of individuals ## r estimation of parameters from gaussian mixture model for initialization ## model describes the partition of variables for each clusters modelSparSig[[indPart]] = gllim(as.matrix(tapp),as.matrix(yapp),in_K=in_K,in_r=list(R=modInit$r),Lw=0,maxiter=maxiter,verb=0,cstr=list(Sigma="bSHOCK"),model = strucSig[[indPart]]) ## size of blocks pg = lapply(strucSig[[indPart]],table) ## number of parameters in each block dimSigma = do.call(sum,lapply(pg,function(x)x*(x+1)/2)) ## K = dim(modShock$Sigma)[3] ## par(mar = rep(2, 4),mfrow=c(1,5)) ## for (k in 1:K)image.plot(modShock$Sigma[,,k]) LL[indPart] = modelSparSig[[indPart]]$LLf nbpar[indPart] = (in_K-1) + in_K*(D*L + D + L + L*(L+1)/2) + dimSigma effectifs[,indPart] = modelSparSig[[indPart]]$pi*N ## size of the largest clique in each class Pg[,indPart] = sapply(pg,max) } ## put the interesting objet in the big lists BigModelSparSig <- modelSparSig ## modShock ## partsSparseSig is more interesting than modShock?? # Used for cleaning partsSparseSig # Used after selection by capushe to run the selected model BigStrucSig <- strucSig ### BigModShock[[k]] <- modShock ### devenu inutile non? BigLL<- LL # Used for capushe after BigNbpar <- nbpar # Used for capushe after BigEffectifs <- effectifs # Used for cleaning SparseSigColl BigPg <- Pg # Used for cleaning SparseSigColl ## STEP 4 : select the right level of sparsity for sigma_k ## i.e. supressing the structure of sigma_k matrix that would ## be unrealistic to estimate, given the size of the cluster ## if the size of the cluster k (number of individuals) ## is too small to estimate sigma_k, we suppress the model supressModel = list() for(kk in 1:in_K){ pg = Pg[kk,] supressModel[[kk]] <- which(pg > effectifs[kk,]) } ## supressModel contains all models to supress supressModel <- unique(unlist(supressModel)) ## once we have the vector supressModel, we actually clean the model collection "modelSparSig" ## the collection of partitions "strucSig" to keep only the right model if(length(supressModel)>1){ modelSparSigClean <- modelSparSig[-supressModel] strucSigClean <- strucSig[-supressModel] nbparClean <- nbpar[-supressModel] LLClean <- LL[-supressModel] } else { modelSparSigClean <- modelSparSig strucSigClean <- strucSig nbparClean <- nbpar LLClean <- LL } BigModelSparSigClean <- modelSparSigClean BigStrucSigClean <- strucSigClean BigLLClean <- LLClean # Used for capushe after BigNbparClean <- nbparClean # Used for capushe after ## STEP 5 : model selection based on the slope heuristic ## We create TabForCapClean, an input for capushe ## to indice the model, we simply use the model dimension ## to avoid mistake when selected the right model TabForCapClean <- cbind(nbparClean,nbparClean,nbparClean,-LLClean) ## select the id of model if (length(nbparClean)>10) { resCap <- capushe(TabForCapClean,n=N,psi.rlm = "lm") id_model_final = which(nbparClean==as.integer(resCap@DDSE@model)) FinalStrucSig = strucSigClean[id_model_final] FinalModelSparSig = modelSparSigClean[id_model_final] FinalLL = LLClean[id_model_final] FinalNbpar = nbparClean[id_model_final] if (plot) { x <- resCap scoef=x@Djump@ModelHat$Kopt/x@Djump@ModelHat$kappa[x@Djump@ModelHat$JumpMax+1] leng=length(x@Djump@graph$model) mleng=length(x@Djump@ModelHat$model_hat) Intervalslope=scoef*x@DDSE@interval$interval Absmax=max((scoef+1)/scoef*x@Djump@ModelHat$Kopt,5/4*Intervalslope[2]) Ordmin=max(which((x@Djump@ModelHat$kappa<=Absmax)==TRUE)) plot(x=x@Djump@ModelHat$Kopt,y=x@Djump@graph$complexity[x@Djump@graph$Modopt],xlim=c(0,Absmax),ylim=c(x@Djump@graph$complexity[x@Djump@ModelHat$model_hat[Ordmin]],x@Djump@graph$complexity[x@Djump@ModelHat$model_hat[1]]),ylab="Model dimension",xlab=expression(paste("Values of the penalty constant ",kappa)),yaxt="n",pch=4,col="blue",main="",lwd=3,xaxt="n") complex=x@Djump@graph$complexity[x@Djump@ModelHat$model_hat[1:Ordmin]] for (i in 1:(mleng-1)){ lines(x=c(x@Djump@ModelHat$kappa[i],x@Djump@ModelHat$kappa[i+1]),y=c(complex[i],complex[i])) } if (x@Djump@ModelHat$kappa[i+1]<Absmax){ lines(x=c(x@Djump@ModelHat$kappa[mleng],Absmax),y=c(complex[mleng],complex[mleng])) } lines(x=c(x@Djump@ModelHat$Kopt/scoef,x@Djump@ModelHat$Kopt/scoef),y=c(complex[x@Djump@ModelHat$JumpMax],complex[x@Djump@ModelHat$JumpMax+1]),col="blue",lty=2) ordon=paste(as.character(complex),"(",as.character(x@Djump@graph$model[x@Djump@ModelHat$model_hat[1:Ordmin]]),")") par(cex.axis=0.6) complex2=complex pas=(max(complex2)-min(complex2))/39*5.6/par("din")[2] leng2=length(complex2) Coord=c() i=leng2 j=leng2-1 while (j>0){ while ((j>1)*((complex2[j]-complex2[i])<pas)){ Coord=c(Coord,-j) j=j-1 } if ((j==1)*((complex2[j]-complex2[i])<pas)){ Coord=c(Coord,-j) j=j-1 } i=j j=j-1 } if (length(Coord)>0){ complex2=complex2[Coord] ordon=ordon[Coord] } axis(2,complex2,las=2) par(cex.axis=1) axis(2,labels="Model dimension",outer=TRUE,at=(x@Djump@graph$complexity[leng]+x@Djump@graph$complexity[x@Djump@ModelHat$model_hat[Ordmin]])/2,lty=0,cex=3) axis(1,labels=expression(hat(kappa)^{dj}),at=x@Djump@ModelHat$Kopt/scoef) axis(1,labels= expression(kappa[opt]),at=x@Djump@ModelHat$Kopt) absci=seq(0,Absmax,by=x@Djump@ModelHat$Kopt/scoef/3)[c(-4)] Empty=c(which(abs(absci-x@Djump@ModelHat$Kopt)<absci[2]/4*(12.093749/par("din")[1])^2*scoef),which(abs(absci-x@Djump@ModelHat$Kopt/scoef)<absci[2]/4*(12.093749/par("din")[1])^2*scoef)) absci=absci[-Empty] axis(1,absci,signif(absci,2)) plength=length(x@DDSE@graph$model)-1 p=plength-x@DDSE@interval$point_using+2 Model=x@DDSE@ModelHat$model_hat[x@DDSE@ModelHat$point_breaking[x@DDSE@ModelHat$imax]] Couleur=c(rep("blue",(p-1)),rep("red",(plength-p+2))) plot(x=x@DDSE@graph$pen,y=-x@DDSE@graph$contrast,main="",xlab="Model dimension",ylab="log-likelihood",col=Couleur,pch=19,lwd=0.1) labelpen=x@DDSE@graph$pen labelmodel=x@DDSE@graph$model pas=(max(labelpen)-min(labelpen))/50*11.5/par("din")[1] leng=length(labelpen) Coord=c() i=1 j=2 while (j<leng){ while ((j<leng)*((labelpen[j]-labelpen[i])<pas)){ Coord=c(Coord,-j) j=j+1 } i=j j=j+1 } if (length(Coord)>0){ labelpen=labelpen[Coord] labelmodel=labelmodel[Coord] } #axis(1,labelpen,labelmodel,las=2) Cof=x@DDSE@graph$reg$coefficients abline(a=Cof[1],b=Cof[2],col="red",lwd=2) abscisse=seq(plength+1,2) } } else { bicfinal = -2*LLClean + log(N)*nbparClean if (plot) {plot(bicfinal ~ nbparClean,pch=16,col="blue",main="Plot of BIC criterion",xlab="# of parameters",ylab="BIC")} # id_model_final = which.max(LLClean) id_model_final = which.min(bicfinal) FinalStrucSig = strucSigClean[id_model_final] FinalModelSparSig = modelSparSigClean[id_model_final] FinalLL = LLClean[id_model_final] FinalNbpar = nbparClean[id_model_final] } ################################################## ## STEP 3 : perform prediction ################################################## ModFinal = FinalModelSparSig[[1]] ModFinal$nbpar = FinalNbpar return(ModFinal) }
/scratch/gouwar.j/cran-all/cranData/xLLiM/R/bllim.R
################### Dumb comparison to the mean ############# mean_cv = function(trainx,trainy,testx,testy){ pred <- colMeans(trainx) pred <- matrix(pred,ncol=ncol(trainx),nrow=nrow(testy),byrow=TRUE) return(pred) } ######################### randomForest ########################## randomForest_cv = function(trainx,trainy,testx,testy){ pred = matrix(0,ncol=ncol(trainx),nrow=nrow(testx)) for (k in 1:ncol(trainx)){ mod = randomForest(x=trainy,y=trainx[,k]) pred[,k] = predict(mod,testy) } return(pred) } ################### LASSO ############# lasso_cv <- function(trainx,trainy,testx,testy){ cv <- cv.glmnet(as.matrix(trainy),as.matrix(trainx),family="mgaussian") mod <- glmnet(as.matrix(trainy),as.matrix(trainx),family="mgaussian",lambda=cv$lambda.min) pred <- predict(mod,as.matrix(testy)) return(pred[,,1]) } ####################### spline regression ####################### mars_cv = function(trainx,trainy,testx,testy){ mod = mars(trainy,trainx) testy = data.frame(testy) pred = predict(mod,testy) return(pred) } ############################## svm ############################# svm_cv = function(trainx,trainy,testx,testy,kernel="linear",type="eps-regression"){ pred = matrix(0,ncol=ncol(trainx),nrow=nrow(testx)) for (k in 1:ncol(trainx)){ tmp = data.frame(trainy,x=trainx[,k]) mod = e1071::svm(x ~ .,data=tmp,kernel=kernel,type=type) testy = data.frame(testy) pred[,k] = predict(mod,testy) } return(pred) } ################### BLLiM ############# bllim_cv <- function(trainx,trainy,testx,testy,K,verb=0,alpha, nfolds,...){ prep_data <- preprocess_data(trainx,trainy,in_K=K,alpha = alpha, nfolds = nfolds) mod <- bllim(t(trainx), t(trainy[,prep_data$selected.variables,drop=FALSE]), in_K=K,maxiter=100, in_r=list(R=prep_data$clusters),plot=FALSE,verb=FALSE) pred <- gllim_inverse_map(t(testy[,prep_data$selected.variables,drop=FALSE]),mod)$x_exp return(t(pred)) } ####################### spls regression ####################### mixOmics_cv = function(trainx,trainy,testx,testy){ X <- trainy # omics data Y <- trainx # pheno data # set range of test values for number of variables to use from trainy dataframe list.keepX <- c(seq(20, 50, 5)) # set range of test values for number of variables to use from Y dataframe list.keepY <- c(ncol(Y)) # tune parameters tune.spls.res <- mixOmics::tune.spls(X, Y, ncomp = 2:6, test.keepX = list.keepX, test.keepY = list.keepY, nrepeat = 1, folds = 10, # use 10 folds mode = 'regression', measure = 'cor') optimal.keepX <- tune.spls.res$choice.keepX # extract optimal number of variables for X dataframe optimal.keepY <- tune.spls.res$choice.keepY # extract optimal number of variables for Y datafram optimal.ncomp <- length(optimal.keepX) # extract optimal number of components # use all tuned values from above final.spls.res <- spls(X, Y, ncomp = optimal.ncomp, keepX = optimal.keepX, keepY = optimal.keepY, mode = "regression") # explanitory approach being used return(predict(final.spls.res , newdata=testy)$predict[,,optimal.ncomp]) } ####################### gllim ####################### gllim_cv <- function(trainx,trainy,testx,testy,K,Lw=0,verb=0,alpha, nfolds,...){ Lt = ncol(trainx) prep_data <- preprocess_data(trainx,trainy,in_K=K,alpha = alpha, nfolds = nfolds) mod <- gllim(t(trainx), t(trainy[,prep_data$selected.variables,drop=FALSE]), in_K=K,Lw=Lw,cstr=list(Sigma="d"), in_r=list(R=prep_data$clusters),verb=FALSE) pred <- gllim_inverse_map(t(testy[,prep_data$selected.variables,drop=FALSE]),mod)$x_exp return(t(pred[1:Lt,])) }
/scratch/gouwar.j/cran-all/cranData/xLLiM/R/compared_methods.R
covParBloc = function(yCen, model){ covY = cov(yCen) Dim = dim(covY)[1] covEmpB = matrix(0,nrow = Dim,ncol = Dim) for (b in 1:max(model)){ ind = which(model == b) covEmpB[ind,ind] = covY[ind,ind] } return(covEst = covEmpB ) }
/scratch/gouwar.j/cran-all/cranData/xLLiM/R/covParBloc.R
createFolds_xllim <- function (y, k = 10, list = TRUE, returnTrain = FALSE) {# adapted from the createFolds function of caret package if (class(y)[1] == "Surv") y <- y[, "time"] if (is.numeric(y)) { cuts <- floor(length(y)/k) if (cuts < 2) cuts <- 2 if (cuts > 5) cuts <- 5 breaks <- unique(quantile(y, probs = seq(0, 1, length = cuts))) y <- cut(y, breaks, include.lowest = TRUE) } if (k < length(y)) { y <- factor(as.character(y)) numInClass <- table(y) foldVector <- vector(mode = "integer", length(y)) for (i in 1:length(numInClass)) { min_reps <- numInClass[i]%/%k if (min_reps > 0) { spares <- numInClass[i]%%k seqVector <- rep(1:k, min_reps) if (spares > 0) seqVector <- c(seqVector, sample(1:k, spares)) foldVector[which(y == names(numInClass)[i])] <- sample(seqVector) } else { foldVector[which(y == names(numInClass)[i])] <- sample(1:k,size = numInClass[i]) } } } else foldVector <- seq(along = y) if (list) { out <- split(seq(along = y), foldVector) names(out) <- paste("Fold", gsub(" ", "0", format(seq(along = out))),sep = "") if (returnTrain) out <- lapply(out, function(data, y) y[-data], y = seq(along = y)) } else out <- foldVector return(out) }
/scratch/gouwar.j/cran-all/cranData/xLLiM/R/createFolds_xllim.R
emgm = function(X, init, maxiter=100,verb=0){ # % Perform EM algorithm for fitting the Gaussian mixture model. # % X: d x n data matrix # % init: k (1 x 1) or posteriors (n x k) or center (d x k) # % Written in Matlab by Michael Chen ([email protected]) # % Converted to R by Emeline Perthame ([email protected]) # %% initialization initialization = function(X, init){ d = nrow(X) ; n = ncol(X); if (is.list(init)) #% initialize with a model {R = expectation(X,init);} else { if (length(init) == 1) #% random initialization {k = init; idx = sample(1:n,k,replace=FALSE); m = X[,idx,drop=FALSE]; label = max.col(t(sweep(t(m)%*%X,1,colSums(m^2)/2,"-"))); u = sort(unique(label)); count=0; while (k != length(u) && count<20){ count=count+1; k=length(u); idx = sample(1:n,k,replace=FALSE); ### m = X[,idx]; m = as.matrix(m); label = max.col(t(sweep(t(m)%*%X,1,colSums(m^2)/2,"-"))); u = sort(unique(label)); } k=length(u); R = as.matrix(sparseMatrix(i=1:n,j=label,x=rep(1,n),dims=c(n,k))) } else { if (nrow(init) == n) {R = init;} else { if (nrow(init) == d) {k = ncol(init); m = init; m = as.matrix(m); label = max.col(t(sweep(t(m)%*%X,2,colSums(m^2)/2,"-"))); R = as.matrix(sparseMatrix(i=1:n,j=label,x=rep(1,n),dims=c(n,k))) ; } else {stop('ERROR: init is not valid.');} } } } return(R) } expectation = function(X, model){ mu = model$mu; Sigma = model$Sigma; w = model$weight; n = ncol(X); k = ncol(mu); logRho = matrix(0,n,k); for (i in 1:k){ logRho[,i] = loggausspdf(X,mu[,i,drop=FALSE],Sigma[,,i]); } logRho = sweep(logRho,2,log(w),"+") TT = logsumexp(logRho,2); llh = sum(TT)/n; logR= sweep(logRho,1,TT,"-") R = exp(logR); return(list(R=R, llh=llh)) } maximization = function(X, R){ d = nrow(X) ; n = ncol(X) k = ncol(R) ; nk = colSums(R); w = nk/n; mu = sweep(X%*%R,2,1/nk,"*") ### attention risque d'erreur ici Sigma = array(0,dim=c(d,d,k)); sqrtR = sqrt(R); for (i in 1:k){ Xo = sweep(X,1,mu[,i],"-") Xo = sweep(Xo,2,sqrtR[,i],"*") Sigma[,,i] = tcrossprod(Xo)/nk[i]; #% add a prior for numerical stability Sigma[,,i] = Sigma[,,i]+diag(d)*(1e-08); } return(list(mu=mu,Sigma=Sigma,weight=w)) } if(verb>=1) print(' EM for Gaussian mixture: running ... '); R = initialization(X,init); label = max.col(R) R = R[,sort(unique(label))]; tol = 1e-14; llh = rep(-Inf, maxiter) converged = FALSE; t = 0; while (!converged & t < maxiter){ t = t+1; if(verb>=1) print(paste(' Step ',t,sep="")); model = maximization(X,as.matrix(R)); tmp = expectation(X,model); R=tmp$R; llh[t]=tmp$llh label = max.col(R) u = unique(label); if (ncol(R) != length(u)) { R = R[,u]; } else {converged = ((llh[t+1]-llh[t]) < tol*abs(llh[t+1]));} #% remove empty components } if(verb>=1) { if (converged) {print(paste('Converged in ',t,' steps.',sep=""));} else {print(paste('Did not converge in ',maxiter,' steps.',sep=""));} } return(list(label= label, model= model, llh= llh[1:t], R=R)) }
/scratch/gouwar.j/cran-all/cranData/xLLiM/R/emgm.R
gllim = function(tapp,yapp,in_K,in_r=NULL,maxiter=100,Lw=0,cstr=NULL,verb=0,in_theta=NULL,...){ # %%%%%%%% General EM Algorithm for Gaussian Locally Linear Mapping %%%%%%%%% # %%% Author: Antoine Deleforge (April 2013) - [email protected] %%% # % Description: Compute maximum likelihood parameters theta and posterior # % probabilities r=p(z_n=k|x_n,y_n;theta) of a gllim model with constraints # % cstr using N associated observations t and y. # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% # %%%% Input %%%% # %- t (LtxN) % Training latent variables # %- y (DxN) % Training observed variables # %- in_K (int) % Initial number of components # % <Optional> # %- Lw (int) % Dimensionality of hidden components (default 0) # %- maxiter (int) % Maximum number of iterations (default 100) # %- in_theta (struct) % Initial parameters (default NULL) # % | same structure as output theta # %- in_r (NxK) % Initial assignments (default NULL) # %- cstr (struct) % Constraints on parameters theta (default NULL,'') # % - cstr$ct % fixed value (LtxK) or ''=uncons. # % - cstr$cw % fixed value (LwxK) or ''=fixed to 0 # % - cstr$Gammat % fixed value (LtxLtxK) or ''=uncons. # % | or {'','d','i'}{'','*','v'} [1] # % - cstr$Gammaw % fixed value (LwxLwxK) or ''=fixed to I # % - cstr$pi % fixed value (1xK) or ''=uncons. or '*'=equal # % - cstr$A % fixed value (DxL) or ''=uncons. # % - cstr$b % fixed value (DxK) or ''=uncons. # % - cstr$Sigma % fixed value (DxDxK) or ''=uncons. # % | or {'','d','i'}{'','*'} [1] # %- verb {0,1,2} % Verbosity (default 1) # %%%% Output %%%% # %- theta (struct) % Estimated parameters (L=Lt+Lw) # % - theta.c (LxK) % Gaussian means of X # % - theta.Gamma (LxLxK) % Gaussian covariances of X # % - theta.pi (1xK) % Gaussian weights of X # % - theta.A (DxLxK) % Affine transformation matrices # % - theta.b (DxK) % Affine transformation vectors # % - theta.Sigma (DxDxK) % Error covariances # %- r (NxK) % Posterior probabilities p(z_n=k|x_n,y_n;theta) # %%% [1] 'd'=diag., 'i'=iso., '*'=equal for all k, 'v'=equal det. for all k # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% # % ======================Input Parameters Retrieval========================= # A faire plus tard mais pas forcement indispensable maintenant? # [Lw, maxiter, in_theta, in_r, cstr, verb] = ... # process_options(varargin,'Lw',0,'maxiter',100,'in_theta',NULL,... # 'in_r',NULL,'cstr',struct(),'verb',1); # % ==========================Default Constraints============================ if(! "ct" %in% names(cstr)) cstr$ct=NULL; if(! "cw" %in% names(cstr)) cstr$cw=NULL; if(! "Gammat" %in% names(cstr)) cstr$Gammat=NULL; if(! "Gammaw" %in% names(cstr)) cstr$Gammaw=NULL; if(! "pi" %in% names(cstr)) cstr$pi=NULL; if(! "A" %in% names(cstr)) cstr$A=NULL; if(! "b" %in% names(cstr)) cstr$b=NULL; if(! "Sigma" %in% names(cstr)) cstr$Sigma="i"; if (ncol(tapp) != ncol(yapp)) {stop("Observations must be in columns and variables in rows")} covParBloc_EM =function(yCen,rk_bar, model){ covY = tcrossprod(yCen)/rk_bar Dim = dim(covY)[1] covEmpB = matrix(0,nrow = Dim,ncol = Dim) for (b in 1:max(model)){ ind = which(model == b) covEmpB[ind,ind] = covY[ind,ind] } return(covEst = covEmpB ) } ExpectationZ = function(tapp,yapp,th,verb){ if(verb>=1) print(' EZ'); if(verb>=3) print(' k='); D= nrow(yapp) N = ncol(yapp) K=length(th$pi); Lt = nrow(tapp) L = nrow(th$c) Lw=L-Lt; logr=matrix(NaN,N,K); for (k in 1:K){ if(verb>=3) print(k); muyk=th$b[,k,drop=FALSE]; #% Dx1 covyk= th$Sigma[,,k]; #% DxD if(Lt>0) {if (L==1) {Atk=th$A[,1:Lt,k,drop=FALSE];} else {Atk=th$A[,1:Lt,k]} #% DxLt muyk= sweep(Atk%*%tapp,1,muyk,"+");#% DxN } if(Lw>0) {Awk=matrix(th$A[,(Lt+1):L,k,drop=FALSE],ncol=Lw,nrow=D); #% DxLw Gammawk=th$Gamma[(Lt+1):L,(Lt+1):L,k]; #% LwxLw cwk=th$c[(Lt+1):L,k]; #% Lwx1 covyk=covyk+Awk%*%Gammawk%*%t(Awk); #% DxD muyk=sweep(muyk,1,Awk%*%cwk,"+"); #% DxN } logr[,k] = log(th$pi[k]);#*rep(1,N); #N x K logr[,k] = logr[,k] + loggausspdf(yapp,muyk,covyk); if (Lt>0) logr[,k] = logr[,k]+ loggausspdf(tapp,th$c[1:Lt,k,drop=FALSE],th$Gamma[1:Lt,1:Lt,k]); } lognormr=logsumexp(logr,2); LL=sum(lognormr); r=exp(sweep(logr,1, lognormr,"-")); # % remove empty clusters ec=rep(TRUE,K); #% false if component k is empty. for (k in 1:K){ if(sum(r[,k])==0 | !is.finite(sum(r[,k]))) {ec[k]=FALSE; if(verb>=1) {print(paste(' WARNING: CLASS ',k,' HAS BEEN REMOVED'));} } } if (sum(ec)==0){ print('REINIT! '); r = emgm(rbind(tapp,yapp), K, 2, verb)$R; ec=rep(TRUE,ncol(r)); } else { r=r[,ec,drop=FALSE]; } return(list(r=r,LL=LL,ec=ec)) } ExpectationW=function(tapp,yapp,th,verb){ if(verb>=1) print(' EW'); if(verb>=3) print(' k='); D = nrow(yapp) ; N=ncol(yapp) K=length(th$pi); Lt = nrow(tapp); L = nrow(th$c) Lw=L-Lt; if(Lw==0) {muw=NULL; Sw=NULL;} Sw=array(0,dim=c(Lw,Lw,K)); muw=array(0,dim=c(Lw,N,K)); for (k in 1:K){ if(verb>=3) print(k) Atk=th$A[,1:Lt,k]; #%DxLt Sigmak=th$Sigma[,,k]; #%DxD if (Lw==0) {Awk = NULL ; Gammawk=NULL ;cwk =NULL;invSwk=NULL} else {Awk=th$A[,(Lt+1):L,k]; Gammawk=th$Gamma[(Lt+1):L,(Lt+1):L,k];cwk=th$c[(Lt+1):L,k];invSwk=diag(Lw)+tcrossprod(Gammawk,Awk) %*% solve(Sigmak)%*%Awk;} #%DxLw # gerer le cas ou Lw=0 Matlab le fait tout seul if (!is.null(tapp)) {Atkt=Atk%*%tapp;} else {Atkt=0;} if (Lw==0) {muw=NULL;Sw=NULL;} else { #invSwk\bsxfun(@plus,Gammawk*Awk'/Sigmak*bsxfun(@minus,y-Atkt,th.b(:,k)),cwk) muw[,,k]= solve(invSwk,sweep(Gammawk %*% t(Awk) %*% solve(Sigmak) %*% sweep(yapp-Atkt,1,th$b[,k],"-"),1,cwk,"+")); #%LwxN Sw[,,k]=solve(invSwk,Gammawk);} } return(list(muw=muw,Sw=Sw)) } Maximization = function(tapp,yapp,r,muw,Sw,cstr,verb,model){ if(verb>=1) print(' M'); if(verb>=3) print(' k='); K = ncol(r); D = nrow(yapp);N=ncol(yapp) Lt = nrow(tapp) Lw = ifelse(is.null(muw),0,nrow(muw)) L=Lt+Lw; th = list() th$c=matrix(NaN,nrow=L,ncol=K) th$Gamma=array(0,dim=c(L,L,K)); if(Lw>0) {th$c[(Lt+1):L,]=cstr$cw; #% LwxK th$Gamma[(Lt+1):L,(Lt+1):L,]=cstr$Gammaw;} #% LwxLwxK} th$pi=rep(NaN,K); th$A=array(NaN,dim=c(D,L,K)); th$b=matrix(NaN,nrow=D,ncol=K); th$Sigma= array(NaN,dim=c(D,D,K)); rk_bar=rep(0,K); for (k in 1:K){ if(verb>=3) print(k); # % Posteriors' sums rk=r[,k]; #% 1xN rk_bar[k]=sum(rk); #% 1x1 if(Lt>0) { if(verb>=3) {print('c');} #% Compute optimal mean ctk if(is.null(cstr$ct)) {th$c[1:Lt,k]=rowSums(sweep(tapp,2,rk,"*"))/rk_bar[k];}# % Ltx1 else {th$c[1:Lt,k]=cstr$ct[,k];} #% Compute optimal covariance matrix Gammatk if(verb>=3) {print('Gt');} diffGamma <- sweep(sweep(tapp,1,th$c[1:Lt,k],"-"),2,sqrt(rk),"*"); #% LtxN if( is.null(cstr$Gammat) || (length(cstr$Gammat)==1 & cstr$Gammat=='*')) # | ou ||? # %%%% Full Gammat {th$Gamma[1:Lt,1:Lt,k]=tcrossprod(diffGamma)/rk_bar[k]; #% DxD } else { if( !is.character(cstr$Gammat)) #%%%% Fixed Gammat {th$Gamma[1:Lt,1:Lt,k]=cstr$Gammat[,,k]; } else { if(cstr$Gammat[1]=='d' | cstr$Gammat[1]=='i') #% Diagonal terms {gamma2=rowSums(diffGamma^2)/rk_bar[k]; #%Ltx1 if(cstr$Gammat[1]=='d') #%%% Diagonal Gamma {th$Gamma[1:Lt,1:Lt,k]=diag(gamma2);} #% LtxLt else #%%% Isotropic Gamma {th$Gamma[1:Lt,1:Lt,k]=mean(gamma2)*diag(Lt);} #% LtxLt } else {if(cstr$Gammat[1]=='v') #%%%% Full Gamma {th$Gamma[1:Lt,1:Lt,k]=tcrossprod(diffGamma)/rk_bar[k];} #% LtxLt else {# cstr$Gammat, stop(' ERROR: invalid constraint on Gamma.'); } } } } } # % Compute optimal weight pik th$pi[k]=rk_bar[k]/N; #% 1x1 if(Lw>0) {x=rbind(tapp,muw[,,k]); #% LxN Skx=rbind(cbind(matrix(0,Lt,Lt),matrix(0,Lt,Lw)),cbind(matrix(0,Lw,Lt),Sw[,,k])); }#% LxL else {x=tapp; #% LtxN Skx=matrix(0,Lt,Lt);} #%LtxLt if(verb>=3) {print('A');} if(is.null(cstr$b)) {# % Compute weighted means of y and x yk_bar=rowSums(sweep(yapp,2,rk,"*"))/rk_bar[k]; #% Dx1 if(L>0) {xk_bar= rowSums(sweep(x,2,rk,"*"))/rk_bar[k];} #% Lx1 else {xk_bar=NULL;} } else {yk_bar=cstr$b[,k]; xk_bar=rep(0,L); th$b[,k]=cstr$b[,k]; } #% Compute weighted, mean centered y and x weights=sqrt(rk); #% 1xN y_stark=sweep(yapp,1,yk_bar,"-"); #% DxN #col or row? y_stark= sweep(y_stark,2,weights,"*"); #% DxN #col or row? if(L>0) { x_stark=sweep(x,1,xk_bar,"-"); #% LxN x_stark= sweep(x_stark,2,weights,"*"); #% LxN } else {x_stark=NULL;} #% Robustly compute optimal transformation matrix Ak #warning off MATLAB:nearlySingularMatrix; if(!all(Skx==0)) {if(N>=L & det(Skx+tcrossprod(x_stark)) >10^(-8)) {th$A[,,k]=tcrossprod(y_stark,x_stark) %*% qr.solve(Skx+tcrossprod(x_stark));} #% DxL else {th$A[,,k]=tcrossprod(y_stark,x_stark) %*% ginv(Skx+tcrossprod(x_stark));} #%DxL } else {if(!all(x_stark==0)) {if(N>=L & det(tcrossprod(x_stark))>10^(-8)) {th$A[,,k]=tcrossprod(y_stark,x_stark) %*% qr.solve(tcrossprod(x_stark));} #% DxL else {if(N<L && det(crossprod(x_stark))>10^(-8)) {th$A[,,k]=y_stark %*% solve(crossprod(x_stark)) %*% t(x_stark);} #% DxL else {if(verb>=3) print('p') th$A[,,k]=y_stark %*% ginv(x_stark);} #% DxL }} else {#% Correspond to null variance in cluster k or L=0: if(verb>=1 & L>0) print('null var\n'); th$A[,,k]=0; # % DxL } } if(verb>=3)print('b'); # % Intermediate variable wk=y-Ak*x if(L>0) {wk=yapp-th$A[,,k]%*%x;} #% DxN else {wk=yapp;} #% Compute optimal transformation vector bk if(is.null(cstr$b)) th$b[,k]=rowSums(sweep(wk,2,rk,"*"))/rk_bar[k]; #% Dx1 if(verb>=3) print('S'); #% Compute optimal covariance matrix Sigmak if(Lw>0) { Awk=th$A[,(Lt+1):L,k]; Swk=Sw[,,k]; ASAwk=Awk%*%tcrossprod(Swk,Awk);} else ASAwk=0; diffSigma=sweep(sweep(wk,1,th$b[,k],"-"),2,sqrt(rk),"*"); #%DxN if (cstr$Sigma %in% c("","*")) {#%%%% Full Sigma th$Sigma[,,k]=tcrossprod(diffSigma)/rk_bar[k]; #% DxD th$Sigma[,,k]=th$Sigma[,,k]+ASAwk; } else { if(!is.character(cstr$Sigma)) #%%%% Fixed Sigma {th$Sigma=cstr$Sigma;} else { if(cstr$Sigma[1]=='d' || cstr$Sigma[1]=='i') #% Diagonal terms {sigma2=rowSums(diffSigma^2)/rk_bar[k]; #%Dx1 if(cstr$Sigma[1]=='d') {#%%% Diagonal Sigma th$Sigma[,,k]=diag(sigma2,ncol=D,nrow=D); #% DxD if (is.null(dim(ASAwk))) {th$Sigma[,,k]=th$Sigma[,,k] + diag(ASAwk,ncol=D,nrow=D)} else {th$Sigma[,,k]=th$Sigma[,,k]+diag(diag(ASAwk));} } else {#%%% Isotropic Sigma th$Sigma[,,k]=mean(sigma2)*diag(D); #% DxD if (is.null(dim(ASAwk))) {th$Sigma[,,k]=th$Sigma[,,k]+sum(diag(ASAwk,ncol=D,nrow=D))/D*diag(D);} else {th$Sigma[,,k]=th$Sigma[,,k]+sum(diag(ASAwk))/D*diag(D);} } } else { if (cstr$Sigma=='bSHOCK') { th$Sigma[,,k] = covParBloc_EM(yCen=diffSigma,rk_bar=rk_bar[k], model=model[[k]]);} else {stop(' ERROR: invalid constraint on Sigma.');}} } } #% Avoid numerical problems on covariances: if(verb>=3) print('n'); if(! is.finite(sum(th$Gamma[1:Lt,1:Lt,k]))) {th$Gamma[1:Lt,1:Lt,k]=0;} th$Gamma[1:Lt,1:Lt,k]=th$Gamma[1:Lt,1:Lt,k]+1e-8*diag(Lt); if(! is.finite(sum(th$Sigma[,,k]))) {th$Sigma[,,k]=0;} th$Sigma[,,k]=th$Sigma[,,k]+1e-8*diag(D); if(verb>=3) print(','); } if(verb>=3) print('end'); if (cstr$Sigma=="*") {#%%% Equality constraint on Sigma th$Sigma=sweep(th$Sigma ,3,rk_bar,"*"); th$Sigma=array(apply(th$Sigma,c(1,2),mean),dim=c(D,D,K)) } if( !is.null(cstr$Gammat) && cstr$Gammat=='v') {#%%% Equal volume constraint on Gamma detG=rep(0,K); for (k in 1:K){ if (D==1) {detG[k]=th$Gamma[1:Lt,1:Lt,k]} else {detG[k]=det(th$Gamma[1:Lt,1:Lt,k]);} #% 1x1 th$Gamma[1:Lt,1:Lt,k] = th$Gamma[1:Lt,1:Lt,k] / detG[k] } th$Gamma[1:Lt,1:Lt,]=sum(detG^(1/Lt)*th$pi)*th$Gamma[1:Lt,1:Lt,]; } if(is.character(cstr$Gammat) && !is.null(cstr$Gammat) && cstr$Gammat[length(cstr$Gammat)]=='*') {#%%% Equality constraint on Gammat for (k in 1:K){ th$Gamma[1:Lt,1:Lt,k]=th$Gamma[1:Lt,1:Lt,k]%*%diag(rk_bar); th$Gamma[1:Lt,1:Lt,k]=matrix(1,Lt,Lt) * sum(th$Gamma[1:Lt,1:Lt,k])/N; } } if( ! is.character(cstr$pi) || is.null(cstr$pi)) {if(! is.null(cstr$pi)) {th$pi=cstr$pi;}} else { if (!is.null(cstr$pi) && cstr$pi[1]=='*') {th$pi=1/K*rep(1,K);} else {stop(' ERROR: invalid constraint on pi.');} } return(th) } remove_empty_clusters= function(th,cstr,ec){ if(sum(ec) != length(ec)) {if( !is.null(cstr$ct) && !is.character(cstr$ct)) cstr$ct=cstr$ct[,ec]; if(!is.null(cstr$cw) && !is.character(cstr$cw)) cstr$cw=cstr$cw[,ec]; if(!is.null(cstr$Gammat) && !is.character(cstr$Gammat)) cstr$Gammat=cstr$Gammat[,,ec]; if(!is.null(cstr$Gammaw) && !is.character(cstr$Gammaw)) cstr$Gammaw=cstr$Gammaw[,,ec]; if(!is.null(cstr$pi) && !is.character(cstr$pi)) cstr$pi=cstr$pi[,ec]; if(!is.null(cstr$A) && !is.character(cstr$A)) cstr$A=cstr$A[,,ec]; if(!is.null(cstr$b) && !is.character(cstr$b)) cstr$b=cstr$b[,ec]; if(!is.null(cstr$Sigma) && !is.character(cstr$Sigma)) cstr$Sigma=cstr$Sigma[,,ec]; th$c=th$c[,ec]; th$Gamma=th$Gamma[,,ec]; th$pi=th$pi[ec]; th$A=th$A[,,ec]; th$b=th$b[,ec]; th$Sigma=th$Sigma[,,ec]; } return(list(th=th,cstr=cstr)) } # % ==========================EM initialization============================== Lt=nrow(tapp) L=Lt+Lw; D = nrow(yapp) ; N = ncol(yapp); if(verb>=1) {print('EM Initializations');} if(!is.null(in_theta)) { theta=in_theta; K=length(theta$pi); if(is.null(cstr$cw)) {cstr$cw=matrix(0,L,K);} # % Default value for cw if(is.null(cstr$Gammaw)) { cstr$Gammaw=array(diag(Lw),dim=c(Lw,Lw,K));} #% Default value for Gammaw tmp = ExpectationZ(tapp,yapp,theta,verb); r = tmp$r ; ec = tmp$ec ; tmp = remove_empty_clusters(theta,cstr,ec); theta = tmp$th ; cstr = tmp$cstr ; tmp = ExpectationW(tapp,yapp,theta,verb); muw = tmp$muw Sw = tmp$Sw if(verb>=1) print(""); } else {if(is.null(in_r)){ r = emgm(rbind(tapp,yapp), in_K, 1000, verb=verb)$R; } else {r=in_r$R;} if(Lw==0) {Sw=NULL; muw=NULL;} else { # % Start by running an M-step without hidden variables (partial # % theta), deduce Awk by local weighted PCA on residuals (complete # % theta), deduce r, muw and Sw from E-steps on complete theta. theta = Maximization(tapp,yapp,r,NULL,NULL,cstr,verb); #print(colMeans(theta$A)) OK no problem here : error is fater K=length(theta$pi); if(is.null(cstr$cw)) {cstr$cw=matrix(0,Lw,K);} theta$c=rbind(theta$c,cstr$cw[,1:K]); Gammaf=array(0,dim=c(L,L,K)); Gammaf[1:Lt,1:Lt,]=theta$Gamma; if(is.null(cstr$Gammaw)) {cstr$Gammaw=array(diag(Lw),dim=c(Lw,Lw,K));} Gammaf[(Lt+1):L,(Lt+1):L,]=cstr$Gammaw[,,1:K]; #%LwxLwxK theta$Gamma=Gammaf; # % Initialize Awk with local weighted PCAs on residuals: Aw=array(0,dim=c(D,Lw,K)); for (k in 1:K) {rk_bar=sum(r[,k]); bk=theta$b[,k]; w=sweep(yapp,1,bk,"-"); #%DxN if(Lt>0) {Ak=theta$A[,,k]; w=w-Ak%*%tapp;} w=sweep(w,2,sqrt(r[,k]/rk_bar),"*"); #%DxN C=tcrossprod(w); #% Residual weighted covariance matrix tmp = eigen(C) ##svd? U = tmp$vectors[,1:Lw] Lambda = tmp$values[1:Lw] #% Weighted residual PCA U:DxLw #% The residual variance is the discarded eigenvalues' mean sigma2k=(sum(diag(C))-sum(Lambda))/(D-Lw); #scalar #print(sigma2k) #OK here theta$Sigma[,,k]=sigma2k * diag(D); Aw[,,k]=U%*%sqrt(diag(Lambda,ncol=length(Lambda),nrow=length(Lambda))-sigma2k*diag(Lw));} theta$A=abind(theta$A,Aw,along=2); #%DxLxK tmp = ExpectationZ(tapp,yapp,theta,verb); r =tmp$r ; ec=tmp$ec; tmp = remove_empty_clusters(theta,cstr,ec); theta = tmp$th ; cstr = tmp$cstr ; tmp = ExpectationW(tapp,yapp,theta,verb); muw = tmp$muw ; Sw = tmp$Sw ; if(verb>=1) print(""); }} # %===============================EM Iterations============================== if(verb>=1) print(' Running EM'); LL = rep(-Inf,maxiter); iter = 0; converged= FALSE; while ( !converged & iter<maxiter){ iter = iter + 1; if(verb>=1) print(paste(' Iteration ',iter,sep="")); # % =====================MAXIMIZATION STEP=========================== theta = Maximization(tapp,yapp,r,muw,Sw,cstr,verb,...); # % =====================EXPECTATION STEPS=========================== tmp = ExpectationZ(tapp,yapp,theta,verb); r = tmp$r ; LL[iter] =tmp$LL; if (verb>=1) {print(LL[iter]);} ec=tmp$ec tmp = remove_empty_clusters(theta,cstr,ec); theta = tmp$th cstr = tmp$cstr tmp = ExpectationW(tapp,yapp,theta,verb); muw=tmp$muw Sw=tmp$Sw if(iter>=3) { deltaLL_total=max(LL[1:iter])-min(LL[1:iter]); deltaLL=LL[iter]-LL[iter-1]; converged=(deltaLL <= (0.001*deltaLL_total)); } if(verb>=1) print(""); } # %%% Final log-likelihood %%%% LLf=LL[iter]; # % =============================Final plots=============================== if(verb>=1) print(paste('Converged in ',iter,' iterations',sep="")); theta$r = r theta$LLf=LLf theta$LL = LL[1:iter] if (cstr$Sigma == "i") {nbparSigma = 1} if (cstr$Sigma == "d") {nbparSigma = D} if (cstr$Sigma == "") {nbparSigma = D*(D+1)/2} if (cstr$Sigma == "*") {nbparSigma = D*(D+1)/(2*in_K)} if (cstr$Sigma == "bSHOCK") {nbparSigma = Inf} if (!is.null(cstr$Gammat)){ if (cstr$Gammat == "i") {nbparGamma = 1} if (cstr$Gammat == "d") {nbparGamma = Lt} if (cstr$Gammat == "") {nbparGamma = Lt*(Lt+1)/2} if (cstr$Gammat == "*") {nbparGamma = Lt*(Lt+1)/(2*in_K)} } if (is.null(cstr$Gammat)){ nbparGamma = Lt*(Lt+1)/2 } theta$nbpar = (in_K-1) + in_K*(D*L + D + Lt + nbparSigma + nbparGamma) return(theta) }
/scratch/gouwar.j/cran-all/cranData/xLLiM/R/gllim.R
gllim_inverse_map = function(y,theta,verb=0){ # %%%%%%%%%%%%%%%%% Inverse Mapping from Gllim Parameters %%%%%%%%%%%%%%%%%%% # %%%% Author: Antoine Deleforge (July 2012) - [email protected] %%% # %% Converted to R: Emeline Perthame (2016) - [email protected] %%% # % Description: Map N observations y using the inverse conditional # % expectation E[x|y;theta] of the gllim model with parameters theta. # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% # %%%% Input %%%% # % - y (DxN) % Input observations to map # % - theta (struct) % Gllim model parameters # % - theta.c (LxK) % Gaussian means of X's prior # % - theta.Gamma (LxLxK) % Gaussian covariances of X's prior # % - theta.pi (1xK) % Gaussian weights of X's prior # % - theta.A (DxLxK) % Affine transformation matrices # % - theta.b (DxK) % Affine transformation vectors # % - theta.Sigma (DxDxK) % Error covariances # % - verb {0,1,2} % Verbosity (def 1) # %%%% Output %%%% # % - x_exp (LxN) % Posterior mean estimates E[xn|yn;theta] # % - alpha (NxK) % Weights of the posterior GMMs # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% D = nrow(y) ; N = ncol(y) ; L = nrow(theta$c) ; K = ncol(theta$c) ; # % ======================Inverse density parameters========================= if(verb>=1) print('Compute K projections to X space and weights') proj=array(NaN,dim=c(L,N,K)); logalpha=matrix(0,N,K); for (k in 1:K){ if(verb>=2) print(paste("k=",k,sep="")); if(verb>=2) print('AbcG '); if (L==1) {Ak=theta$A[,,k,drop=FALSE];} else {Ak=matrix(theta$A[,,k],ncol=L,nrow=D);} # % DxL bk=theta$b[,k]; # % Dx1 Sigmak=theta$Sigma[,,k]; # %DxD ## OK if (L==1) {ck=theta$c[,k,drop=FALSE];} else {ck=theta$c[,k];} # % Lx1 Gammak=theta$Gamma[,,k]; # % LxL ## OK if(verb>=2) print('cks '); cks=Ak%*%ck+bk; ## OK if(verb>=2) print('Gks '); Gammaks=Sigmak+Ak%*%tcrossprod(Gammak,Ak); ## OK if(verb>=2) print('iSks '); iSk = solve(Sigmak) #diag(1/diag(Sigmak)) invSigmaks2=diag(L)+Gammak%*%crossprod(Ak, iSk)%*%Ak; if(verb>=2) print('Aks '); Aks=solve(invSigmaks2,Gammak)%*%crossprod(Ak, iSk) if(verb>=2) print('bks '); bks= solve(invSigmaks2) %*% (ck-Gammak%*%crossprod(Ak, iSk%*%bk)) if(verb>=2) print('projections '); proj[,,k]=sweep(Aks%*%y,1,bks,"+"); if(verb>=2) print('logalpha '); logalpha[,k]=log(theta$pi[k])+loggausspdf(y,cks,Gammaks); if(verb>=2) print(''); } den=logsumexp(logalpha,2); logalpha= sweep(logalpha,1,den,"-") alpha=exp(logalpha); x_exp = lapply(1:L,function(l) proj[l,,]*alpha) x_exp = lapply(x_exp,rowSums) x_exp = do.call(rbind, x_exp) return(list(x_exp=x_exp,alpha=alpha)) }
/scratch/gouwar.j/cran-all/cranData/xLLiM/R/gllim_inverse_map.R
inv_digamma = function(y,niter=5){ # % INV_DIGAMMA Inverse of the digamma function. # % # % inv_digamma(y) returns x such that digamma(x) = y. #% never need more than 5 iterations #% Newton iteration to solve digamma(x)-y = 0 x = exp(y)+1/2; i = which(y <= -2.22); x[i] = -1/(y[i] - digamma(1)); for (iter in 1:niter){ x = x - (digamma(x)-y)/trigamma(x);} return(x) }
/scratch/gouwar.j/cran-all/cranData/xLLiM/R/inv_digamma.R
kmeans_probs <- function(mat,m){ tmp <- apply(m,1,function(x){rowSums(sweep(mat,2,x,"-")^2)}) tmp <- tmp/rowSums(tmp) return(tmp) }
/scratch/gouwar.j/cran-all/cranData/xLLiM/R/kmeans_probs.R
loggausspdf = function(X, mu, Sigma){ d = nrow(X) ; n = ncol(X) ; if (ncol(mu) == n) {X=X-mu;}#sweep(X,2,mu,"-")} else {X=sweep(X,1,mu,"-")} #X = #scale(X,center=mu,scale=FALSE) # d x n ### X ou t(X) p = is.positive.definite(Sigma) if (! p) { print("SNPD !"); y= rep(-Inf,n) } else { U = chol(Sigma) # d x d Q = solve(t(U),X) # d x n q = colSums(Q^2) # 1xn quadratic term (M distance) c = d*log(2*pi)+2*sum(log(diag(U))) #1x1 normalization constant y = -(c+q)/2;} # 1xn return(y) }
/scratch/gouwar.j/cran-all/cranData/xLLiM/R/loggausspdf.R
logsumexp = function(x,dimension=c(1,2)){ # % Compute log(sum(exp(x),dim)) while avoiding numerical underflow. # % By default dim = 2 (columns). if (is.null(dimension)) dimension=1 ; # % subtract the largest in each column y = apply(x,1,max) x = x-y#sweep(x,1,y,"-") s = y+log(rowSums(exp(x))) i = is.infinite(y) if (sum(i) > 0) s[i]=y[i] return(s) }
/scratch/gouwar.j/cran-all/cranData/xLLiM/R/logsumexp.R
#% Arellano-Valle and Bolfarine generalized t distribution for dimension D logtpdfD = function(logDetSigma, mahaly, alpha, gammakn, D){ y = lgamma(alpha+D/2) - lgamma(alpha) - (D/2)*log(2*pi) - (D/2)*log(gammakn) - logDetSigma - (alpha+D/2)*(log(mahaly/(2*gammakn) + 1)); # % 1x1 normalization constant return(y)}
/scratch/gouwar.j/cran-all/cranData/xLLiM/R/logtpdfD.R
#% Arellano-Valle and Bolfarine generalized t distribution for dimension L logtpdfL = function(logDetGamma, mahalx, alpha, L){ y = lgamma(alpha+L/2) - lgamma(alpha) - (L/2)*log(2*pi) - logDetGamma - (alpha+L/2)*(log(mahalx/2 + 1)); #% 1x1 normalization constant return(y)}
/scratch/gouwar.j/cran-all/cranData/xLLiM/R/logtpdfL.R
mahalanobis_distance = function(x,mu,Sigma){ #%Compute the mahalanobis distance n = ncol(x); if (ncol(mu) == n) {x=x-mu;}#sweep(X,2,mu,"-")} else {x=sweep(x,1,mu,"-")} # [U,num] = cholcov(sigma); # if num > 0 # fprintf(1,'toto'); # end p = is.positive.definite(Sigma) if (p) {U = chol(Sigma); Q = solve(t(U)) %*% x; #% dxn y = colSums(Q^2);} #% 1xn quadratic term (M distance) else { print('SNPD! '); y=rep(Inf,n);} # % 1xn %%% EP=-Inf a l'origine ; plutot valeur Inf?? return(y) }
/scratch/gouwar.j/cran-all/cranData/xLLiM/R/mahalanobis_distance.R
preprocess_data = function(tapp,yapp,in_K,...){ L <- ncol(tapp) init.kmeans = kmeans(cbind(tapp,yapp),in_K) ind = c() probs <- kmeans_probs(cbind(tapp,yapp), init.kmeans$centers) for (k in 1:in_K){ cv <- cv.glmnet(as.matrix(yapp[init.kmeans$cluster== k,]), as.matrix(tapp[init.kmeans$cluster== k,]), family="mgaussian",...) lambda <- min(cv$lambda.1se, max(cv$lambda[cv$nzero >= L])) mod <- glmnet(as.matrix(yapp[init.kmeans$cluster== k,]), as.matrix(tapp[init.kmeans$cluster== k,]), family="mgaussian", lambda=lambda, ...) indk <- c() for (l in 1:dim(tapp)[2]){ indk = c(indk, which(mod$beta[[l]] !=0)) } indk <- unique(indk) if (length(indk) == 0){ mod <- glmnet(as.matrix(yapp[init.kmeans$cluster== k,]), as.matrix(tapp[init.kmeans$cluster== k,]),family="mgaussian", lambda=cv$lambda, ...) mod <- glmnet(as.matrix(yapp[init.kmeans$cluster== k,]), as.matrix(tapp[init.kmeans$cluster== k,]),family="mgaussian", lambda=max(cv$lambda[mod$dfmat[1,] >= 1]), ...) } for (l in 1:dim(tapp)[2]){ ind = c(ind, which(mod$beta[[l]] !=0)) } } ind <- unique(ind) if (in_K == 1) { clusters <- data.frame(cluster1 = init.kmeans$cluster) } else { clusters <- probs } colnames(clusters) <- paste0("cluster",1:ncol(clusters)) return(list(selected.variables=sort(ind),clusters=clusters)) }
/scratch/gouwar.j/cran-all/cranData/xLLiM/R/preprocess_data.R
sllim = function(tapp,yapp,in_K,in_r=NULL,maxiter=100,Lw=0,cstr=NULL,verb=0,in_theta=NULL,in_phi=NULL){ # %%%%%%%% General EM Algorithm for Gaussian Locally Linear Mapping %%%%%%%%% # %%% Author: Antoine Deleforge (April 2013) - [email protected] %%% # % Description: Compute maximum likelihood parameters theta and posterior # % probabilities r=p(z_n=k|x_n,y_n;theta) of a sllim model with constraints # % cstr using N associated observations t and y. # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% # %%%% Input %%%% # %- t (LtxN) % Training latent variables # %- y (DxN) % Training observed variables # %- in_K (int) % Initial number of components # % <Optional> # %- Lw (int) % Dimensionality of hidden components (default 0) # %- maxiter (int) % Maximum number of iterations (default 100) # %- in_theta (struct)% Initial parameters (default []) # %| same structure as output theta # %- in_r (NxK) % Initial assignments (default []) # %- cstr (struct) % Constraints on parameters theta (default [],'') # %- cstr.ct % fixed value (LtxK) or ''=uncons. # %- cstr.cw % fixed value (LwxK) or ''=fixed to 0 # %- cstr.Gammat% fixed value (LtxLtxK) or ''=uncons. # %| or {'','d','i'}{'','*','v'} (1) # %- cstr.Gammaw% fixed value (LwxLwxK) or ''=fixed to I # %- cstr.pi % fixed value (1xK) or ''=uncons. or '*'=equal # %- cstr.A % fixed value (DxL) or ''=uncons. # %- cstr.b % fixed value (DxK) or ''=uncons. # %- cstr.Sigma% fixed value (DxDxK) or ''=uncons. # %| or {'','d','i'}{'','*'} (1) # %- verb {0,1,2}% Verbosity (default 1) # %%%% Output %%%% # %- theta (struct) % Estimated parameters (L=Lt+Lw) # %- theta.c (LxK) % Gaussian means of X # %- theta.Gamma (LxLxK) % Gaussian covariances of X # %- theta.A (DxLxK) % Affine transformation matrices # %- theta.b (DxK) % Affine transformation vectors # %- theta.Sigma (DxDxK) % Error covariances # %- theta.gamma (1xK)% Arellano-Valle and Bolfarine's Generalized t # %- phi (struct)% Estimated parameters # %- phi.pi (1xK) % t weights of X # %- phi.alpha (1xK) % Arellano-Valle and Bolfarine's Generalized t # %- r (NxK) % Posterior probabilities p(z_n=k|x_n,y_n;theta) # %- u (NxK) % Posterior probabilities E[u_n|z_n=k,x_n,y_n;theta,phi) # %%% (1) 'd'=diag., 'i'=iso., '*'=equal for all k, 'v'=equal det. for all k # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% # % ======================Input Parameters Retrieval========================= # [Lw, maxiter, in_theta, in_r, cstr, verb] = ... # process_options(varargin,'Lw',0,'maxiter',100,'in_theta',[],... # 'in_r',[],'cstr',struct(),'verb',0); # % ==========================Default Constraints============================ if(! "ct" %in% names(cstr)) cstr$ct=NULL; if(! "cw" %in% names(cstr)) cstr$cw=NULL; if(! "Gammat" %in% names(cstr)) cstr$Gammat=NULL; if(! "Gammaw" %in% names(cstr)) cstr$Gammaw=NULL; if(! "pi" %in% names(cstr)) cstr$pi=NULL; if(! "A" %in% names(cstr)) cstr$A=NULL; if(! "b" %in% names(cstr)) cstr$b=NULL; if(! "Sigma" %in% names(cstr)) cstr$Sigma="i"; if(! "alpha" %in% names(cstr)) cstr$alpha=NULL; if(! "gamma" %in% names(cstr)) cstr$gamma=NULL; ExpectationZU = function(tapp,yapp,th,ph,verb){ if(verb>=1) print(' EZU'); if(verb>=3) print(' k='); D= nrow(yapp) N = ncol(yapp) K=length(ph$pi); Lt = nrow(tapp) L = nrow(th$c) Lw=L-Lt; # Space allocation logr=matrix(NaN,N,K); u=matrix(NaN,N,K); # matrix of weights mahaly = matrix(0,N,K); mahalt = matrix(0,N,K); for (k in 1:K){ if(verb>=3) print[k]; alphak = ph$alpha[k]; #1 muyk=th$b[,k,drop=FALSE]; #% Dx1 covyk= th$Sigma[,,k]; #% DxD if(Lt>0) {if (L==1) {Atk=th$A[,1:Lt,k,drop=FALSE];} else {Atk=th$A[,1:Lt,k]} #% DxLt muyk= sweep(Atk%*%tapp,1,muyk,"+");#% DxN } if(Lw>0) {Awk=matrix(th$A[,(Lt+1):L,k,drop=FALSE],ncol=Lw,nrow=D); #% DxLw Gammawk=th$Gamma[(Lt+1):L,(Lt+1):L,k]; #% LwxLw cwk=th$c[(Lt+1):L,k]; #% Lwx1 covyk=covyk+Awk%*%Gammawk%*%t(Awk); #% DxD muyk=sweep(muyk,1,Awk%*%cwk,"+"); #% DxN } mahaly[,k] = mahalanobis_distance(yapp,muyk,covyk); mahalt[,k] = mahalanobis_distance(tapp,th$c[1:Lt,k,drop=FALSE],th$Gamma[1:Lt,1:Lt,k]); u[,k] = (alphak + (D+Lt)/2)/ (1 + 0.5*(mahalt[,k] + mahaly[,k])); #%%% modif EP #[R,p] = chol(covyk); p = is.positive.definite(covyk) if (!p) {sldR = -Inf;} else {R = chol(covyk) ; sldR=sum(log(diag(R)));} #%%% modif EP logr[,k] = rep(log(ph$pi[k]),N) + logtpdfL(sldR,mahalt[,k],alphak, Lt) + logtpdfD(sum(log(diag(chol(th$Gamma[1:Lt,1:Lt,k])))),mahaly[,k],alphak + Lt/2, (1+mahalt[,k]/2), D) ; #% log_rnk } lognormr=logsumexp(logr,2); LL=sum(lognormr); r=exp(sweep(logr,1, lognormr,"-")); # % remove empty clusters ec=rep(TRUE,K); #% false if component k is empty. for (k in 1:K){ if(sum(r[,k])==0 | !is.finite(sum(r[,k]))) {ec[k]=FALSE; if(verb>=1) {print(paste(' WARNING: CLASS ',k,' HAS BEEN REMOVED'));} } } if (sum(ec)==0) {print('REINIT! '); r = emgm(rbind(tapp,yapp), K, 2, verb)$R; ec=rep(TRUE,ncol(r));} else {r=r[,ec];} return(list(r=r,LL=LL,ec=ec,u=u,mahalt=mahalt,mahaly=mahaly)) } ExpectationW = function(tapp,yapp,u,th,ph,verb){ if(verb>=1) print(' EW'); if(verb>=3) print(' k='); D = nrow(yapp) ; N=ncol(yapp) K=length(ph$pi); Lt = nrow(tapp); L = nrow(th$c) Lw=L-Lt; if(Lw==0) {muw=NULL; Sw=NULL;} Sw=array(0,dim=c(Lw,Lw,K)); muw=array(0,dim=c(Lw,N,K)); for (k in 1:K){ if(verb>=3) print(k) Atk=th$A[,1:Lt,k]; #%DxLt Sigmak=th$Sigma[,,k]; #%DxD if (Lw==0) {Awk = NULL ; Gammawk=NULL ;cwk =NULL;invSwk=NULL} else {Awk=th$A[,(Lt+1):L,k]; Gammawk=th$Gamma[(Lt+1):L,(Lt+1):L,k];cwk=th$c[(Lt+1):L,k];invSwk=diag(Lw)+tcrossprod(Gammawk,Awk) %*% solve(Sigmak)%*%Awk;} #%DxLw # gerer le cas ou Lw=0 Matlab le fait tout seul if (!is.null(tapp)) {Atkt=Atk%*%tapp;} else {Atkt=0;} if (Lw==0) {muw=NULL;Sw=NULL;} else { muw[,,k]= solve(invSwk,sweep(Gammawk %*% t(Awk) %*% solve(Sigmak) %*% sweep(yapp-Atkt,1,th$b[,k],"-"),1,cwk,"+")); #%LwxN Sw[,,k]=solve(invSwk,Gammawk);} } return(list(muw=muw,Sw=Sw)) } Maximization = function(tapp,yapp,r,u,phi,muw,Sw,mahalt,mahaly,cstr,verb){ if(verb>=1) print(' M'); if(verb>=3) print(' k='); K = ncol(r); D = nrow(yapp);N=ncol(yapp) Lt = nrow(tapp) Lw = ifelse(is.null(muw),0,nrow(muw)) L=Lt+Lw; th = list() ph = list() th$c=matrix(NaN,nrow=L,ncol=K) th$Gamma=array(0,dim=c(L,L,K)); if(Lw>0) {th$c[(Lt+1):L,]=cstr$cw; #% LwxK th$Gamma[(Lt+1):L,(Lt+1):L,]=cstr$Gammaw;} #% LwxLwxK} ph$pi=rep(NaN,K); th$A=array(NaN,dim=c(D,L,K)); th$b=matrix(NaN,nrow=D,ncol=K); th$Sigma= array(NaN,dim=c(D,D,K)); rk_bar=rep(0,K); for (k in 1:K){ if(verb>=3) print(k); # % Posteriors' sums rk=r[,k]; #% 1xN rk_bar[k]=sum(rk); #% 1x1 uk=u[,k]; #% 1xN rk_tilde = rk * uk; rk_bar_tilde = sum(rk_tilde); if(Lt>0) { if(verb>=3) {print('c');} #% Compute optimal mean ctk if(is.null(cstr$ct)) {th$c[1:Lt,k]=rowSums(sweep(tapp,2, rk_tilde,"*"))/rk_bar_tilde;}# % Ltx1 else {th$c[1:Lt,k]=cstr$ct[,k];} #% Compute optimal covariance matrix Gammatk if(verb>=3) {print('Gt');} diffGamma= sweep(sweep(tapp,1,th$c[1:Lt,k],"-"),2,sqrt(rk),"*"); #% LtxN ### rk_tilde??? if( is.null(cstr$Gammat) || (length(cstr$Gammat)==1 & cstr$Gammat=='*')) # | ou ||? # %%%% Full Gammat {th$Gamma[1:Lt,1:Lt,k]=tcrossprod(diffGamma)/rk_bar[k]; #% DxD }#th$Gamma[1:Lt,1:Lt,k]=th$Gamma[1:Lt,1:Lt,k]; else { if( !is.character(cstr$Gammat)) #%%%% Fixed Gammat {th$Gamma[1:Lt,1:Lt,k]=cstr$Gammat[,,k]; } else { if(cstr$Gammat[1]=='d' | cstr$Gammat[1]=='i') #% Diagonal terms {gamma2=rowSums(diffGamma^2)/rk_bar[k]; #%Ltx1 if(cstr$Gammat[1]=='d') #%%% Diagonal Gamma {th$Gamma[1:Lt,1:Lt,k]=diag(gamma2);} #% LtxLt else #%%% Isotropic Gamma {th$Gamma[1:Lt,1:Lt,k]=mean(gamma2)*diag(Lt);} #% LtxLt } else {if(cstr$Gammat[1]=='v') #%%%% Full Gamma {th$Gamma[1:Lt,1:Lt,k]=tcrossprod(diffGamma)/rk_bar[k];} #% LtxLt else {# cstr$Gammat, stop(' ERROR: invalid constraint on Gamma.'); } } } } } #% Compute optimal weight pik ph$pi[k]=rk_bar[k]/N; #% 1x1 if(Lw>0) {x=rbind(tapp,muw[,,k]); #% LxN Skx=rbind(cbind(matrix(0,Lt,Lt),matrix(0,Lt,Lw)),cbind(matrix(0,Lw,Lt),Sw[,,k])); }#% LxL else {x=tapp; #% LtxN Skx=matrix(0,Lt,Lt);} #%LtxLt if(verb>=3) {print('A');} if(is.null(cstr$b)) {# % Compute weighted means of y and x yk_bar=rowSums(sweep(yapp,2,rk_tilde,"*"))/rk_bar[k]; #% Dx1 if(L>0) {xk_bar= rowSums(sweep(x,2, rk_tilde,"*"))/rk_bar[k];} #% Lx1 else {xk_bar=NULL;} } else {yk_bar=cstr$b[,k]; xk_bar=rep(0,L); th$b[,k]=cstr$b[,k]; } #% Compute weighted, mean centered y and x weights=sqrt(rk_tilde)/sqrt(rk_bar[k]); #% 1xN y_stark=sweep(yapp,1,yk_bar,"-"); #% DxN #col or row? y_stark= sweep(y_stark,2,weights,"*"); #% DxN #col or row? if(L>0) { x_stark=sweep(x,1,xk_bar,"-"); #% LxN x_stark= sweep(x_stark,2,weights,"*"); #% LxN } else {x_stark=NULL;} #% Robustly compute optimal transformation matrix Ak #warning off MATLAB:nearlySingularMatrix; if(!all(Skx==0)) {if(N>=L & det(Skx+tcrossprod(x_stark))>10^(-8)) {th$A[,,k]=tcrossprod(y_stark,x_stark)%*%solve(Skx+tcrossprod(x_stark));} #% DxL else {th$A[,,k]=tcrossprod(y_stark,x_stark)%*%ginv(Skx+tcrossprod(x_stark));} #%DxL } else {if(!all(x_stark==0)) {if(N>=L & det(tcrossprod(x_stark))>10^(-8)) {th$A[,,k]=tcrossprod(y_stark,x_stark)%*% solve(tcrossprod(x_stark));} #% DxL else {if(N<L && det(crossprod(x_stark))>10^(-8)) {th$A[,,k]=y_stark %*% solve(crossprod(x_stark)) %*% t(x_stark);} #% DxL else {if(verb>=3) print('p') th$A[,,k]=y_stark %*% ginv(x_stark);} #% DxL }} else {#% Correspond to null variance in cluster k or L=0: if(verb>=1 & L>0) print('null var\n'); th$A[,,k]=0; # % DxL } } if(verb>=3)print('b'); # % Intermediate variable wk=y-Ak*x if(L>0) {wk=yapp-th$A[,,k]%*%x;} #% DxN #attention au reshape? else {wk=yapp;} #% Compute optimal transformation vector bk if(is.null(cstr$b)) th$b[,k]=rowSums(sweep(wk,2,rk_tilde,"*"))/rk_bar_tilde; #% Dx1 #col ou row? if(verb>=3) print('S'); #% Compute optimal covariance matrix Sigmak if(Lw>0) { Awk=th$A[,(Lt+1):L,k]; Swk=Sw[,,k]; ASAwk=Awk%*%tcrossprod(Swk,Awk);} else ASAwk=0; diffSigma=sweep(sweep(wk,1,th$b[,k],"-"),2,sqrt(rk_tilde),"*"); #%DxN if (cstr$Sigma %in% c("","*")) {#%%%% Full Sigma th$Sigma[,,k]=tcrossprod(diffSigma)/rk_bar[k]; #% DxD th$Sigma[,,k]=th$Sigma[,,k]+ASAwk; } else { if(!is.character(cstr$Sigma)) #%%%% Fixed Sigma {th$Sigma=cstr$Sigma;} else { if(cstr$Sigma[1]=='d' || cstr$Sigma[1]=='i') #% Diagonal terms {sigma2=rowSums(diffSigma^2)/rk_bar[k]; #%Dx1 if(cstr$Sigma[1]=='d') {#%%% Diagonal Sigma th$Sigma[,,k]=diag(sigma2,ncol=D,nrow=D); #% DxD if (is.null(dim(ASAwk))) {th$Sigma[,,k]=th$Sigma[,,k] + diag(ASAwk,ncol=D,nrow=D)} else {th$Sigma[,,k]=th$Sigma[,,k]+diag(diag(ASAwk));} } else {#%%% Isotropic Sigma th$Sigma[,,k]=mean(sigma2)*diag(D); #% DxD if (is.null(dim(ASAwk))) {th$Sigma[,,k]=th$Sigma[,,k]+sum(diag(ASAwk,ncol=D,nrow=D))/D*diag(D);} else {th$Sigma[,,k]=th$Sigma[,,k]+sum(diag(ASAwk))/D*diag(D);} } } else { cstr$Sigma ; stop(' ERROR: invalid constraint on Sigma.');} } } #% Avoid numerical problems on covariances: if(verb>=3) print('n'); if(! is.finite(sum(th$Gamma[1:Lt,1:Lt,k]))) {th$Gamma[1:Lt,1:Lt,k]=0;} th$Gamma[1:Lt,1:Lt,k]=th$Gamma[1:Lt,1:Lt,k]+1e-8*diag(Lt); if(! is.finite(sum(th$Sigma[,,k]))) {th$Sigma[,,k]=0;} th$Sigma[,,k]=th$Sigma[,,k]+1e-8*diag(D); if(verb>=3) print(','); } if(verb>=3) print('end'); if (cstr$Sigma=="*") {#%%% Equality constraint on Sigma th$Sigma=sweep(th$Sigma ,3,rk_bar,"*"); th$Sigma=array(apply(th$Sigma,c(1,2),mean),dim=c(D,D,K)) } if( !is.null(cstr$Gammat) && cstr$Gammat=='v') {#%%% Equal volume constraint on Gamma detG=rep(0,K); for (k in 1:K){ if (D==1) {detG[k]=th$Gamma[1:Lt,1:Lt,k]} else {detG[k]=det(th$Gamma[1:Lt,1:Lt,k]);} #% 1x1 th$Gamma[1:Lt,1:Lt,k] = th$Gamma[1:Lt,1:Lt,k] / detG[k] } th$Gamma[1:Lt,1:Lt,]=sum(detG^(1/Lt)*ph$pi)*th$Gamma[1:Lt,1:Lt,]; } if(is.character(cstr$Gammat) && !is.null(cstr$Gammat) && cstr$Gammat[length(cstr$Gammat)]=='*') {#%%% Equality constraint on Gammat for (k in 1:K){ th$Gamma[1:Lt,1:Lt,k]=th$Gamma[1:Lt,1:Lt,k]%*%diag(rk_bar); th$Gamma[1:Lt,1:Lt,k]=matrix(1,Lt,Lt) * sum(th$Gamma[1:Lt,1:Lt,k])/N; } # % Compute phi.alpha % if(!is.null(mahalt) && !is.null(mahaly)) { ph$alpha[k] = inv_digamma((digamma(phi$alpha[k] + (D+Lt)/2) - (1/rk_bar[k]) * sum( rk * log(1 + (1/2) * (mahaly[,k] + mahalt[,k]))))); ## potentielle erreur?passage difficile if(verb>=3) print(paste("K",k,"-> alpha=",ph$alpha[k]));} else {ph$alpha = phi$alpha;} } if( ! is.character(cstr$pi) || is.null(cstr$pi)) {if(! is.null(cstr$pi)) {ph$pi=cstr$pi;}} else { if (!is.null(cstr$pi) && cstr$pi[1]=='*') {ph$pi=1/K*rep(1,K);} else {stop(' ERROR: invalid constraint on pi.');} } return(list(ph=ph,th=th)) } remove_empty_clusters = function(th1,phi,cstr1,ec){ th=th1; ph=phi; cstr=cstr1; if(sum(ec) != length(ec)) {if( !is.null(cstr$ct) && !is.character(cstr$ct)) cstr$ct=cstr$ct[,ec]; if(!is.null(cstr$cw) && !is.character(cstr$cw)) cstr$cw=cstr$cw[,ec]; if(!is.null(cstr$Gammat) && !is.character(cstr$Gammat)) cstr$Gammat=cstr$Gammat[,,ec]; if(!is.null(cstr$Gammaw) && !is.character(cstr$Gammaw)) cstr$Gammaw=cstr$Gammaw[,,ec]; if(!is.null(cstr$pi) && !is.character(cstr$pi)) cstr$pi=cstr$pi[,ec]; if(!is.null(cstr$A) && !is.character(cstr$A)) cstr$A=cstr$A[,,ec]; if(!is.null(cstr$b) && !is.character(cstr$b)) cstr$b=cstr$b[,ec]; if(!is.null(cstr$Sigma) && !is.character(cstr$Sigma)) cstr$Sigma=cstr$Sigma[,,ec]; th$c=th$c[,ec]; th$Gamma=th$Gamma[,,ec]; ph$pi=ph$pi[ec]; th$A=th$A[,,ec]; th$b=th$b[,ec]; th$Sigma=th$Sigma[,,ec]; } return(list(th=th,ph=ph,cstr=cstr)) } #% ==========================EM initialization============================== Lt=nrow(tapp) L=Lt+Lw; D = nrow(yapp) ; N = ncol(yapp); if(verb>=1) {print('EM Initializations');} if(!is.null(in_theta) & !is.null(in_phi)) { theta=in_theta; ph = in_phi; K=length(ph$pi); if(is.null(cstr$cw)) {cstr$cw=matrix(0,L,K);} # % Default value for cw if(is.null(cstr$Gammaw)) { cstr$Gammaw=array(diag(Lw),dim=c(Lw,Lw,K));} #% Default value for Gammaw tmp = ExpectationZU(tapp,yapp,theta,verb); r = tmp$r ; ec = tmp$ec ; tmp = remove_empty_clusters(theta,cstr,ec); theta = tmp$theta ; cstr = tmp$cstr ; tmp = ExpectationW(tapp,yapp,theta,verb); muw = tmp$muw Sw = tmp$Sw if(verb>=1) print(""); } else {if(is.null(in_r)){ # en commentaire dans le code original : pourquoi? # % Initialise posteriors with K-means + GMM on joint observed data # % [~,C] = kmeans([t;y]',in_K); # % [~, ~, ~, r] = emgm([t;y], C', 3, verb); # % [~, ~, ~, r] = emgm([t;y], in_K, 3, verb); r = emgm(rbind(tapp,yapp), in_K, 1000, verb=verb)$R; # % [~,cluster_idx]=max(r,NULL,2); # % fig=figure;clf(fig); # % scatter(t(1,:),t(2,:),200,cluster_idx','filled'); # % weight=model.weight; # % K=length(weight); # % mutt=model.mu(1:Lt,:); # % Sigmatt=model.Sigma[1:Lt,1:Lt,]; # % normr=zeros(N,1); # % r=zeros(N,K); # % for k=1:K # % r[,k]=weight[k]*mvnpdf(t',mutt[,k]',reshape(Sigmatt[,,k],Lt,Lt)); # % normr=normr+reshape(r[,k],N,1); # % end # % r=sweep(@rdivide,r,normr); # % fig=figure;clf(fig); # % [~,classes]=max(r,NULL,2); % Nx1 # % scatter(y(1,:),y(2,:),200,classes','filled'); } else {r=in_r$R;} # %Initializing parameters phi = list() phi$pi = colMeans(r);# 1 x K u = matrix(1,N,in_K) ; K = ncol(r); #% extracting K, the number of affine components phi$alpha = rep(20,K); mahalt=NULL; mahaly=NULL; if(Lw==0) {Sw=NULL; muw=NULL;} else { # % Start by running an M-step without hidden variables (partial # % theta), deduce Awk by local weighted PCA on residuals (complete # % theta), deduce r, muw and Sw from E-steps on complete theta. tmp = Maximization_hybrid(tapp,yapp,r,u,phi,NULL,NULL,NULL,NULL,cstr,verb); theta = tmp$th phi = tmp$ph K=length(phi$pi); if(is.null(cstr$cw)) {cstr$cw=matrix(0,Lw,K);} theta$c=rbind(theta$c,cstr$cw[,1:K]); Gammaf=array(0,dim=c(L,L,K)); Gammaf[1:Lt,1:Lt,]=theta$Gamma; if(is.null(cstr$Gammaw)) {cstr$Gammaw=array(diag(Lw),dim=c(Lw,Lw,K));} Gammaf[(Lt+1):L,(Lt+1):L,]=cstr$Gammaw[,,1:K]; #%LwxLwxK theta$Gamma=Gammaf; # % Initialize Awk with local weighted PCAs on residuals: Aw=array(0,dim=c(D,Lw,K)); for (k in 1:K) {rk_bar=sum(r[,k]); bk=theta$b[,k]; w=sweep(yapp,1,bk,"-"); #%DxN if(Lt>0) {Ak=theta$A[,,k]; w=w-Ak%*%tapp;} w=sweep(w,2,sqrt(r[,k]/rk_bar),"*"); #%DxN C=tcrossprod(w); #% Residual weighted covariance matrix tmp = eigen(C) ##svd? ##### j'avais ajoute des lignes avce des seuillages, a ajouter en R aussi? U = tmp$vectors[,1:Lw] Lambda = tmp$values[1:Lw] #% Weighted residual PCA U:DxLw #% The residual variance is the discarded eigenvalues' mean sigma2k=(sum(diag(C))-sum(Lambda))/(D-Lw); #scalar sigma2k[sigma2k < 1e-8] = 1e-8; theta$Sigma[,,k]=sigma2k * diag(D); Lambda[Lambda< 1e-8] = 1e-8; Aw[,,k]=U%*%sqrt(diag(Lambda,ncol=length(Lambda),nrow=length(Lambda))-sigma2k*diag(Lw));} theta$A=abind(theta$A,Aw,along=2); #%DxLxK tmp = ExpectationZU(tapp,yapp,theta,phi,verb); r =tmp$r ; u = tmp$u; ec=tmp$ec; mahalt = tmp$mahalt; mahaly = tmp$mahaly; tmp = remove_empty_clusters(theta,phi,cstr,ec); theta = tmp$th ; phi = tmp$ph; cstr = tmp$cstr ; tmp = ExpectationW(tapp,yapp,u,theta,phi,verb); muw = tmp$muw ; Sw = tmp$Sw ; if(verb>=1) print(""); }} # %===============================EM Iterations============================== if(verb>=1) print(' Running EM'); LL = rep(-Inf,maxiter); iter = 0; converged= FALSE; while ( !converged & iter<maxiter) {iter = iter + 1; if(verb>=1) print(paste(' Iteration ',iter,sep="")); # % =====================MAXIMIZATION STEP=========================== tmp = Maximization_hybrid(tapp,yapp,r,u,phi,muw,Sw,mahalt,mahaly,cstr,verb); theta = tmp$th #print(theta$c)###c'est ici que la valeur de c plante phi = tmp$ph # % =====================EXPECTATION STEPS=========================== tmp = ExpectationZU(tapp,yapp,theta,phi,verb); r =tmp$r ; u = tmp$u LL[iter] =tmp$LL; if (verb>=1) {print(LL[iter]);} ec=tmp$ec mahalt = tmp$mahalt mahaly = tmp$mahaly tmp =remove_empty_clusters(theta,phi,cstr,ec); theta = tmp$th phi = tmp$ph cstr =tmp$cstr tmp = ExpectationW(tapp,yapp,u,theta,phi,verb); muw = tmp$muw Sw = tmp$Sw if(iter>=3) {deltaLL_total=max(LL[1:iter])-min(LL[1:iter]); deltaLL=LL[iter]-LL[iter-1]; converged=(deltaLL < (0.001*deltaLL_total)); } if(verb>=1) print(""); } # %%% Final log-likelihood %%%% LLf=LL[iter]; phi$r = r; if (cstr$Sigma == "i") {nbparSigma = 1} if (cstr$Sigma == "d") {nbparSigma = D} if (cstr$Sigma == "") {nbparSigma = D*(D+1)/2} if (cstr$Sigma == "*") {nbparSigma = D*(D+1)/(2*K)} if (!is.null(cstr$Gammat)){ if (cstr$Gammat == "i") {nbparGamma = 1} if (cstr$Gammat == "d") {nbparGamma = Lt} if (cstr$Gammat == "") {nbparGamma = Lt*(Lt+1)/2} if (cstr$Gammat == "*") {nbparGamma = Lt*(Lt+1)/(2*K)} } if (is.null(cstr$Gammat)){ nbparGamma = Lt*(Lt+1)/2 } theta$nbpar = (in_K-1) + in_K*(1 + D*L + D + Lt + nbparSigma + nbparGamma) # % =============================Final plots=============================== if(verb>=1) print(paste('Converged in ',iter,' iterations',sep="")); return(list(theta=theta,phi=phi,LLf=LLf,LL=LL[1:iter])) }
/scratch/gouwar.j/cran-all/cranData/xLLiM/R/sllim.R
sllim_inverse_map = function(y,theta,verb=0){ # %%%%%%%%%%%%%%%%% Inverse Mapping from Gllim Parameters %%%%%%%%%%%%%%%%%%% # %%%% Author: Antoine Deleforge (July 2012) - [email protected] %%% # %% Converted to R: Emeline Perthame (2016) - [email protected] %%% # % Description: Map N observations y using the inverse conditional # % expectation E[x|y;theta] of the sllim model with parameters theta. # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% # %%%% Input %%%% # % - y (DxN) % Input observations to map # % - theta (struct) % Gllim model parameters # % - theta.c (LxK) % Gaussian means of X's prior # % - theta.Gamma (LxLxK) % Gaussian covariances of X's prior # % - theta.pi (1xK) % Gaussian weights of X's prior # % - theta.A (DxLxK) % Affine transformation matrices # % - theta.b (DxK) % Affine transformation vectors # % - theta.Sigma (DxDxK) % Error covariances # % - verb {0,1,2} % Verbosity (def 1) # %- phi (struct) % Estimated parameters # % - phi.pi (1xK) % t weights of X # % - phi.alpha (1xK) % Arellano-Valle and Bolfarine's Generalized t # % distrib - alpha parameter # % - phi.gamma (1xK) % Arellano-Valle and Bolfarine's Generalized t # % distrib - gamma parameter # %%%% Output %%%% # % - x_exp (LxN) % Posterior mean estimates E[xn|yn;theta] # % - alpha (NxK) % Weights of the posterior GMMs # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% phi = theta$phi theta = theta$theta D = nrow(y) ; N = ncol(y) ; L = nrow(theta$c) ; K = ncol(theta$c) ; # % ======================Inverse density parameters========================= if(verb>=1) print('Compute K projections to X space and weights') proj=array(NaN,dim=c(L,N,K)); logalpha=matrix(0,N,K); for (k in 1:K){ if(verb>=2) print(paste("k=",k,sep="")); if(verb>=2) print('AbcG '); if (L==1) {Ak=theta$A[,,k,drop=FALSE];} else {Ak=theta$A[,,k];} # % DxL bk=theta$b[,k]; # % Dx1 Sigmak=theta$Sigma[,,k]; # %DxD ## OK if (L==1) {ck=theta$c[,k,drop=FALSE];} else {ck=theta$c[,k];} # % Lx1 Gammak=theta$Gamma[,,k]; # % LxL ## OK if(verb>=2) print('cks '); cks=Ak%*%ck+bk; ## OK #####theta_star.c(:,k) = cks; if(verb>=2) print('Gks '); Gammaks=Sigmak+Ak%*%tcrossprod(Gammak,Ak); ## OK ######theta_star.Gamma(:,:,k) = Gammaks; if(verb>=2) print('iSks '); iSk = solve(Sigmak) #diag(1/diag(Sigmak)) invSigmaks2=diag(L)+Gammak%*%crossprod(Ak, iSk)%*%Ak; ######theta_star.Sigma(:,:,k) = invSigmaks2; if(verb>=2) print('Aks '); Aks=solve(invSigmaks2,Gammak)%*%crossprod(Ak, iSk) ######theta_star.A(:,:,k) = Aks; if(verb>=2) print('bks '); bks= solve(invSigmaks2) %*% (ck-Gammak%*%crossprod(Ak, iSk%*%bk)) ######theta_star.b(:,k) = bks; if(verb>=2) print('projections '); proj[,,k]=sweep(Aks%*%y,1,bks,"+"); if(verb>=2) print('logalpha '); p = is.positive.definite(Gammaks) if (!p) {sldR = -Inf;} else {R = chol(Gammaks) ; sldR=sum(log(diag(R)));} logalpha[,k]=log(phi$pi[k])+ logtpdfL(sum(log(diag(R))),mahalanobis_distance(y,cks,Gammaks),phi$alpha[k], D); if(verb>=2) print(''); } den=logsumexp(logalpha,2); logalpha= sweep(logalpha,1,den,"-") alpha=exp(logalpha); x_exp = lapply(1:L,function(l) proj[l,,]*alpha) x_exp = lapply(x_exp,rowSums) x_exp = do.call(rbind, x_exp) return(list(x_exp=x_exp,alpha=alpha)) }
/scratch/gouwar.j/cran-all/cranData/xLLiM/R/sllim_inverse_map.R
thresholdAbsSPath2 = function (Sabs) { labelsPath <- list() valThres <- Sabs[upper.tri(Sabs)] orderValue <- c(0,valThres[order(valThres)]) labelsPath <- lapply(orderValue,function(lambdaR){ E <- Sabs E[Sabs > lambdaR] <- 1 E[Sabs < lambdaR] <- 0 E[Sabs == lambdaR] <- 0 goutput <- graph.adjacency(E, mode = "undirected", weighted = NULL) return(clusters(goutput)$membership) }) return(list(partitionList = unique(labelsPath), lambdaPath = unique(orderValue))) }
/scratch/gouwar.j/cran-all/cranData/xLLiM/R/thresholdAbsPath2.R
EwLw2Series <- function(x, ew = 0.5, lw = NULL) { if (is.null(lw)) { lw <- ew } n <- length(x$limits) - 1 x$limits.ew <- x$limits.lw <- vector(mode = "integer", length = n) message(x$name) for (i in 1:n) { message(paste(x$years[i + 1], i)) EwLw <- EwLw2Years(x$profile, x$limits[i + 0:1], ew = ew, lw = lw) x$limits.ew[i] <- EwLw[1] x$limits.lw[i] <- EwLw[2] } x$trw <- cbind( x$trw, data.frame(x$limits.ew - x$limits[1:n], x$limits[-1] - x$limits.lw) ) colnames(x$trw) <- paste(x$name, c("trw", "ew", "lw"), sep = ".") return(x) }
/scratch/gouwar.j/cran-all/cranData/xRing/R/EwLw2Series.R
EwLw2Years <- function(profile, limits, ew = 0.5, lw = NULL) { if (is.null(lw)) { lw <- ew } profile <- profile[limits[1]:limits[2]] profile.std <- profile - min(profile) profile.std <- profile.std / max(profile.std) minDensMaxDens <- minDmaxD(profile.std) minDens <- minDensMaxDens[1] if (is.na(minDensMaxDens[1])) { minDensMaxDens[1] <- minDens <- max(which(profile.std == min(profile.std[1:round((diff(limits) + 1) * 2 / 3)]))) } if (is.na(minDensMaxDens[2])) { minDensMaxDens[2] <- maxDens <- min(which(profile.std == max(profile.std[-1:-round((diff(limits) + 1) * (2 / 3))]))) } maxDens <- which(profile.std == max(profile.std[-1:-minDens])) # - 1 maxDens <- min(maxDens, minDensMaxDens[2], na.rm = TRUE) firstValley <- min(minDens, findValleys(profile.std)) profile.std[1:firstValley] <- min(profile.std[1:firstValley]) profile.std <- profile.std - min(profile.std[1:maxDens]) profile.std <- profile.std / max(profile.std) profile.std[profile.std < 0] <- 0 getEwLw(profile.std, limits, maxDens = maxDens, ew = ew, lw = lw ) }
/scratch/gouwar.j/cran-all/cranData/xRing/R/EwLw2Years.R
# # @importFrom graphics polygon # abline1 <- function(v = NULL, col = 2, y = c(-2000, 0, 0, -2000)) { n <- length(v) col1 <- col if (length(col) < n) { col1 <- rep(col, n) } if (!is.null(v)) { for (vi in 1:length(v)) { graphics::polygon( # x = v[vi] + c(-.5, -.5, .5, .5), x = v[vi] + c(0, 0, 1, 1), y = y, col = col1[vi], border = col1[vi] ) } } }
/scratch/gouwar.j/cran-all/cranData/xRing/R/abline1.R
#' @name addRing #' @title Add Tree-Ring Border(s) #' @description Add a tree-ring border by defining the position of the new border #' @param object an object of class "xRingList" or "xRing" #' @param x the position (number of the resp. pixel(s)) to set the new tree-ring border #' @param series the name of the series to be changed when the \code{object} is "xRingList", by default is \code{NULL} #' @return a "xRing" or "xRingList" object with a tree-ring border added at the position \code{x} for the series given by \code{series} argument #' @export #' @examples #' #' data(PaPiRaw) #' data(PaPiSpan) #' PaPi <- detectRings(PaPiRaw, PaPiSpan) #' plot(PaPi$"AFO1001a") #' PaPi$AFO1001a <- removeRing(PaPi$AFO1001a, 47) #' plot(PaPi$"AFO1001a") #' PaPi <- addRing(PaPi, series = "AFO1001a", x = 47) #' plot(PaPi$"AFO1001a") #' addRing <- function(object, x, series = NULL) { if (!any(c(is.xRing(object), is.xRingList(object)))) { stop("Use only with \"xRingList\" and \"xRing\" objects.") } if (is.xRingList(object) && is.null(series)) { stop("please provide the argument \"series\" for objects of class \"xRingList\"") } if (!is.null(series)) { object[[series]] <- addRingSeries(object[[series]], x) return(object) } addRingSeries(object, x) }
/scratch/gouwar.j/cran-all/cranData/xRing/R/addRing.R
addRingSeries <- function(xray, x) { for (i in 1:length(x)) { xray$limits <- limits <- sort(c(xray$limits, round(x[i]))) xray$years <- years <- c(xray$years[1] - 1, xray$years) xray$trw <- as.data.frame(matrix(diff(limits), dimnames = list(years[-1], xray$name) )) } xray }
/scratch/gouwar.j/cran-all/cranData/xRing/R/addRingSeries.R
as.xRing <- function(x) { # x <- x[c( # "profile.raw", # "profile.smooth", # "profile", # "trw", # "density", # "limits.problems", # "limits", # "limits.ew", # "limits.lw", # "years", # "scale", # "span", # "name" # )] x <- x[!is.na(names(x))] class(x) <- c("xRing", "list") x }
/scratch/gouwar.j/cran-all/cranData/xRing/R/as.xRing.R
# helper #' @export "[.xRingList" <- function(x, i, ...) { r <- NextMethod("[") class(r) <- class(x) r } as.xRingList <- function(x) { x <- lapply(x, as.xRing) class(x) <- c("xRingList", "list") x }
/scratch/gouwar.j/cran-all/cranData/xRing/R/as.xRingList.R
border <- function(x, k = 3, threshold = 200) { x.dif <- rollMax(x, k = k, fill = NA, align = "right" ) + rollMax(-x, k = k, fill = NA, align = "center" ) x0 <- which(x.dif > threshold) breaks <- unique(c(1, which(dif(x0) != 1), length(x0))) out <- NULL if (length(breaks) > 1) { for (i in 2:length(breaks)) { win <- x0[breaks[(i - 1)]:(breaks[(i)] - 1)] if (length(win) > 1) { win.dif <- dif(x[win]) out <- c(out, win[which(win.dif == min(win.dif, na.rm = TRUE))]) } } } floor(out) }
/scratch/gouwar.j/cran-all/cranData/xRing/R/border.R
#' @name stepIncrease #' @title Calculate the Steps Thickness of the Calibration Wedge #' @description convenience function to calculate the thickness of each steps of the calibration wedge for wedges with continous step increase. #' #' @param step.increase height increase per wedge step #' @param nsteps total number of steps (the first step has the thickness of 0 - the area beside the wedge. Mention that when setting nsteps) #' #' @return a numeric vector #' @export #' stepIncrease <- function(step.increase = 0.24, nsteps = 7) { step.increase * (seq_len(nsteps) - 1) } #' @title Fit a Calibration Curve #' @description #' Fit a model to calibrate a film from X-ray densitometry. #' @param grayvalues a numeric vector containing the gray values of the steps of the calibration wedge at various thicknesses given by the argument `thickness` #' @param thickness a vector specifying the thickness of the calibration wedge at each step. #' @param density the density of the reference material #' @param plot if TRUE the calibration model is displayed #' @param ... further arguments to be passed to \link{loess} #' @return an object of class `loess` representing the film calibration #' @seealso #' \link{getSteps} #' @export #' @examples #' if (interactive()) { #' # read a sample file #' im <- imRead(file = system.file("img", "AFO1046.1200dpi.png", package = "xRing")) #' #' # display the image #' imDisplay(im) #' #' # get the grayvalues from the calibration wedge on the film #' grayvalues <- getSteps(im, 7) #' #' # calibrate the film by fitting a model: #' calibration <- fitCalibrationModel(grayvalues, #' thickness = stepIncrease(0.24, 7), #' density = 1.2922, #' plot = TRUE #' ) #' } #' fitCalibrationModel <- function(grayvalues, thickness = stepIncrease(0.24, 7), density = 1.2922, plot = TRUE, ...) { # input validation if (!(is.numeric(grayvalues) && is.numeric(thickness) && (length(grayvalues) == length(thickness)))) { stop("`grayvalues` and `thickness` need to be provided as numeric vectors of the same length") } if (!((length(density)) == 1 && is.numeric(density))) { stop("`density` must be provided as a numeric vector of length 1") } # main function optical_density <- density * thickness cal_film <- loess(optical_density ~ grayvalues, ...) if (plot) { rng_grayvalues <- range(grayvalues) xrange <- seq(rng_grayvalues[[1]], rng_grayvalues[[2]], length.out = 1000) plot(optical_density ~ grayvalues) lines(xrange, predict(cal_film, newdata = c(grayvalues = xrange)), col = "red") } cal_film } #' @title Calibrate Film #' @description #' Convenience function to do the whole calibration of a densitometry image in one function call internally calling \link{getSteps} and \link{fitCalibrationModel} #' @param im a grayscale image #' @param thickness a vector specifying the thickness of the calibration wedge at each step #' @param density the density of the reference material (i.e. the calibration wedge) #' @param auto logical. If TRUE, automatic detection of the steps given a line is carried out. Use with care #' @param nPixel if `auto = TRUE`: number of pixels gives the line width #' @param plot if TRUE the calibration model is displayed #' @param plotAuto if TRUE the automatic detection of the grayscale values is displayed #' @param ... further arguments to be passed to \link{loess} #' @return an object of class `loess` representing the film calibration #' @seealso #' \link{getSteps} #' @export #' @examples #' if (interactive()) { #' # read a sample file #' im <- imRead(file = system.file("img", "AFO1046.1200dpi.png", package = "xRing")) #' #' # display the image #' imDisplay(im) #' #' # calibrate the film: #' calibration <- calibrateFilm(im, #' thickness = stepIncrease(0.24, 7), #' density = 1.2922, #' plot = TRUE #' ) #' } #' calibrateFilm <- function(im, thickness = stepIncrease(0.24, 7), density = 1.2922, plot = TRUE, auto = FALSE, nPixel = 50, plotAuto = FALSE, ...) { nSteps <- length(thickness) grayvalues <- getSteps(im, nSteps, auto = auto, nPixel = nPixel) fitCalibrationModel( grayvalues, thickness = thickness, density = density, plot = plot, ... ) }
/scratch/gouwar.j/cran-all/cranData/xRing/R/calibrateFilm.R
calibrateSeries <- function(profile, thickness, calibration) { if (NCOL(profile) == 2) { profile <- profile[, 2] } if (is.list(calibration)) { calibration <- loess(calibration$y ~ calibration$x) } profile <- pmax(pmin(profile, max(calibration$x)), min(calibration$x)) optical_density <- predict(calibration, newdata = profile) if (is.list(optical_density)) { optical_density <- optical_density$y } density <- optical_density / thickness density }
/scratch/gouwar.j/cran-all/cranData/xRing/R/calibrateSeries.R
#' @title Combine Fragments #' @description #' This function combines fragments by series #' @param x an "xRingList" object #' @param frag integer, defines the character position within the series name that identifies fragments. If \code{NULL} the function considers series with names having one more character as fragments #' @return an object of class "xRingList" with merged fragments #' @export #' @examples #' #' data(PaPiRaw) #' data(PaPiSpan) #' PaPi <- detectRings(PaPiRaw, PaPiSpan) #' PaPi.merge <- combineFrag(PaPi, frag = 9) #' combineFrag <- function(x, frag = NULL) { if (!(c("xRingList") %in% class(x))) { stop("Use only with \"xRingList\" objects.") } seriesName <- names(x) nNameLength <- unique(nchar(seriesName)) if (length(nNameLength) == 1) { message("Series without fragments") return(x) } if (is.null(frag)) { frag <- nNameLength[length(nNameLength) - 1] + 1 } coresNames <- substr(seriesName, 1, frag - 1) uniqueSeries <- unique(coresNames) out <- vector("list", length(uniqueSeries)) names(out) <- uniqueSeries for (i in unique(coresNames)) { out[i] <- putTogether(x[coresNames %in% i], newName = i) } class(out) <- c("xRingList", "list") out }
/scratch/gouwar.j/cran-all/cranData/xRing/R/combineFrag.R
#' @title Correct Tree-Ring Borders Interactively #' @description A Graphical User Interface (GUI) to correct tree-ring borders #' @param x an \code{xRingList} object #' @param chrono a data.frame with a reference chronology, if \code{NULL} a reference chronology is calculated using tree-ring width series from \code{x} #' @details #' This function uses the \code{tkRplot} function (tkRplotR package) to interact with X-ray microdensity profiles. #' @return an \code{xRingList} object #' @import tkRplotR #' @importFrom stats cor #' @importFrom stats na.omit #' @importFrom grDevices dev.off #' @export #' @examples #' if (interactive()) { #' data(PaPiRaw) #' data(PaPiSpan) #' PaPi <- detectRings(PaPiRaw, PaPiSpan) #' PaPiCorrect <- correctRings(PaPi) #' } #' correctRings <- local({ parent <- NULL flagZoom <- FALSE flagMotion <- FALSE done <- tclVar(0) xOriginal <- NULL ptsX <- c() ptsX0 <- c() ptsX1 <- c() series <- 1 nSeries <- NULL selectSeries <- NULL x0 <- 0 x1 <- NULL function(x, chrono = NULL) { tclValue2R <- function(x, numeric = TRUE) { if (numeric) { return(as.numeric(strsplit(tclvalue(x), " ")[[1]])) } # if (numeric) as.numeric(unlist(strsplit(tclvalue(x), split = ' '))) strsplit(tclvalue(x), " ")[[1]] } usr2tk <- function(x, y = NULL) { c((x - getVariable("xCoef")[2]) / getVariable("xCoef")[1]) } if (!any(c("xRingList") %in% class(x))) { stop("Use only with \"xRingList\" objects.") } if (is.null(x[[1]]$years)) { stop("Please first use the detectRings function!") } if (is.null(chrono)) { chrono <- as.data.frame(rowMeans(getTrw(x), na.rm = TRUE)) } done <<- tclVar(0) xOriginal <<- x ptsX <<- c() ptsX1 <<- c() series <<- 1 nSeries <<- length(x) selectSeries <<- x[[series]] x0 <<- 0 x1 <<- length(selectSeries$profile.raw) try(tkdestroy(parent), silent = TRUE) InsideCanvas <- function(x) { pmin(pmax(x, getVariable("usr")[1] + 1), getVariable("usr")[2]) } InsideCanvasTkX <- function(x) { pmin(pmax(x, 1), getVariable("tkRplotRcanvasWidth") - 2) } PreviousSeries <- function() { ptsX <<- c() tkdelete(parent$env$canvas, "TK_TMP") series <<- max(1, series - 1) selectSeries <<- x[[series]] x0 <<- 0 x1 <<- length(selectSeries$profile.raw) tkRreplot(parent) } NextSeries <- function() { ptsX <<- c() tkdelete(parent$env$canvas, "TK_TMP") series <<- min(nSeries, series + 1) selectSeries <<- x[[series]] x0 <<- 0 x1 <<- length(selectSeries$profile.raw) tkRreplot(parent) } GoTo <- function() { seriesID <- c() series.name <- modalDialog(question = "Go to the next series:") if (length(series.name) != 0) { if (series.name %in% as.character(1:nSeries)) { seriesID <- as.integer(series.name) series.name <- names(x)[seriesID] } else { seriesID <- which(names(x) == series.name) } } if (!length(seriesID)) { # The user click the cancel button or seriesID is not a valid name invisible(tkmessageBox( message = "please select a series", icon = "warning", type = "ok" )) } else { series <<- seriesID ptsX <<- c() tkdelete(parent$env$canvas, "TK_TMP") selectSeries <<- x[[series]] x0 <<- 0 x1 <<- length(selectSeries$profile.raw) tkRreplot(parent) } } AddRing <- function() { if (!is.null(ptsX)) { ptsX <- InsideCanvas(ptsX) x <<- addRing(x, unique(ptsX), series) selectSeries <<- x[[series]] tkRreplot(parent) ptsX <<- c() tkdelete(parent$env$canvas, "TK_TMP") } } RemoveRing <- function() { if (!is.null(ptsX)) { x <<- removeRing(x, ptsX, series) selectSeries <<- x[[series]] tkRreplot(parent) ptsX <<- c() tkdelete(parent$env$canvas, "TK_TMP") } } SetLastYear <- function() { NOT_VALID_YEAR <- FALSE last.year <- modalDialog(question = " Last year:", entryInit = "", entryWidth = 5) last.year <- AsNumeric(last.year) if (!length(last.year)) { NOT_VALID_YEAR <- TRUE } else { if (!is.na(last.year)) { selectSeries <<- x[[series]] <<- setLastYear(x[[series]], last.year) ptsX <<- c() tkdelete(parent$env$canvas, "TK_TMP") } else { NOT_VALID_YEAR <- TRUE } } if (NOT_VALID_YEAR) { return(invisible( tkmessageBox( message = "Not a valid year", icon = "warning", type = "ok" ) )) } tkRreplot(parent) } Zoom <- function() { if (length(ptsX) == 0) { x0 <<- 0 x1 <<- length(selectSeries$profile.raw) tkRreplot(parent) } else { if (length(ptsX) == 1) { tkmessageBox( message = "2 limits are need to zoom in", icon = "warning", type = "ok" ) } else { x.limits <- range(ptsX) x0 <<- x.limits[1] x1 <<- x.limits[2] ptsX <<- ptsX <- c() selectSeries <<- x[[series]] tkRreplot(parent) tkdelete(parent$env$canvas, "TK_TMP") } } } GetOriginalSeries <- function() { if (!identical(x[[series]], xOriginal[[series]])) { selectSeries <<- x[[series]] <<- xOriginal[[series]] tkRreplot(parent) } ptsX <<- c() tkdelete(parent$env$canvas, "TK_TMP") Zoom() } Clear <- function(...) { ptsX <<- c() tkdelete(parent$env$canvas, "TK_TMP") } Save <- function() { tclvalue(done) <- 1 } Cancel <- function() { tclvalue(done) <- 2 } Close <- function() { ans <- tk_messageBox("yesnocancel", "Save changes?") if (ans == "cancel") { return() } tkdestroy(parent) if (ans == "yes") { tclvalue(done) <- 1 } if (ans == "no") { tclvalue(done) <- 2 } } AddButton <- function(parent, name, fun) { for (i in 1:length(name)) { tkpack( tkbutton( parent, text = name[i], command = fun[[i]], relief = "solid" ), fill = "x", pady = 2, padx = 4 ) } } parent <<- tktoplevel(width = 1, height = 1) tkwm.withdraw(parent) parent$env$fL <- tkframe(parent, padx = 3) tktitle(parent) <- "CorrectRings" tkpack(parent$env$fL, side = "left", fill = "y") parent <- tkRplot(parent, function(...) { plotRings( selectSeries, xlim = c(x0, x1), id = series, corr = round(cor(na.omit( mergeRwl(chrono, selectSeries$trw) ))[1, 2], 2) ) }) tkconfigure(parent$env$canvas, cursor = "cross") AddButton( parent$env$fL, c( "Go to", "Previous", "Next", "Add ring", "Remove Ring", "Zoom", "Last Year", "Reset", "Clear", "Close" ), list( GoTo, PreviousSeries, NextSeries, AddRing, RemoveRing, Zoom, SetLastYear, GetOriginalSeries, Clear, Close ) ) tkbind(parent$env$canvas, "<Button-1>", function(W, x, y, ...) { ptsX0 <<- x ptsX <<- c(ptsX, tk2usr(x, y)[1]) yLimits <- (1 - getVariable("plt")[3:4]) * getVariable("tkRplotRcanvasHeight") roi <- tkcreate( W, "line", c(x, yLimits[1], x, yLimits[2]), fill = "#ff0000", width = 2, dash = "- -" ) tkaddtag(W, "TK_TMP", "withtag", roi) flagZoom <<- TRUE }) tkbind(parent$env$canvas, "<B1-ButtonRelease>", function(W, x, y, ...) { tkconfigure(parent$env$canvas, cursor = "cross") ptsX1 <<- tk2usr(x, y)[1] if (!flagMotion) { flagZoom <<- FALSE ptsX <- InsideCanvas(c(ptsX, ptsX1)) return() } if (flagZoom) { flagZoom <<- FALSE tkdelete(W, "TK_TMP_MOVE") if ((ptsX1 - ptsX[1]) < 0 & length(ptsX) == 1) { ptsX <<- c() tkdelete(W, "TK_TMP") Zoom() return() } else { if (identical(ptsX1, ptsX)) { ptsX <<- InsideCanvas(ptsX) return() } if (abs(ptsX1 - ptsX[1]) < 10) { tkdelete(W, "TK_TMP") ptsX <<- c() } } if (length(ptsX) == 1) { tkdelete(W, "TK_TMP") ptsX <<- InsideCanvas(c(ptsX, ptsX1)) Zoom() } } flagZoom <<- FALSE }) tkbind(parent$env$canvas, "<B1-Motion>", function(W, x, y, ...) { x <- InsideCanvasTkX(as.numeric(x)) flagMotion <<- FALSE if (length(ptsX) == 1 & flagZoom) { tkconfigure(parent$env$canvas, cursor = "hand2") flagMotion <<- TRUE tkdelete(W, "TK_TMP_MOVE") yLimits <- (1 - getVariable("plt")[3:4]) * getVariable("tkRplotRcanvasHeight") roi <- tkcreate( W, "line", c( ptsX0, yLimits[1] + 2, ptsX0, yLimits[2] - 2, x, yLimits[2] - 2, x, yLimits[1] + 2, ptsX0, yLimits[1] + 2 ), fill = "#ff0000", width = 2, dash = "- -", joinstyle = "miter", capstyle = "butt" ) tkaddtag(W, "TK_TMP_MOVE", "withtag", roi) } }) RefreshLinesPosition <- function(W, ptsX) { xNewPos <- usr2tk(ptsX) if (length(xNewPos) > 0) { tkdelete(W, "TK_TMP") yLimits <- (1 - getVariable("plt")[3:4]) * getVariable("tkRplotRcanvasHeight") for (i in 1:length(xNewPos)) { x <- xNewPos[i] roi <- tkcreate( W, "line", c(x, yLimits[1], x, yLimits[2]), fill = "#ff0000", width = 2, dash = "- -" ) tkaddtag(W, "TK_TMP", "withtag", roi) } } } tkbind(parent, "<Enter>", function() { width <- as.numeric(.Tcl(paste("winfo width", parent$env$canvas))) height <- as.numeric(.Tcl(paste("winfo height", parent$env$canvas))) widthPrevious <- parent$env$width heightPrevious <- parent$env$height if (abs(width - widthPrevious) > 0 | abs(height - heightPrevious) > 0) { parent$env$height <- height parent$env$width <- width tkpack.forget(parent$env$canvas) tkRreplot(parent) tkpack(parent$env$canvas, expand = 1, fill = "both" ) } setVariable("tkRplotRcanvasWidth", width) setVariable("tkRplotRcanvasHeight", height) setVariable("usr", parent$env$usr) setVariable("plt", parent$env$plt) parent$env$canvas$coef <- getCoef() RefreshLinesPosition(parent$env$canvas, ptsX) }) tkbind(parent, "<FocusIn>", function() { width <- as.numeric(.Tcl(paste("winfo width", parent$env$canvas))) height <- as.numeric(.Tcl(paste("winfo height", parent$env$canvas))) widthPrevious <- parent$env$width heightPrevious <- parent$env$height if ((abs(width - widthPrevious) > 0) | (abs(height - heightPrevious) > 0)) { parent$env$height <- height parent$env$width <- width tkpack.forget(parent$env$canvas) tkRreplot(parent) tkpack(parent$env$canvas, expand = 1, fill = "both" ) } setVariable("tkRplotRcanvasWidth", width) setVariable("tkRplotRcanvasHeight", height) setVariable("usr", parent$env$usr) setVariable("plt", parent$env$plt) parent$env$canvas$coef <- getCoef() RefreshLinesPosition(parent$env$canvas, ptsX) }) tkbind(parent, "<Expose>", function() { width <- as.numeric(.Tcl(paste("winfo width", parent$env$canvas))) height <- as.numeric(.Tcl(paste("winfo height", parent$env$canvas))) widthPrevious <- parent$env$width heightPrevious <- parent$env$height if ((abs(width - widthPrevious) > 0) | (abs(height - heightPrevious) > 0)) { parent$env$height <- height parent$env$width <- width tkpack.forget(parent$env$canvas) tkRreplot(parent) tkpack(parent$env$canvas, expand = 1, fill = "both" ) } setVariable("tkRplotRcanvasWidth", width) setVariable("tkRplotRcanvasHeight", height) setVariable("usr", parent$env$usr) setVariable("plt", parent$env$plt) parent$env$canvas$coef <- getCoef() RefreshLinesPosition(parent$env$canvas, ptsX) }) tkwm.protocol(parent, "WM_DELETE_WINDOW", Close) tkbind(parent, "<q>", Close) tkbind(parent, "<Control-KeyPress-z>", Clear) tkbind(parent, "<Escape>", Close) tkwm.minsize(parent, tclvalue(tkwinfo("reqheight", parent)), tclvalue(tkwinfo("reqheight", parent$env$fL))) on.exit({ if (tclvalue(done) == 1) { return(x) } else { return(xOriginal) } if (tclvalue(done) == "0") { tkdestroy(parent) tclvalue(done) <- 1 } }) tkwm.deiconify(parent) tkwait.variable(done) } })
/scratch/gouwar.j/cran-all/cranData/xRing/R/correctRings.R
#' @title Detect the Transition from Earlywood to Latewood #' @description #' This function detects the end of earlywood and the start of latewood #' @param x an "xRingList" object #' @param ew defines the end of earlywood as the ratio of the density range. The default value is 0.5, which means that the end of earlywood is placed at the point where the density is half the range between the minimum and maximum density values within an annual ring #' @param lw defines the start of latewood, the default value is \code{NULL}. When ew is 0.5 and lw is \code{NULL} the boundary between earlywood and latewood is placed where the density is half the range between the minimum and maximum density values within an annual ring #' @return an "xRingList" object with limits.ew and limits.lw added. #' @export #' @examples #' #' data(PaPiRaw) #' data(PaPiSpan) #' PaPi <- detectRings(PaPiRaw, PaPiSpan) #' PaPi.merge <- combineFrag(PaPi, frag = 9) #' PaPiRings <- detectEwLw(PaPi.merge, ew = 0.5) #' detectEwLw <- function(x, ew = 0.5, lw = NULL) { if (!is.xRingList(x)) { stop("Use only with \"xRingList\" objects.") } if (is.null(lw)) { lw <- ew } out <- lapply(x, EwLw2Series, ew, lw) as.xRingList(out) }
/scratch/gouwar.j/cran-all/cranData/xRing/R/detectEwLw.R
#' @title Detect Tree-Ring Borders #' @description #' This function identifies tree-ring borders on X-ray microdensity profiles. #' @param x a dataframe with X-ray microdensity profiles or an "xRingList" object #' @param y a dataframe with the first and last year in columns and the series in rows, is \code{NULL} by default #' @param k width of the rolling window to find the local maximum and minimum (for more details please see the help of \code{\link{getBorders}} function) #' @param minTrw integer width of the narrowest tree-ring, rings narrower than this value will not be considered #' @param threshold the minimum difference between local maximum and minimum density to identify a tree-ring border #' @details #' This function uses the \code{\link{getBorders}} function to identify tree-ring borders based on the difference between local maximum and minimum density. #' @return \code{detectRings} returns an "xRingList" object, an S3 class with "xRing" lists as members, with the following elements: #' @return \code{span} first and last year #' @return \code{trw} gives the tree-ring width #' @return \code{name} a \code{string} giving the series name #' @return \code{limits} a \code{vector} with the position of the tree-ring borders #' @return \code{years} a \code{vector} with the calendar year #' @return \code{profile.raw} a \code{vector} with the input #' @seealso #' \link{getBorders} #' @export #' @examples #' #' data(PaPiRaw) #' data(PaPiSpan) #' PaPi <- toxRingList(PaPiRaw, PaPiSpan) #' PaPi <- detectRings(PaPi) #' # give the same #' PaPi <- detectRings(PaPiRaw, PaPiSpan) #' # Because the last year is not supplied the last year for all series is the last calendar year #' # as.numeric(format(Sys.time(), "%Y"))-1 #' PaPi <- detectRings(PaPiRaw) #' detectRings <- function(x, y = NULL, k = 3, minTrw = 3, threshold = 0.215) { # if ("xRingList" %in% class(x)) { if (is.xRingList(x)) { out <- x } else { out <- toxRingList(x, y) } # out <- lapply(out, # FUN = getBorders, # minTrw = minTrw, # threshold = threshold) for (i in seq_along(out)) { out[[i]] <- getBorders(out[[i]], minTrw = minTrw, threshold = threshold, k = k) } class(out) <- c("xRingList", "list") return(out) }
/scratch/gouwar.j/cran-all/cranData/xRing/R/detectRings.R
dif <- function(x, lag = 1, differences = 1, ...) { c( rep(NA, lag * differences), diff(x, lag = lag, differences = differences, ...) ) }
/scratch/gouwar.j/cran-all/cranData/xRing/R/dif.R
#' @importFrom graphics abline axis lines mtext par plot points title drawLine <- function(x, ...) { opar <- par("xpd" = NA) on.exit(par(opar)) for (i in 1:length(x)) { lines(c(x[i], x[i]), c(-1.08, 1.425), ...) } }
/scratch/gouwar.j/cran-all/cranData/xRing/R/drawLine.R
drawPolygon <- function(x, y, r = 20) { x0 <- x[1] y0 <- y[1] for (i in 2:length(x)) { x1 <- x[2] y1 <- y[2] delta_x <- x0 - x1 delta_y <- y0 - y1 angle <- atan2(delta_y, delta_x) * 180 / pi ang <- (angle + c(90, -90)) * pi / 180 xx1 <- x1 + r * cos(ang) yy1 <- y1 + r * sin(ang) out <- c(xx1[2], yy1[2]) xx0 <- x0 + r * cos(ang) yy0 <- y0 + r * sin(ang) out <- c(out, xx1[1], yy1[1], xx0[1], yy0[1], xx0[2], yy0[2]) } return(out) }
/scratch/gouwar.j/cran-all/cranData/xRing/R/drawPolygon.R
edge <- function(x, k = 3, threshold = 50) { x.dif <- rollMax(x, k = k, align = "center" ) - rollMax(x, k = k, align = "right" ) x0 <- which(x.dif > threshold) breaks <- unique(c(which(dif(x0) > 1) - 1, length(x0))) x0[breaks] }
/scratch/gouwar.j/cran-all/cranData/xRing/R/edge.R
findPeaks <- function(x) { which(diff(sign(diff(x, na.pad = FALSE)), na.pad = FALSE) < 0) + 1 }
/scratch/gouwar.j/cran-all/cranData/xRing/R/findPeaks.R
findValleys <- function(x) { which(diff(sign(diff(x, na.pad = FALSE)), na.pad = FALSE) > 0) + 1 }
/scratch/gouwar.j/cran-all/cranData/xRing/R/findValleys.R
#' @title Get Tree-Ring Borders #' @description Identify tree-ring borders #' @param x an object of class "xRing" #' @param k integer; width of the rolling window #' @param minTrw integer; width of the narrowest tree-ring, rings narrower than this value will not be considered #' @param threshold the minimum difference between the local maximum and minimum density to detect tree-ring borders #' @param addLastBorder logical; if \code{FALSE} the last border is not added. If \code{TRUE} the last border is placed at the position of the last value. #' @details #' This function uses local maximum and minimum densities in order to detect tree-ring borders. #' @return The \code{getBorders} function returns an object of lass "xRing" including the following elements: #' @return \code{names} a \code{string} giving the series name #' @return \code{span} the first and last year #' @return \code{trw} a \code{data.frame} with tree-ring width #' @return \code{limits} a \code{vector} with the position of the tree-ring borders #' @return \code{years} a \code{vector} with the calendar year #' @return \code{profile.raw} a \code{vector} with the raw X-ray values #' @return \code{profile} a \code{vector} with the the smoothed X-ray values (if is supplied in the input) #' @export #' @examples #' #' data("PaPiRaw") #' data("PaPiSpan") #' AFO1001a <- toxRing(PaPiRaw, PaPiSpan, "AFO1001a") #' AFO1001a <- getBorders(AFO1001a) #' #' AFO1001a <- toxRing(PaPiRaw, seriesName = "AFO1001a") #' AFO1001a <- getBorders(AFO1001a) #' getBorders <- function(x, k = 3, minTrw = 3, threshold = 0.215, addLastBorder = FALSE) { extractedProfile <- x$profile lastYear <- x$span[[2]] if (is.na(lastYear)) { lastYear <- as.integer(format(Sys.time(), "%Y")) - 1 message(paste(x$name, lastYear, "#")) x$span[2] <- lastYear } else { message(paste(x$name, lastYear)) } lastBorder <- NULL if (addLastBorder) { lastBorder <- length(extractedProfile) } limits <- Limits <- c( border(x = extractedProfile, k = k, threshold = threshold), lastBorder ) limits0 <- NA problems <- which(dif(limits) < minTrw) - 1 if (length(problems) > 0) { limits <- Limits[-problems] limits.problems <- Limits[which(dif(Limits) < minTrw) - 1] } years <- lastYear - (length(limits[-1]):0) x$trw <- as.data.frame(matrix(diff(limits), dimnames = list(years[-1], paste0(x$name, ".trw")))) x$limits <- limits x$years <- years x$limits0 <- limits0 if (is.na(x$span[1])) { x$span[1] <- years[1] } as.xRing(x) }
/scratch/gouwar.j/cran-all/cranData/xRing/R/getBorders.R
getDenSeries <- function(x) { # if (!is.xRing(x)) { # stop("Use only with \"xRing\" objects.") # } out <- x nYears <- length(x$limits) - 1 years <- x$years[-1] dens.names <- c("Dmean", "Dmin", "Dmax", "Dew", "Dlw") OUT <- data.frame(matrix( NA, nrow = nYears, 5, dimnames = list(years, dens.names) )) i0 <- (x$limits[1] + 1) for (i in 1:nYears) { i1 <- x$limits[i + 1] xD <- x$profile[i0:i1] OUT[i, 1] <- mean(xD) OUT[i, 2] <- min(xD) OUT[i, 3] <- max(xD) if (!is.null(x$limits.ew[i])) { xEw <- 1:(x$limits.ew[i] - i0) OUT[i, 4] <- mean(xD[xEw]) OUT[i, 5] <- mean(xD[-xEw]) } i0 <- (i1 + 1) } out$density <- OUT out }
/scratch/gouwar.j/cran-all/cranData/xRing/R/getDenSeries.R
#' @title Get Density Values #' @description #' Get wood density parameters by tree-ring. #' @param x a "xRingList" or "xRing" object #' @return a "xRingList" or "xRing" object with density values c("Dmean", "Dmin", "Dmax", "Dew", "Dlw") for each ring #' @export #' @examples #' #' data(PaPiRaw) #' data(PaPiSpan) #' PaPi <- detectRings(PaPiRaw, PaPiSpan) #' PaPi.merge <- combineFrag(PaPi, frag = 9) #' PaPiRings <- detectEwLw(PaPi.merge, ew = 0.5) #' #' PaPi <- detectRings(PaPiRaw, PaPiSpan) #' PaPiRings <- detectEwLw(PaPi, ew = 0.5) #' #' # xRingList object #' PaPiDen <- getDensity(PaPiRings) #' #' PaPiDen$AFO1001a[] #' PaPiDen$AFO1001a$density #' #' # xRing object #' PaPi_AFO1001a <- getDensity(PaPi$AFO1001a) #' # the same #' PaPi_1 <- getDensity(PaPi[[1]]) #' identical(PaPi_AFO1001a, PaPi_1) #' #' # do not work for PaPi[1] #' # class(PaPi[1]) #' # getDensity(PaPi[1]) # 'list' class #' getDensity <- function(x) { # if ("xRingList" %in% class(x)) { if (is.xRingList(x)) { out <- lapply(x, getDenSeries) class(out) <- c("xRingList", "list") return(out) } # if ("xRing" %in% class(x)) { if (is.xRing(x)) { return(getDenSeries(x)) } else { stop("Use only with \"xRingList\" or \"xRing\" objects.") } }
/scratch/gouwar.j/cran-all/cranData/xRing/R/getDensity.R
getEwLw <- function(profile, limits, maxDens = NULL, ew = 0.5, lw = NULL, trueLw = NULL) { if (is.null(lw)) { lw <- ew } if (diff(limits) == 0) { return(rep(NA, 2)) } if (!is.null(trueLw)) { profile0 <- profile profile0[1:(round(1 / 3 * (diff(limits) + 1)) - 1)] <- 0 maxDens <- min(which(profile0 >= trueLw)) if (is.infinite(maxDens)) { maxDens <- round(2 / 3 * (diff(limits) + 1)) } } ew.end <- max(which((profile[1:maxDens] <= ew) == 1)) if (is.infinite(ew.end)) { ew.end <- round(2 / 3 * (diff(limits) + 1)) } ew.limite <- limits[1] + ew.end - 1 ew.limite <- min(ew.limite, limits[2] - 1) # to guarantee that latewood starts before the maxDensity profile[1:ew.end] <- 0 lw.limite <- limits[1] + min(which((profile >= lw) == 1)) - 1 if (!is.finite(lw.limite)) { lw.limite <- ew.limite + 1 } lw.limite <- min(lw.limite, limits[2]) return(c(ew.limite, lw.limite)) }
/scratch/gouwar.j/cran-all/cranData/xRing/R/getEwLw.R
#' @title Get Data-Frames With Ring Width and Density Values #' @description Produce a list with 8 data.frames (trw, ew, lw, Dmean, Dew, Dlw, Dmin, Dmax ) that can be used by other packages (dplR, detrendeR) #' @param x an "xRingList" object #' @return a list with 8 elements: ##' \describe{ ##' \item{trw}{a data.frame with tree-ring widths} ##' \item{ew}{a data.frame with earlywood widths} ##' \item{lw }{a data.frame with latewood widths} ##' \item{Dmean}{a data.frame with mean tree-ring density} ##' \item{Dew}{a data.frame with mean earlywood density} ##' \item{Dlw}{a data.frame with mean latewood density} ##' \item{Dmin}{a data.frame with the minimum ring density} ##' \item{Dmax}{a data.frame with the maximum ring density} ##' } #' @export #' @importFrom dplR combine.rwl #' @examples #' #' data(PaPiRaw) #' data(PaPiSpan) #' PaPi <- detectRings(PaPiRaw, PaPiSpan) #' PaPi <- combineFrag(PaPi) #' PaPi <- detectEwLw(PaPi) #' rwls <- getRwls(PaPi) #' names(rwls) #' library(dplR) #' rwl.report(rwls$trw) #' library(detrendeR) #' RwlInfo(rwls$trw) #' getRwls <- function(x) { if (ncol(x[[1]]$trw) < 2) { return(message("You should first detect the earlywood and latewood rings.")) } if (is.null(x[[1]]$density)) { x <- getDensity(x) } nSeries <- length(x) name <- rep(NA, nSeries) trw <- ew <- lw <- Dtr <- Dmin <- Dmax <- Dew <- Dlw <- vector("list", nSeries) for (i in 1:length(x)) { name[i] <- x[[i]]$name trw[[i]] <- x[[i]]$trw[, 1, drop = FALSE] ew[[i]] <- x[[i]]$trw[, 2, drop = FALSE] lw[[i]] <- x[[i]]$trw[, 3, drop = FALSE] Dtr[[i]] <- x[[i]]$density[, "Dmean", drop = FALSE] Dmin[[i]] <- x[[i]]$density[, "Dmin", drop = FALSE] Dmax[[i]] <- x[[i]]$density[, "Dmax", drop = FALSE] Dew[[i]] <- x[[i]]$density[, "Dew", drop = FALSE] Dlw[[i]] <- x[[i]]$density[, "Dlw", drop = FALSE] } trw <- combine.rwl(trw) ew <- combine.rwl(ew) lw <- combine.rwl(lw) Dtr <- combine.rwl(Dtr) Dmin <- combine.rwl(Dmin) Dmax <- combine.rwl(Dmax) Dew <- combine.rwl(Dew) Dlw <- combine.rwl(Dlw) names(trw) <- names(ew) <- names(lw) <- names(Dtr) <- names(Dmin) <- names(Dmax) <- names(Dew) <- names(Dlw) <- name out <- list(trw, ew, lw, Dtr, Dew, Dlw, Dmin, Dmax) names(out) <- c("trw", "ew", "lw", "Dmean", "Dew", "Dlw", "Dmin", "Dmax") out }
/scratch/gouwar.j/cran-all/cranData/xRing/R/getRwls.R
# helpers ----------------------------------------------------------------- divide <- function(x) { x[[1]] / x[[2]] } tkCanvasX0 <- function(canvas) { as.numeric(tkcanvasx(canvas, 0)) } tkCanvasY0 <- function(canvas) { as.numeric(tkcanvasy(canvas, 0)) } xInsideImage <- function(x, width) { pmax(pmin(x, width - 1), 1) } yInsideImage <- function(y, height) { pmax(pmin(y, height - 1), 1) } coord2tcl <- function(xy) { as.vector(matrix(c(xy$x, xy$y), nrow = 2, byrow = TRUE)) } rollMin <- function(x, k, align = c("center", "left", "right"), fill = NA) { n_s <- length(x) - k + 1 out <- rep(NA, n_s) for (i in seq_len(n_s)) { out[i] <- min(x[i + 0:(k - 1)]) } out <- switch(match.arg(align), "left" = { c(out, rep(fill, k - 1)) }, "center" = { c(rep(fill, floor((k - 1) / 2)), out, rep(fill, ceiling((k - 1) / 2))) }, "right" = { c(rep(fill, k - 1), out) } ) out } getStepsManual <- function(im, nSteps) { tt <- imDisplay(im) tktitle(tt) <- "Select Steps" tkconfigure(tt$env$canvas, cursor = "cross") done <- tclVar(0) n <- 0 n.steps <- nSteps - 1 ROI_TMP <- list(x = NULL, y = NULL) CAL_ROI <- matrix(NA, nrow = 0, ncol = 5) addRoiTmp <- function(CAN, xy, col = "#ff0000") { tkdelete(CAN, "TK_ROI_TMP") n <- length(xy$x) out <- vector("numeric", length = 2 * n) for (i in 1:n) { out[i * 2 - 1] <- xy$x[i] out[i * 2] <- xy$y[i] } roi <- tkcreate(CAN, "rectangle", out, "-outline", col) tkaddtag(CAN, "TK_ROI_TMP", "withtag", roi) } Button1 <- function(x, y) { if (n > n.steps) { tclvalue(done) <- 3 } ROI_TMP$x <<- tkCanvasX0(tt$env$canvas) + as.numeric(x) ROI_TMP$y <<- tkCanvasY0(tt$env$canvas) + as.numeric(y) } Button1Motion <- function(x, y) { nPoints <- length(ROI_TMP$x) if (nPoints == 1) { x <- xInsideImage( tkCanvasX0(tt$env$canvas) + as.numeric(x), tt$env$IMAGE_WIDTH ) y <- yInsideImage( tkCanvasY0(tt$env$canvas) + as.numeric(y), tt$env$IMAGE_HEIGHT ) ROI_TMP$x <- c(ROI_TMP$x, x) ROI_TMP$y <- c(ROI_TMP$y, y) addRoiTmp(tt$env$canvas, ROI_TMP) } } Button1Release <- function(x, y) { nPoints <- length(ROI_TMP$x) x <- xInsideImage( tkCanvasX0(tt$env$canvas) + as.numeric(x), tt$env$IMAGE_WIDTH ) y <- yInsideImage( tkCanvasY0(tt$env$canvas) + as.numeric(y), tt$env$IMAGE_HEIGHT ) tkdelete(tt$env$canvas, "TK_ROI_TMP") if (n > n.steps) { ROI_TMP <<- list(x = NULL, y = NULL) return() } if (ROI_TMP$x == x) { ROI_TMP <<- list(x = NULL, y = NULL) return() } if (ROI_TMP$y == y) { ROI_TMP <<- list(x = NULL, y = NULL) return() } ROI_TMP$x <<- ROI_TMP$x <- c(ROI_TMP$x, x) ROI_TMP$y <<- ROI_TMP$y <- c(ROI_TMP$y, y) roi <- tkcreate( tt$env$canvas, "rectangle", coord2tcl(ROI_TMP), "-outline", "blue" ) tkaddtag( tt$env$canvas, paste0("TK_CAL_ROI_", n <<- n + 1), "withtag", roi ) lab <- tcltk::tkcreate( tt$env$canvas, "text", mean(ROI_TMP$x), mean(ROI_TMP$y), text = as.character(n), fill = "red" ) tkaddtag(tt$env$canvas, paste0("TK_CAL_ROI_LAB", n), "withtag", lab) XX <- seqRange(round(ROI_TMP$x * tt$env$ZOOM)) YY <- seqRange(round(ROI_TMP$y * tt$env$ZOOM)) CAL_ROI <<- rbind(CAL_ROI, c(coord2tcl(ROI_TMP), mean(im[XX, YY, , ]))) if (n > n.steps) { tclvalue(done) <- 2 } ROI_TMP <<- list("x" = NULL, "y" = NULL) } tkbind(tt$env$canvas, "<Button-1>", Button1) tkbind(tt$env$canvas, "<Motion>", Button1Motion) tkbind(tt$env$canvas, "<B1-ButtonRelease>", Button1Release) tkbind(tt, "<q>", function() { tclvalue(done) <- 1 }) tkbind(tt, "<Escape>", function() { tclvalue(done) <- 1 }) tkbind(tt, "<Return>", function() { if (n > n.steps) { tclvalue(done) <- 3 } }) tkbind(tt, "<KP_Enter>", function() { if (n > n.steps) { tclvalue(done) <- 3 } }) deleteLastStep <- function(x, y) { if (n > 0) { tkdelete(tt$env$canvas, paste0("TK_CAL_ROI_", n)) tkdelete(tt$env$canvas, paste0("TK_CAL_ROI_LAB", n)) CAL_ROI <<- CAL_ROI[-n, , drop = FALSE] n <<- n - 1 } } tkbind(tt, "<Control-KeyPress-z>", deleteLastStep) tkwm.protocol(tt, "WM_DELETE_WINDOW", function() { tk_messageBox("ok", "Please use 'Esc' or 'q' to close the window.") }) tkMenu <- tkmenu(tt, tearoff = FALSE) tkadd(tkMenu, "command", label = "Delete", command = deleteLastStep) tkadd( tkMenu, "command", label = "Exit", command = function() { if (n > n.steps) { tclvalue(done) <<- 3 } else { tclvalue(done) <<- 1 } } ) .Tcl( # A function to pop up the menu "proc popupMenu {theMenu theX theY} { tk_popup $theMenu $theX $theY }" ) .Tcl(paste("bind ", tt, " <3> {popupMenu ", tkMenu, " %X %Y}")) tkwait.variable(done) if (tclvalue(done) == "1") { tkdestroy(tt) return(NULL) } if (tclvalue(done) == "3") { tkdestroy(tt) } else { done <- tclVar(0) tkbind(tt, "<Destroy>", function() { tclvalue(done) <- 2 }) tkwm.protocol(tt, "WM_DELETE_WINDOW", function() { tclvalue(done) <- 2 }) tkwait.variable(done) } tkdestroy(tt) grayscale <- CAL_ROI[, 5] grayscale } detectBreakpoints <- function(x, nSteps = NULL, minPeakHeight = NULL) { diffProfile <- rollMax(x, 5, "left") - rollMin(x, 5, "right") diffProfile[is.na(diffProfile)] <- 0 diffProfile <- predict(smooth.spline(diffProfile, spar = 0.3))$y if (is.null(minPeakHeight)) { minPeakHeight <- round(max(diffProfile) / 60) } peaks <- findPeaks(diffProfile) peaks <- peaks[diffProfile[peaks] >= minPeakHeight] rngSegDistance <- range(diff(peaks)) while (divide(rngSegDistance) < .5) { minPeakHeight <- minPeakHeight * 1.05 peaks <- findPeaks(diffProfile) peaks <- peaks[diffProfile[peaks] >= minPeakHeight] rngSegDistance <- range(diff(peaks)) } if (is.null(nSteps)) { nSteps <- length(peaks) } if (is.na(peaks[nSteps])) { if ((length(x) - max(peaks)) > (rngSegDistance[2] / 2)) { nSteps <- nSteps peaks <- c(peaks, length(x)) } } peaks <- peaks[1:nSteps] peaks[!is.na(peaks)] } getStepsAuto <- function(im, nSteps = NULL, nPixel = 50) { message("Please draw a line from the step with lowest density to the step with highest density.") profile <- selectProfiles(im, nPixel, multiple = FALSE) breakpoints <- detectBreakpoints(profile, nSteps) group <- cut(seq_along(profile), c(1, breakpoints), right = FALSE) out <- tapply(profile, group, mean, na.rm = TRUE) plot(profile / 255, ylab = "grayscale x 255", xlab = "", type = "l" ) abline(h = out / 255, col = "red") as.numeric(out) } # main function ----------------------------------------------------------- #' @title Select the Steps of a Calibration Wedge Interactively #' @description Obtain the Grayvalue of Each Step of a Calibration Wedge #' @param im an image. #' @param nSteps number of steps of the calibration wedge to obtain grayvalues from. #' @param auto logical. If TRUE, automatic detection of the steps given a line is carried out. Use with care. #' @param nPixel gives the line width when `auto = TRUE` #' @importFrom stats loess predict smooth.spline #' @return a numeric vector #' @export #' @examples #' if (interactive()) { #' # read a sample file #' im <- imRead(file = system.file("img", "AFO1046.1200dpi.png", package = "xRing")) #' #' # display the image #' imDisplay(im) #' #' # get the grayvalues from the calibration wedge on the film #' steps <- grayvalues <- getSteps(im, 7) # select 7 ROIs #' steps1 <- grayvalues <- getSteps(im, 7, auto = TRUE) # select a single ROI #' cor(steps, steps1) #' } #' getSteps <- function(im, nSteps = NULL, auto = FALSE, nPixel = 50) { # input validation if (!"cimg" %in% class(im)) { stop("please provide an image of class 'cimg'") } if (!is.null(nSteps) && !(is.numeric(nSteps) && length(nSteps) == 1 && (nSteps %% 1 == 0))) { stop( "please provide an numeric vector of length 1 containing a whole number as argument `nSteps`" ) } if (!(is.numeric(nPixel) && length(nPixel) == 1 && (nPixel %% 1 == 0))) { stop( "please provide an numeric vector of length 1 containing a whole number as argument `nPixel`" ) } # main function if (auto) { getStepsAuto(im, nSteps, nPixel) } else { getStepsManual(im, nSteps) } }
/scratch/gouwar.j/cran-all/cranData/xRing/R/getSteps.R
getTrw <- function(x) { out <- x[[1]]$trw[, 1, drop = FALSE] for (i in 2:length(x)) { if (nrow(x[[i]]$trw) > 2) { out <- mergeRwl(x = out, y = x[[i]]$trw[, 1, drop = FALSE]) } } out }
/scratch/gouwar.j/cran-all/cranData/xRing/R/getTrw.R
# helpers plt <- function(im, xlim = c(1, width(im)), ylim = c(1, height(im))) { im <- as.cimg(im[seqRange(xlim), seqRange(ylim), , ]) w <- width(im) h <- height(im) zoom <- max(round(w / tkDim()[1]), round(h / tkDim()[2])) im <- resizeIm(im, zoom) plot(im, ann = FALSE, axes = FALSE) # TODO rescale = FALSE im / (2^16-1) op <- par(new = TRUE) on.exit(par(op)) plot( NA, xlim = xlim, ylim = ylim[2:1], ann = FALSE, axes = FALSE, asp = 1L, xaxs = "i", yaxs = "i" ) } #' @title Crop Image Interactively #' @description A GUI for cropping an image #' @param im a cimg object #' @return a cropped image #' @export #' @examples #' #' if (interactive()) { #' file_path <- #' system.file("img", "AFO1046.1200dpi.png", package = "xRing") #' im <- imRead(file_path) #' print(dim(im)) #' im_crop <- imCrop(im) #' print(dim(im_crop)) #' } #' imCrop <- function(im) { FLAG <- FALSE ROI_TMP <- list(x = NULL, y = NULL) n <- 0 done <- tclVar(0) xR0 <- xR <- 1:dim(im)[1] yR0 <- yR <- 1:dim(im)[2] tt <- tktoplevel() tcl("wm", "attribute", tt, alpha = 0) tktitle(tt) <- "crop image" tt <- tkRplot(tt, width = tkDim()[1], height = tkDim()[2], function() { im <<- im[xR0, yR0, , , drop = FALSE] plt(im) }) tcl("wm", "attribute", tt, alpha = 1) CAN <- tt$env$canvas tkconfigure(CAN, cursor = "cross") rplot <- function(...) { if (!identical(xR0, xR) || !identical(yR0, yR)) { xR0 <<- xR yR0 <<- yR n <<- 0 tkdelete(CAN, "TK_ROI_TMP") if (length(xR) > 10 && length(yR) > 10) { tkRreplot(tt) } # else{ # message("Are you kidding me?") # } } } tkMenu <- tkmenu(tt, tearoff = FALSE) tkadd( tkMenu, "command", label = "Crop", command = function() { if (n > 0) { rplot() } } ) tkadd( tkMenu, "command", label = "Cancel ", command = function() { tkdelete(CAN, "TK_ROI_TMP") n <<- 0 } ) tkMenuExit <- tkmenu(tt, tearoff = FALSE) tkadd( tkMenuExit, "command", label = "Exit", command = function() { tkdelete(CAN, "TK_ROI_TMP") tclvalue(done) <<- 1 } ) addRoiTmp <- function(W, xy, col = "#0000ff") { tkdelete(W, "TK_ROI_TMP") n <- length(xy$x) out <- vector("numeric", length = 2 * n) for (i in 1:n) { out[i * 2 - 1] <- xy$x[i] out[i * 2] <- xy$y[i] } roi <- tkcreate(W, "rectangle", out, outline = col, dash = "- -") tkaddtag(W, "TK_ROI_TMP", "withtag", roi) } Button1 <- function(W, x, y, X, Y) { if (n > 0 && FLAG) { tkpopup(tkMenu, X, Y) } ROI_TMP$x <<- tkCanvasX0x(W, x) ROI_TMP$y <<- tkCanvasY0y(W, y) } Button1Motion <- function(W, x, y) { nPoints <- length(ROI_TMP$x) if (nPoints == 1) { ROI_TMP$x <- c(ROI_TMP$x, tkCanvasX0x(W, x)) ROI_TMP$y <- c(ROI_TMP$y, tkCanvasY0y(W, y)) addRoiTmp(W, ROI_TMP) } } Button1Release <- function(W, x, y, X, Y) { X0 <- tkCanvasX0(W) Y0 <- tkCanvasY0(W) nPoints <- length(ROI_TMP$x) x <- X0 + min(max(as.numeric(x), 0), tt$env$IMAGE_WIDTH) y <- Y0 + min(max(as.numeric(y), 0), tt$env$IMAGE_HEIGHT) if (ROI_TMP$x == x) { ROI_TMP <<- list(x = NULL, y = NULL) return() } if (ROI_TMP$y == y) { ROI_TMP <<- list(x = NULL, y = NULL) return() } ROI_TMP$x <<- c(ROI_TMP$x, x) ROI_TMP$y <<- c(ROI_TMP$y, y) roi <- tkcreate(CAN, "rectangle", coord2tcl(ROI_TMP), outline = "blue", dash = "- -" ) tkaddtag(CAN, "TK_ROI_TMP", "withtag", roi) n <<- 1 cropXY <- tk2usr(ROI_TMP$x, ROI_TMP$y) xR <<- seqRange(round(xInsideImage(cropXY[1:2], width(im) + 1))) yR <<- seqRange(round(yInsideImage(cropXY[3:4], height(im) + 1))) FLAG <<- FALSE tkpopup(tkMenu, X, Y) } Button3 <- function(X, Y) { if (n == 1) { tkpopup(tkMenu, X, Y) } else { tkpopup(tkMenuExit, X, Y) } } tkbind(tt, "<3>", Button3) tkbind(CAN, "<Button-1>", Button1) tkbind(CAN, "<Motion>", Button1Motion) tkbind(CAN, "<B1-ButtonRelease>", Button1Release) tkbind(tt, "<q>", function() { tclvalue(done) <- 1 }) tkbind(tt, "<Escape>", function() { tclvalue(done) <- 1 }) tkwm.protocol(tt, "WM_DELETE_WINDOW", function() { if (n == 0) { tclvalue(done) <<- 1 } else { tclvalue(done) <<- 3 } }) tkwait.variable(done) tkdestroy(tt) if (tclvalue(done) == "3") { if (length(xR) > 10 && length(yR) > 10) { im <- im[xR, yR, , , drop = FALSE] } } im }
/scratch/gouwar.j/cran-all/cranData/xRing/R/imCrop.R
# helpers #' @importFrom imager as.cimg #' #' .tcl2num <- function(x) { as.numeric(unlist(strsplit(tclvalue(x), split = " "))) } tkDim <- function(win = ".") { as.numeric(unlist(strsplit(tclvalue( tkwm.maxsize(win) ), " "))) } resizeIm <- function(im, n = NULL, outputList = FALSE) { if (is.null(n)) { n <- round(max(width(im) / tkDim()[1]), height(im) / tkDim()[2]) } if (n <= 1) { if (outputList) { return(list(image = im, zoom = 1)) } return(im) } x <- seq( from = 1, to = width(im), by = n ) y <- seq( from = 1, to = height(im), by = n ) image <- as.cimg(im[x, y, , ]) zoom <- n if (outputList) { return(list(image = image, zoom = zoom)) } image } updateWindow <- function(tt) { IMAGE_WIDTH <- tt$env$IMAGE_WIDTH IMAGE_HEIGHT <- tt$env$IMAGE_HEIGHT XSCR <- tt$env$XSCR YSCR <- tt$env$YSCR widthT <- as.numeric(.Tcl(paste("winfo width", tt))) heightT <- as.numeric(.Tcl(paste("winfo height", tt))) if (widthT >= IMAGE_WIDTH) { tkgrid.forget(tt$env$hscroll) tkwm.maxsize(tt, IMAGE_WIDTH, .tcl2num(tkwm.maxsize(tt))[2]) } else { tkgrid( tt$env$hscroll, row = 1, column = 0, sticky = "we" ) tkwm.maxsize(tt, XSCR, .tcl2num(tkwm.maxsize(tt))[2]) } if (heightT >= IMAGE_HEIGHT) { tkgrid.forget(tt$env$vscroll) tkwm.maxsize(tt, .tcl2num(tkwm.maxsize(tt))[1], IMAGE_HEIGHT) } else { tkgrid( tt$env$vscroll, row = 0, column = 1, sticky = "ns" ) tkwm.maxsize(tt, .tcl2num(tkwm.maxsize(tt))[1], YSCR) } } showImage <- function(image = NULL, parent = .TkRoot, title = NULL) { IMAGE_WIDTH <- as.integer(tkimage.width(image)) IMAGE_HEIGHT <- as.integer(tkimage.height(image)) tt <- tktoplevel(parent = parent, background = "grey90") XSCR <- tkDim(tt)[1] YSCR <- tkDim(tt)[2] tkwm.maxsize(tt, min(IMAGE_WIDTH, XSCR), min(IMAGE_HEIGHT, YSCR)) widthCan <- min(XSCR, IMAGE_WIDTH) heightCan <- min(YSCR, IMAGE_HEIGHT) tt$env$canvas <- tkcanvas( tt, width = widthCan, height = heightCan, scrollregion = paste(0, 0, IMAGE_WIDTH, IMAGE_HEIGHT) ) tcl(tt$env$canvas, "create", "image", 0, 0, image = image, anchor = "nw" ) tktitle(tt) <- title tt$env$hscroll <- tkscrollbar(tt, orient = "horiz", command = paste(tt$env$canvas$ID, "xview") ) tt$env$vscroll <- tkscrollbar(tt, command = paste(tt$env$canvas$ID, "yview")) tkconfigure( tt$env$canvas, xscrollcommand = function(...) { tkset(tt$env$hscroll, ...) } ) tkconfigure( tt$env$canvas, yscrollcommand = function(...) { tkset(tt$env$vscroll, ...) } ) tkgrid(tt$env$canvas, row = 0, column = 0, sticky = "nswe" ) tkgrid.rowconfigure(tt, 0, weight = 1) tkwm.minsize(tt, round(XSCR / 5), round(YSCR / 5)) tkgrid.columnconfigure(tt, 0, weight = 1) tt$env$IMAGE_WIDTH <- IMAGE_WIDTH tt$env$IMAGE_HEIGHT <- IMAGE_HEIGHT tt$env$XSCR <- XSCR tt$env$YSCR <- YSCR tkbind(tt, "<Configure>", function() { updateWindow(tt) }) if (IMAGE_WIDTH > XSCR | IMAGE_HEIGHT > YSCR) { # updateWindow(tt) tkwm.resizable(tt, 1, 1) } else { tkwm.resizable(tt, 0, 0) } return(tt) } #' @importFrom grDevices png png2tcltk <- function(im, filePath = "tmp.png", title = NULL) { png( filename = filePath, width = width(im), height = height(im) ) on.exit(unlink(filePath)) par(mar = rep(0, 4)) plot(im) dev.off() imageWork <- tkimage.create("photo", "xRingImageWork", file = filePath) showImage(imageWork, title = title) } #' @export #' @title Display Image Using tcltk Package #' @usage imDisplay(im, zoom = NULL, title = NULL) #' @description xRing #' @param im an image (an object of class "\link{cimg}") #' @param zoom the zoom factor (ratio), for zoom = 1 the image is shown with no zoom (original size), when zoom is less than 1 the image is zoomed out. The default value of zoom is NULL. #' @param title the window title #' @return a tcltk object #' @examples #' if (interactive()) { #' file_path <- system.file("img", "AFO1046.1200dpi.png", package = "xRing") #' im <- imRead(file_path) #' tkWin <- imDisplay(im, zoom = .25) #' tkWin$env$ZOOM # 4 means 25% zoom #' } #' imDisplay <- function(im, zoom = NULL, title = NULL) { title <- if (is.null(title)) { deparse(substitute(im)) } else { title } if (!is.null(zoom)) zoom <- 1 / zoom im <- resizeIm(im, outputList = TRUE, n = zoom) title <- paste0(title, " [", round(1 / im$zoom, 2), "x]") tmpFile <- tempfile(tmpdir = tempdir(), fileext = ".png") tt <- png2tcltk(im$image, tmpFile, title = title) tt$env$ZOOM <- im$zoom return(invisible(tt)) }
/scratch/gouwar.j/cran-all/cranData/xRing/R/imDisplay.R
#' @export #' @title Load Image From a File #' @description Load an image using the \link{load.image} function from \link{imager} package #' @param file path to file #' @return an object of class "\link{cimg}" #' @seealso #' \link{load.image} #' @examples #' if (interactive()) { #' file_path <- system.file("img", "AFO1046.1200dpi.png", package = "xRing") #' im <- imRead(file_path) #' imDisplay(im) #' } #' imRead <- function(file) { on.exit(gc()) im <- load.image(file) if (dim(im)[4] > 1) { im <- grayscale(im) } # max_image <- max(im) max_image <- max(im[sample(1:nrow(im), 10), sample(1:ncol(im), 10), , ]) # faster if (max_image <= 1) { im <- im * 255 } if (max_image <= 2^8) { im <- im * 255 } storage.mode(im) <- "integer" im }
/scratch/gouwar.j/cran-all/cranData/xRing/R/imRead.R
is.xRing <- function(x) inherits(x, "xRing") # isTRUE("xRing" %in% class(x))
/scratch/gouwar.j/cran-all/cranData/xRing/R/is.xRing.R
is.xRingList <- function(x) inherits(x, "xRingList") # isTRUE("xRingList" %in% class(x))
/scratch/gouwar.j/cran-all/cranData/xRing/R/is.xRingList.R
lengthSeries <- function(rwl) { apply( rwl, 2, FUN = function(x) { length(na.omit(x)) } ) }
/scratch/gouwar.j/cran-all/cranData/xRing/R/lengthSeries.R
#' @import imager #' @title Measure Profiles Interactively #' @description Several profiles can be selected in an image and a calibration for that image is used to convert pixels into wood density #' @param im an image #' @param nPixel the line width #' @param cal calibration #' @return an xRingList object with all xRing objects #' @export #' @examples #' if (interactive()) { #' # read a sample file #' im <- imRead(file = system.file("img", "AFO1046.1200dpi.png", package = "xRing")) #' #' # to display the image #' imDisplay(im) #' #' cal1 <- calibrateFilm(im, thickness = stepIncrease(0.24, 7), density = 1.2922, plot = TRUE) #' profiles <- measureProfiles(im, cal = cal1) #' } #' measureProfiles <- function(im, nPixel = 50, cal = NULL) { selectProfiles(im, nPixel, cal) }
/scratch/gouwar.j/cran-all/cranData/xRing/R/measureProfiles.R
mergeRwl <- function(x, y) { X <- as.list(as.data.frame(x)) Y <- as.list(as.data.frame(y)) rangeX <- range(as.integer(row.names(x))) rangeY <- range(as.integer(row.names(y))) ADD.na <- function(x, n = 0) { c(rep(NA, n), x) } ADD.na.End <- function(x, n = 0) { c(x, rep(NA, n)) } FLAG <- rangeX - rangeY if (FLAG[1] != 0) {{ if (FLAG[1] < 0) { lapply(Y, FUN = ADD.na, n = abs(FLAG[1])) -> Y } else { lapply(X, FUN = ADD.na, n = abs(FLAG[1])) -> X } }} if (FLAG[2] != 0) {{ if (FLAG[2] < 0) { lapply(X, FUN = ADD.na.End, n = abs(FLAG[2])) -> X } else { lapply(Y, FUN = ADD.na.End, n = abs(FLAG[2])) -> Y } }} list(X, Y) -> out as.data.frame(out) -> out rownames(out) <- min(rangeX[1], rangeY[1]):max(rangeX[2], rangeY[2]) out }
/scratch/gouwar.j/cran-all/cranData/xRing/R/mergeRwl.R
minDmaxD <- function(y) { mM1 <- c(min(c(findValleys(y), Inf)), max(findPeaks(y))) if (any(is.infinite(mM1))) { mM1[is.infinite(mM1)] <- NA return(mM1) } if (y[mM1[2]] < 0.9) { mM1[2] <- length(y) } yTrim <- y[mM1[1]:mM1[2]] return(c(min(which( yTrim %in% range(yTrim)[1] )), min(which( yTrim %in% range(yTrim)[2] ))) + mM1[1] - 1) }
/scratch/gouwar.j/cran-all/cranData/xRing/R/minDmaxD.R
#' @import tcltk AsNumeric <- function(x) { suppressWarnings(as.numeric(x)) } AsNumericNaN <- function(x) { x <- AsNumeric(x) if (is.na(x)) x <- "" x } modalDialog <- function(title = " ", question = "", entryInit = "", entryWidth = 20, returnValOnCancel = "") { dlg <- tktoplevel(borderwidth = 0) tcl("wm", "attributes", dlg, topmost = TRUE) tkwm.iconify(dlg) tkwm.title(dlg, title) tkgrab.set(dlg) frm0Black <- tkframe(dlg, borderwidth = 1, background = "black") tkpack(frm0Black, anchor = "center", expand = "y") frm0 <- tkframe(frm0Black, borderwidth = 0) tkpack(frm0, anchor = "center", expand = "y") row1 <- tkframe(frm0) tkpack(row1) row2 <- tkframe(frm0) tkpack(row2) textEntryVarTcl <- tclVar(paste(entryInit)) textEntryWidget <- tkentry( row1, width = paste(entryWidth), textvariable = textEntryVarTcl, background = "white" ) tkpack( tklabel(row1, text = paste0(" ", question)), textEntryWidget, tklabel(row1, text = " "), side = "left", pady = 10, padx = 1 ) ReturnVal <- returnValOnCancel onOK <- function() { ReturnVal <<- tclvalue(textEntryVarTcl) tkgrab.release(dlg) tkdestroy(dlg) } onCancel <- function() { ReturnVal <<- returnValOnCancel tkgrab.release(dlg) tkdestroy(dlg) } OK.but <- tkbutton(row2, text = "Ok", width = 6, command = onOK ) Cancel.but <- tkbutton(row2, text = "Cancel", width = 6, command = onCancel ) tkpack(Cancel.but, OK.but, side = "left", padx = 2, pady = 4 ) tkbind(dlg, "<Destroy>", function() { tkgrab.release(dlg) }) tkbind(textEntryWidget, "<Return>", onOK) tkbind(textEntryWidget, "<KP_Enter>", onOK) tkwm.deiconify(dlg) tkfocus(dlg) tkwait.window(dlg) ReturnVal }
/scratch/gouwar.j/cran-all/cranData/xRing/R/modalDialog.R
# helpers years2xLim <- function(x, years) { years <- pmin(pmax(years, min(x$years) + 1), max(x$years)) YEARmin <- which(x$years == min(years - 1)) YEARmax <- which(x$years == max(years)) c(range(x$limits[YEARmin:YEARmax])) + c(-1, 1) } #' @name plot #' @title Plot xRing and xRingList Objects #' @description Plot method for objects of class "xRing" and "xRingList". #' @param x an object of class "xRing" or "xRingList". #' @param years the years to be plotted, if \code{NULL} the whole time span is plotted. #' @param EwLw logical. If \code{TRUE} the earlywood and latewood boundaries and width is plotted. #' @param xlim vector of length 2 giving the x limits for the plot. #' @param ylim the y limits of the plot. #' @param ... other arguments to be passed to plotRings function #' @return None. #' @seealso #' \link{plotRings} #' @export #' @examples #' #' data(PaPiRaw) #' data(PaPiSpan) #' #' PaPi <- detectRings(PaPiRaw, PaPiSpan) #' class(PaPi) #' #' PaPiRings <- detectEwLw(PaPi, ew = 0.5) #' plot(PaPiRings, series = "AFO1001a") #' #' PaPiRings1 <- detectEwLw(PaPi, ew = 0.35, lw = 0.55) #' plot(PaPiRings1, series = "AFO1001a") #' #' plot(PaPiRings, series = "AFO1001a", years = c(1990, 2000)) #' plot(PaPiRings$AFO1001a) #' #' @name plot #' @aliases plot.xRing #' @export #' @usage \method{plot}{xRing}(x, years = NULL, EwLw = TRUE, xlim = NULL, ylim = NULL, ...) plot.xRing <- function(x, years = NULL, EwLw = TRUE, xlim = NULL, ylim = NULL, ...) { mar <- par("mar") on.exit(par("mar" = mar)) if (!is.null(years)) { xlim <- years2xLim(x, years) } local(plotRings( x, EwLw = EwLw, xlim = xlim, ylim = ylim, ... )) } #' @name plot #' @aliases plot.xRingList #' @param series gives the name (or the index) of the series to be plotted, by default is 1 (i.e., the first series) #' @export #' @usage \method{plot}{xRingList}(x, series = 1, years = NULL, EwLw = TRUE, xlim = NULL, ylim = NULL, ...) plot.xRingList <- function(x, series = 1, years = NULL, EwLw = TRUE, xlim = NULL, ylim = NULL, ...) { if (series %in% as.character(1:length(x))) { series <- names(x)[as.integer(series)] } seriesID <- which(names(x) == series) if (length(seriesID) == 0) { return(message( paste("Please correct the series name or ID (ID <", length(x), ")") )) } x <- x[[seriesID]] if (!is.null(years)) { xlim <- years2xLim(x, years) } mar <- par("mar") on.exit(par("mar" = mar)) local(plotRings( x, EwLw = EwLw, xlim = xlim, ylim = ylim, ... )) }
/scratch/gouwar.j/cran-all/cranData/xRing/R/plot.R
#' @importFrom grDevices grey #' @title Plot xRing Objects #' @description Plot "xRing" objects. #' @param x an object of class "xRing" #' @param xlim the x limits of the plot. The default value, NULL, indicates that the whole profile will be plotted. #' @param ylim the y limits of the plot. #' @param id a sufix to be added to the name of the series (<series_name> [id]) #' @param corr value to be print at the top of the graph #' @param EwLw logical. If \code{TRUE} the earlywood and latewood assignments are plotted, by default is \code{TRUE} #' @return None. A plot is produced. #' @seealso #' \link{plot.xRing} #' @importFrom graphics polygon #' @export #' @examples #' if (interactive()) { #' data(PaPiRaw) #' data(PaPiSpan) #' #' PaPi <- detectRings(PaPiRaw[, 1, drop = FALSE], PaPiSpan) #' plotRings(PaPi$AFO1001a) #' plotRings(PaPi, series = "AFO1001a") #' plotRings(PaPi, series = "AFO1001a", xlim = c(120, 450)) #' #' PaPi1 <- detectEwLw(PaPi, ew = 0.5) #' plotRings(PaPi1, series = "AFO1001a", EwLw = FALSE) #' plotRings(PaPi1, series = "AFO1001a") #' } #' plotRings <- local({ function(x, xlim = NULL, ylim = NULL, id = NULL, corr = NULL, EwLw = TRUE) { if (!inherits(x, "xRing")) { stop("Use only with 'xRing' objects.") } if (is.null(ylim)) { ylim <- range(x$profile, na.rm = TRUE) } AtY <- pretty.default(ylim, n = 4) ylim <- ylim - c(diff(ylim) / 1.25, 0) if (!is.null(id)) { id <- paste0("[", id, "]") } if (is.null(xlim)) { xlim <- c(0, length(x$profile)) } else { xlim <- pmax(0, pmin(range(xlim), length(x$profile))) } par("mar" = c(3, 3, 6, 1)) borders0 <- which(x$limits %in% seqRange(xlim)) borders <- sort(borders0, decreasing = TRUE)[-1] plot( NA, type = "n", ylim = ylim, ann = FALSE, axes = FALSE, xaxs = "i", xlim = xlim ) grey_color <- grey(1 - x$profile / max(x$profile, na.rm = TRUE)) yUp <- ylim[1] + diff(ylim) / 3 # 6 yUp1 <- ylim[1] + diff(ylim) / 9 # 18 abline1( v = 1:length(x$profile), col = grey_color, y = c(-2000, yUp, yUp, -2000) ) par( "mar" = c(3, 3, 6, 1), new = TRUE ) plot( x$profile, type = "l", ylim = ylim, ann = FALSE, axes = FALSE, xaxs = "i", xlim = xlim ) axis(2, line = 0.5, cex = 0.9, at = AtY ) AT <- x$limits[-1] at2plot <- { AT >= xlim[1] & AT <= xlim[2] } Xyears <- x$years[-1] if (any(at2plot)) { mtext( Xyears[at2plot], at = AT[at2plot], adj = -.25, las = 2, padj = 0, col = "blue", cex = 1 ) } title( main = paste(x$name, id), line = 4, cex = 1 ) xx <- x$limits yy <- x$profile[x$limits] par(xpd = NA) points(xx, yy, col = 2) par(xpd = FALSE) abline(v = x$limits, col = 4) if (!is.null(corr)) { mtext( corr, line = 1.5, side = 3, col = 2, cex = 1, padj = -3, adj = 1, las = 1 ) } axis(1, line = 0.5) if (EwLw & !is.null(x$limits.ew)) { k <- .5 k1 <- 1 if (max(x$limits.lw - x$limits.ew) > 1) { k <- 0 k1 <- 0 } xEw <- x$limits.ew[borders] xLw <- x$limits.lw[borders] points(xEw, x$profile[xEw], pch = 3, col = 4) points(xLw - k1, x$profile[xLw - k1], pch = 4, col = 4) y <- c(rep(par("usr")[3], 2), yUp1, yUp1) if (max(x$limits.lw - x$limits.ew) > 1) { T0 <- x$limits[min(borders)] T1 <- x$limits[max(borders) + 1] xT <- c(T0, T1, T1, T0) polygon(xT, y, col = "grey60") } for (i in borders) { E0 <- x$limits[i] E1 <- x$limits.ew[i] #+ k L0 <- x$limits.lw[i] - k1 L1 <- x$limits[i + 1] xE <- c(E0, E1, E1, E0) xL <- c(L0, L1, L1, L0) polygon(xE, y, col = "white") polygon(xL, y, col = "black") } } } })
/scratch/gouwar.j/cran-all/cranData/xRing/R/plotRings.R
#' @name print #' @title Print xRing and xRingList Objects #' @description Print method for objects of class "xRing" and "xRingList". #' @param x the object of class "xRing" or "xRingList" to print #' @param ... additional parameters #' @return None #' @export #' @examples #' #' data(PaPiRaw) #' data(PaPiSpan) #' PaPi <- detectRings(PaPiRaw, PaPiSpan) #' class(PaPi) #' print(PaPi$AFO1001a) #' PaPi$AFO1001a #' PaPi$AFO1001a[] #' print(PaPi) #' PaPi #' #' @name print #' @aliases print.xRing #' @usage \method{print}{xRing}(x, ...) #' @export print.xRing <- function(x, ...) { cat(paste0( x$name, ": ", x$span[1], "-", x$span[2], " (Length: ", length(x$profile.raw), ")" )) invisible(x) } #' @name print #' @aliases print.xRingList #' @usage \method{print}{xRingList}(x, ...) #' @export print.xRingList <- function(x, ...) { nn <- names(x) ll <- length(x) nSeries <- formatC(sapply(seq.int(ll), FUN = toString)) if (length(nn) != ll) { for (i in seq_len(ll)) { nn[i] <- x[[i]]$name } } nn <- formatC(nn) for (i in seq_len(ll)) { span <- as.vector(x[[i]]$span) len <- formatC(length(x[[i]]$profile.raw), width = 4) cat(paste0(nSeries[i], ": ", nn[i], ": ", span[1], "-", span[2], " (Length: ", len, ")\n")) } invisible(x) }
/scratch/gouwar.j/cran-all/cranData/xRing/R/print.R
put.together <- function(x2, newName) { x2 <- x2[order(unlist((lapply( x2, FUN = function(x) { x$span[[1]] } ))), decreasing = F)] x2 <- lapply(x2, trimSeries) x2 <- lapply(x2, setName, newName) OUT <- x2[[1]] for (j in 2:length(x2)) { shift <- max(OUT$limits) OUT$profile.raw <- c(OUT$profile.raw, x2[[j]]$profile.raw[-1]) OUT$span[[2]] <- x2[[j]]$span[[2]] OUT$trw <- rbind(OUT$trw, x2[[j]]$trw) OUT$years <- c(OUT$years, x2[[j]]$years[-1]) OUT$limits0 <- c(OUT$limits0, shift + x2[[j]]$limits0) OUT$limits <- c(OUT$limits, shift + x2[[j]]$limits[-1] - 1) if ("limits.ew" %in% names(OUT)) { OUT$limits.ew <- c(OUT$limits.ew, shift + x2[[j]]$limits.ew[-1] - 1) } if ("limits.lw" %in% names(OUT)) { OUT$limits.lw <- c(OUT$limits.lw, shift + x2[[j]]$limits.lw[-1] - 1) } if ("profile" %in% names(OUT)) { OUT$profile <- c(OUT$profile, x2[[j]]$profile[-1]) } } out <- vector("list", 1) names(out) <- newName out[[1]] <- OUT return(out) }
/scratch/gouwar.j/cran-all/cranData/xRing/R/put.together.R
putTogether <- function(x, newName) { if (length(x) < 2) { return(x) } put.together(x, newName) }
/scratch/gouwar.j/cran-all/cranData/xRing/R/putTogether.R
#' @title Remove Tree-Ring Border(s) #' @description Remove the closest tree-ring border #' @param object an object of class "xRing" or "xRingList" #' @param x the position to delete the closest tree-ring border #' @param series the name of the series to be changed when the object is a "xRingList", by default is NULL #' @return an object of class "xRing" or "xRingList" without the tree-ring border at the position \code{x} for the series given by \code{series} argument #' @export #' @examples #' data(PaPiRaw) #' data(PaPiSpan) #' PaPi <- detectRings(PaPiRaw, PaPiSpan) #' plotRings(PaPi$AFO1001a) #' abline(v = 60, lty = 2, col = 2) #' PaPi$AFO1001a <- removeRing(PaPi$AFO1001a, x = 60) #' # PaPi$AFO1001a <- removeRing(PaPi$AFO1001a, x = locator(1)$x) #' plotRings(PaPi$AFO1001a) #' removeRing <- function(object, x, series = NULL) { if (!any(c("xRingList", "xRing") %in% class(object))) { stop("Use only with \"xRingList\" and \"xRing\" objects.") } if (!is.null(series)) { object[[series]] <- removeRingSeries(object[[series]], x) return(object) } removeRingSeries(object, x) }
/scratch/gouwar.j/cran-all/cranData/xRing/R/removeRing.R
removeRingSeries <- function(xray, x) { for (i in 1:length(x)) { xLimite <- abs(xray$limits - x[i]) year <- xray$years[which(xLimite == min(xLimite))[1]] xray$limits <- limits <- xray$limits[-which(xray$years == year)] xray$years <- years <- xray$years[-1] xray$trw <- as.data.frame(matrix(diff(limits), dimnames = list(years[-1], xray$names) )) } xray }
/scratch/gouwar.j/cran-all/cranData/xRing/R/removeRingSeries.R
rmNA <- function(x) { as.data.frame(x[apply( x, 1, function(x) { !all(is.na(x)) } ), , drop = FALSE]) }
/scratch/gouwar.j/cran-all/cranData/xRing/R/rmNA.R
rollMax <- function(x, k, align = c("center", "left", "right"), fill = NA) { n_s <- length(x) - k + 1 out <- rep(NA, n_s) for (i in seq(1, n_s)) { # seq_len out[i] <- max(x[i + 0:(k - 1)]) } out <- switch(match.arg(align), "left" = { c(out, rep(fill, k - 1)) }, "center" = { c(rep(fill, floor((k - 1) / 2)), out, rep(fill, ceiling((k - 1) / 2))) }, "right" = { c(rep(fill, k - 1), out) } ) out }
/scratch/gouwar.j/cran-all/cranData/xRing/R/rollMax.R
# helpers ---------------------------------------------------------------------- tkCanvasX0x <- function(canvas, x) { tkCanvasX0(canvas) + as.numeric(x) } # as.numeric(tclvalue(tkcanvasx(canvas,x)) #TODO tkCanvasY0y <- function(canvas, y) { tkCanvasY0(canvas) + as.numeric(y) } addFrame <- function(im, nPixel = 1) { im <- squeeze(im) cM <- matrix(NA, nrow = dim(im)[1], ncol = nPixel) im1 <- cbind(cM, cM, im, cM) rM <- matrix(NA, nrow = nPixel, ncol = dim(im1)[2]) im2 <- rbind(rM, rM, im1, rM) as.cimg(im2) } get_angle <- function(x, y) { delta_x <- x[1] - x[2] delta_y <- y[1] - y[2] -atan2(delta_y, delta_x) * 180 / pi } gcd <- function(x, y) { r <- x %% y return(ifelse(r, gcd(y, r), y)) } crop_along_line <- function(x, y, im, split = TRUE, width = 40) { shift <- 2 * width im <- addFrame(im, shift) out <- NULL xx3 <- x + shift yy3 <- y + shift if (split & (abs(diff(x)) > 200 & abs(diff(y)) > 200)) { # this step is important for speed x_part <- diff(x) / abs(gcd(diff(x), diff(y))) xx3 <- seq(x[1], x[2], x_part) # divide image into equal parts according to the great common divisor yy3 <- seq(y[1], y[2], by = x_part / (diff(x) / diff(y))) } xx3 <- xx3 + shift yy3 <- yy3 + shift x_start <- xx3[1] y_start <- yy3[1] for (i in 2:length(xx3)) { x_end <- xx3[i] y_end <- yy3[i] xx <- c(x_start, x_end) yy <- c(y_start, y_end) len_profile <- round(sqrt(diff(xx3[i - 1:0])^2 + diff(yy3[i - 1:0])^2)) xR <- range(as.integer(drawPolygon( c(x_start, x_end), c(y_start, y_end), 2 * width ))[1:4 * 2 - 1]) yR <- range(as.integer(drawPolygon( c(x_start, x_end), c(y_start, y_end), 2 * width ))[1:4 * 2]) im1 <- im[seqRange(xR), seqRange(yR), , , drop = FALSE] angle <- get_angle(xx, yy) im2 <- imrotate(im1, angle) x_crop <- seqRange(round(width(im2) / 2) + c( -floor(len_profile / 2), len_profile - floor(len_profile / 2) - 1 )) y_crop <- seqRange(round(height(im2) / 2) + (c(-1, 1) * width / 2)) im3 <- im2[x_crop, y_crop, , , drop = FALSE] out <- c(out, rowMeans(im3, na.rm = TRUE)) x_start <- x_end y_start <- y_end # TODO merge all image segments and return also an image } out } #' @import imager #' @title Select Profile(s) #' @description Uses a line to select a profile (or a region of interest), when selecting a radius the line should start at the pith side and end at the bark side of the sample. #' @param im an image #' @param nPixel the width of the line #' @param cal calibration #' @param multiple a single or several profiles #' @return a vector with the average grayvalue along the selected line when a multiple is TRUE and a list when multiple is FALSE #' @examples #' if (interactive()) { #' # read a sample file #' im <- imRead(file = system.file("img", "AFO1046.1200dpi.png", package = "xRing")) #' #' # to display the image #' imDisplay(im) #' #' # select a profile #' profile <- selectProfile(im) #' #' # to display the profile #' plot(profile, type = "l") #' } #' selectProfiles <- function(im, nPixel = 50, cal = NULL, multiple = TRUE) { name <- "" thickness <- "" button1IsOk <- TRUE OUT <- NULL n <- 0 done <- tclVar(0) tt <- imDisplay(im) tktitle(tt) <- ifelse(multiple, "GetProfiles", "GetOneProfile") CAN <- tt$env$canvas ZOOM <- tt$env$ZOOM nPixel <- nPixel / ZOOM ROI_TMP <- list(x = NULL, y = NULL) tkconfigure(tt$env$canvas, cursor = "cross") addRoiTmp <- function(CAN, xy, col = "#ff0000") { tkdelete(CAN, "TK_ROI_TMP") polygon_coord <- as.integer(drawPolygon(xy$x, xy$y, nPixel / 2)) roi <- tkcreate(CAN, "polygon", polygon_coord, fill = "", outline = col ) tkaddtag(CAN, "TK_ROI_TMP", "withtag", roi) roi <- tkcreate( CAN, "line", coord2tcl(xy), fill = col, width = 1, dash = "--" ) tkaddtag(CAN, "TK_ROI_TMP", "withtag", roi) } Button1 <- function(W, x, y) { if (!multiple & n > 0) { # if there is a profile and multiple is FALSE return the profile and closes the window return(tkdestroy(tt)) } # TODO call a dialog box to know what to do if (!button1IsOk) { return() } ROI_TMP$x <<- xInsideImage(tkCanvasX0x(W, x), tt$env$IMAGE_WIDTH) ROI_TMP$y <<- yInsideImage(tkCanvasY0y(W, y), tt$env$IMAGE_HEIGHT) } Button1Motion <- function(W, x, y, ...) { if (!multiple & n > 0) { return() } nPoints <- length(ROI_TMP$x) if (nPoints == 1) { x <- xInsideImage(tkCanvasX0x(W, x), tt$env$IMAGE_WIDTH) y <- yInsideImage(tkCanvasY0y(W, y), tt$env$IMAGE_HEIGHT) ROI_TMP$x <- c(ROI_TMP$x, x) ROI_TMP$y <- c(ROI_TMP$y, y) ifelse((( abs(ROI_TMP$x - x) + abs(ROI_TMP$y - y) )) < nPixel / 2, col <- "blue", col <- "red") addRoiTmp(tt$env$canvas, ROI_TMP, col = col) } } Button1Release <- function(W, x, y, ...) { if (!button1IsOk) { tklower(tt) return() } if (!multiple & n > 0) { return() } gc() on.exit(ROI_TMP <<- list("x" = NULL, "y" = NULL)) nPoints <- length(ROI_TMP$x) x <- xInsideImage(tkCanvasX0x(W, x), tt$env$IMAGE_WIDTH) y <- yInsideImage(tkCanvasY0y(W, y), tt$env$IMAGE_HEIGHT) if ((ROI_TMP$x == x && ROI_TMP$y == y) | ((abs(ROI_TMP$x - x) + abs(ROI_TMP$y - y)) < nPixel / 2)) { return() } ROI_TMP$x <- x <- c(ROI_TMP$x, x) ROI_TMP$y <- y <- c(ROI_TMP$y, y) polygon_coord <- as.integer(drawPolygon(x, y, nPixel)) xx <- round(x * ZOOM) yy <- round(y * ZOOM) ROI_TMP <<- list("x" = NULL, "y" = NULL) if (multiple) { currentSeries <- varEntryDialog( vars = c("name", "lastYear", "thickness"), valInitials = c(name, "", thickness), fun = list(make.names, AsNumericNaN, AsNumeric) ) tkdelete(CAN, "TK_ROI_TMP") if (!is.null(currentSeries)) { name <<- currentSeries$name thickness <<- ifelse(is.na(currentSeries$thickness), "", currentSeries$thickness ) n <<- n + 1 polygon_coord <- as.integer(drawPolygon(x, y, nPixel / 2)) roi0 <- roi <- tkcreate(CAN, "polygon", polygon_coord, fill = "", outline = "yellow" ) tkaddtag(CAN, paste0("ray", n), "withtag", roi) roi <- tkcreate( CAN, "line", coord2tcl(ROI_TMP), fill = "yellow", width = 1, dash = "--" ) tkaddtag(CAN, paste0("ray", n), "withtag", roi) profile.raw <- crop_along_line(xx, yy, im, width = nPixel) if (multiple) { name <- make.names(c(names(OUT), currentSeries$name), unique = TRUE) name <- name[length(name)] } profileCalibrated <- NULL if (!is.null(cal)) { profileCalibrated <- calibrateSeries(profile.raw, thickness = currentSeries$thickness, calibration = cal ) } OUT[[n]] <<- list( "coordinates" = list(x = x * ZOOM, y = y * ZOOM), "nPixel" = nPixel * ZOOM, "profile.raw" = profile.raw, "profile" = profileCalibrated, "thickness" = currentSeries$thickness, "span" = c(NA, AsNumeric(currentSeries$lastYear)), "name" = name ) names(OUT)[n] <<- name } } else { tkdelete(CAN, "TK_ROI_TMP") { n <<- n + 1 polygon_coord <- as.integer(drawPolygon(x, y, nPixel / 2)) roi0 <- roi <- tkcreate(CAN, "polygon", polygon_coord, fill = "", outline = "yellow" ) tkaddtag(CAN, paste0("ray", n), "withtag", roi) roi <- tkcreate( CAN, "line", coord2tcl(ROI_TMP), fill = "yellow", width = 1, dash = "--" ) tkaddtag(CAN, paste0("ray", n), "withtag", roi) OUT[[n]] <<- crop_along_line(xx, yy, im, width = nPixel) } } tkraise(tt) } tkbind(tt$env$canvas, "<Button-1>", Button1) tkbind(tt$env$canvas, "<Motion>", Button1Motion) tkbind(tt$env$canvas, "<B1-ButtonRelease>", Button1Release) tkbind(tt, "<q>", function() { tclvalue(done) <- 1 }) tkbind(tt, "<Escape>", function() { tclvalue(done) <- 1 }) tkbind(tt, "<Return>", function() { tclvalue(done) <- 3 }) tkbind(tt, "<KP_Enter>", function() { tclvalue(done) <- 3 }) tkbind(tt, "<Control-KeyPress-z>", function(x, y) { if (n >= 0) { tkdelete(tt$env$canvas, paste0("ray", n)) tkdelete(CAN, "TK_ROI_TMP") OUT <<- OUT[-n, drop = FALSE] n <<- n - 1 } }) tkwm.protocol(tt, "WM_DELETE_WINDOW", function() { done <- tclVar(1) }) # tkwait.variable(done) if (tclvalue(done) == "1") { tkdestroy(tt) return(NULL) } if (tclvalue(done) == "3") { tkdestroy(tt) } else { done <- tclVar(0) tkbind(tt, "<Destroy>", function() { tclvalue(done) <- 2 }) tkwm.protocol(tt, "WM_DELETE_WINDOW", function() { tclvalue(done) <- 2 }) tkwait.variable(done) } tkdestroy(tt) if (n == 0) { return(NULL) } if (!multiple) { return(OUT[[1]]) } as.xRingList(OUT) }
/scratch/gouwar.j/cran-all/cranData/xRing/R/selectProfiles.R
seqRange <- function(x) { x[1]:x[2] }
/scratch/gouwar.j/cran-all/cranData/xRing/R/seqRange.R
setFirstYear <- function(rwl, n = 0) { rownames(rwl) <- as.integer(rownames(rwl)) + n as.data.frame(rwl) }
/scratch/gouwar.j/cran-all/cranData/xRing/R/setFirstYear.R
#' @title Set Last Year #' @description #' Changes the calendar year of the last ring for a specific series. #' @param x an "xRing" or "xRingList" object #' @param lastYear the new calendar year for the last tree ring #' @param series individual series to be changed when the object is a "xRingList", by default is NULL #' @return the modified input object with new set last ring of the specified series. #' @export #' @examples #' #' data(PaPiRaw) #' data(PaPiSpan) #' PaPi <- detectRings(PaPiRaw, PaPiSpan) #' plot(PaPi, series = "AFO1001b") #' PaPi <- setLastYear(PaPi, 2005, series = "AFO1001b") #' plot(PaPi, series = "AFO1001b") #' setLastYear <- function(x, lastYear, series = NULL) { if (!any(c("xRingList", "xRing") %in% class(x))) { stop("Use only with \"xRingList\" and \"xRing\" objects.") } if (!is.null(series)) { x[[series]] <- setLastYearSeries(x[[series]], lastYear) return(x) } x <- setLastYearSeries(x, lastYear) return(x) }
/scratch/gouwar.j/cran-all/cranData/xRing/R/setLastYear.R
setLastYearSeries <- function(x, lastYear) { x$years <- lastYear - ((length(x$years) - 1):0) rownames(x$trw) <- x$years[-1] x$span <- range(x$years) return(x) }
/scratch/gouwar.j/cran-all/cranData/xRing/R/setLastYearSeries.R
setName <- function(x, newName) { colnames(x$trw) <- newName x$name <- newName x }
/scratch/gouwar.j/cran-all/cranData/xRing/R/setName.R
#' @importFrom stats qt sigCor <- function(p = 0.05, n = 50, tail = 2) { t <- qt((p / tail), n - 2) t / (sqrt((n - tail) + t^2)) }
/scratch/gouwar.j/cran-all/cranData/xRing/R/sigCor.R
#' @title Create an "xRing" Object #' @description #' Converts a dataframe with X-ray microdensity profiles into an "xRing" object #' @param x a dataframe with X-ray microdensity profiles #' @param y a dataframe with the numerical values of the first and last year in columns. The individual series are specified as row names. #' @param seriesName the name of series from x and y to be used to produce the "xRing" object. #' @return an "xRing" object, an S3 class with the following elements: #' @return \code{profile.raw} a \code{vector} with the input density profile #' @return \code{span} first and last year #' @return \code{name} a \code{string} giving the series name #' @seealso #' \link{toxRingList} #' @export #' @examples #' #' data(PaPiRaw) #' data(PaPiSpan) #' PaPi.AFO1001a <- toxRing(PaPiRaw, PaPiSpan, seriesName = "AFO1001a") #' class(PaPi.AFO1001a) #' toxRing <- function(x, y = NULL, seriesName) { if (is.null(y)) { span <- c(NA, NA) } else { span <- y[seriesName, ] span <- c(span[[1]], span[[2]]) } out <- list( "profile.raw" = as.vector(na.omit(x[, seriesName])), "span" = span, "name" = seriesName ) as.xRing(out) }
/scratch/gouwar.j/cran-all/cranData/xRing/R/toxRing.R
#' @title Create a "xRingList" Object #' @description Converts a dataframe with X-ray microdensity profiles in an "xRingList" object #' @param x a dataframe with X-ray microdensity profiles #' @param y a dataframe with the numerical values of the first and last year in columns. The individual series are specified as row names. By default is NULL #' @return an "xRingList" object, an S3 class which list membera are "xRing" objects containing: #' @return \code{profile.raw} a \code{vector} with the input density profile #' @return \code{span} first and last year #' @return \code{name} a \code{string} giving the series name #' @seealso #' \link{toxRing} #' @export #' @examples #' #' data(PaPiRaw) #' data(PaPiSpan) #' PaPi <- toxRingList(PaPiRaw, PaPiSpan) #' class(PaPi) #' toxRingList <- function(x, y = NULL) { n <- ncol(x) seriesName <- colnames(x) out <- vector("list", n) names(out) <- seriesName for (i in 1:n) { out[[i]] <- toxRing(x, y, seriesName[i]) } class(out) <- c("xRingList", "list") out }
/scratch/gouwar.j/cran-all/cranData/xRing/R/toxRingList.R
trimSeries <- function(x) { xrange <- range(x$limits) x$limits <- x$limits - xrange[1] + 1 x$profile.raw <- x$profile.raw[xrange[1]:xrange[2]] if ("profile" %in% names(x)) { x$profile <- x$profile[xrange[1]:xrange[2]] } x }
/scratch/gouwar.j/cran-all/cranData/xRing/R/trimSeries.R
# Adapted from https://gist.github.com/jbryer/3342915 varEntryDialog <- function(vars, labels = vars, valInitials = rep("", length(vars)), fun = rep(list(as.numeric), length(vars)), title = "", width = 10, prompt = NULL) { stopifnot(length(vars) == length(labels), length(labels) == length(fun)) entries <- list() tclvars <- list() results <- list() done <- tclVar(0) win <- tktoplevel() tcl("wm", "attributes", win, topmost = TRUE) tkgrab.set(win) tkfocus(win) tkwm.title(win, title) tkbind(win, "<Destroy>", function() { tclvalue(done) <- 2 }) frm0 <- tkframe(win, borderwidth = 1, background = "black") tkpack(frm0, anchor = "center", expand = "y") frm1 <- tkframe(frm0) tkpack(frm1 <- tkframe(frm0)) reset <- function(...) { for (i in seq_along(entries)) { tclvalue(tclvars[[i]]) <<- "" } } ok <- function(...) { for (i in seq_along(vars)) { tryCatch( { results[[vars[[i]]]] <<- fun[[i]](tclvalue(tclvars[[i]])) # tclvalue(done) <- 1 }, error = function(e) { tkmessageBox(message = geterrmessage()) }, finally = { } ) } varWithProblems <- is.na(results) if (all(!varWithProblems)) { tclvalue(done) <- 1 } varWithProblemsId <- which(varWithProblems) for (i in varWithProblemsId) { tclvalue(tclvars[[i]]) <<- "" tkconfigure(entries[[i]], background = "red") } varWithoutProblems <- which(!varWithProblems) for (i in varWithoutProblems) { tkconfigure(entries[[i]], background = "white") } } tkbind(win, "<Return>", ok) tkbind(win, "<KP_Enter>", ok) cancel <- function() { tclvalue(done) <- 2 } if (!is.null(prompt)) { tkpack(tklabel(frm1, text = prompt), anchor = "center", expand = TRUE ) } frm2 <- tkframe(frm1, borderwidth = 2) tkpack(frm2, side = "top") for (i in seq_along(vars)) { tclvars[[i]] <- tclVar(valInitials[i]) entries[[i]] <- tkentry( frm2, textvariable = tclvars[[i]], width = width, background = "white", relief = "sunken" ) } for (i in seq_along(vars)) { tkgrid( tklabel( frm2, text = paste0(labels[i], ":"), justify = "right", relief = "flat" ), entries[[i]], pady = 5, padx = 2, sticky = "ewns", columnspan = 2 ) } tt2 <- tkframe(frm1, borderwidth = 2) tkpack(tt2, side = "top") reset.but <- tkbutton( tt2, text = "Reset", command = reset, relief = "raised", width = 8 ) cancel.but <- tkbutton( tt2, text = "Cancel", command = cancel, relief = "groove", width = 8 ) ok.but <- tkbutton( tt2, text = "Ok", command = ok, relief = "groove", width = 8 ) tkpack( reset.but, cancel.but, ok.but, pady = 2, padx = 2, side = "left" ) tkfocus(win) tkbind(win, "<Destroy>", function() { tkgrab.release(win) tclvalue(done) <- 2 }) tkwait.variable(done) if (tclvalue(done) != 1) { results <- NULL } try(tkdestroy(win), silent = TRUE) results }
/scratch/gouwar.j/cran-all/cranData/xRing/R/varEntryDialog.R