From c459550c035041e5e844170ed98b20018eb37be2 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Thu, 18 Nov 2021 15:47:57 +0000 Subject: [PATCH 001/226] bumped version to 0.8.0 --- DESCRIPTION | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/DESCRIPTION b/DESCRIPTION index 3971c74..4c3c1d0 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -1,6 +1,6 @@ Package: MFassign Title: Molecular formula assignment for high resolution metabolomics -Version: 0.7.3 +Version: 0.8.0 Authors@R: person("Jasen", "Finch", email = "jsf9@aber.ac.uk", role = c("aut", "cre")) Description: Molecular formula assignment for high resolution metabolomics. Depends: R (>= 3.5.0), From 4c38a6313b6e65bf5b97c182d4f18c212d47d63e Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Thu, 18 Nov 2021 16:07:45 +0000 Subject: [PATCH 002/226] fixed DESCRIPTION collate field --- DESCRIPTION | 1 + 1 file changed, 1 insertion(+) diff --git a/DESCRIPTION b/DESCRIPTION index 4c3c1d0..3e47582 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -63,5 +63,6 @@ Collate: 'calcCorrelations-method.R' 'filterCorrelations-method.R' 'plotSpectrum-method.R' + reexports.R Suggests: testthat, covr From 85455e7cc273759dbe88e808f4fbd1acc4e1bfaa Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Thu, 18 Nov 2021 16:08:20 +0000 Subject: [PATCH 003/226] isolated plotFeatureSolutions plotting function to reduce returned plot size and added unit test --- R/plotFeatureSolutions.R | 85 ++++++++++++++++++--------------- tests/testthat/test-assignMFs.R | 8 ++++ 2 files changed, 54 insertions(+), 39 deletions(-) diff --git a/R/plotFeatureSolutions.R b/R/plotFeatureSolutions.R index 8d2521a..465c621 100644 --- a/R/plotFeatureSolutions.R +++ b/R/plotFeatureSolutions.R @@ -1,3 +1,46 @@ + +plotSolutions <- function(graph,selectedComp,feature){ + graph %>% + map(~{ + stats <- nodes(.) %>% + select(Component:Plausibility) %>% + .[1,] + + if (stats$Component[1] == selectedComp){ + border <- 'red' + } else { + border <- 'black' + } + + g <- . + g <- g %>% + mutate(Feat = Feature == feature) %>% + create_layout('nicely') + ggraph(g) + + geom_edge_link(aes(colour = r)) + + scale_edge_color_gradient(low = 'white',high = 'black',limits = c(0.5,1)) + + geom_node_label(aes(label = name,fill = Feat),size = 2,) + + scale_fill_manual(values = c('white','steelblue')) + + theme_graph(title_size = 12, + title_face = 'plain', + foreground = border, + plot_margin = margin(5, 5, 5, 5)) + + labs(title = str_c('Component ',stats$Component), + caption = str_c('Size = ',stats$Size,'; ', + 'Nodes = ',stats$Nodes,'; ', + 'Weight = ',stats$Weight %>% round(2),'; ', + 'Density = ',stats$Density %>% round(2),'; ', + 'AIS = ',stats$AIS %>% round(2),'; ', + 'Plausibility = ',stats$Plausibility %>% round(2))) + + xlim(min(g$x) - (max(g$x) - min(g$x)) * 0.05, + max(g$x) + (max(g$x) - min(g$x)) * 0.05) + + ylim(min(g$y) - (max(g$y) - min(g$y)) * 0.05, + max(g$y) + (max(g$y) - min(g$y)) * 0.05) + + guides(fill = FALSE) + }) %>% + wrap_plots() + plot_annotation(title = str_c('Solutions for feature ',feature)) +} + #' plotFeatureSolutions #' @rdname plotFeatureSolutions #' @description Plot possible MF solutions for a given feature. @@ -50,43 +93,7 @@ setMethod('plotFeatureSolutions',signature = 'Assignment', filter(Feature == feature) %>% .$Component - graph %>% - map(~{ - stats <- nodes(.) %>% - select(Component:Plausibility) %>% - .[1,] - - if (stats$Component[1] == selectedComp){ - border <- 'red' - } else { - border <- 'black' - } - - g <- . - g <- g %>% - mutate(Feat = Feature == feature) %>% - create_layout('nicely') - ggraph(g) + - geom_edge_link(aes(colour = r)) + - scale_edge_color_gradient(low = 'white',high = 'black',limits = c(0.5,1)) + - geom_node_label(aes(label = name,fill = Feat),size = 2,) + - scale_fill_manual(values = c('white','steelblue')) + - theme_graph(title_size = 12, - title_face = 'plain', - foreground = border, - plot_margin = margin(5, 5, 5, 5)) + - labs(title = str_c('Component ',stats$Component), - caption = str_c('Size = ',stats$Size,'; ', - 'Nodes = ',stats$Nodes,'; ', - 'Weight = ',stats$Weight %>% round(2),'; ', - 'Density = ',stats$Density %>% round(2),'; ', - 'AIS = ',stats$AIS %>% round(2),'; ', - 'Plausibility = ',stats$Plausibility %>% round(2))) + - xlim(min(g$x) - (max(g$x) - min(g$x)) * 0.05, - max(g$x) + (max(g$x) - min(g$x)) * 0.05) + - ylim(min(g$y) - (max(g$y) - min(g$y)) * 0.05, - max(g$y) + (max(g$y) - min(g$y)) * 0.05) + - guides(fill = FALSE) - }) %>% - wrap_plots() + plot_annotation(title = str_c('Solutions for feature ',feature)) + pl <- plotSolutions(graph,selectedComp,feature) + + return(pl) }) diff --git a/tests/testthat/test-assignMFs.R b/tests/testthat/test-assignMFs.R index d222963..cd16589 100644 --- a/tests/testthat/test-assignMFs.R +++ b/tests/testthat/test-assignMFs.R @@ -11,4 +11,12 @@ assignment <- assignMFs(peakData, test_that('assignMFs works',{ expect_s4_class(assignment,"Assignment") +}) + +test_that('feature solutions can be plotted',{ + pl <- plotFeatureSolutions(assignment, + 'n191.01962', + maxComponents = 2) + + expect_s3_class(pl,'patchwork') }) \ No newline at end of file From cfb432e1d8020402f86d656d4b67040844920b3f Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Thu, 18 Nov 2021 16:11:12 +0000 Subject: [PATCH 004/226] fixed warnings in plotFeatureSolutions() --- R/plotFeatureSolutions.R | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/R/plotFeatureSolutions.R b/R/plotFeatureSolutions.R index 465c621..51bd292 100644 --- a/R/plotFeatureSolutions.R +++ b/R/plotFeatureSolutions.R @@ -21,7 +21,8 @@ plotSolutions <- function(graph,selectedComp,feature){ scale_edge_color_gradient(low = 'white',high = 'black',limits = c(0.5,1)) + geom_node_label(aes(label = name,fill = Feat),size = 2,) + scale_fill_manual(values = c('white','steelblue')) + - theme_graph(title_size = 12, + theme_graph(base_family = '', + title_size = 12, title_face = 'plain', foreground = border, plot_margin = margin(5, 5, 5, 5)) + @@ -36,7 +37,7 @@ plotSolutions <- function(graph,selectedComp,feature){ max(g$x) + (max(g$x) - min(g$x)) * 0.05) + ylim(min(g$y) - (max(g$y) - min(g$y)) * 0.05, max(g$y) + (max(g$y) - min(g$y)) * 0.05) + - guides(fill = FALSE) + guides(fill = 'none') }) %>% wrap_plots() + plot_annotation(title = str_c('Solutions for feature ',feature)) } From 7f2bd9f6372b2e3148a3616db55cc703db31ae60 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Fri, 19 Nov 2021 09:00:22 +0000 Subject: [PATCH 005/226] plausibility function added to internals --- DESCRIPTION | 1 + R/calcComponents.R | 2 +- R/internals.R | 4 ++++ R/recalcComponents.R | 2 +- 4 files changed, 7 insertions(+), 2 deletions(-) create mode 100644 R/internals.R diff --git a/DESCRIPTION b/DESCRIPTION index 3e47582..eba306d 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -64,5 +64,6 @@ Collate: 'filterCorrelations-method.R' 'plotSpectrum-method.R' reexports.R + internals.R Suggests: testthat, covr diff --git a/R/calcComponents.R b/R/calcComponents.R index d3c8197..4818937 100644 --- a/R/calcComponents.R +++ b/R/calcComponents.R @@ -37,7 +37,7 @@ calcComponents <- function(MFs,rel,parameters) { Density = (2 * Size) / (Nodes * (Nodes - 1)), Weight = sum(Weight) / Nodes, AIS = sum(AddIsoScore) / Nodes, - Plausibility = AIS * Size * Weight) %>% + Plausibility = plausibility(AIS,Size,Weight)) %>% unmorph() return(graph) diff --git a/R/internals.R b/R/internals.R new file mode 100644 index 0000000..53e2f43 --- /dev/null +++ b/R/internals.R @@ -0,0 +1,4 @@ + +plausibility <- function(AIS,Size,Weight){ + AIS + Weight + Size/10 +} diff --git a/R/recalcComponents.R b/R/recalcComponents.R index 13ffbae..6c4cff4 100644 --- a/R/recalcComponents.R +++ b/R/recalcComponents.R @@ -32,6 +32,6 @@ recalcComponents <- function(graph,parameters){ Density = (2 * Size) / (Nodes * (Nodes - 1)), Weight = sum(Weight) / Nodes, AIS = sum(AddIsoScore) / Nodes, - Plausibility = AIS * Size * Weight) %>% + Plausibility = plausibility(AIS,Size,Weight)) %>% unmorph() } \ No newline at end of file From 89badb289331cddfb2f9be8bfc0fb1074557a6e4 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Fri, 19 Nov 2021 09:34:38 +0000 Subject: [PATCH 006/226] move component calculation functions to the same file --- DESCRIPTION | 3 +- R/{calcComponents.R => components.R} | 42 +++++++++++++++++++++++++++- R/recalcComponents.R | 37 ------------------------ 3 files changed, 42 insertions(+), 40 deletions(-) rename R/{calcComponents.R => components.R} (53%) delete mode 100644 R/recalcComponents.R diff --git a/DESCRIPTION b/DESCRIPTION index eba306d..691127b 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -42,7 +42,7 @@ Collate: 'MFscore.R' 'addIsoScore.R' 'addMFs.R' - 'calcComponents.R' + components.R 'assignMethods.R' 'peakData.R' 'LCassignment.R' @@ -57,7 +57,6 @@ Collate: 'networkComponents.R' 'addNames.R' 'eliminate.R' - 'recalcComponents.R' 'plotAdductDist-method.R' 'plotFeatureSolutions.R' 'calcCorrelations-method.R' diff --git a/R/calcComponents.R b/R/components.R similarity index 53% rename from R/calcComponents.R rename to R/components.R index 4818937..ab82ed5 100644 --- a/R/calcComponents.R +++ b/R/components.R @@ -34,11 +34,51 @@ calcComponents <- function(MFs,rel,parameters) { morph(to_components) %>% mutate(Size = graph_size(), Nodes = n(), + Degree = degree(Nodes,Size),, Density = (2 * Size) / (Nodes * (Nodes - 1)), Weight = sum(Weight) / Nodes, AIS = sum(AddIsoScore) / Nodes, - Plausibility = plausibility(AIS,Size,Weight)) %>% + Plausibility = plausibility(AIS,Degree,Weight)) %>% unmorph() return(graph) +} + +#' @importFrom tidygraph to_components +#' @importFrom dplyr n + +recalcComponents <- function(graph,parameters){ + g <- graph %>% + activate(nodes) + + comp <- g %>% + nodes() %>% + .$Component %>% + unique() + + weights <- comp %>% + future_map(~{ + graph %>% + filter(Component == .x) %>% + edges() %>% + .$r %>% + mean() %>% + tibble(Weight = .) + },graph = g) %>% + set_names(comp) %>% + bind_rows(.id = 'Component') %>% + mutate(Component = as.numeric(Component)) + + g %>% + select(-Weight) %>% + left_join(weights,by = 'Component') %>% + morph(to_components) %>% + mutate(Size = graph_size(), + Nodes = n(), + Degree = degree(Nodes,Size), + Density = (2 * Size) / (Nodes * (Nodes - 1)), + Weight = sum(Weight) / Nodes, + AIS = sum(AddIsoScore) / Nodes, + Plausibility = plausibility(AIS,Size,Weight)) %>% + unmorph() } \ No newline at end of file diff --git a/R/recalcComponents.R b/R/recalcComponents.R deleted file mode 100644 index 6c4cff4..0000000 --- a/R/recalcComponents.R +++ /dev/null @@ -1,37 +0,0 @@ -#' @importFrom tidygraph to_components -#' @importFrom dplyr n - -recalcComponents <- function(graph,parameters){ - g <- graph %>% - activate(nodes) - - comp <- g %>% - nodes() %>% - .$Component %>% - unique() - - weights <- comp %>% - future_map(~{ - graph %>% - filter(Component == .x) %>% - edges() %>% - .$r %>% - mean() %>% - tibble(Weight = .) - },graph = g) %>% - set_names(comp) %>% - bind_rows(.id = 'Component') %>% - mutate(Component = as.numeric(Component)) - - g %>% - select(-Weight) %>% - left_join(weights,by = 'Component') %>% - morph(to_components) %>% - mutate(Size = graph_size(), - Nodes = n(), - Density = (2 * Size) / (Nodes * (Nodes - 1)), - Weight = sum(Weight) / Nodes, - AIS = sum(AddIsoScore) / Nodes, - Plausibility = plausibility(AIS,Size,Weight)) %>% - unmorph() -} \ No newline at end of file From e2ddd2b2c6b9911360a7e78e4eec913f666a43d0 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Fri, 19 Nov 2021 09:34:49 +0000 Subject: [PATCH 007/226] added degree function --- R/internals.R | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/R/internals.R b/R/internals.R index 53e2f43..7998d8c 100644 --- a/R/internals.R +++ b/R/internals.R @@ -1,4 +1,8 @@ -plausibility <- function(AIS,Size,Weight){ - AIS + Weight + Size/10 +degree <- function(n_nodes,n_edges){ + 2 * (n_edges / n_nodes) +} + +plausibility <- function(AIS,degree,weight){ + AIS + weight + degree/10 } From 5ded93bc95215dccb71a3e39236b374ae305c695 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Fri, 19 Nov 2021 09:35:49 +0000 Subject: [PATCH 008/226] moved network components to internals --- DESCRIPTION | 1 - R/internals.R | 4 ++++ R/networkComponents.R | 4 ---- 3 files changed, 4 insertions(+), 5 deletions(-) delete mode 100644 R/networkComponents.R diff --git a/DESCRIPTION b/DESCRIPTION index 691127b..aa3828b 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -54,7 +54,6 @@ Collate: 'access-methods.R' 'summariseAssignment-method.R' 'plotNetwork-method.R' - 'networkComponents.R' 'addNames.R' 'eliminate.R' 'plotAdductDist-method.R' diff --git a/R/internals.R b/R/internals.R index 7998d8c..440edc9 100644 --- a/R/internals.R +++ b/R/internals.R @@ -1,4 +1,8 @@ +networkComponents <- function(nodes,edges){ + graph <- as_tbl_graph(edges,directed = F) +} + degree <- function(n_nodes,n_edges){ 2 * (n_edges / n_nodes) } diff --git a/R/networkComponents.R b/R/networkComponents.R deleted file mode 100644 index 5babed4..0000000 --- a/R/networkComponents.R +++ /dev/null @@ -1,4 +0,0 @@ - -networkComponents <- function(nodes,edges){ - graph <- as_tbl_graph(edges,directed = F) -} \ No newline at end of file From 6e7699fe5146653be4e56547495c4e941b6c7309 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Fri, 19 Nov 2021 09:56:01 +0000 Subject: [PATCH 009/226] Removed redundant metrics from plotFeatureSolutions --- R/plotFeatureSolutions.R | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/R/plotFeatureSolutions.R b/R/plotFeatureSolutions.R index 51bd292..8798569 100644 --- a/R/plotFeatureSolutions.R +++ b/R/plotFeatureSolutions.R @@ -27,10 +27,8 @@ plotSolutions <- function(graph,selectedComp,feature){ foreground = border, plot_margin = margin(5, 5, 5, 5)) + labs(title = str_c('Component ',stats$Component), - caption = str_c('Size = ',stats$Size,'; ', - 'Nodes = ',stats$Nodes,'; ', + caption = str_c('Degree = ',stats$Degree %>% round(2),'; ', 'Weight = ',stats$Weight %>% round(2),'; ', - 'Density = ',stats$Density %>% round(2),'; ', 'AIS = ',stats$AIS %>% round(2),'; ', 'Plausibility = ',stats$Plausibility %>% round(2))) + xlim(min(g$x) - (max(g$x) - min(g$x)) * 0.05, From b540d87e41ae0f1d2885cd9d0782df0c3f597144 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Fri, 19 Nov 2021 09:57:29 +0000 Subject: [PATCH 010/226] moved component metrics functions to components file --- R/components.R | 36 ++++++++++++++++++++++-------------- R/internals.R | 8 -------- 2 files changed, 22 insertions(+), 22 deletions(-) diff --git a/R/components.R b/R/components.R index ab82ed5..2860687 100644 --- a/R/components.R +++ b/R/components.R @@ -1,3 +1,23 @@ + +degree <- function(n_nodes,n_edges){ + 2 * (n_edges / n_nodes) +} + +plausibility <- function(AIS,degree,weight){ + AIS + weight + degree/10 +} + +componentMetrics <- function(component){ + component %>% + mutate(Size = graph_size(), + Nodes = n(), + Degree = degree(Nodes,Size),, + Density = (2 * Size) / (Nodes * (Nodes - 1)), + Weight = sum(Weight) / Nodes, + AIS = sum(AddIsoScore) / Nodes, + Plausibility = plausibility(AIS,Degree,Weight)) +} + #' @importFrom tidygraph as_tbl_graph activate morph unmorph graph_size group_components tbl_graph #' @importFrom magrittr set_names @@ -32,13 +52,7 @@ calcComponents <- function(MFs,rel,parameters) { graph <- graph %>% left_join(weights,by = 'Component') %>% morph(to_components) %>% - mutate(Size = graph_size(), - Nodes = n(), - Degree = degree(Nodes,Size),, - Density = (2 * Size) / (Nodes * (Nodes - 1)), - Weight = sum(Weight) / Nodes, - AIS = sum(AddIsoScore) / Nodes, - Plausibility = plausibility(AIS,Degree,Weight)) %>% + componentMetrics() %>% unmorph() return(graph) @@ -73,12 +87,6 @@ recalcComponents <- function(graph,parameters){ select(-Weight) %>% left_join(weights,by = 'Component') %>% morph(to_components) %>% - mutate(Size = graph_size(), - Nodes = n(), - Degree = degree(Nodes,Size), - Density = (2 * Size) / (Nodes * (Nodes - 1)), - Weight = sum(Weight) / Nodes, - AIS = sum(AddIsoScore) / Nodes, - Plausibility = plausibility(AIS,Size,Weight)) %>% + componentMetrics() %>% unmorph() } \ No newline at end of file diff --git a/R/internals.R b/R/internals.R index 440edc9..bcd4130 100644 --- a/R/internals.R +++ b/R/internals.R @@ -2,11 +2,3 @@ networkComponents <- function(nodes,edges){ graph <- as_tbl_graph(edges,directed = F) } - -degree <- function(n_nodes,n_edges){ - 2 * (n_edges / n_nodes) -} - -plausibility <- function(AIS,degree,weight){ - AIS + weight + degree/10 -} From bd93ef79871e1e7a74d0dd7e6047d06ab4495151 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Fri, 19 Nov 2021 10:03:01 +0000 Subject: [PATCH 011/226] removed redundant networkComponents() --- DESCRIPTION | 1 - R/internals.R | 4 ---- 2 files changed, 5 deletions(-) delete mode 100644 R/internals.R diff --git a/DESCRIPTION b/DESCRIPTION index aa3828b..b2856fb 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -62,6 +62,5 @@ Collate: 'filterCorrelations-method.R' 'plotSpectrum-method.R' reexports.R - internals.R Suggests: testthat, covr diff --git a/R/internals.R b/R/internals.R deleted file mode 100644 index bcd4130..0000000 --- a/R/internals.R +++ /dev/null @@ -1,4 +0,0 @@ - -networkComponents <- function(nodes,edges){ - graph <- as_tbl_graph(edges,directed = F) -} From c7f3de395e5a4c20825aa46b21b274cfad2e7b83 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Fri, 19 Nov 2021 10:09:52 +0000 Subject: [PATCH 012/226] Moved plotFeatureSolutions generic and fixed declaration --- R/plotFeatureSolutions.R | 9 ++++++++- man/plotFeatureSolutions.Rd | 4 ++-- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/R/plotFeatureSolutions.R b/R/plotFeatureSolutions.R index 8798569..9f7ed9f 100644 --- a/R/plotFeatureSolutions.R +++ b/R/plotFeatureSolutions.R @@ -40,7 +40,7 @@ plotSolutions <- function(graph,selectedComp,feature){ wrap_plots() + plot_annotation(title = str_c('Solutions for feature ',feature)) } -#' plotFeatureSolutions +#' Plot the solutions for a feature #' @rdname plotFeatureSolutions #' @description Plot possible MF solutions for a given feature. #' @param assignment S4 object of class Assignent @@ -51,6 +51,13 @@ plotSolutions <- function(graph,selectedComp,feature){ #' @importFrom ggplot2 scale_fill_manual margin xlim ylim guides #' @export +setGeneric('plotFeatureSolutions', + function(assignment,feature,maxComponents = 10) + standardGeneric('plotFeatureSolutions') +) + +#' @rdname plotFeatureSolutions + setMethod('plotFeatureSolutions',signature = 'Assignment', function(assignment,feature,maxComponents = 10){ diff --git a/man/plotFeatureSolutions.Rd b/man/plotFeatureSolutions.Rd index f16a65d..80e53df 100644 --- a/man/plotFeatureSolutions.Rd +++ b/man/plotFeatureSolutions.Rd @@ -1,9 +1,9 @@ % Generated by roxygen2: do not edit by hand -% Please edit documentation in R/allGenerics.R, R/plotFeatureSolutions.R +% Please edit documentation in R/plotFeatureSolutions.R \name{plotFeatureSolutions} \alias{plotFeatureSolutions} \alias{plotFeatureSolutions,Assignment-method} -\title{plotFeatureSolutions} +\title{Plot the solutions for a feature} \usage{ plotFeatureSolutions(assignment, feature, maxComponents = 10) From 3d0b1b31d053b6490daf395466b450c5b4c77008 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Fri, 19 Nov 2021 10:10:29 +0000 Subject: [PATCH 013/226] moved plotNetwork generic and fixed declaration --- R/allGenerics.R | 10 ---------- R/{plotNetwork-method.R => plotNetwork.R} | 8 +++++++- man/plotNetwork.Rd | 4 ++-- 3 files changed, 9 insertions(+), 13 deletions(-) rename R/{plotNetwork-method.R => plotNetwork.R} (95%) diff --git a/R/allGenerics.R b/R/allGenerics.R index e077c6c..c3ba302 100644 --- a/R/allGenerics.R +++ b/R/allGenerics.R @@ -46,21 +46,11 @@ setGeneric('assignedData',function(assignment){ standardGeneric('assignedData') }) -#' @rdname plotNetwork -setGeneric('plotNetwork',function(assignment, layout = 'stress', rThreshold = 0.7){ -standardGeneric('plotNetwork') -}) - #' @rdname plotAdductDist setGeneric('plotAdductDist',function(assignment){ standardGeneric('plotAdductDist') }) -#' @rdname plotFeatureSolutions -setGeneric('plotFeatureSolutions',function(assignment,feature,maxComponents = 10){ - standardGeneric('plotFeatureSolutions') -}) - #' @rdname plotSpectrum setGeneric('plotSpectrum',function(assignment,MF){ standardGeneric('plotSpectrum') diff --git a/R/plotNetwork-method.R b/R/plotNetwork.R similarity index 95% rename from R/plotNetwork-method.R rename to R/plotNetwork.R index 6fa9799..6e0687b 100644 --- a/R/plotNetwork-method.R +++ b/R/plotNetwork.R @@ -1,4 +1,4 @@ -#' plotNetwork-Assignment +#' Plot an assignment network #' @rdname plotNetwork #' @description plot assignment network #' @param assignment of class Assignment @@ -12,6 +12,12 @@ #' @importFrom graphlayouts layout_igraph_stress #' @export +setGeneric('plotNetwork',function(assignment, layout = 'stress', rThreshold = 0.7){ + standardGeneric('plotNetwork') +}) + +#' @rdname plotNetwork + setMethod('plotNetwork',signature = 'Assignment', function(assignment, layout = 'stress', rThreshold = 0.7){ diff --git a/man/plotNetwork.Rd b/man/plotNetwork.Rd index 466f2c9..d79d612 100644 --- a/man/plotNetwork.Rd +++ b/man/plotNetwork.Rd @@ -1,9 +1,9 @@ % Generated by roxygen2: do not edit by hand -% Please edit documentation in R/allGenerics.R, R/plotNetwork-method.R +% Please edit documentation in R/plotNetwork-method.R \name{plotNetwork} \alias{plotNetwork} \alias{plotNetwork,Assignment-method} -\title{plotNetwork-Assignment} +\title{Plot an assignment network} \usage{ plotNetwork(assignment, layout = "stress", rThreshold = 0.7) From e0ed04dcfbbe351578e9a3ba61a026806f897a7a Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Fri, 19 Nov 2021 10:10:47 +0000 Subject: [PATCH 014/226] Updated NAMESPACE and DESCRIPTION --- DESCRIPTION | 4 ++-- NAMESPACE | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/DESCRIPTION b/DESCRIPTION index b2856fb..682d393 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -28,7 +28,7 @@ Imports: CHNOSZ, License: GPL (>= 3) Encoding: UTF-8 LazyData: true -RoxygenNote: 7.0.2 +RoxygenNote: 7.1.2 Collate: 'allGenerics.R' 'allClasses.R' @@ -53,7 +53,7 @@ Collate: 'show-method.R' 'access-methods.R' 'summariseAssignment-method.R' - 'plotNetwork-method.R' + plotNetwork.R 'addNames.R' 'eliminate.R' 'plotAdductDist-method.R' diff --git a/NAMESPACE b/NAMESPACE index 7de078c..42cb0ed 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -6,14 +6,14 @@ export(continueAssignment) export(edges) export(nodes) export(plan) +export(plotFeatureSolutions) +export(plotNetwork) exportClasses(Assignment) exportClasses(AssignmentParameters) exportMethods(assignedData) exportMethods(assignmentData) exportMethods(assignments) exportMethods(plotAdductDist) -exportMethods(plotFeatureSolutions) -exportMethods(plotNetwork) exportMethods(plotSpectrum) exportMethods(show) exportMethods(summariseAssignment) From 837fc57d93cd0dfa2eaf8639d74720efb0e7b62c Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Fri, 19 Nov 2021 10:15:40 +0000 Subject: [PATCH 015/226] Moved doAssignment method and generic --- DESCRIPTION | 1 - R/allGenerics.R | 4 ---- R/assignMFs.R | 51 +++++++++++++++++++++++++++++------------ R/doAssignment-method.R | 16 ------------- 4 files changed, 36 insertions(+), 36 deletions(-) delete mode 100644 R/doAssignment-method.R diff --git a/DESCRIPTION b/DESCRIPTION index 682d393..c251304 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -48,7 +48,6 @@ Collate: 'LCassignment.R' 'MFassign.R' 'FIEassignment.R' - 'doAssignment-method.R' 'continueAssignment.R' 'show-method.R' 'access-methods.R' diff --git a/R/allGenerics.R b/R/allGenerics.R index c3ba302..99d2c43 100644 --- a/R/allGenerics.R +++ b/R/allGenerics.R @@ -22,10 +22,6 @@ setGeneric("transformationAssign", function(assignment) { standardGeneric("transformationAssign") }) -setGeneric('doAssignment',function(assignment){ - standardGeneric('doAssignment') -}) - #' @rdname assignments setGeneric('assignments',function(assignment){ standardGeneric('assignments') diff --git a/R/assignMFs.R b/R/assignMFs.R index a77713f..d6e069b 100644 --- a/R/assignMFs.R +++ b/R/assignMFs.R @@ -1,3 +1,24 @@ + +setGeneric('doAssignment',function(assignment){ + standardGeneric('doAssignment') +}) + +setMethod('doAssignment',signature = 'Assignment', + function(assignment){ + assignmentMethod <- assignMethods(assignment@parameters@technique) + + elements <- names(assignmentMethod()) + elements <- elements[!(elements %in% assignment@flags)] + + for(i in elements){ + method <- assignmentMethod(i) + assignment <- method(assignment) + assignment@flags <- c(assignment@flags,i) + } + + return(assignment) + }) + #' assignMFs #' @description assign molecular formulas to a set of given m/z. #' @param dat tibble containing the peak intensities of m/z for which to assign molecular formulas @@ -41,19 +62,19 @@ assignMFs <- function(dat,parameters,verbose = TRUE) { parameters = parameters) assignment@log$verbose <- verbose - assignment <- assignment %>% - doAssignment() - - if (verbose == T) { - endTime <- proc.time() - elapsed <- {endTime - startTime} %>% - .[3] %>% - round(1) %>% - seconds_to_period() %>% - str_c('[',.,']') - message(rep('_',console_width())) - message('\n',green('Complete! '),elapsed,'\n') - } - - return(assignment) + assignment <- assignment %>% + doAssignment() + + if (verbose == TRUE) { + endTime <- proc.time() + elapsed <- {endTime - startTime} %>% + .[3] %>% + round(1) %>% + seconds_to_period() %>% + str_c('[',.,']') + message(rep('_',console_width())) + message('\n',green('Complete! '),elapsed,'\n') + } + + return(assignment) } \ No newline at end of file diff --git a/R/doAssignment-method.R b/R/doAssignment-method.R deleted file mode 100644 index e03fc9e..0000000 --- a/R/doAssignment-method.R +++ /dev/null @@ -1,16 +0,0 @@ - -setMethod('doAssignment',signature = 'Assignment', - function(assignment){ - assignmentMethod <- assignMethods(assignment@parameters@technique) - - elements <- names(assignmentMethod()) - elements <- elements[!(elements %in% assignment@flags)] - - for(i in elements){ - method <- assignmentMethod(i) - assignment <- method(assignment) - assignment@flags <- c(assignment@flags,i) - } - - return(assignment) - }) \ No newline at end of file From 0e37a37720a6768bfdb87eaa2b88ad6cd4108c14 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Fri, 19 Nov 2021 10:31:12 +0000 Subject: [PATCH 016/226] fixed DESCRIPTION --- DESCRIPTION | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/DESCRIPTION b/DESCRIPTION index c251304..ab93515 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -24,7 +24,9 @@ Imports: CHNOSZ, mzAnnotation, metabolyseR, ggrepel, - graphlayouts + graphlayouts, + furrr, + future License: GPL (>= 3) Encoding: UTF-8 LazyData: true From 6a51712f6780c843abd9e98753e42d695a307853 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Fri, 19 Nov 2021 10:35:34 +0000 Subject: [PATCH 017/226] moved ggraph to imports --- DESCRIPTION | 36 ++++++++++++++++++------------------ 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/DESCRIPTION b/DESCRIPTION index ab93515..637eb24 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -3,30 +3,30 @@ Title: Molecular formula assignment for high resolution metabolomics Version: 0.8.0 Authors@R: person("Jasen", "Finch", email = "jsf9@aber.ac.uk", role = c("aut", "cre")) Description: Molecular formula assignment for high resolution metabolomics. -Depends: R (>= 3.5.0), - ggraph +Depends: R (>= 3.5.0) Imports: CHNOSZ, + cli, + crayon, dplyr, + furrr, + future, + ggplot2, + ggraph, + ggrepel, + ggthemes, + graphlayouts, + igraph, + lubridate, magrittr, - stringr, - tibble, methods, - tidyr, - crayon, - purrr, - cli, - lubridate, - tidygraph, - igraph, - ggthemes, - ggplot2, - patchwork, mzAnnotation, metabolyseR, - ggrepel, - graphlayouts, - furrr, - future + patchwork, + purrr, + stringr, + tibble, + tidygraph, + tidyr License: GPL (>= 3) Encoding: UTF-8 LazyData: true From 806b2d794c7f7540d96c0c45ab703d465dc6012e Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Fri, 19 Nov 2021 10:36:05 +0000 Subject: [PATCH 018/226] fix ggraph function import --- NAMESPACE | 1 + R/plotFeatureSolutions.R | 10 ++++++---- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/NAMESPACE b/NAMESPACE index 42cb0ed..43fcf7c 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -71,6 +71,7 @@ importFrom(ggraph,geom_node_label) importFrom(ggraph,geom_node_point) importFrom(ggraph,geom_node_text) importFrom(ggraph,ggraph) +importFrom(ggraph,guide_edge_colourbar) importFrom(ggraph,scale_edge_color_gradient) importFrom(ggraph,theme_graph) importFrom(ggrepel,geom_text_repel) diff --git a/R/plotFeatureSolutions.R b/R/plotFeatureSolutions.R index 9f7ed9f..9ac52f3 100644 --- a/R/plotFeatureSolutions.R +++ b/R/plotFeatureSolutions.R @@ -1,3 +1,6 @@ +#' @importFrom patchwork plot_annotation +#' @importFrom ggraph create_layout scale_edge_color_gradient geom_node_label guide_edge_colourbar +#' @importFrom ggplot2 scale_fill_manual margin xlim ylim guides plotSolutions <- function(graph,selectedComp,feature){ graph %>% @@ -37,7 +40,9 @@ plotSolutions <- function(graph,selectedComp,feature){ max(g$y) + (max(g$y) - min(g$y)) * 0.05) + guides(fill = 'none') }) %>% - wrap_plots() + plot_annotation(title = str_c('Solutions for feature ',feature)) + wrap_plots() + + plot_annotation(title = str_c('Solutions for feature ', + feature)) } #' Plot the solutions for a feature @@ -46,9 +51,6 @@ plotSolutions <- function(graph,selectedComp,feature){ #' @param assignment S4 object of class Assignent #' @param feature name of feature to plot #' @param maxComponents maximum number of components to plot -#' @importFrom patchwork plot_annotation -#' @importFrom ggraph create_layout scale_edge_color_gradient geom_node_label -#' @importFrom ggplot2 scale_fill_manual margin xlim ylim guides #' @export setGeneric('plotFeatureSolutions', From 52df842ac35aa42250b7220a37a2147aaf1de071 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Fri, 19 Nov 2021 10:36:35 +0000 Subject: [PATCH 019/226] udpate documentation --- man/plotNetwork.Rd | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/man/plotNetwork.Rd b/man/plotNetwork.Rd index d79d612..adc5718 100644 --- a/man/plotNetwork.Rd +++ b/man/plotNetwork.Rd @@ -1,5 +1,5 @@ % Generated by roxygen2: do not edit by hand -% Please edit documentation in R/plotNetwork-method.R +% Please edit documentation in R/plotNetwork.R \name{plotNetwork} \alias{plotNetwork} \alias{plotNetwork,Assignment-method} From 464f6aff44d8a670075502e1e5c2316cbf7b014b Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Fri, 19 Nov 2021 10:44:20 +0000 Subject: [PATCH 020/226] plotFeatureSolutions() layout --- NAMESPACE | 1 + R/plotFeatureSolutions.R | 10 ++++++++-- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/NAMESPACE b/NAMESPACE index 43fcf7c..d43e7d5 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -108,6 +108,7 @@ importFrom(mzAnnotation,transformMF) importFrom(mzAnnotation,transformations) importFrom(parallel,detectCores) importFrom(patchwork,plot_annotation) +importFrom(patchwork,plot_layout) importFrom(patchwork,wrap_plots) importFrom(purrr,map) importFrom(purrr,map_dbl) diff --git a/R/plotFeatureSolutions.R b/R/plotFeatureSolutions.R index 9ac52f3..409af54 100644 --- a/R/plotFeatureSolutions.R +++ b/R/plotFeatureSolutions.R @@ -1,4 +1,4 @@ -#' @importFrom patchwork plot_annotation +#' @importFrom patchwork plot_annotation plot_layout #' @importFrom ggraph create_layout scale_edge_color_gradient geom_node_label guide_edge_colourbar #' @importFrom ggplot2 scale_fill_manual margin xlim ylim guides @@ -29,6 +29,9 @@ plotSolutions <- function(graph,selectedComp,feature){ title_face = 'plain', foreground = border, plot_margin = margin(5, 5, 5, 5)) + + theme(plot.title = element_text(face = 'bold', + hjust = 0.5), + plot.caption = element_text(hjust = 0)) + labs(title = str_c('Component ',stats$Component), caption = str_c('Degree = ',stats$Degree %>% round(2),'; ', 'Weight = ',stats$Weight %>% round(2),'; ', @@ -41,8 +44,11 @@ plotSolutions <- function(graph,selectedComp,feature){ guides(fill = 'none') }) %>% wrap_plots() + + plot_layout(guides = 'collect') + plot_annotation(title = str_c('Solutions for feature ', - feature)) + feature), + theme = theme(plot.title = element_text(face = 'bold', + hjust = 0.5))) } #' Plot the solutions for a feature From d128d9166bfe087f0dc614e56048360bf7d9e6d4 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Fri, 19 Nov 2021 10:48:29 +0000 Subject: [PATCH 021/226] moved ggraph back to depends --- DESCRIPTION | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/DESCRIPTION b/DESCRIPTION index 637eb24..238e821 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -3,7 +3,8 @@ Title: Molecular formula assignment for high resolution metabolomics Version: 0.8.0 Authors@R: person("Jasen", "Finch", email = "jsf9@aber.ac.uk", role = c("aut", "cre")) Description: Molecular formula assignment for high resolution metabolomics. -Depends: R (>= 3.5.0) +Depends: R (>= 3.5.0), + ggraph Imports: CHNOSZ, cli, crayon, @@ -11,7 +12,6 @@ Imports: CHNOSZ, furrr, future, ggplot2, - ggraph, ggrepel, ggthemes, graphlayouts, From ae2dc30d9ddf942c353bd8fee7f7302a8430ff62 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Fri, 19 Nov 2021 11:53:15 +0000 Subject: [PATCH 022/226] Moved plotAdductDist() generic to method file and improved plot theme --- R/allGenerics.R | 5 ----- R/plotAdductDist-method.R | 27 ++++++++++++++++++++++----- man/plotAdductDist.Rd | 6 +++--- 3 files changed, 25 insertions(+), 13 deletions(-) diff --git a/R/allGenerics.R b/R/allGenerics.R index 99d2c43..ec75320 100644 --- a/R/allGenerics.R +++ b/R/allGenerics.R @@ -42,11 +42,6 @@ setGeneric('assignedData',function(assignment){ standardGeneric('assignedData') }) -#' @rdname plotAdductDist -setGeneric('plotAdductDist',function(assignment){ - standardGeneric('plotAdductDist') -}) - #' @rdname plotSpectrum setGeneric('plotSpectrum',function(assignment,MF){ standardGeneric('plotSpectrum') diff --git a/R/plotAdductDist-method.R b/R/plotAdductDist-method.R index 2b7c675..e621778 100644 --- a/R/plotAdductDist-method.R +++ b/R/plotAdductDist-method.R @@ -1,16 +1,28 @@ -#' plotAdductDist-Assignment +#' Plot adduct frequency distributions #' @rdname plotAdductDist -#' @description Plot adduct distributions. +#' @description Plot adduct frequency distributions. #' @param assignment S4 object of class Assignment #' @importFrom patchwork wrap_plots #' @importFrom ggthemes ptol_pal #' @importFrom ggplot2 ggplot geom_bar theme_bw facet_wrap theme element_text +#' @importFrom tidyr replace_na #' @export +setGeneric('plotAdductDist',function(assignment){ + standardGeneric('plotAdductDist') +}) + +#' @rdname plotAdductDist + setMethod('plotAdductDist',signature = 'Assignment', function(assignment){ + + isotopes <- assignmen + assign <- assignment %>% - assignments() + assignments() %>% + replace_na(list(Isotope = '')) %>% + mutate(Isotope = factor(Isotope,levels = c())) assign$Mode[assign$Mode == 'n'] <- 'Negative Mode' assign$Mode[assign$Mode == 'p'] <- 'Positive Mode' @@ -25,9 +37,14 @@ setMethod('plotAdductDist',signature = 'Assignment', labs(title = d$Mode[1], y = 'Count', caption = str_c('N = ',nrow(d))) + - theme(plot.title = element_text(face = 'bold'), + theme(plot.title = element_text(face = 'bold',hjust = 0.5), axis.title = element_text(face = 'bold'), - axis.text.x = element_text(angle = 45, hjust = 1)) + axis.text.x = element_text(angle = 45, hjust = 1), + panel.border = element_blank(), + axis.line = element_line(), + panel.grid = element_blank(), + strip.background = element_blank(), + strip.text = element_text(face = 'bold')) }) %>% wrap_plots() } diff --git a/man/plotAdductDist.Rd b/man/plotAdductDist.Rd index 6f96f34..d466f69 100644 --- a/man/plotAdductDist.Rd +++ b/man/plotAdductDist.Rd @@ -1,9 +1,9 @@ % Generated by roxygen2: do not edit by hand -% Please edit documentation in R/allGenerics.R, R/plotAdductDist-method.R +% Please edit documentation in R/plotAdductDist-method.R \name{plotAdductDist} \alias{plotAdductDist} \alias{plotAdductDist,Assignment-method} -\title{plotAdductDist-Assignment} +\title{Plot adduct frequency distributions} \usage{ plotAdductDist(assignment) @@ -13,5 +13,5 @@ plotAdductDist(assignment) \item{assignment}{S4 object of class Assignment} } \description{ -Plot adduct distributions. +Plot adduct frequency distributions. } From 1313da45a1a5149de672df60f3e2c8780c36f682 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Fri, 19 Nov 2021 11:54:59 +0000 Subject: [PATCH 023/226] Moved AssignmentParameters class to it's own file along with it's show method. Added iso() getting and setting the isotopes parameter --- DESCRIPTION | 5 +- NAMESPACE | 6 +- R/allClasses.R | 57 ----------- R/parameters.R | 127 ++++++++++++++++++++++++ R/show-method.R | 40 +------- man/AssignmentParameters-class.Rd | 2 +- man/parameters.Rd | 32 ++++++ man/show-AssignmentParameters-method.Rd | 14 --- 8 files changed, 167 insertions(+), 116 deletions(-) create mode 100644 R/parameters.R create mode 100644 man/parameters.Rd delete mode 100644 man/show-AssignmentParameters-method.Rd diff --git a/DESCRIPTION b/DESCRIPTION index 238e821..58fadd8 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -30,10 +30,9 @@ Imports: CHNOSZ, License: GPL (>= 3) Encoding: UTF-8 LazyData: true +Roxygen: list(markdown = TRUE) RoxygenNote: 7.1.2 -Collate: - 'allGenerics.R' - 'allClasses.R' +Collate: parameters.R allGenerics.R allClasses.R 'prepCorrelations-method.R' 'addIsoAssign-method.R' 'transformationAssign-method.R' diff --git a/NAMESPACE b/NAMESPACE index d43e7d5..8c5cfab 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -1,11 +1,14 @@ # Generated by roxygen2: do not edit by hand +export("iso<-") export(assignMFs) export(assignmentParameters) export(continueAssignment) export(edges) +export(iso) export(nodes) export(plan) +export(plotAdductDist) export(plotFeatureSolutions) export(plotNetwork) exportClasses(Assignment) @@ -13,9 +16,7 @@ exportClasses(AssignmentParameters) exportMethods(assignedData) exportMethods(assignmentData) exportMethods(assignments) -exportMethods(plotAdductDist) exportMethods(plotSpectrum) -exportMethods(show) exportMethods(summariseAssignment) importFrom(CHNOSZ,count.elements) importFrom(cli,console_width) @@ -133,5 +134,6 @@ importFrom(tidygraph,tbl_graph) importFrom(tidygraph,to_components) importFrom(tidygraph,unmorph) importFrom(tidyr,gather) +importFrom(tidyr,replace_na) importFrom(utils,capture.output) importFrom(utils,packageVersion) diff --git a/R/allClasses.R b/R/allClasses.R index dd345fb..1e202dd 100644 --- a/R/allClasses.R +++ b/R/allClasses.R @@ -1,60 +1,3 @@ -#' AssignmentParameters -#' @description An S4 class to store assignment parameters. -#' @slot technique assignment technique to use -#' @slot correlations list of correlation parameters to be passed to metabolyseR correlation analysis -#' @slot filter list of r and n thresholds for filtering correlations -#' @slot maxM maximum M for which to assign molecular formulas -#' @slot maxMFscore threshold for molecular formula score -#' @slot ppm ppm threshold -#' #' @slot adducts named list of character vectors containing the adducuts to use for each mode -#' @slot limit amu deviation limit for relationship prediction -#' @slot RTwindow retention time window for chromatographic associations -#' @slot adducts list of character vectors containing the adducts to use. List element names should denote ionisation mode. -#' @slot isotopes character vector of isotopes to use -#' @slot transformations character vector of transformations to use -#' @slot adductRules tibble containing adduct formation rules as returned by mzAnnotation::adducts() -#' @slot isotopeRules tibble containing isotope rules as returned by mzAnnotation::isotopes() -#' @slot transformationRules tibble containing transformation rules as returned by mzAnnotation::transformations() -#' @importFrom mzAnnotation transformations -#' @export - -setClass('AssignmentParameters', - slots = list( - technique = 'character', - correlations = 'list', - filter = 'list', - maxM = 'numeric', - maxMFscore = 'numeric', - ppm = 'numeric', - limit = 'numeric', - RTwindow = 'numeric', - adducts = 'list', - isotopes = 'character', - transformations = 'character', - adductRules = 'tbl_df', - isotopeRules = 'tbl_df', - transformationRules = 'tbl_df' - ), - prototype = list( - technique = 'FIE', - correlations = list(method = 'pearson',pAdjustMethod = 'bonferroni',corPvalue = 0.05), - filter = list(rthresh = 0.7,n = 200000,rIncrement = 0.01,nIncrement = 20000), - maxM = 1000, - maxMFscore = 5, - ppm = 5, - limit = 0.001, - RTwindow = numeric(), - isotopes = c('13C','18O','13C2'), - adducts = list(n = c("[M-H]1-", "[M+Cl]1-", "[M+K-2H]1-", - "[M-2H]2-", "[M+Cl37]1-","[2M-H]1-"), - p = c('[M+H]1+','[M+K]1+','[M+Na]1+','[M+K41]1+', - '[M+NH4]1+','[M+2H]2+','[2M+H]1+')), - transformations = transformations()$`MF Change`, - adductRules = adducts(), - isotopeRules = isotopes(), - transformationRules = transformations() - )) - #' Assignment #' @description An S4 class to store assignment results #' @slot log list containing assignment logs diff --git a/R/parameters.R b/R/parameters.R new file mode 100644 index 0000000..1335428 --- /dev/null +++ b/R/parameters.R @@ -0,0 +1,127 @@ +#' AssignmentParameters +#' @description An S4 class to store assignment parameters. +#' @slot technique assignment technique to use +#' @slot correlations list of correlation parameters to be passed to metabolyseR correlation analysis +#' @slot filter list of r and n thresholds for filtering correlations +#' @slot maxM maximum M for which to assign molecular formulas +#' @slot maxMFscore threshold for molecular formula score +#' @slot ppm ppm threshold +#' #' @slot adducts named list of character vectors containing the adducuts to use for each mode +#' @slot limit amu deviation limit for relationship prediction +#' @slot RTwindow retention time window for chromatographic associations +#' @slot adducts list of character vectors containing the adducts to use. List element names should denote ionisation mode. +#' @slot isotopes character vector of isotopes to use +#' @slot transformations character vector of transformations to use +#' @slot adductRules tibble containing adduct formation rules as returned by mzAnnotation::adducts() +#' @slot isotopeRules tibble containing isotope rules as returned by mzAnnotation::isotopes() +#' @slot transformationRules tibble containing transformation rules as returned by mzAnnotation::transformations() +#' @importFrom mzAnnotation transformations +#' @export + +setClass('AssignmentParameters', + slots = list( + technique = 'character', + correlations = 'list', + filter = 'list', + maxM = 'numeric', + maxMFscore = 'numeric', + ppm = 'numeric', + limit = 'numeric', + RTwindow = 'numeric', + adducts = 'list', + isotopes = 'character', + transformations = 'character', + adductRules = 'tbl_df', + isotopeRules = 'tbl_df', + transformationRules = 'tbl_df' + ), + prototype = list( + technique = 'FIE', + correlations = list(method = 'pearson',pAdjustMethod = 'bonferroni',corPvalue = 0.05), + filter = list(rthresh = 0.7,n = 200000,rIncrement = 0.01,nIncrement = 20000), + maxM = 1000, + maxMFscore = 5, + ppm = 5, + limit = 0.001, + RTwindow = numeric(), + isotopes = c('13C','18O','13C2'), + adducts = list(n = c("[M-H]1-", "[M+Cl]1-", "[M+K-2H]1-", + "[M-2H]2-", "[M+Cl37]1-","[2M-H]1-"), + p = c('[M+H]1+','[M+K]1+','[M+Na]1+','[M+K41]1+', + '[M+NH4]1+','[M+2H]2+','[2M+H]1+')), + transformations = transformations()$`MF Change`, + adductRules = adducts(), + isotopeRules = isotopes(), + transformationRules = transformations() + )) + +#' @importFrom methods show +#' @importFrom crayon yellow +#' @importFrom purrr map + +setMethod('show',signature = 'AssignmentParameters', + function(object){ + cat(yellow('\nAssignment Parameters:'),'\n') + cat('\n') + cat('\t','Technique:\t\t',object@technique,'\n') + cat('\t','Max M:\t\t\t',object@maxM,'\n') + cat('\t','Max MF score:\t\t',object@maxMFscore,'\n') + cat('\t','PPM threshold:\t\t',object@ppm,'\n') + cat('\t','Relationship limit:\t',object@limit,'\n') + + if (object@technique != 'FIE') { + cat('\t','RT window:\t\t',object@RTwindow,'\n') + } + + cat('\n\t','Adducts:','\n') + adducts <- map(names(object@adducts),~{ + a <- str_c(object@adducts[[.]],collapse = ', ') + str_c(.,': ',a) + }) %>% + str_c(collapse = '\n\t ') + cat('\t',adducts,'\n') + + cat('\t','Isotopes:',str_c(object@isotopes,collapse = ', '),'\n') + + cat('\t','Transformations:',str_c(object@transformations,collapse = ', ')) + + cat('\n') + } +) + +#' Parameter get and set methods +#' @rdname parameters +#' @description Get and set methods for the `AssignmentParameters` S4 class. +#' @param x S4 object of class `AssignmentParameters` +#' @param value value to set +#' @examples +#' assignment_parameters <- assignmentParameters('FIE') +#' +#' ## Return isotopes +#' iso(assignment_parameters) +#' +#' @export + +setGeneric('iso',function(x) + standardGeneric('iso')) + +#' @rdname parameters + +setMethod('iso',signature = 'AssignmentParameters', + function(x){ + x@isotopes + }) + +#' @rdname parameters +#' @export + +setGeneric('iso<-',function(x,value) + standardGeneric('iso<-')) + +#' @rdname parameters + +setMethod('iso<-',signature = 'AssignmentParameters', + function(x,value){ + x@isotopes <- value + return(x) + }) diff --git a/R/show-method.R b/R/show-method.R index 4a3e4a9..2b8f1e3 100644 --- a/R/show-method.R +++ b/R/show-method.R @@ -1,41 +1,3 @@ -#' show-AssignmentParameters -#' @description show method for AssignmentParameters class. -#' @param object S4 object of class AssignmentParameters -#' @importFrom methods show -#' @importFrom crayon yellow -#' @importFrom purrr map -#' @export - -setMethod('show',signature = 'AssignmentParameters', - function(object){ - cat(yellow('\nAssignment Parameters:'),'\n') - cat('\n') - cat('\t','Technique:\t\t',object@technique,'\n') - cat('\t','Max M:\t\t\t',object@maxM,'\n') - cat('\t','Max MF score:\t\t',object@maxMFscore,'\n') - cat('\t','PPM threshold:\t\t',object@ppm,'\n') - cat('\t','Relationship limit:\t',object@limit,'\n') - - if (object@technique != 'FIE') { - cat('\t','RT window:\t\t',object@RTwindow,'\n') - } - - cat('\n\t','Adducts:','\n') - adducts <- map(names(object@adducts),~{ - a <- str_c(object@adducts[[.]],collapse = ', ') - str_c(.,': ',a) - }) %>% - str_c(collapse = '\n\t ') - cat('\t',adducts,'\n') - - cat('\t','Isotopes:',str_c(object@isotopes,collapse = ', '),'\n') - - cat('\t','Transformations:',str_c(object@transformations,collapse = ', ')) - - cat('\n') - } -) - #' show-Assignment #' @description show mehtod for Assignment class. #' @param object S4 object of class Assignment @@ -43,7 +5,7 @@ setMethod('show',signature = 'AssignmentParameters', #' @importFrom purrr map_dbl #' @importFrom utils packageVersion #' @importFrom igraph E -#' @export +#' @exporti setMethod('show',signature = 'Assignment', function(object){ diff --git a/man/AssignmentParameters-class.Rd b/man/AssignmentParameters-class.Rd index 1d3faf5..07833fc 100644 --- a/man/AssignmentParameters-class.Rd +++ b/man/AssignmentParameters-class.Rd @@ -1,5 +1,5 @@ % Generated by roxygen2: do not edit by hand -% Please edit documentation in R/allClasses.R +% Please edit documentation in R/parameters.R \docType{class} \name{AssignmentParameters-class} \alias{AssignmentParameters-class} diff --git a/man/parameters.Rd b/man/parameters.Rd new file mode 100644 index 0000000..e329f11 --- /dev/null +++ b/man/parameters.Rd @@ -0,0 +1,32 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/parameters.R +\name{iso} +\alias{iso} +\alias{iso,AssignmentParameters-method} +\alias{iso<-} +\alias{iso<-,AssignmentParameters-method} +\title{Parameter get and set methods} +\usage{ +iso(x) + +\S4method{iso}{AssignmentParameters}(x) + +iso(x) <- value + +\S4method{iso}{AssignmentParameters}(x) <- value +} +\arguments{ +\item{x}{S4 object of class \code{AssignmentParameters}} + +\item{value}{value to set} +} +\description{ +Get and set methods for the \code{AssignmentParameters} S4 class. +} +\examples{ +assignment_parameters <- assignmentParameters('FIE') + +## Return isotopes +iso(assignment_parameters) + +} diff --git a/man/show-AssignmentParameters-method.Rd b/man/show-AssignmentParameters-method.Rd deleted file mode 100644 index e27905e..0000000 --- a/man/show-AssignmentParameters-method.Rd +++ /dev/null @@ -1,14 +0,0 @@ -% Generated by roxygen2: do not edit by hand -% Please edit documentation in R/show-method.R -\name{show,AssignmentParameters-method} -\alias{show,AssignmentParameters-method} -\title{show-AssignmentParameters} -\usage{ -\S4method{show}{AssignmentParameters}(object) -} -\arguments{ -\item{object}{S4 object of class AssignmentParameters} -} -\description{ -show method for AssignmentParameters class. -} From 9217b37bd6189fd1952b41c8d257532b6304bfb4 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Fri, 19 Nov 2021 12:00:09 +0000 Subject: [PATCH 024/226] Moved assignment class and methods to their own file --- R/access-methods.R | 75 ---------------------- R/allClasses.R | 39 ------------ R/allGenerics.R | 15 ----- R/assignment.R | 152 +++++++++++++++++++++++++++++++++++++++++++++ R/graph.R | 22 +++++++ R/show-method.R | 45 -------------- 6 files changed, 174 insertions(+), 174 deletions(-) delete mode 100644 R/access-methods.R delete mode 100644 R/allClasses.R create mode 100644 R/assignment.R create mode 100644 R/graph.R delete mode 100644 R/show-method.R diff --git a/R/access-methods.R b/R/access-methods.R deleted file mode 100644 index c9af841..0000000 --- a/R/access-methods.R +++ /dev/null @@ -1,75 +0,0 @@ -#' assignments-Assignment -#' @rdname assignments -#' @description Get table of assigned features from an Assignment -#' @param assignment S4 object of class Assignment -#' @export - -setMethod('assignments',signature = 'Assignment', - function(assignment){ - assignment@assignments -}) - -#' nodes -#' @description extract node table from tbl_graph object. -#' @param graph object of class tbl_graph -#' @export - -nodes <- function(graph){ - graph %>% - vertex.attributes() %>% - as_tibble() -} - -#' edges -#' @description extract edge table from tbl_graph object. -#' @param graph object of class tbl_graph -#' @importFrom igraph edge.attributes -#' @export - -edges <- function(graph){ - graph %>% - edge.attributes() %>% - as_tibble() -} - -#' assignmentData -#' @rdname assignmentData -#' @description Return data table used for assignments. -#' @param assignment S4 object of class Assignment -#' @export - -setMethod('assignmentData', signature = 'Assignment', - function(assignment){ - assignment@data -}) - -#' assignedData -#' @rdname assignedData -#' @description Return data table used for assignments with feature assignments added to column names. -#' @param assignment S4 object of class Assignment -#' @export - -setMethod('assignedData', signature = 'Assignment', - function(assignment){ - - d <- assignment %>% - assignmentData() - - assignedFeats <- assignment %>% - assignments() %>% - select(Feature,Name) - - assignedFeats <- left_join( - tibble(Feature = d %>% colnames()), - assignedFeats, - by = "Feature") - - assignedFeats$Name[is.na(assignedFeats$Name)] <- assignedFeats$Feature[is.na(assignedFeats$Name)] - - assignedFeats <- assignedFeats %>% - filter(!duplicated(Feature)) - - colnames(d) <- assignedFeats$Name - - return(d) -}) \ No newline at end of file diff --git a/R/allClasses.R b/R/allClasses.R deleted file mode 100644 index 1e202dd..0000000 --- a/R/allClasses.R +++ /dev/null @@ -1,39 +0,0 @@ -#' Assignment -#' @description An S4 class to store assignment results -#' @slot log list containing assignment logs -#' @slot flags charactor vector containing completed assignment elements -#' @slot parameters An S4 object of class AssignmentParameters containing the assignment parameters -#' @slot data A tibble containing the peak intensity matrix -#' @slot correlations A tibble containing the correlations -#' @slot preparedCorrelations A tibble containing the prepared correlations ready for analysis -#' @slot relationships A tibble containing the predicted relationships -#' @slot addIsoAssign A list containing the results of the adduct and isotope assignment -#' @slot transAssign A list containing the results of the transformation assignment -#' @slot assignments A tibble containing the assigned molecular formulas -#' @export - -setClass('Assignment', - slots = list( - log = 'list', - flags = 'character', - parameters = 'AssignmentParameters', - data = 'tbl_df', - correlations = 'tbl_df', - preparedCorrelations = 'tbl_df', - relationships = 'tbl_df', - addIsoAssign = 'list', - transAssign = 'list', - assignments = 'tbl_df' - ), - prototype = list( - log = list(date = date(),verbose = TRUE), - flags = character(), - parameters = new('AssignmentParameters'), - data = tibble(), - correlations = tibble(), - preparedCorrelations = tibble(), - relationships = tibble(), - addIsoAssign = list(), - transAssign = list(), - assignments = tibble() - )) \ No newline at end of file diff --git a/R/allGenerics.R b/R/allGenerics.R index ec75320..67c097a 100644 --- a/R/allGenerics.R +++ b/R/allGenerics.R @@ -22,26 +22,11 @@ setGeneric("transformationAssign", function(assignment) { standardGeneric("transformationAssign") }) -#' @rdname assignments -setGeneric('assignments',function(assignment){ - standardGeneric('assignments') -}) - #' @rdname summariseAssignment setGeneric('summariseAssignment',function(assignment){ standardGeneric('summariseAssignment') }) -#' @rdname assignmentData -setGeneric('assignmentData',function(assignment){ - standardGeneric('assignmentData') -}) - -#' @rdname assignedData -setGeneric('assignedData',function(assignment){ - standardGeneric('assignedData') -}) - #' @rdname plotSpectrum setGeneric('plotSpectrum',function(assignment,MF){ standardGeneric('plotSpectrum') diff --git a/R/assignment.R b/R/assignment.R new file mode 100644 index 0000000..35901c0 --- /dev/null +++ b/R/assignment.R @@ -0,0 +1,152 @@ +#' Assignment +#' @description An S4 class to store assignment results +#' @slot log list containing assignment logs +#' @slot flags charactor vector containing completed assignment elements +#' @slot parameters An S4 object of class AssignmentParameters containing the assignment parameters +#' @slot data A tibble containing the peak intensity matrix +#' @slot correlations A tibble containing the correlations +#' @slot preparedCorrelations A tibble containing the prepared correlations ready for analysis +#' @slot relationships A tibble containing the predicted relationships +#' @slot addIsoAssign A list containing the results of the adduct and isotope assignment +#' @slot transAssign A list containing the results of the transformation assignment +#' @slot assignments A tibble containing the assigned molecular formulas +#' @export + +setClass('Assignment', + slots = list( + log = 'list', + flags = 'character', + parameters = 'AssignmentParameters', + data = 'tbl_df', + correlations = 'tbl_df', + preparedCorrelations = 'tbl_df', + relationships = 'tbl_df', + addIsoAssign = 'list', + transAssign = 'list', + assignments = 'tbl_df' + ), + prototype = list( + log = list(date = date(),verbose = TRUE), + flags = character(), + parameters = new('AssignmentParameters'), + data = tibble(), + correlations = tibble(), + preparedCorrelations = tibble(), + relationships = tibble(), + addIsoAssign = list(), + transAssign = list(), + assignments = tibble() + )) + +#' @importFrom crayon blue red green +#' @importFrom purrr map_dbl +#' @importFrom utils packageVersion +#' @importFrom igraph E + +setMethod('show',signature = 'Assignment', + function(object){ + cat(blue('\nMFassign'),red(str_c('v',packageVersion('MFassign') %>% as.character())),'\n') + cat(yellow('Assignment:'),'\n') + cat('\t','Features:\t\t',ncol(object@data),'\n') + cat('\t','Correlations:\t\t',nrow(object@correlations),'\n') + cat('\t','Relationships:\t\t',nrow(object@relationships),'\n') + cat('\n') + if (length(object@addIsoAssign) > 0) { + cat('\t',green('Adduct & isotope assignment:'),'\n') + cat('\t\t','MFs:\t\t',length(unique(object@addIsoAssign$assigned$MF)),'\n') + cat('\t\t','Relationships:\t',object@addIsoAssign$filteredGraph %>% E() %>% length(),'\n') + cat('\t\t','Assigned:\t',nrow(object@addIsoAssign$assigned),'\n') + cat('\n') + } + if (length(object@transAssign) > 0) { + cat('\t',green('Transformation assignment:'),'\n') + cat('\t\t','Iterations:\t',length(object@transAssign),'\n') + transAssigned <- object@transAssign %>% + {.[map_dbl(.,length) > 0]} %>% + map_dbl(~{ + return(nrow(.$assigned)) + }) %>% + sum() + cat('\t\t','Assigned:\t',transAssigned,'\n') + cat('\n') + } + if (nrow(object@assignments) > 0) { + cat('\t','Total assignments:\t',blue(nrow(object@assignments)), + blue(str_c('(',round(nrow(object@assignments)/ncol(object@data) * 100),'%)')), + '\n') + cat('\t','Unique MFs:\t\t',blue(length(unique(object@assignments$MF))),'\n') + cat('\n') + } + } +) + +#' assignments-Assignment +#' @rdname assignments +#' @description Get table of assigned features from an Assignment +#' @param assignment S4 object of class Assignment +#' @export + +setGeneric('assignments',function(assignment){ + standardGeneric('assignments') +}) + +#' @rdname assignments + +setMethod('assignments',signature = 'Assignment', + function(assignment){ + assignment@assignments + }) + +#' assignmentData +#' @rdname assignmentData +#' @description Return data table used for assignments. +#' @param assignment S4 object of class Assignment +#' @export + +setGeneric('assignmentData',function(assignment){ + standardGeneric('assignmentData') +}) + +#' @rdname assignmentData + +setMethod('assignmentData', signature = 'Assignment', + function(assignment){ + assignment@data + }) + +#' assignedData +#' @rdname assignedData +#' @description Return data table used for assignments with feature assignments added to column names. +#' @param assignment S4 object of class Assignment +#' @export + +setGeneric('assignedData',function(assignment){ + standardGeneric('assignedData') +}) + +#' @rdname assignedData + +setMethod('assignedData', signature = 'Assignment', + function(assignment){ + + d <- assignment %>% + assignmentData() + + assignedFeats <- assignment %>% + assignments() %>% + select(Feature,Name) + + assignedFeats <- left_join( + tibble(Feature = d %>% colnames()), + assignedFeats, + by = "Feature") + + assignedFeats$Name[is.na(assignedFeats$Name)] <- assignedFeats$Feature[is.na(assignedFeats$Name)] + + assignedFeats <- assignedFeats %>% + filter(!duplicated(Feature)) + + colnames(d) <- assignedFeats$Name + + return(d) + }) diff --git a/R/graph.R b/R/graph.R new file mode 100644 index 0000000..8adc0fc --- /dev/null +++ b/R/graph.R @@ -0,0 +1,22 @@ +#' nodes +#' @description extract node table from tbl_graph object. +#' @param graph object of class tbl_graph +#' @export + +nodes <- function(graph){ + graph %>% + vertex.attributes() %>% + as_tibble() +} + +#' edges +#' @description extract edge table from tbl_graph object. +#' @param graph object of class tbl_graph +#' @importFrom igraph edge.attributes +#' @export + +edges <- function(graph){ + graph %>% + edge.attributes() %>% + as_tibble() +} diff --git a/R/show-method.R b/R/show-method.R deleted file mode 100644 index 2b8f1e3..0000000 --- a/R/show-method.R +++ /dev/null @@ -1,45 +0,0 @@ -#' show-Assignment -#' @description show mehtod for Assignment class. -#' @param object S4 object of class Assignment -#' @importFrom crayon blue red green -#' @importFrom purrr map_dbl -#' @importFrom utils packageVersion -#' @importFrom igraph E -#' @exporti - -setMethod('show',signature = 'Assignment', - function(object){ - cat(blue('\nMFassign'),red(str_c('v',packageVersion('MFassign') %>% as.character())),'\n') - cat(yellow('Assignment:'),'\n') - cat('\t','Features:\t\t',ncol(object@data),'\n') - cat('\t','Correlations:\t\t',nrow(object@correlations),'\n') - cat('\t','Relationships:\t\t',nrow(object@relationships),'\n') - cat('\n') - if (length(object@addIsoAssign) > 0) { - cat('\t',green('Adduct & isotope assignment:'),'\n') - cat('\t\t','MFs:\t\t',length(unique(object@addIsoAssign$assigned$MF)),'\n') - cat('\t\t','Relationships:\t',object@addIsoAssign$filteredGraph %>% E() %>% length(),'\n') - cat('\t\t','Assigned:\t',nrow(object@addIsoAssign$assigned),'\n') - cat('\n') - } - if (length(object@transAssign) > 0) { - cat('\t',green('Transformation assignment:'),'\n') - cat('\t\t','Iterations:\t',length(object@transAssign),'\n') - transAssigned <- object@transAssign %>% - {.[map_dbl(.,length) > 0]} %>% - map_dbl(~{ - return(nrow(.$assigned)) - }) %>% - sum() - cat('\t\t','Assigned:\t',transAssigned,'\n') - cat('\n') - } - if (nrow(object@assignments) > 0) { - cat('\t','Total assignments:\t',blue(nrow(object@assignments)), - blue(str_c('(',round(nrow(object@assignments)/ncol(object@data) * 100),'%)')), - '\n') - cat('\t','Unique MFs:\t\t',blue(length(unique(object@assignments$MF))),'\n') - cat('\n') - } - } -) \ No newline at end of file From a722c35dfd83c29562d8c98dbe1297b16ad978ed Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Fri, 19 Nov 2021 12:04:09 +0000 Subject: [PATCH 025/226] fixed collate field in DESCRIPTION --- DESCRIPTION | 17 ++++++----------- 1 file changed, 6 insertions(+), 11 deletions(-) diff --git a/DESCRIPTION b/DESCRIPTION index 58fadd8..603a786 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -32,14 +32,11 @@ Encoding: UTF-8 LazyData: true Roxygen: list(markdown = TRUE) RoxygenNote: 7.1.2 -Collate: parameters.R allGenerics.R allClasses.R - 'prepCorrelations-method.R' - 'addIsoAssign-method.R' - 'transformationAssign-method.R' - 'relationships-method.R' - 'assignmentParameters.R' - 'assignMFs.R' - 'MFgen.R' +Collate: parameters.R assignment.R allGenerics.R + prepCorrelations-method.R addIsoAssign-method.R + transformationAssign-method.R relationships-method.R + graph.R assignMFs.R MFgen.R + assignmentParameters.R 'MFscore.R' 'addIsoScore.R' 'addMFs.R' @@ -50,14 +47,12 @@ Collate: parameters.R allGenerics.R allClasses.R 'MFassign.R' 'FIEassignment.R' 'continueAssignment.R' - 'show-method.R' - 'access-methods.R' 'summariseAssignment-method.R' plotNetwork.R 'addNames.R' 'eliminate.R' 'plotAdductDist-method.R' - 'plotFeatureSolutions.R' + plotFeatureSolutions.R 'calcCorrelations-method.R' 'filterCorrelations-method.R' 'plotSpectrum-method.R' From cad89decb77bedf8652153d97ad11bcc2b15de61 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Fri, 19 Nov 2021 12:18:19 +0000 Subject: [PATCH 026/226] Assignment class now inherits from AssignmentParameters class --- R/addIsoAssign-method.R | 2 +- R/assignMFs.R | 8 +++++--- R/assignment.R | 3 +-- R/calcCorrelations-method.R | 8 +++++--- R/filterCorrelations-method.R | 14 ++++++++------ R/parameters.R | 4 ++-- R/relationships-method.R | 2 +- R/transformationAssign-method.R | 2 +- tests/testthat/test-assignMFs.R | 14 +++++++++++++- 9 files changed, 37 insertions(+), 20 deletions(-) diff --git a/R/addIsoAssign-method.R b/R/addIsoAssign-method.R index f9bdd05..b74e90b 100644 --- a/R/addIsoAssign-method.R +++ b/R/addIsoAssign-method.R @@ -12,7 +12,7 @@ setMethod('addIsoAssign',signature = 'Assignment', message(blue('Adduct & isotope assignment '),cli::symbol$continue,'\r',appendLF = FALSE) } - parameters <- assignment@parameters + parameters <- as(assignment,'AssignmentParameters') rel <- assignment@relationships %>% filter(is.na(Transformation1) & is.na(Transformation2) & r > 0) %>% diff --git a/R/assignMFs.R b/R/assignMFs.R index d6e069b..905ca45 100644 --- a/R/assignMFs.R +++ b/R/assignMFs.R @@ -5,7 +5,9 @@ setGeneric('doAssignment',function(assignment){ setMethod('doAssignment',signature = 'Assignment', function(assignment){ - assignmentMethod <- assignMethods(assignment@parameters@technique) + parameters <- as(assignment,'AssignmentParameters') + + assignmentMethod <- assignMethods(parameters@technique) elements <- names(assignmentMethod()) elements <- elements[!(elements %in% assignment@flags)] @@ -58,8 +60,8 @@ assignMFs <- function(dat,parameters,verbose = TRUE) { } assignment <- new('Assignment', - data = dat, - parameters = parameters) + parameters, + data = dat) assignment@log$verbose <- verbose assignment <- assignment %>% diff --git a/R/assignment.R b/R/assignment.R index 35901c0..30d2188 100644 --- a/R/assignment.R +++ b/R/assignment.R @@ -13,10 +13,10 @@ #' @export setClass('Assignment', + contains = 'AssignmentParameters', slots = list( log = 'list', flags = 'character', - parameters = 'AssignmentParameters', data = 'tbl_df', correlations = 'tbl_df', preparedCorrelations = 'tbl_df', @@ -28,7 +28,6 @@ setClass('Assignment', prototype = list( log = list(date = date(),verbose = TRUE), flags = character(), - parameters = new('AssignmentParameters'), data = tibble(), correlations = tibble(), preparedCorrelations = tibble(), diff --git a/R/calcCorrelations-method.R b/R/calcCorrelations-method.R index 16bf7d9..1218f97 100644 --- a/R/calcCorrelations-method.R +++ b/R/calcCorrelations-method.R @@ -9,9 +9,11 @@ setMethod('calcCorrelations',signature = 'Assignment',function(assignment){ } p <- analysisParameters('correlations') - p@correlations <- assignment@parameters@correlations + parameters <- as(assignment,'AssignmentParameters') - if (str_detect(assignment@parameters@technique,'LC')) { + p@correlations <- parameters@correlations_parameters + + if (str_detect(parameters@technique,'LC')) { feat <- tibble(Feature = colnames(assignment@data)) %>% mutate(RT = str_split_fixed(Feature,'@',2)[,2] %>% as.numeric()) @@ -21,7 +23,7 @@ setMethod('calcCorrelations',signature = 'Assignment',function(assignment){ select(-Feature) %>% dist() %>% hclust() %>% - cutree(h = assignment@parameters@RTwindow) %>% + cutree(h = parameters@RTwindow) %>% {tibble(Feature = names(.),Group = .)} RTsum <- RTgroups %>% diff --git a/R/filterCorrelations-method.R b/R/filterCorrelations-method.R index 6fda1cb..5f8ea77 100644 --- a/R/filterCorrelations-method.R +++ b/R/filterCorrelations-method.R @@ -26,15 +26,17 @@ setMethod('filterCorrelations',signature = 'Assignment',function(assignment){ message(blue('Filtering correlations '),cli::symbol$continue,'\r',appendLF = FALSE) } - if (str_detect(assignment@parameters@technique,'LC')) { + parameters <- as(assignment,'AssignmentParameters') + + if (str_detect(parameters@technique,'LC')) { cors <- assignment@correlations %>% - filter(r < -(assignment@parameters@filter$rthresh) | r > assignment@parameters@filter$rthresh) + filter(r < -(parameters@filter$rthresh) | r > parameters@filter$rthresh) } else { cors <- assignment@correlations %>% - filterCors(rthresh = assignment@parameters@filter$rthresh, - n = assignment@parameters@filter$n, - rIncrement = assignment@parameters@filter$rIncrement, - nIncrement = assignment@parameters@filter$nIncrement + filterCors(rthresh = parameters@filter$rthresh, + n = parameters@filter$n, + rIncrement = parameters@filter$rIncrement, + nIncrement = parameters@filter$nIncrement ) } diff --git a/R/parameters.R b/R/parameters.R index 1335428..bcf92ab 100644 --- a/R/parameters.R +++ b/R/parameters.R @@ -21,7 +21,7 @@ setClass('AssignmentParameters', slots = list( technique = 'character', - correlations = 'list', + correlations_parameters = 'list', filter = 'list', maxM = 'numeric', maxMFscore = 'numeric', @@ -37,7 +37,7 @@ setClass('AssignmentParameters', ), prototype = list( technique = 'FIE', - correlations = list(method = 'pearson',pAdjustMethod = 'bonferroni',corPvalue = 0.05), + correlations_parameters = list(method = 'pearson',pAdjustMethod = 'bonferroni',corPvalue = 0.05), filter = list(rthresh = 0.7,n = 200000,rIncrement = 0.01,nIncrement = 20000), maxM = 1000, maxMFscore = 5, diff --git a/R/relationships-method.R b/R/relationships-method.R index 06431f5..38b98da 100644 --- a/R/relationships-method.R +++ b/R/relationships-method.R @@ -15,7 +15,7 @@ setMethod('relationships',signature = 'Assignment', message(blue('Calculating relationships '),cli::symbol$continue,'\r',appendLF = 'FALSE') } - parameters <- assignment@parameters + parameters <- as(assignment,'AssignmentParameters') cors <- assignment@preparedCorrelations diff --git a/R/transformationAssign-method.R b/R/transformationAssign-method.R index 73531d4..04bb565 100644 --- a/R/transformationAssign-method.R +++ b/R/transformationAssign-method.R @@ -5,7 +5,7 @@ setMethod('transformationAssign',signature = 'Assignment', function(assignment){ - parameters <- assignment@parameters + parameters <- as(assignment,'AssignmentParameters') count <- length(assignment@transAssign) assigned <- assignment@assignments diff --git a/tests/testthat/test-assignMFs.R b/tests/testthat/test-assignMFs.R index cd16589..7233a68 100644 --- a/tests/testthat/test-assignMFs.R +++ b/tests/testthat/test-assignMFs.R @@ -19,4 +19,16 @@ test_that('feature solutions can be plotted',{ maxComponents = 2) expect_s3_class(pl,'patchwork') -}) \ No newline at end of file +}) + +# test_that('assignment network can be plotted',{ +# pl <- plotNetwork(assignment) +# +# expect_s3_class(pl,'patchwork') +# }) + +test_that('adduct distributions can be plotted',{ + pl <- plotAdductDist(assignment) + + expect_s3_class(pl,'patchwork') +}) From 862ae8755531a8b812234faab07aa840fe246f75 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Fri, 19 Nov 2021 13:10:52 +0000 Subject: [PATCH 027/226] added add() method for AssignmentParameters class --- R/parameters.R | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/R/parameters.R b/R/parameters.R index bcf92ab..1fa756f 100644 --- a/R/parameters.R +++ b/R/parameters.R @@ -100,6 +100,16 @@ setMethod('show',signature = 'AssignmentParameters', #' ## Return isotopes #' iso(assignment_parameters) #' +#' ## Set isotopes +#' iso(assignment_parameters) <- '13C' +#' +#' ## Return adducts +#' add(assignment_parameters) +#' +#' ## Set adducts +#' add(assignment_parameters) <- list(n = c('[M-H]1-','[M+Cl]1-'), +#' p = c('[M+H]1+','[M+K]1+')) +#' #' @export setGeneric('iso',function(x) @@ -125,3 +135,30 @@ setMethod('iso<-',signature = 'AssignmentParameters', x@isotopes <- value return(x) }) + +#' @rdname parameters +#' @export + +setGeneric('add',function(x) + standardGeneric('add')) + +#' @rdname parameters + +setMethod('add',signature = 'AssignmentParameters', + function(x){ + x@adducts + }) + +#' @rdname parameters +#' @export + +setGeneric('add<-',function(x,value) + standardGeneric('add<-')) + +#' @rdname parameters + +setMethod('add<-',signature = 'AssignmentParameters', + function(x,value){ + x@adducts <- value + return(x) + }) \ No newline at end of file From 3df1a353e2db27f8a951c85f75379ac4e5898b9f Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Fri, 19 Nov 2021 13:11:30 +0000 Subject: [PATCH 028/226] updated NAMESPACE and documentation --- NAMESPACE | 8 +++++--- R/plotAdductDist-method.R | 10 ++++++---- man/Assignment-class.Rd | 2 +- man/assignedData.Rd | 2 +- man/assignmentData.Rd | 2 +- man/assignments.Rd | 2 +- man/edges.Rd | 2 +- man/nodes.Rd | 2 +- man/parameters.Rd | 22 ++++++++++++++++++++++ man/show-Assignment-method.Rd | 14 -------------- 10 files changed, 39 insertions(+), 27 deletions(-) delete mode 100644 man/show-Assignment-method.Rd diff --git a/NAMESPACE b/NAMESPACE index 8c5cfab..478e531 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -1,8 +1,13 @@ # Generated by roxygen2: do not edit by hand +export("add<-") export("iso<-") +export(add) export(assignMFs) +export(assignedData) +export(assignmentData) export(assignmentParameters) +export(assignments) export(continueAssignment) export(edges) export(iso) @@ -13,9 +18,6 @@ export(plotFeatureSolutions) export(plotNetwork) exportClasses(Assignment) exportClasses(AssignmentParameters) -exportMethods(assignedData) -exportMethods(assignmentData) -exportMethods(assignments) exportMethods(plotSpectrum) exportMethods(summariseAssignment) importFrom(CHNOSZ,count.elements) diff --git a/R/plotAdductDist-method.R b/R/plotAdductDist-method.R index e621778..345ba7d 100644 --- a/R/plotAdductDist-method.R +++ b/R/plotAdductDist-method.R @@ -17,12 +17,13 @@ setGeneric('plotAdductDist',function(assignment){ setMethod('plotAdductDist',signature = 'Assignment', function(assignment){ - isotopes <- assignmen - assign <- assignment %>% assignments() %>% replace_na(list(Isotope = '')) %>% - mutate(Isotope = factor(Isotope,levels = c())) + mutate(Isotope = factor(Isotope, + levels = c('',iso(assignment))), + Adduct = factor(Adduct, + levels = )) assign$Mode[assign$Mode == 'n'] <- 'Negative Mode' assign$Mode[assign$Mode == 'p'] <- 'Positive Mode' @@ -33,7 +34,8 @@ setMethod('plotAdductDist',signature = 'Assignment', ggplot(d,aes(x = Adduct)) + geom_bar(colour = 'black',fill = ptol_pal()(1)) + theme_bw() + - facet_wrap(~Isotope) + + facet_wrap(~Isotope, + scales = 'free') + labs(title = d$Mode[1], y = 'Count', caption = str_c('N = ',nrow(d))) + diff --git a/man/Assignment-class.Rd b/man/Assignment-class.Rd index 229e623..71bafaf 100644 --- a/man/Assignment-class.Rd +++ b/man/Assignment-class.Rd @@ -1,5 +1,5 @@ % Generated by roxygen2: do not edit by hand -% Please edit documentation in R/allClasses.R +% Please edit documentation in R/assignment.R \docType{class} \name{Assignment-class} \alias{Assignment-class} diff --git a/man/assignedData.Rd b/man/assignedData.Rd index d539ce4..3555f17 100644 --- a/man/assignedData.Rd +++ b/man/assignedData.Rd @@ -1,5 +1,5 @@ % Generated by roxygen2: do not edit by hand -% Please edit documentation in R/allGenerics.R, R/access-methods.R +% Please edit documentation in R/assignment.R \name{assignedData} \alias{assignedData} \alias{assignedData,Assignment-method} diff --git a/man/assignmentData.Rd b/man/assignmentData.Rd index e686ea5..36c0ec7 100644 --- a/man/assignmentData.Rd +++ b/man/assignmentData.Rd @@ -1,5 +1,5 @@ % Generated by roxygen2: do not edit by hand -% Please edit documentation in R/allGenerics.R, R/access-methods.R +% Please edit documentation in R/assignment.R \name{assignmentData} \alias{assignmentData} \alias{assignmentData,Assignment-method} diff --git a/man/assignments.Rd b/man/assignments.Rd index 247ba00..34b6986 100644 --- a/man/assignments.Rd +++ b/man/assignments.Rd @@ -1,5 +1,5 @@ % Generated by roxygen2: do not edit by hand -% Please edit documentation in R/allGenerics.R, R/access-methods.R +% Please edit documentation in R/assignment.R \name{assignments} \alias{assignments} \alias{assignments,Assignment-method} diff --git a/man/edges.Rd b/man/edges.Rd index 25c4b37..c64b073 100644 --- a/man/edges.Rd +++ b/man/edges.Rd @@ -1,5 +1,5 @@ % Generated by roxygen2: do not edit by hand -% Please edit documentation in R/access-methods.R +% Please edit documentation in R/graph.R \name{edges} \alias{edges} \title{edges} diff --git a/man/nodes.Rd b/man/nodes.Rd index b970e2a..94cdb6f 100644 --- a/man/nodes.Rd +++ b/man/nodes.Rd @@ -1,5 +1,5 @@ % Generated by roxygen2: do not edit by hand -% Please edit documentation in R/access-methods.R +% Please edit documentation in R/graph.R \name{nodes} \alias{nodes} \title{nodes} diff --git a/man/parameters.Rd b/man/parameters.Rd index e329f11..1007d04 100644 --- a/man/parameters.Rd +++ b/man/parameters.Rd @@ -5,6 +5,10 @@ \alias{iso,AssignmentParameters-method} \alias{iso<-} \alias{iso<-,AssignmentParameters-method} +\alias{add} +\alias{add,AssignmentParameters-method} +\alias{add<-} +\alias{add<-,AssignmentParameters-method} \title{Parameter get and set methods} \usage{ iso(x) @@ -14,6 +18,14 @@ iso(x) iso(x) <- value \S4method{iso}{AssignmentParameters}(x) <- value + +add(x) + +\S4method{add}{AssignmentParameters}(x) + +add(x) <- value + +\S4method{add}{AssignmentParameters}(x) <- value } \arguments{ \item{x}{S4 object of class \code{AssignmentParameters}} @@ -29,4 +41,14 @@ assignment_parameters <- assignmentParameters('FIE') ## Return isotopes iso(assignment_parameters) +## Set isotopes +iso(assignment_parameters) <- '13C' + +## Return adducts +add(assignment_parameters) + +## Set adducts +add(assignment_parameters) <- list(n = c('[M-H]1-','[M+Cl]1-'), + p = c('[M+H]1+','[M+K]1+')) + } diff --git a/man/show-Assignment-method.Rd b/man/show-Assignment-method.Rd deleted file mode 100644 index 3614a72..0000000 --- a/man/show-Assignment-method.Rd +++ /dev/null @@ -1,14 +0,0 @@ -% Generated by roxygen2: do not edit by hand -% Please edit documentation in R/show-method.R -\name{show,Assignment-method} -\alias{show,Assignment-method} -\title{show-Assignment} -\usage{ -\S4method{show}{Assignment}(object) -} -\arguments{ -\item{object}{S4 object of class Assignment} -} -\description{ -show mehtod for Assignment class. -} From 3ede8718221d55b2945a6502f1c383eb07e5d6ab Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Fri, 19 Nov 2021 13:23:31 +0000 Subject: [PATCH 029/226] added parameters unit tests --- R/parameters.R | 2 +- tests/testthat/test-parameters.R | 25 +++++++++++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) create mode 100644 tests/testthat/test-parameters.R diff --git a/R/parameters.R b/R/parameters.R index 1fa756f..66ea01f 100644 --- a/R/parameters.R +++ b/R/parameters.R @@ -161,4 +161,4 @@ setMethod('add<-',signature = 'AssignmentParameters', function(x,value){ x@adducts <- value return(x) - }) \ No newline at end of file + }) diff --git a/tests/testthat/test-parameters.R b/tests/testthat/test-parameters.R new file mode 100644 index 0000000..ef14255 --- /dev/null +++ b/tests/testthat/test-parameters.R @@ -0,0 +1,25 @@ + +p <- assignmentParameters('FIE') + +test_that("isotopes can be returned", { + expect_type(iso(p),'character') +}) + +test_that("isotopes can be set", { + new_isotopes <- '13C' + iso(p) <- new_isotopes + + expect_identical(iso(p),new_isotopes) +}) + +test_that("adducts can be returned", { + expect_type(add(p),'list') +}) + +test_that("adducts can be set", { + new_adducts <- list(n = c("[M-H]1-","[M+Cl]1-"), + p = c("[M+H]1+","[M+K]1+")) + add(p) <- new_adducts + + expect_identical(add(p),new_adducts) +}) From 8a0d69655d216cc09d05fcd88d7530864fb88209 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Fri, 19 Nov 2021 13:31:21 +0000 Subject: [PATCH 030/226] fixed assignment generics --- R/assignment.R | 15 ++++++--------- 1 file changed, 6 insertions(+), 9 deletions(-) diff --git a/R/assignment.R b/R/assignment.R index 30d2188..3ea8fcb 100644 --- a/R/assignment.R +++ b/R/assignment.R @@ -85,9 +85,8 @@ setMethod('show',signature = 'Assignment', #' @param assignment S4 object of class Assignment #' @export -setGeneric('assignments',function(assignment){ - standardGeneric('assignments') -}) +setGeneric('assignments',function(assignment) + standardGeneric('assignments')) #' @rdname assignments @@ -102,9 +101,8 @@ setMethod('assignments',signature = 'Assignment', #' @param assignment S4 object of class Assignment #' @export -setGeneric('assignmentData',function(assignment){ - standardGeneric('assignmentData') -}) +setGeneric('assignmentData',function(assignment) + standardGeneric('assignmentData')) #' @rdname assignmentData @@ -119,9 +117,8 @@ setMethod('assignmentData', signature = 'Assignment', #' @param assignment S4 object of class Assignment #' @export -setGeneric('assignedData',function(assignment){ - standardGeneric('assignedData') -}) +setGeneric('assignedData',function(assignment) + standardGeneric('assignedData')) #' @rdname assignedData From 7af18cdf8e88e1e9daa489c34f6ac846babb8364 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Fri, 19 Nov 2021 13:42:48 +0000 Subject: [PATCH 031/226] renamed plotAdductDist file --- DESCRIPTION | 2 +- NAMESPACE | 1 + R/plotAdductDist-method.R | 53 ------------------------------------ R/plotAdductDist.R | 56 +++++++++++++++++++++++++++++++++++++++ man/plotAdductDist.Rd | 2 +- 5 files changed, 59 insertions(+), 55 deletions(-) delete mode 100644 R/plotAdductDist-method.R create mode 100644 R/plotAdductDist.R diff --git a/DESCRIPTION b/DESCRIPTION index 603a786..4dc605a 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -51,7 +51,7 @@ Collate: parameters.R assignment.R allGenerics.R plotNetwork.R 'addNames.R' 'eliminate.R' - 'plotAdductDist-method.R' + plotAdductDist.R plotFeatureSolutions.R 'calcCorrelations-method.R' 'filterCorrelations-method.R' diff --git a/NAMESPACE b/NAMESPACE index 478e531..5ca1c11 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -54,6 +54,7 @@ importFrom(future,plan) importFrom(ggplot2,aes) importFrom(ggplot2,coord_fixed) importFrom(ggplot2,element_blank) +importFrom(ggplot2,element_line) importFrom(ggplot2,element_text) importFrom(ggplot2,facet_wrap) importFrom(ggplot2,geom_bar) diff --git a/R/plotAdductDist-method.R b/R/plotAdductDist-method.R deleted file mode 100644 index 345ba7d..0000000 --- a/R/plotAdductDist-method.R +++ /dev/null @@ -1,53 +0,0 @@ -#' Plot adduct frequency distributions -#' @rdname plotAdductDist -#' @description Plot adduct frequency distributions. -#' @param assignment S4 object of class Assignment -#' @importFrom patchwork wrap_plots -#' @importFrom ggthemes ptol_pal -#' @importFrom ggplot2 ggplot geom_bar theme_bw facet_wrap theme element_text -#' @importFrom tidyr replace_na -#' @export - -setGeneric('plotAdductDist',function(assignment){ - standardGeneric('plotAdductDist') -}) - -#' @rdname plotAdductDist - -setMethod('plotAdductDist',signature = 'Assignment', - function(assignment){ - - assign <- assignment %>% - assignments() %>% - replace_na(list(Isotope = '')) %>% - mutate(Isotope = factor(Isotope, - levels = c('',iso(assignment))), - Adduct = factor(Adduct, - levels = )) - - assign$Mode[assign$Mode == 'n'] <- 'Negative Mode' - assign$Mode[assign$Mode == 'p'] <- 'Positive Mode' - - assign %>% split(.$Mode) %>% - map(~{ - d <- . - ggplot(d,aes(x = Adduct)) + - geom_bar(colour = 'black',fill = ptol_pal()(1)) + - theme_bw() + - facet_wrap(~Isotope, - scales = 'free') + - labs(title = d$Mode[1], - y = 'Count', - caption = str_c('N = ',nrow(d))) + - theme(plot.title = element_text(face = 'bold',hjust = 0.5), - axis.title = element_text(face = 'bold'), - axis.text.x = element_text(angle = 45, hjust = 1), - panel.border = element_blank(), - axis.line = element_line(), - panel.grid = element_blank(), - strip.background = element_blank(), - strip.text = element_text(face = 'bold')) - }) %>% - wrap_plots() - } -) \ No newline at end of file diff --git a/R/plotAdductDist.R b/R/plotAdductDist.R new file mode 100644 index 0000000..4421e47 --- /dev/null +++ b/R/plotAdductDist.R @@ -0,0 +1,56 @@ + +#' @importFrom ggthemes ptol_pal +#' @importFrom ggplot2 ggplot geom_bar theme_bw facet_wrap theme element_text element_line + +plotDist <- function(x){ + ggplot(x,aes(x = Adduct)) + + geom_bar(colour = 'black',fill = ptol_pal()(1)) + + theme_bw() + + facet_wrap(~Isotope, + scales = 'free') + + labs(title = x$Mode[1], + y = 'Count', + caption = str_c('N = ',nrow(x))) + + theme(plot.title = element_text(face = 'bold',hjust = 0.5), + axis.title = element_text(face = 'bold'), + axis.text.x = element_text(angle = 45, hjust = 1), + panel.border = element_blank(), + axis.line = element_line(), + panel.grid = element_blank(), + strip.background = element_blank(), + strip.text = element_text(face = 'bold')) +} + +#' Plot adduct frequency distributions +#' @rdname plotAdductDist +#' @description Plot adduct frequency distributions. +#' @param assignment S4 object of class Assignment +#' @importFrom patchwork wrap_plots +#' @importFrom tidyr replace_na +#' @export + +setGeneric('plotAdductDist',function(assignment){ + standardGeneric('plotAdductDist') +}) + +#' @rdname plotAdductDist + +setMethod('plotAdductDist',signature = 'Assignment', + function(assignment){ + + assign <- assignment %>% + assignments() %>% + replace_na(list(Isotope = '')) %>% + mutate(Isotope = factor(Isotope, + levels = c('',iso(assignment))) + ) + + assign$Mode[assign$Mode == 'n'] <- 'Negative Mode' + assign$Mode[assign$Mode == 'p'] <- 'Positive Mode' + + assign %>% + split(.$Mode) %>% + map(plotDist) %>% + wrap_plots() + } +) \ No newline at end of file diff --git a/man/plotAdductDist.Rd b/man/plotAdductDist.Rd index d466f69..193757d 100644 --- a/man/plotAdductDist.Rd +++ b/man/plotAdductDist.Rd @@ -1,5 +1,5 @@ % Generated by roxygen2: do not edit by hand -% Please edit documentation in R/plotAdductDist-method.R +% Please edit documentation in R/plotAdductDist.R \name{plotAdductDist} \alias{plotAdductDist} \alias{plotAdductDist,Assignment-method} From e553365b6760df096d6e12f7ea97211f2d701475 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Fri, 19 Nov 2021 13:59:01 +0000 Subject: [PATCH 032/226] fixed S4 class documentation --- R/assignment.R | 1 + R/parameters.R | 3 ++- man/{Assignment-class.Rd => Assignment.Rd} | 0 man/{AssignmentParameters-class.Rd => AssignmentParameters.Rd} | 2 +- 4 files changed, 4 insertions(+), 2 deletions(-) rename man/{Assignment-class.Rd => Assignment.Rd} (100%) rename man/{AssignmentParameters-class.Rd => AssignmentParameters.Rd} (97%) diff --git a/R/assignment.R b/R/assignment.R index 3ea8fcb..8a1f0f7 100644 --- a/R/assignment.R +++ b/R/assignment.R @@ -1,4 +1,5 @@ #' Assignment +#' @rdname Assignment #' @description An S4 class to store assignment results #' @slot log list containing assignment logs #' @slot flags charactor vector containing completed assignment elements diff --git a/R/parameters.R b/R/parameters.R index 66ea01f..31b9295 100644 --- a/R/parameters.R +++ b/R/parameters.R @@ -1,4 +1,5 @@ -#' AssignmentParameters +#' S4 class for assignment parameters +#' @rdname AssignmentParameters #' @description An S4 class to store assignment parameters. #' @slot technique assignment technique to use #' @slot correlations list of correlation parameters to be passed to metabolyseR correlation analysis diff --git a/man/Assignment-class.Rd b/man/Assignment.Rd similarity index 100% rename from man/Assignment-class.Rd rename to man/Assignment.Rd diff --git a/man/AssignmentParameters-class.Rd b/man/AssignmentParameters.Rd similarity index 97% rename from man/AssignmentParameters-class.Rd rename to man/AssignmentParameters.Rd index 07833fc..4993934 100644 --- a/man/AssignmentParameters-class.Rd +++ b/man/AssignmentParameters.Rd @@ -3,7 +3,7 @@ \docType{class} \name{AssignmentParameters-class} \alias{AssignmentParameters-class} -\title{AssignmentParameters} +\title{S4 class for assignment parameters} \description{ An S4 class to store assignment parameters. } From e59d5fb15f5d9dac1ecb3d1054f50d35a5764caf Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Fri, 19 Nov 2021 14:14:19 +0000 Subject: [PATCH 033/226] fixed plotNetwork() when no transformation assignments were made --- R/plotNetwork.R | 76 +++++++++++++++++++++++++++++-------------------- 1 file changed, 45 insertions(+), 31 deletions(-) diff --git a/R/plotNetwork.R b/R/plotNetwork.R index 6e0687b..725138f 100644 --- a/R/plotNetwork.R +++ b/R/plotNetwork.R @@ -1,3 +1,31 @@ + +networkPlot <- function(network,layout,rThreshold,assignedNodes,explainedEdges){ + rt <- str_c('Visualised using threshold of r > ',rThreshold) + nn <- str_c('Total nodes = ',sum(assignedNodes)) + an <- str_c('Assigned nodes = ', + assignedNodes[1], + ' (', + {assignedNodes[1]/sum(assignedNodes) * 100} %>% + round(),'%)') + ne <- str_c('Total edges = ',sum(explainedEdges)) + ee <- str_c('Explained edges = ', + explainedEdges[1], + ' (', + {explainedEdges[1]/sum(explainedEdges) * 100} %>% + round(),'%)') + + ggraph(network,layout = layout) + + geom_edge_link(alpha = 0.2) + + geom_node_point(aes(fill = Assigned),shape = 21) + + scale_fill_ptol() + + theme_graph() + + theme(legend.title = element_blank()) + + coord_fixed() + + facet_edges(~Explained) + + labs(title = str_c('Assignment correlation network'), + caption = str_c(rt,nn,an,ne,ee,sep = '\n')) +} + #' Plot an assignment network #' @rdname plotNetwork #' @description plot assignment network @@ -25,13 +53,18 @@ setMethod('plotNetwork',signature = 'Assignment', TA <- assignment@transAssign %>% map(~{.$filteredGraph}) - graph <- AI %>% - bind_graphs({a <- TA[[1]] - for (i in 2:length(TA)) { - a <- bind_graphs(a,TA[[i]]) - } - a - }) + graph <- AI + + if (length(TA) > 0){ + graph <- bind_graphs( + {a <- TA[[1]] + for (i in 2:length(TA)) { + a <- bind_graphs(a,TA[[i]]) + } + a + } + ) + } e <- edges(graph) %>% mutate(Explained = 'Explained') @@ -71,28 +104,9 @@ setMethod('plotNetwork',signature = 'Assignment', .$Assigned %>% table() - rt <- str_c('Visualised using threshold of r > ',rThreshold) - nn <- str_c('Total nodes = ',sum(assignedNodes)) - an <- str_c('Assigned nodes = ', - assignedNodes[1], - ' (', - {assignedNodes[1]/sum(assignedNodes) * 100} %>% - round(),'%)') - ne <- str_c('Total edges = ',sum(explainedEdges)) - ee <- str_c('Explained edges = ', - explainedEdges[1], - ' (', - {explainedEdges[1]/sum(explainedEdges) * 100} %>% - round(),'%)') - - ggraph(network,layout = layout) + - geom_edge_link(alpha = 0.2) + - geom_node_point(aes(fill = Assigned),shape = 21) + - scale_fill_ptol() + - theme_graph() + - theme(legend.title = element_blank()) + - coord_fixed() + - facet_edges(~Explained) + - labs(title = str_c('Assignment correlation network'), - caption = str_c(rt,nn,an,ne,ee,sep = '\n')) + networkPlot(network, + layout, + rThreshold, + assignedNodes, + explainedEdges) }) \ No newline at end of file From 2f855cebd2f08ceb3ab0c3c23bd0d2f130139646 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Fri, 19 Nov 2021 14:14:34 +0000 Subject: [PATCH 034/226] added unit test for plotNetwork() --- tests/testthat/test-assignMFs.R | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/tests/testthat/test-assignMFs.R b/tests/testthat/test-assignMFs.R index 7233a68..96d70c8 100644 --- a/tests/testthat/test-assignMFs.R +++ b/tests/testthat/test-assignMFs.R @@ -21,11 +21,11 @@ test_that('feature solutions can be plotted',{ expect_s3_class(pl,'patchwork') }) -# test_that('assignment network can be plotted',{ -# pl <- plotNetwork(assignment) -# -# expect_s3_class(pl,'patchwork') -# }) +test_that('assignment network can be plotted',{ + pl <- plotNetwork(assignment) + + expect_s3_class(pl,'ggraph') +}) test_that('adduct distributions can be plotted',{ pl <- plotAdductDist(assignment) From ece1fd901e1ac39829979fcfab8376ce4338c7cd Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Fri, 19 Nov 2021 14:14:58 +0000 Subject: [PATCH 035/226] expanded edges of plotAdductDist() output --- R/plotAdductDist.R | 2 ++ 1 file changed, 2 insertions(+) diff --git a/R/plotAdductDist.R b/R/plotAdductDist.R index 4421e47..84ea247 100644 --- a/R/plotAdductDist.R +++ b/R/plotAdductDist.R @@ -5,6 +5,8 @@ plotDist <- function(x){ ggplot(x,aes(x = Adduct)) + geom_bar(colour = 'black',fill = ptol_pal()(1)) + + scale_y_continuous(expand = c(0,0)) + + scale_x_discrete(expand = c(0,0)) + theme_bw() + facet_wrap(~Isotope, scales = 'free') + From e8f2cdd976a8d2c57a78e1ff26d0fa3c1ebfb107 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Fri, 19 Nov 2021 14:25:02 +0000 Subject: [PATCH 036/226] improved plotSpectrum() aesthetics and added unit test --- R/allGenerics.R | 5 ----- R/plotSpectrum-method.R | 35 ++++++++++++++++++++++++++------- tests/testthat/test-assignMFs.R | 6 ++++++ 3 files changed, 34 insertions(+), 12 deletions(-) diff --git a/R/allGenerics.R b/R/allGenerics.R index 67c097a..aa4ec26 100644 --- a/R/allGenerics.R +++ b/R/allGenerics.R @@ -26,8 +26,3 @@ setGeneric("transformationAssign", function(assignment) { setGeneric('summariseAssignment',function(assignment){ standardGeneric('summariseAssignment') }) - -#' @rdname plotSpectrum -setGeneric('plotSpectrum',function(assignment,MF){ - standardGeneric('plotSpectrum') -}) \ No newline at end of file diff --git a/R/plotSpectrum-method.R b/R/plotSpectrum-method.R index 72aedb6..13326e7 100644 --- a/R/plotSpectrum-method.R +++ b/R/plotSpectrum-method.R @@ -1,3 +1,25 @@ + +spectrumPlot <- function(dat,MF){ + dat$Mode[dat$Mode == 'n'] <- 'Negative mode' + dat$Mode[dat$Mode == 'n'] <- 'Positive mode' + + ggplot(dat) + + geom_segment(aes(x = `m/z`,xend = `m/z`, y = 0, yend = `Relative Abundance`),colour = ptol_pal()(1)) + + geom_text_repel(aes(x = `m/z`,y = `Relative Abundance`,label = Label)) + + theme_bw() + + theme(panel.border = element_blank(), + panel.grid = element_blank(), + axis.line = element_line(), + axis.title = element_text(face = 'bold'), + strip.background = element_blank(), + strip.text = element_text(face = 'bold'), + plot.title = element_text(face = 'bold', + hjust = 0.5)) + + labs(title = MF, + y = 'Relative Abundance') + + facet_wrap(~Mode,scales = 'free') +} + #' plotSpectrum #' @rdname plotSpectrum #' @description Plot a spectrum for a given molecular formula @@ -9,6 +31,11 @@ #' @importFrom ggrepel geom_text_repel #' @export +setGeneric('plotSpectrum',function(assignment,MF) + standardGeneric('plotSpectrum')) + +#' @rdname plotSpectrum + setMethod('plotSpectrum',signature = 'Assignment',function(assignment,MF){ mf <- MF @@ -30,11 +57,5 @@ setMethod('plotSpectrum',signature = 'Assignment',function(assignment,MF){ dat <- dat %>% mutate(Label = str_c(Isotope,Adduct,sep = ' ')) - ggplot(dat) + - geom_segment(aes(x = `m/z`,xend = `m/z`, y = 0, yend = `Relative Abundance`),colour = ptol_pal()(1)) + - geom_text_repel(aes(x = `m/z`,y = `Relative Abundance`,label = Label)) + - theme_bw() + - labs(title = MF, - y = 'Relative Abundance') + - facet_wrap(~Mode,scales = 'free') + spectrumPlot(dat,MF) }) \ No newline at end of file diff --git a/tests/testthat/test-assignMFs.R b/tests/testthat/test-assignMFs.R index 96d70c8..3044535 100644 --- a/tests/testthat/test-assignMFs.R +++ b/tests/testthat/test-assignMFs.R @@ -32,3 +32,9 @@ test_that('adduct distributions can be plotted',{ expect_s3_class(pl,'patchwork') }) + +test_that('assignment spectrum can be plotted',{ + pl <- plotSpectrum(assignment,'C6H8O7') + + expect_s3_class(pl,'patchwork') +}) From 5bf6ea1bbb67159f7151ac2b69b47bd3bc46ff6d Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Fri, 19 Nov 2021 14:28:48 +0000 Subject: [PATCH 037/226] renamed plotSpectrum file --- DESCRIPTION | 2 +- R/{plotSpectrum-method.R => plotSpectrum.R} | 0 2 files changed, 1 insertion(+), 1 deletion(-) rename R/{plotSpectrum-method.R => plotSpectrum.R} (100%) diff --git a/DESCRIPTION b/DESCRIPTION index 4dc605a..21929cd 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -55,7 +55,7 @@ Collate: parameters.R assignment.R allGenerics.R plotFeatureSolutions.R 'calcCorrelations-method.R' 'filterCorrelations-method.R' - 'plotSpectrum-method.R' + plotSpectrum.R reexports.R Suggests: testthat, covr diff --git a/R/plotSpectrum-method.R b/R/plotSpectrum.R similarity index 100% rename from R/plotSpectrum-method.R rename to R/plotSpectrum.R From f3482280c2c9c7698d770e272aba4056ec3ab753 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Fri, 19 Nov 2021 14:29:00 +0000 Subject: [PATCH 038/226] fixed plotSpectrum() unit test --- tests/testthat/test-assignMFs.R | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/testthat/test-assignMFs.R b/tests/testthat/test-assignMFs.R index 3044535..727432d 100644 --- a/tests/testthat/test-assignMFs.R +++ b/tests/testthat/test-assignMFs.R @@ -36,5 +36,5 @@ test_that('adduct distributions can be plotted',{ test_that('assignment spectrum can be plotted',{ pl <- plotSpectrum(assignment,'C6H8O7') - expect_s3_class(pl,'patchwork') + expect_s3_class(pl,'ggplot') }) From e6955572fce8b604e9f4fd4336fd5b9c106cd39f Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Fri, 19 Nov 2021 14:33:35 +0000 Subject: [PATCH 039/226] fix function imports, update documenation --- NAMESPACE | 4 +++- R/plotAdductDist.R | 2 +- man/plotSpectrum.Rd | 2 +- 3 files changed, 5 insertions(+), 3 deletions(-) diff --git a/NAMESPACE b/NAMESPACE index 5ca1c11..8d2eb88 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -16,9 +16,9 @@ export(plan) export(plotAdductDist) export(plotFeatureSolutions) export(plotNetwork) +export(plotSpectrum) exportClasses(Assignment) exportClasses(AssignmentParameters) -exportMethods(plotSpectrum) exportMethods(summariseAssignment) importFrom(CHNOSZ,count.elements) importFrom(cli,console_width) @@ -64,6 +64,8 @@ importFrom(ggplot2,guides) importFrom(ggplot2,labs) importFrom(ggplot2,margin) importFrom(ggplot2,scale_fill_manual) +importFrom(ggplot2,scale_x_continuous) +importFrom(ggplot2,scale_y_continuous) importFrom(ggplot2,theme) importFrom(ggplot2,theme_bw) importFrom(ggplot2,xlim) diff --git a/R/plotAdductDist.R b/R/plotAdductDist.R index 84ea247..6ef0492 100644 --- a/R/plotAdductDist.R +++ b/R/plotAdductDist.R @@ -1,6 +1,6 @@ #' @importFrom ggthemes ptol_pal -#' @importFrom ggplot2 ggplot geom_bar theme_bw facet_wrap theme element_text element_line +#' @importFrom ggplot2 ggplot geom_bar theme_bw facet_wrap theme element_text element_line scale_y_continuous scale_x_continuous plotDist <- function(x){ ggplot(x,aes(x = Adduct)) + diff --git a/man/plotSpectrum.Rd b/man/plotSpectrum.Rd index 50311d8..ada1c33 100644 --- a/man/plotSpectrum.Rd +++ b/man/plotSpectrum.Rd @@ -1,5 +1,5 @@ % Generated by roxygen2: do not edit by hand -% Please edit documentation in R/allGenerics.R, R/plotSpectrum-method.R +% Please edit documentation in R/plotSpectrum.R \name{plotSpectrum} \alias{plotSpectrum} \alias{plotSpectrum,Assignment-method} From 689718e1b56bdf874e1f424bdf865c722f882b7a Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Fri, 19 Nov 2021 14:38:08 +0000 Subject: [PATCH 040/226] function import fixes --- NAMESPACE | 3 ++- R/addIsoAssign-method.R | 1 + R/plotAdductDist.R | 2 +- 3 files changed, 4 insertions(+), 2 deletions(-) diff --git a/NAMESPACE b/NAMESPACE index 8d2eb88..7977d2a 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -64,7 +64,7 @@ importFrom(ggplot2,guides) importFrom(ggplot2,labs) importFrom(ggplot2,margin) importFrom(ggplot2,scale_fill_manual) -importFrom(ggplot2,scale_x_continuous) +importFrom(ggplot2,scale_x_discrete) importFrom(ggplot2,scale_y_continuous) importFrom(ggplot2,theme) importFrom(ggplot2,theme_bw) @@ -101,6 +101,7 @@ importFrom(metabolyseR,dat) importFrom(metabolyseR,keepFeatures) importFrom(metabolyseR,metabolyse) importFrom(metabolyseR,sinfo) +importFrom(methods,as) importFrom(methods,new) importFrom(methods,show) importFrom(mzAnnotation,adducts) diff --git a/R/addIsoAssign-method.R b/R/addIsoAssign-method.R index b74e90b..f3c8490 100644 --- a/R/addIsoAssign-method.R +++ b/R/addIsoAssign-method.R @@ -3,6 +3,7 @@ #' @importFrom mzAnnotation calcM calcMZ ppmError #' @importFrom igraph vertex.attributes V #' @importFrom furrr furrr_options +#' @importFrom methods as setMethod('addIsoAssign',signature = 'Assignment', function(assignment){ diff --git a/R/plotAdductDist.R b/R/plotAdductDist.R index 6ef0492..3a23766 100644 --- a/R/plotAdductDist.R +++ b/R/plotAdductDist.R @@ -1,6 +1,6 @@ #' @importFrom ggthemes ptol_pal -#' @importFrom ggplot2 ggplot geom_bar theme_bw facet_wrap theme element_text element_line scale_y_continuous scale_x_continuous +#' @importFrom ggplot2 ggplot geom_bar theme_bw facet_wrap theme element_text element_line scale_y_continuous scale_x_discrete plotDist <- function(x){ ggplot(x,aes(x = Adduct)) + From 40c40493a5a5afdb6b735cd9510c8c85677e41d4 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Fri, 19 Nov 2021 14:39:18 +0000 Subject: [PATCH 041/226] documenation name fix --- R/parameters.R | 2 +- man/{AssignmentParameters.Rd => AssignmentParameters-class.Rd} | 0 2 files changed, 1 insertion(+), 1 deletion(-) rename man/{AssignmentParameters.Rd => AssignmentParameters-class.Rd} (100%) diff --git a/R/parameters.R b/R/parameters.R index 31b9295..6645da7 100644 --- a/R/parameters.R +++ b/R/parameters.R @@ -1,5 +1,5 @@ #' S4 class for assignment parameters -#' @rdname AssignmentParameters +#' @rdname AssignmentParameters-class #' @description An S4 class to store assignment parameters. #' @slot technique assignment technique to use #' @slot correlations list of correlation parameters to be passed to metabolyseR correlation analysis diff --git a/man/AssignmentParameters.Rd b/man/AssignmentParameters-class.Rd similarity index 100% rename from man/AssignmentParameters.Rd rename to man/AssignmentParameters-class.Rd From 7994e2e992ccdd72e1291f6ea4f8a80f7a3677cb Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Fri, 19 Nov 2021 14:45:24 +0000 Subject: [PATCH 042/226] documentation fixes --- R/assignment.R | 1 - R/parameters.R | 2 +- man/Assignment.Rd | 2 -- man/AssignmentParameters-class.Rd | 2 +- 4 files changed, 2 insertions(+), 5 deletions(-) diff --git a/R/assignment.R b/R/assignment.R index 8a1f0f7..3eb564e 100644 --- a/R/assignment.R +++ b/R/assignment.R @@ -3,7 +3,6 @@ #' @description An S4 class to store assignment results #' @slot log list containing assignment logs #' @slot flags charactor vector containing completed assignment elements -#' @slot parameters An S4 object of class AssignmentParameters containing the assignment parameters #' @slot data A tibble containing the peak intensity matrix #' @slot correlations A tibble containing the correlations #' @slot preparedCorrelations A tibble containing the prepared correlations ready for analysis diff --git a/R/parameters.R b/R/parameters.R index 6645da7..f951ab2 100644 --- a/R/parameters.R +++ b/R/parameters.R @@ -2,7 +2,7 @@ #' @rdname AssignmentParameters-class #' @description An S4 class to store assignment parameters. #' @slot technique assignment technique to use -#' @slot correlations list of correlation parameters to be passed to metabolyseR correlation analysis +#' @slot correlations_parameters list of correlation parameters to be passed to metabolyseR correlation analysis #' @slot filter list of r and n thresholds for filtering correlations #' @slot maxM maximum M for which to assign molecular formulas #' @slot maxMFscore threshold for molecular formula score diff --git a/man/Assignment.Rd b/man/Assignment.Rd index 71bafaf..9df24f0 100644 --- a/man/Assignment.Rd +++ b/man/Assignment.Rd @@ -14,8 +14,6 @@ An S4 class to store assignment results \item{\code{flags}}{charactor vector containing completed assignment elements} -\item{\code{parameters}}{An S4 object of class AssignmentParameters containing the assignment parameters} - \item{\code{data}}{A tibble containing the peak intensity matrix} \item{\code{correlations}}{A tibble containing the correlations} diff --git a/man/AssignmentParameters-class.Rd b/man/AssignmentParameters-class.Rd index 4993934..ee1f808 100644 --- a/man/AssignmentParameters-class.Rd +++ b/man/AssignmentParameters-class.Rd @@ -12,7 +12,7 @@ An S4 class to store assignment parameters. \describe{ \item{\code{technique}}{assignment technique to use} -\item{\code{correlations}}{list of correlation parameters to be passed to metabolyseR correlation analysis} +\item{\code{correlations_parameters}}{list of correlation parameters to be passed to metabolyseR correlation analysis} \item{\code{filter}}{list of r and n thresholds for filtering correlations} From 9e8d943496e0f2d1f57803367eea36e6afb70d82 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Fri, 19 Nov 2021 16:11:28 +0000 Subject: [PATCH 043/226] plotFeatureSolutions() now throws an error if an incorrect feature is specified --- R/plotFeatureSolutions.R | 5 +++++ tests/testthat/test-assignMFs.R | 5 +++++ 2 files changed, 10 insertions(+) diff --git a/R/plotFeatureSolutions.R b/R/plotFeatureSolutions.R index 409af54..473ac82 100644 --- a/R/plotFeatureSolutions.R +++ b/R/plotFeatureSolutions.R @@ -71,6 +71,11 @@ setMethod('plotFeatureSolutions',signature = 'Assignment', n <- nodes(assignment@addIsoAssign$graph) + if (!(feature %in% n$Feature)){ + stop('Feature not found in assignment graph.', + call. = FALSE) + } + comp <- n %>% filter(Feature == feature) %>% select(Component,Plausibility) %>% diff --git a/tests/testthat/test-assignMFs.R b/tests/testthat/test-assignMFs.R index 727432d..1f2c4df 100644 --- a/tests/testthat/test-assignMFs.R +++ b/tests/testthat/test-assignMFs.R @@ -21,6 +21,11 @@ test_that('feature solutions can be plotted',{ expect_s3_class(pl,'patchwork') }) +test_that('feature solutions plotting throws an error if an incorrect feature is provided',{ + expect_error(plotFeatureSolutions(assignment, + 'test')) +}) + test_that('assignment network can be plotted',{ pl <- plotNetwork(assignment) From a87d9243469798df94f82a15302513ec985b5c19 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Fri, 19 Nov 2021 17:57:52 +0000 Subject: [PATCH 044/226] moved elemental maximum frequency calculation to function outside of MFgen() --- R/MFgen.R | 25 ++++++++++++++++++------- 1 file changed, 18 insertions(+), 7 deletions(-) diff --git a/R/MFgen.R b/R/MFgen.R index 142e64c..63285b7 100644 --- a/R/MFgen.R +++ b/R/MFgen.R @@ -1,7 +1,4 @@ -#' @importFrom mzAnnotation generateMF -#' @importFrom tibble as_tibble - -MFgen <- function(M,mz,ppm = 6){ +maxElementFrequencies <- function(M){ carb <- round(M/12) Hs <- round(carb * 2) NO <- round(carb / 2) @@ -14,6 +11,17 @@ MFgen <- function(M,mz,ppm = 6){ P = PS, S = PS) + return(maxi) +} + + +#' @importFrom mzAnnotation generateMF +#' @importFrom tibble as_tibble + +MFgen <- function(M,mz,ppm = 6){ + + max_element_frequencies <- maxElementFrequencies(M) + if (M < 100) { ppm <- 10 } else { @@ -23,12 +31,15 @@ MFgen <- function(M,mz,ppm = 6){ ppm <- (ppm/10^6 * mz)/M * 10^6 if (M < 200) { - gr <- F + gr <- FALSE } else { - gr <- T + gr <- TRUE } - res <- generateMF(M,ppm = ppm,charge = 0,validation = gr,element_max = maxi) %>% + res <- generateMF(M,ppm = ppm, + charge = 0, + validation = gr, + element_max = max_element_frequencies) %>% rename(`Theoretical M` = Mass) %>% mutate(`Measured M` = M, `Measured m/z` = mz) return(res) From af63471059f0b8c347e1f0c3286b985b46455fa1 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Mon, 22 Nov 2021 12:58:03 +0000 Subject: [PATCH 045/226] temporary remote dependency --- DESCRIPTION | 2 ++ 1 file changed, 2 insertions(+) diff --git a/DESCRIPTION b/DESCRIPTION index 21929cd..b1ff949 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -59,3 +59,5 @@ Collate: parameters.R assignment.R allGenerics.R reexports.R Suggests: testthat, covr +Remotes: jasenfinch/mzAnnotation@tmp, + jasenfinch/metabolyseR From 217da3bb7112f892a349deffed0cc3fdd2645f29 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Tue, 23 Nov 2021 11:34:31 +0000 Subject: [PATCH 046/226] moved addIsoAssign generic alongside method and fixed syntax --- R/addIsoAssign-method.R | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/R/addIsoAssign-method.R b/R/addIsoAssign-method.R index f3c8490..201f258 100644 --- a/R/addIsoAssign-method.R +++ b/R/addIsoAssign-method.R @@ -1,3 +1,8 @@ + +setGeneric("addIsoAssign", function(assignment) + standardGeneric("addIsoAssign") +) + #' @importFrom dplyr arrange rowwise slice_sample left_join ungroup #' @importFrom stringr str_detect #' @importFrom mzAnnotation calcM calcMZ ppmError From b99f2eaeab9ab17ffcb984b8d82ac21244a74ebf Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Tue, 23 Nov 2021 11:35:30 +0000 Subject: [PATCH 047/226] fixed generics --- R/allGenerics.R | 34 ++++++++++++---------------------- 1 file changed, 12 insertions(+), 22 deletions(-) diff --git a/R/allGenerics.R b/R/allGenerics.R index aa4ec26..e4e4fbc 100644 --- a/R/allGenerics.R +++ b/R/allGenerics.R @@ -1,28 +1,18 @@ -setGeneric('calcCorrelations', function(assignment){ - standardGeneric('calcCorrelations') -}) +setGeneric('calcCorrelations', function(assignment) + standardGeneric('calcCorrelations')) -setGeneric('filterCorrelations', function(assignment){ - standardGeneric('filterCorrelations') -}) +setGeneric('filterCorrelations', function(assignment) + standardGeneric('filterCorrelations')) -setGeneric('prepCorrelations', function(assignment){ - standardGeneric('prepCorrelations') -}) +setGeneric('prepCorrelations', function(assignment) + standardGeneric('prepCorrelations')) -setGeneric("relationships", function(assignment,transformations = TRUE) { - standardGeneric("relationships") -}) +setGeneric("relationships", function(assignment,transformations = TRUE) + standardGeneric("relationships")) -setGeneric("addIsoAssign", function(assignment) { - standardGeneric("addIsoAssign") -}) - -setGeneric("transformationAssign", function(assignment) { - standardGeneric("transformationAssign") -}) +setGeneric("transformationAssign", function(assignment) + standardGeneric("transformationAssign")) #' @rdname summariseAssignment -setGeneric('summariseAssignment',function(assignment){ - standardGeneric('summariseAssignment') -}) +setGeneric('summariseAssignment',function(assignment) + standardGeneric('summariseAssignment')) From cdfcb99fb5cc2311b8510ec6b95f773e31c0b860 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Tue, 23 Nov 2021 11:37:17 +0000 Subject: [PATCH 048/226] fixed remotes field in DESCRIPTION --- DESCRIPTION | 2 ++ 1 file changed, 2 insertions(+) diff --git a/DESCRIPTION b/DESCRIPTION index 21929cd..b1ff949 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -59,3 +59,5 @@ Collate: parameters.R assignment.R allGenerics.R reexports.R Suggests: testthat, covr +Remotes: jasenfinch/mzAnnotation@tmp, + jasenfinch/metabolyseR From 9dabeef74f87d3be1e73d4b2cb276044453ca6e7 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Tue, 23 Nov 2021 11:48:00 +0000 Subject: [PATCH 049/226] fixed parameter rules --- NAMESPACE | 6 +++--- R/parameters.R | 10 +++++----- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/NAMESPACE b/NAMESPACE index 7977d2a..891fcf5 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -104,15 +104,15 @@ importFrom(metabolyseR,sinfo) importFrom(methods,as) importFrom(methods,new) importFrom(methods,show) -importFrom(mzAnnotation,adducts) +importFrom(mzAnnotation,adduct_rules) importFrom(mzAnnotation,calcM) importFrom(mzAnnotation,calcMZ) importFrom(mzAnnotation,generateMF) -importFrom(mzAnnotation,isotopes) +importFrom(mzAnnotation,isotope_rules) importFrom(mzAnnotation,ppmError) importFrom(mzAnnotation,relationshipCalculator) importFrom(mzAnnotation,transformMF) -importFrom(mzAnnotation,transformations) +importFrom(mzAnnotation,transformation_rules) importFrom(parallel,detectCores) importFrom(patchwork,plot_annotation) importFrom(patchwork,plot_layout) diff --git a/R/parameters.R b/R/parameters.R index f951ab2..6643105 100644 --- a/R/parameters.R +++ b/R/parameters.R @@ -16,7 +16,7 @@ #' @slot adductRules tibble containing adduct formation rules as returned by mzAnnotation::adducts() #' @slot isotopeRules tibble containing isotope rules as returned by mzAnnotation::isotopes() #' @slot transformationRules tibble containing transformation rules as returned by mzAnnotation::transformations() -#' @importFrom mzAnnotation transformations +#' @importFrom mzAnnotation adduct_rules isotope_rules transformation_rules #' @export setClass('AssignmentParameters', @@ -50,10 +50,10 @@ setClass('AssignmentParameters', "[M-2H]2-", "[M+Cl37]1-","[2M-H]1-"), p = c('[M+H]1+','[M+K]1+','[M+Na]1+','[M+K41]1+', '[M+NH4]1+','[M+2H]2+','[2M+H]1+')), - transformations = transformations()$`MF Change`, - adductRules = adducts(), - isotopeRules = isotopes(), - transformationRules = transformations() + transformations = transformation_rules()$`MF Change`, + adductRules = adduct_rules(), + isotopeRules = isotope_rules(), + transformationRules = transformation_rules() )) #' @importFrom methods show From 585c067aed2a26e8d8b80770706b77dd8bf180fd Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Tue, 23 Nov 2021 11:49:41 +0000 Subject: [PATCH 050/226] moved relationships generic alongside method --- R/allGenerics.R | 3 --- R/parameters.R | 9 +++++++-- R/relationships-method.R | 5 ++++- 3 files changed, 11 insertions(+), 6 deletions(-) diff --git a/R/allGenerics.R b/R/allGenerics.R index e4e4fbc..2d0dbb8 100644 --- a/R/allGenerics.R +++ b/R/allGenerics.R @@ -7,9 +7,6 @@ setGeneric('filterCorrelations', function(assignment) setGeneric('prepCorrelations', function(assignment) standardGeneric('prepCorrelations')) -setGeneric("relationships", function(assignment,transformations = TRUE) - standardGeneric("relationships")) - setGeneric("transformationAssign", function(assignment) standardGeneric("transformationAssign")) diff --git a/R/parameters.R b/R/parameters.R index 6643105..30fe7f9 100644 --- a/R/parameters.R +++ b/R/parameters.R @@ -38,8 +38,13 @@ setClass('AssignmentParameters', ), prototype = list( technique = 'FIE', - correlations_parameters = list(method = 'pearson',pAdjustMethod = 'bonferroni',corPvalue = 0.05), - filter = list(rthresh = 0.7,n = 200000,rIncrement = 0.01,nIncrement = 20000), + correlations_parameters = list(method = 'pearson', + pAdjustMethod = 'bonferroni', + corPvalue = 0.05), + filter = list(rthresh = 0.7, + n = 200000, + rIncrement = 0.01, + nIncrement = 20000), maxM = 1000, maxMFscore = 5, ppm = 5, diff --git a/R/relationships-method.R b/R/relationships-method.R index 38b98da..0df6519 100644 --- a/R/relationships-method.R +++ b/R/relationships-method.R @@ -1,3 +1,7 @@ + +setGeneric("relationships", function(assignment,transformations = TRUE) + standardGeneric("relationships")) + #' @importFrom furrr future_map #' @importFrom dplyr mutate bind_rows filter vars contains #' @importFrom dplyr inner_join semi_join select mutate_at @@ -5,7 +9,6 @@ #' @importFrom mzAnnotation relationshipCalculator #' @importFrom magrittr %>% #' @importFrom tibble tibble -#' @importFrom mzAnnotation adducts isotopes setMethod('relationships',signature = 'Assignment', function(assignment,transformations = T){ From 4ef9c91401078b1f6f6ae1bce4a40f31e5152b5f Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Tue, 23 Nov 2021 11:57:30 +0000 Subject: [PATCH 051/226] renamed iso and add methods --- NAMESPACE | 8 +++--- R/parameters.R | 32 ++++++++++++------------ R/plotAdductDist.R | 2 +- man/parameters.Rd | 42 ++++++++++++++++---------------- tests/testthat/test-parameters.R | 12 ++++----- 5 files changed, 48 insertions(+), 48 deletions(-) diff --git a/NAMESPACE b/NAMESPACE index 891fcf5..be1e555 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -1,8 +1,8 @@ # Generated by roxygen2: do not edit by hand -export("add<-") -export("iso<-") -export(add) +export("adducts<-") +export("isotopes<-") +export(adducts) export(assignMFs) export(assignedData) export(assignmentData) @@ -10,7 +10,7 @@ export(assignmentParameters) export(assignments) export(continueAssignment) export(edges) -export(iso) +export(isotopes) export(nodes) export(plan) export(plotAdductDist) diff --git a/R/parameters.R b/R/parameters.R index 30fe7f9..59928d1 100644 --- a/R/parameters.R +++ b/R/parameters.R @@ -104,26 +104,26 @@ setMethod('show',signature = 'AssignmentParameters', #' assignment_parameters <- assignmentParameters('FIE') #' #' ## Return isotopes -#' iso(assignment_parameters) +#' isotopes(assignment_parameters) #' #' ## Set isotopes -#' iso(assignment_parameters) <- '13C' +#' isotopes(assignment_parameters) <- '13C' #' #' ## Return adducts -#' add(assignment_parameters) +#' adducts(assignment_parameters) #' #' ## Set adducts -#' add(assignment_parameters) <- list(n = c('[M-H]1-','[M+Cl]1-'), +#' adducts(assignment_parameters) <- list(n = c('[M-H]1-','[M+Cl]1-'), #' p = c('[M+H]1+','[M+K]1+')) #' #' @export -setGeneric('iso',function(x) - standardGeneric('iso')) +setGeneric('isotopes',function(x) + standardGeneric('isotopes')) #' @rdname parameters -setMethod('iso',signature = 'AssignmentParameters', +setMethod('isotopes',signature = 'AssignmentParameters', function(x){ x@isotopes }) @@ -131,12 +131,12 @@ setMethod('iso',signature = 'AssignmentParameters', #' @rdname parameters #' @export -setGeneric('iso<-',function(x,value) - standardGeneric('iso<-')) +setGeneric('isotopes<-',function(x,value) + standardGeneric('isotopes<-')) #' @rdname parameters -setMethod('iso<-',signature = 'AssignmentParameters', +setMethod('isotopes<-',signature = 'AssignmentParameters', function(x,value){ x@isotopes <- value return(x) @@ -145,12 +145,12 @@ setMethod('iso<-',signature = 'AssignmentParameters', #' @rdname parameters #' @export -setGeneric('add',function(x) - standardGeneric('add')) +setGeneric('adducts',function(x) + standardGeneric('adducts')) #' @rdname parameters -setMethod('add',signature = 'AssignmentParameters', +setMethod('adducts',signature = 'AssignmentParameters', function(x){ x@adducts }) @@ -158,12 +158,12 @@ setMethod('add',signature = 'AssignmentParameters', #' @rdname parameters #' @export -setGeneric('add<-',function(x,value) - standardGeneric('add<-')) +setGeneric('adducts<-',function(x,value) + standardGeneric('adducts<-')) #' @rdname parameters -setMethod('add<-',signature = 'AssignmentParameters', +setMethod('adducts<-',signature = 'AssignmentParameters', function(x,value){ x@adducts <- value return(x) diff --git a/R/plotAdductDist.R b/R/plotAdductDist.R index 3a23766..bd48d7a 100644 --- a/R/plotAdductDist.R +++ b/R/plotAdductDist.R @@ -44,7 +44,7 @@ setMethod('plotAdductDist',signature = 'Assignment', assignments() %>% replace_na(list(Isotope = '')) %>% mutate(Isotope = factor(Isotope, - levels = c('',iso(assignment))) + levels = c('',isotopes(assignment))) ) assign$Mode[assign$Mode == 'n'] <- 'Negative Mode' diff --git a/man/parameters.Rd b/man/parameters.Rd index 1007d04..7e446fc 100644 --- a/man/parameters.Rd +++ b/man/parameters.Rd @@ -1,31 +1,31 @@ % Generated by roxygen2: do not edit by hand % Please edit documentation in R/parameters.R -\name{iso} -\alias{iso} -\alias{iso,AssignmentParameters-method} -\alias{iso<-} -\alias{iso<-,AssignmentParameters-method} -\alias{add} -\alias{add,AssignmentParameters-method} -\alias{add<-} -\alias{add<-,AssignmentParameters-method} +\name{isotopes} +\alias{isotopes} +\alias{isotopes,AssignmentParameters-method} +\alias{isotopes<-} +\alias{isotopes<-,AssignmentParameters-method} +\alias{adducts} +\alias{adducts,AssignmentParameters-method} +\alias{adducts<-} +\alias{adducts<-,AssignmentParameters-method} \title{Parameter get and set methods} \usage{ -iso(x) +isotopes(x) -\S4method{iso}{AssignmentParameters}(x) +\S4method{isotopes}{AssignmentParameters}(x) -iso(x) <- value +isotopes(x) <- value -\S4method{iso}{AssignmentParameters}(x) <- value +\S4method{isotopes}{AssignmentParameters}(x) <- value -add(x) +adducts(x) -\S4method{add}{AssignmentParameters}(x) +\S4method{adducts}{AssignmentParameters}(x) -add(x) <- value +adducts(x) <- value -\S4method{add}{AssignmentParameters}(x) <- value +\S4method{adducts}{AssignmentParameters}(x) <- value } \arguments{ \item{x}{S4 object of class \code{AssignmentParameters}} @@ -39,16 +39,16 @@ Get and set methods for the \code{AssignmentParameters} S4 class. assignment_parameters <- assignmentParameters('FIE') ## Return isotopes -iso(assignment_parameters) +isotopes(assignment_parameters) ## Set isotopes -iso(assignment_parameters) <- '13C' +isotopes(assignment_parameters) <- '13C' ## Return adducts -add(assignment_parameters) +adducts(assignment_parameters) ## Set adducts -add(assignment_parameters) <- list(n = c('[M-H]1-','[M+Cl]1-'), +adducts(assignment_parameters) <- list(n = c('[M-H]1-','[M+Cl]1-'), p = c('[M+H]1+','[M+K]1+')) } diff --git a/tests/testthat/test-parameters.R b/tests/testthat/test-parameters.R index ef14255..f497d02 100644 --- a/tests/testthat/test-parameters.R +++ b/tests/testthat/test-parameters.R @@ -2,24 +2,24 @@ p <- assignmentParameters('FIE') test_that("isotopes can be returned", { - expect_type(iso(p),'character') + expect_type(isotopes(p),'character') }) test_that("isotopes can be set", { new_isotopes <- '13C' - iso(p) <- new_isotopes + isotopes(p) <- new_isotopes - expect_identical(iso(p),new_isotopes) + expect_identical(isotopes(p),new_isotopes) }) test_that("adducts can be returned", { - expect_type(add(p),'list') + expect_type(adducts(p),'list') }) test_that("adducts can be set", { new_adducts <- list(n = c("[M-H]1-","[M+Cl]1-"), p = c("[M+H]1+","[M+K]1+")) - add(p) <- new_adducts + adducts(p) <- new_adducts - expect_identical(add(p),new_adducts) + expect_identical(adducts(p),new_adducts) }) From bd66c4f6bda91bd3fa71909ea9cd5e13d220ee43 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Tue, 23 Nov 2021 12:00:52 +0000 Subject: [PATCH 052/226] renamed relationships file --- DESCRIPTION | 2 +- R/{relationships-method.R => relationships.R} | 0 2 files changed, 1 insertion(+), 1 deletion(-) rename R/{relationships-method.R => relationships.R} (100%) diff --git a/DESCRIPTION b/DESCRIPTION index b1ff949..ac1b855 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -34,7 +34,7 @@ Roxygen: list(markdown = TRUE) RoxygenNote: 7.1.2 Collate: parameters.R assignment.R allGenerics.R prepCorrelations-method.R addIsoAssign-method.R - transformationAssign-method.R relationships-method.R + transformationAssign-method.R relationships.R graph.R assignMFs.R MFgen.R assignmentParameters.R 'MFscore.R' diff --git a/R/relationships-method.R b/R/relationships.R similarity index 100% rename from R/relationships-method.R rename to R/relationships.R From 6854cd7835e4fc079eb51cd98b590bbe2610a38f Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Tue, 23 Nov 2021 12:03:45 +0000 Subject: [PATCH 053/226] formated addIsoAssign() file --- DESCRIPTION | 2 +- R/{addIsoAssign-method.R => addIsoAssign.R} | 68 +++++++++++++++++---- 2 files changed, 57 insertions(+), 13 deletions(-) rename R/{addIsoAssign-method.R => addIsoAssign.R} (62%) diff --git a/DESCRIPTION b/DESCRIPTION index ac1b855..436d2a8 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -33,7 +33,7 @@ LazyData: true Roxygen: list(markdown = TRUE) RoxygenNote: 7.1.2 Collate: parameters.R assignment.R allGenerics.R - prepCorrelations-method.R addIsoAssign-method.R + prepCorrelations-method.R addIsoAssign.R transformationAssign-method.R relationships.R graph.R assignMFs.R MFgen.R assignmentParameters.R diff --git a/R/addIsoAssign-method.R b/R/addIsoAssign.R similarity index 62% rename from R/addIsoAssign-method.R rename to R/addIsoAssign.R index 201f258..fa8ffe4 100644 --- a/R/addIsoAssign-method.R +++ b/R/addIsoAssign.R @@ -21,16 +21,35 @@ setMethod('addIsoAssign',signature = 'Assignment', parameters <- as(assignment,'AssignmentParameters') rel <- assignment@relationships %>% - filter(is.na(Transformation1) & is.na(Transformation2) & r > 0) %>% - filter(!(is.na(Isotope1) & !is.na(Isotope2) & Adduct1 == Adduct2 & log2IntensityRatio < 0)) %>% - filter(!(!is.na(Isotope1) & is.na(Isotope2) & Adduct1 == Adduct2)) + filter(is.na(Transformation1) & + is.na(Transformation2) & + r > 0) %>% + filter(!(is.na(Isotope1) & + !is.na(Isotope2) & + Adduct1 == Adduct2 & + log2IntensityRatio < 0)) %>% + filter(!(!is.na(Isotope1) & + is.na(Isotope2) & + Adduct1 == Adduct2)) - M <- bind_rows(select(rel,mz = `m/z1`,RetentionTime = RetentionTime1,Isotope = Isotope1, Adduct = Adduct1, Feature = Feature1), - select(rel,mz = `m/z2`,RetentionTime = RetentionTime2,Isotope = Isotope2, Adduct = Adduct2, Feature = Feature2)) %>% + M <- bind_rows(select(rel, + mz = `m/z1`, + RetentionTime = RetentionTime1, + Isotope = Isotope1, + Adduct = Adduct1, + Feature = Feature1), + select(rel, + mz = `m/z2`, + RetentionTime = RetentionTime2, + Isotope = Isotope2, + Adduct = Adduct2, + Feature = Feature2)) %>% filter(!duplicated(.)) %>% arrange(mz) %>% rowwise() %>% - mutate(M = calcM(mz,adduct = Adduct,isotope = Isotope)) %>% + mutate(M = calcM(mz, + adduct = Adduct, + isotope = Isotope)) %>% arrange(M) %>% filter(M <= parameters@maxM) @@ -70,21 +89,46 @@ setMethod('addIsoAssign',signature = 'Assignment', rel <- rel %>% addMFs(MF) %>% filter(MF1 == MF2) %>% - mutate(RetentionTime1 = as.numeric(RetentionTime1),RetentionTime2 = as.numeric(RetentionTime2)) %>% + mutate(RetentionTime1 = as.numeric(RetentionTime1), + RetentionTime2 = as.numeric(RetentionTime2)) %>% addNames() - MFs <- bind_rows(select(rel,Name = Name1,Feature = Feature1,mz = `m/z1`,RetentionTime = RetentionTime1,Isotope = Isotope1, Adduct = Adduct1, MF = MF1), - select(rel,Name = Name2,Feature = Feature2,mz = `m/z2`,RetentionTime = RetentionTime2,Isotope = Isotope2, Adduct = Adduct2,MF = MF2)) %>% + MFs <- bind_rows(select(rel, + Name = Name1, + Feature = Feature1, + mz = `m/z1`, + RetentionTime = RetentionTime1, + Isotope = Isotope1, + Adduct = Adduct1, + MF = MF1), + select(rel, + Name = Name2, + Feature = Feature2, + mz = `m/z2`, + RetentionTime = RetentionTime2, + Isotope = Isotope2, + Adduct = Adduct2, + MF = MF2)) %>% mutate(RetentionTime = as.numeric(RetentionTime)) %>% arrange(mz) %>% select(-mz) %>% - left_join(MF, by = c("Feature", "RetentionTime", "Isotope", "Adduct",'MF')) %>% + left_join(MF, by = c("Feature", + "RetentionTime", + "Isotope", + "Adduct", + 'MF')) %>% distinct() %>% mutate(ID = 1:nrow(.)) - graph <- calcComponents(MFs,rel,parameters) + graph <- calcComponents(MFs, + rel, + parameters) - filters <- tibble(Measure = c('Plausibility','Size','AIS','Score','PPM Error'), + filters <- tibble(Measure = c('Plausibility', + 'Size', + 'AIS', + 'Score', + 'PPM Error'), Direction = c(rep('max',3),rep('min',2))) filteredGraph <- graph From 869549e994384e04a356c0cc8d523929602208fa Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Tue, 23 Nov 2021 12:47:20 +0000 Subject: [PATCH 054/226] renamed assignment test file --- tests/testthat/{test-assignMFs.R => test-assignment.R} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename tests/testthat/{test-assignMFs.R => test-assignment.R} (100%) diff --git a/tests/testthat/test-assignMFs.R b/tests/testthat/test-assignment.R similarity index 100% rename from tests/testthat/test-assignMFs.R rename to tests/testthat/test-assignment.R From e6d3a08c20e54f3ff68c080bcf23fc0e10333d88 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Tue, 23 Nov 2021 12:49:27 +0000 Subject: [PATCH 055/226] renamed example data --- data/feature_data.RData | Bin 0 -> 4342 bytes data/peakData.RData | Bin 4763 -> 0 bytes 2 files changed, 0 insertions(+), 0 deletions(-) create mode 100644 data/feature_data.RData delete mode 100644 data/peakData.RData diff --git a/data/feature_data.RData b/data/feature_data.RData new file mode 100644 index 0000000000000000000000000000000000000000..14e4ead6dd969eba0c48a24a53226e00d69421ed GIT binary patch literal 4342 zcmVdHUHNkO`+0@$-|Oe$>lN;`qUT#- zKRMUR&`0fyBOQ|stf<=abb70R1ZqDl9m}^3IrXDbl=9g8=53TUe;$6Z zMGh5u2_kaVX}CM|M6NO}1C<6B%@al4P_eCG?r!b^%3Gzz$c)vvQ}E-d(u-%P)I5C5 z!A2Q(zV+un;D|*Tb6JPb@KID|e50tJ?m@*3rYC08-%(yZv59}A7^NoepF*~8M@3Qe zqo@b3P;oB8jCAlQuGi|M?b$Sf%C6vUwUM=`{uKM=Y2+Q0NnGBQRM>^ePr-Q!8+=e| zwcw`YDuoKO1hcy2Ih56~og0o$U#aWn?)p3m?$C}GJD>Z2GFAHXO1IQd*%)N9Gwls3 zO)`_&m1R&ZbJo4Z>nlpG9&0=sm4d2?2!^aKo)sQ^yU61Ws&cZ|`&Uk_`WzOxF1}dqJoN@#zl75rr zltcjEnDz7e4G2CHHNaMukAM>+Ar8M~B8VePzfO??TE(U`zS{)+wl^gzIM#wT-xIwn ziHy+Lf;}3!P4HPTdOpgVi(Rj+ebSff5iIQEZI+Y+n&2q$)vyt}*9~;_ZZ?4Ld!G5+ zMoR=%?s$2fq(FM z=A0eH2wb|mV?=#7Xz^iZ+NFE3tMXR6iw6sQTqSVQEM}i z1Z9ZzNzxlWP+4y~|K76;`aQ~W_AZ97CFVqU;?tjlyN&!(<+@;gq4r;M$QI&NJ zbOf$%70}NBRq9mA*M?T;|4?o3ms13V+7{CJC>I1rPPbhR543aHh7LdXgTb*DafJ~@ z=tW$eZ9irLM9sSLSLwnahMxb_4oQ%^bDPXfC87V_ht=dg4V0x$9&?^KXbr~{l!|@; zXt(oe#Y3RXd}8hBb_DTwsq0-$5vZzLGQN+_Lc48UM9)kL^x7qZ`0oaTBDhhCHm?c2 zho=^<+E_w+O_V-wQVjG{5Ac@F?*h5MAVhZDALO0N&tt7wKnxwAa4MZXP;J{wO4(n7qL5cTcqAIe_8%oa3(JFijPCb)U#CI!>U}Ujs0+%z)DGM1U=ZFZ z(QQfPt3Km$~8go+xa7 ze%(w&TNmV^>rCOA0U$h_o~Z`^2?}>pN8q>1(A#>!FTV8yWPHoXA86b#%(|aawG;xQ ziTWGn*=o@7>8|m%dI7C2vj6GUL!h!VbU)J?hPk_z`Sq@6pp1FOjXx@bfufP-w-=t! z%Y0a+d8!$NVuM_H3OC3D`@ejoH9;>;F4W2`2wJar1@0_d2f(fCLYiP`L?S*muMcSoP7hu#^RVS9)0YmYRrtduiK~yU1H69Ow_QN2*swH|T z{1DOnlqL&`BN02%Cb4o~HmA|Gv4EO)OE3HlJFJrXxOb~hKtJr{w)3``Fc{fp(K1~E zeed(>;U+%70_nZ5*&k`827uaty&LLv9QJN&Ydt*33KEVw}+*g-i3AUelTS)xpI6V6~@lJ1!sTc!0B6V z(3d4A7}*=y+#l72v7^pl7=ty8$b`J0iW5vn8s$$evVmILc8~i#3ygYcJMT$9gt6M3 zEB&$~j2X@KnupV2XkHulnc*x9`bRch`>_>v>JuFKyHa4}nm-jPBLLlR>00?|aWLBL zmT|Yh6GqcD!FGF0U|8FypwVUpLf2U0*5F52H{TrO3YUV-;NDPQg>>lqDmEYDuZLxk zh|QV(3UCOYi8tkvg6%?>oBNm>Y_iTvGwe%;MLD)RnO=lls+UZ^nHntTHy^All!ukj zP0kp`2w3I1E=`Ln!-D-NktjRk>$%vL^Auc_rdMJwO zd{zSKaot8U6-`J*d2w{ScZK-#IBGvF6Qr0Aaw?!e%(&qpOLhz-+l4&;3@wC+LHx8r z@_r~?VVJo6iWyQb`q$jEv4V7uMbU_(Fr+QG#%qX`ycE&)3-|?sU$I& zc&l$ekn8|k9`$b*U5sHHaJNzVL^+I0Y$BznWTC_Ew&u#x6m;!8U(M4CLXDf&Dig9E znhEA_x;s9Av?WME)!{Di?09tH6<<)b4^($|D?@ww#3CJg7NiomV-0ie!bF)%I>8Cp zEOxV)lN=0n8^_L;$!tK&1^WQ9q> z`Y`+aK(9SC{+OUY>l_KorqXw9Y?ooXCQDnID+9J;Q4CTQk*hvydULszZcT--Jxf@` z84Hj)@L8O_Hk#-JC8^1-d+K+f?xS`i zUSbm5g~mTpSN6~LvZ`N3R0d+KK3?QsWa<8Tz;-NhkVR*DHC})6pv#m{DL6P@>OU4O z#oDS|hkV0O^QG-B6b)NG}xFaxy&y-^Bt_ zlx{KTeP$e0x5+?q&8@ECnpE)0*@Ta(O@Q-Kr^HdZ!;lFu6nU9=6SA!bbNc*FgYR*U zK@z(Lq>o0aIXvVgItw#yiE>^Ai9@KFgP{)VxF1FcS=<1>&+w-MH4?wLZ`+6XfBRT)Kloty0)`^%!4niTLa1^GTQyM(p*qqaF^dH>Xb&%kD|#se~m1?5T1^AO}e zr5SBqh+lGF2RiG}6H}rpib@`lVD>oP7eG=aKFzR%Q4R+Y^L6}ltyM8#4v6h@3a=p+ zPhEK%u~rbAr#Fg4MQtM{L!A~J^%cN)C^X!J)Iv<|Tjv^I(nTy#8p!i^T#4Ar@*7V_ z27;$9Izv%n4)psK+LcsjME{M@N0~B8M9dl0m%j}-fSxOV*>I?pcww)yX8+>7zxPc% z+v1hld0&)hV`#Fy5GcRO5@ag~3$KX2$LB2G*YdJicf;^3pp@e3IgAOe1Ou^!fBKM0au$qjP*yW=rRYFWY}nF0IQXCNnMP&&TfoosX<-q3@pAzs0LKNE4T42Ia1*Yfgm^Zy8$eS*C9{S@*1 zUyJ6y@RxA!AP-;vzaqw!=&vc;&(@5p|K63v|C{IU#d!YPwfRdPvPox?s@f(UE%kp9 zbyYQW4K=NQ5sjZjTYHtLt81z1=xFI^{EKL->X5ZGwEjQQQ73EuLo`;_Qd85?`MU-o k8rqtwYMMHmS0x(Sn^%DL%1?B3OFzed0G1Y@)t?do00dlvxc~qF literal 0 HcmV?d00001 diff --git a/data/peakData.RData b/data/peakData.RData deleted file mode 100644 index 868b37649ce90a19fc15b902a05a3628ed979b6f..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 4763 zcmZ8l2{={T`!?RpWGwS=j3FV%xZiWkA~O}rEGJ{7k}{Pf)V&&zipp3TB(so616Nck zm6WNt#)we-PygS&e)sw9=lS+t-@D%Rerv67Kl@qxb2Qzm#j%xxfq{XUf%!K^24+@z zlY!O6*<4MRfq{jI?l3a2FtF2~Y~lXiL8jgj-gK@2-T#I0(9ICFFAsN2Hn5{=_p|9O zLQ<&x6kRDtw4-`COW(Tr392H6ICa^(Q6+FZ;v;Pl_qSTAt?T@ViYI1{&iTHms2m(< z5`Kf~*kye-$yccOcK({@!C6$PG3Jn!gHR#s^S;f|50%$=L=3naP+2*Yw8QRq+?{86 zu#lfxwF|aT(5}S@n-^*eZ3?x+UkI8soDTOlrZS~7bg(%OxaK7Q%M^yW< z6wI6p!(AI!ujOY2D0eE~I^^7sN^!~)%bT}R*8FAo-fM23%` zGUGc%^HdKiZm>MHnErwC@`(+CBgH5+^Y|RPZ5t|zVje|5c#Vp4krt!_M{vDX@AU2s zBdF{O>DCxojq1;FU!O(YL7CL$oymn=sQes~m$=RsrPd4XDsD2Uut>D1OPNDi4ad3R zm~{HSZtSklqu>thSh35wk0?`TJg;&~1C@=zW;;&5MWtD03a6?Zs^!jlw0M6*$r#etGnvwh!M5R6M)g)Bm_4Tnx&H+t$l=x=ch+S(2x_UPn!S4g#d~V|=1XXT-b-i2_yRs_+jPJW) z=U*KAbBaI0E9T5GqX(N2ME1E$a(M=y*N3?-#hgJv$a&VB?ZpUMy1RWua~Eg{;b+=q zd$F_fR=cYw8+_gBMqVVJKv0j!2bZP8pwYxTk0|Yj(~w0gABjLv8F!?{ngxWbM9(N1 z#=~cHGiO6H3BjlNC%?ZMgm0r{*CCq;1Xf&+&yocE<>#mJuVy3g=P_}&M^EADzPqrD z)(by{(MZ#!B!sLnn)Hw;M38yPe9F*agkKLDA7X2Q=e{d~mN#k;W~@K?WV;nyyrA|IezB%X&#}<@|e*|c^^J&FHpv-(`@91^{@nos% zeN7Rl>YFoujLt&0ZB1m)Oezf8rGo|UhJYfxUWPWW4TFa#7p~fFg6^tlL;mDg7^dy# zFPq;9a(_Xn{CEJ!J5*o9*|32a+E3--JPad$T2mF}5TFyhmHA~E^p7b1rvADM#%^|s zaSe1``5vyaZ932-io%j|ECHAH@q3}Epsv}|vQ6s=^jg%tTUqY_o}!YYqGzCg-Ji#^ z-vz{|J_F13*L1#?l(P^SSmGKP*Rp^?g8$)oqeAF^nRC7%a}89x_L5T0H=roxRSzDH zfvLkMsV}06ARlFTeDB*dsNTH~<_Gmb*_+m3mmLDaCpD%mxqKzh2Cf;YLLNiV=1P0+ zbTJHC#KJ(pU>L}Ab?0)dI)KR`(G(t6X!~cbyS+Oa8(&p3W6Uh(6P%3!2yqW%4)7Ys5VR%xGX2BF-bP@c*Q^1!~Y zpJ+`mIIR$7?H&xB*Ze|v7OsQfFRy!DbP$GS-S#J0set~OB)+xjAd0oLX1eykwEiOP z(#Z=j>8q-f$nAi!IPtpk#ZeGjk?_Mi;cIDgk)qlhjjtsk=Uhg>p$9?a!4ET@3A?`

8)hg zTyR;O;IW6JeT}NB_zWDAo1F!2M8bjDeoQj)C9IWxt}B;$2OIB7=UqZVu(BB2ph?Y# z&8Yu5-v9+zeYwi+N3wur_WSW4{qC?9Z8^St@*x}<6RiTKnqW2Ve_L0*9_A9^i`|_& zV4)W7Bp~U4O&SIl)_C~CoXPCUv4u34y7U&D{h0&j@43NWmz-hZU}AfJR3D~JdV}Fi zHZUO*io$BnFdu1DJh8|DYHiy+-Vbar>80(sC;Jel8gp)p%T6$5wlruSPKU8&ZTuIe zvoPu(*>LUW7T9Y}aOLkzg^64KRG6F)^uMR;CKf$K?<{(dm3~UGYg!w6@!_ZH;`JiAuHWi84p4q1a$B3B(a~>JkErh#! zjJd-$>%1(}-gH=%W1F-2McAi#%k^7mVAK4@1C@n}uok(=9m^aE>s+^`X>nCpaULO( z;VYO#bexabex z$SMDI2K&!BOk~jW1536Cgms*p%o`LT!g0D#u+RnKq$1se?|L91OxV@34HI*p%g>$g zVu#FZ%n5BTGDNMD!nDetLGD4$cHYA*P&TVN(peD!@rYV6w-_z3KJHQ3P2bmbHCct4 zEZtDsy!TMs?VXT5BL1OIY%Rn)kG)azD}{7q%d!ZM0n|N}#r3|Zfb^tpy@i@KWTL&f zIzG5T@_-JPP#|I2@Q^J#7Sin^UVnuZLd+;(S}A28RIV^h+m z?%7&Hw#TYy#7PvgRy^Z11YMUR-k$OjAPwfd2}`&P*{JmSE1m98auDvA_w9yoJ;y8) zLob*v`P*9NH$vJY+JxU@9wc?%V_##*P@E~68=b6!x(42rxf(%fAFo2HsV05>@&(^= zMj@9wq|<{VARU)^8~P;=D&Bb)wVjP2cBl7PzH|x%NP0pNjR&C2lwuGYPy|x#sxK;1 zdm+LTT6);f3j)7iGZfPZ11X$+ZN_K`e>p&yDm($X+7`wa5x+xb-kEeS zvJoOF`BkgOzeB9GJ-fGY7x8n~sF88@daSOGF}%9_J!Je-D4%!qujJWj_T=kYV^dfg z?798d_)|C+zWZu&FA9whi{TGGmOAZ@|Jkle)=b60YhRk0eVfVH2(sD>kMCo2&x~pZ2xE zY+Ze5Y2PXco3tWyZT=jbUp4XNXPO25j=U^>`{-0%ks%+xDk8!j4b#`$bn% z*ahBgls#S!(-PY#*(rJGak{U%vNQ#Kd#~5?jKa|1rM1e1u7!4@<=gI#k05OhR#JDo z3p_s-Q+UM>RNej6-QB9toj$(Ez?lV^MBX^#oVzen<&jNv1~y9EEaoPMK-1Q#vt=?H zkhZMdqt*c9b&m`0SyX_ku+ycNV1%}zcpm4`%P?<#?%A9>4olIJo90KWLFHJC^Kw^) z)!ahrTFpFIdUrc;p!?kUx?5Dp*sXvf!F& z((VO?sHM^Pr5wmj4)6+!?FQAI-SbA-7?fIq>lJ$Ppcdm;ZGOlA8l|uEzZLUB&2w&A zm4m*2SDusmp2vf7ahRs75e$XKD1neej##%HrvtXyK&E-o-A3saG-5>yGTq-n>tV_5 zZG%stNeZdG4)uAr^Gu;rdI(uz2$r&m#lU?^T??BU6<3@tiBzOx=f2Ps@3prj@ z^~;INL4w`aoBW$ReO>>5f#Yb@Ae-Lwiof>60oN&!QgCs-GJGOliq%yo*)PpAuk>?F z*C+m==SIx&Uyce)3L={KU+iEOzW~|DDE%VDXVx!fz|U^Um!`H_&mcFPB|1z%-0FdwN}M~H88HvIiiMGJbC3^w9le#940B#^GE@Td!LSH3QVTJ;ca2*@Nf)s|X&}$vaU1YFAOC5&bv99%ag@5V2>}U;Q!Q2u7a#W#ge%;-!Pys(p+1{+T!Ne6x32=Y4Ua zjj74*LXhGL9`EtTmOMoc;+1t9*YM^7V)Q7DGXLiW;@vq`+mx>3E4(Qx-zfvt%S3NX zjj85^^(*+-`}4+5Vv@uJVepU=DhUCG9RJWkA!1|5Ha{-xGE~J=8nI|CbOq-I(I&x8>#K=KmqG`UZRN{YB!V8}r{)nBO9N zf<65L{`Q#Z-rr3QKYD3KJzx)A_aHM~nmX!wdOCVq|3Y-t^~gF}{~e{NNk{ZF$=d(rXwhS7Xz1wujj)Gm>1wNM XXzOiUp=jxDqyxJ2K@1E_zwG}2{l=e; From e9b6ecb16f5ce5faf93e205ebf560b401bf9666d Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Tue, 23 Nov 2021 12:51:44 +0000 Subject: [PATCH 056/226] added parameters accessor methods --- NAMESPACE | 14 +++ R/parameters.R | 193 +++++++++++++++++++++++++++++++ tests/testthat/test-parameters.R | 38 +++++- 3 files changed, 239 insertions(+), 6 deletions(-) diff --git a/NAMESPACE b/NAMESPACE index be1e555..204de6c 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -1,7 +1,13 @@ # Generated by roxygen2: do not edit by hand +export("adductRules<-") export("adducts<-") +export("isotopeRules<-") export("isotopes<-") +export("limit<-") +export("transformationRules<-") +export("transformations<-") +export(adductRules) export(adducts) export(assignMFs) export(assignedData) @@ -10,13 +16,18 @@ export(assignmentParameters) export(assignments) export(continueAssignment) export(edges) +export(isotopeRules) export(isotopes) +export(limit) export(nodes) export(plan) export(plotAdductDist) export(plotFeatureSolutions) export(plotNetwork) export(plotSpectrum) +export(technique) +export(transformationRules) +export(transformations) exportClasses(Assignment) exportClasses(AssignmentParameters) exportMethods(summariseAssignment) @@ -40,6 +51,7 @@ importFrom(dplyr,left_join) importFrom(dplyr,mutate) importFrom(dplyr,mutate_at) importFrom(dplyr,n) +importFrom(dplyr,relocate) importFrom(dplyr,rename) importFrom(dplyr,rowwise) importFrom(dplyr,select) @@ -125,10 +137,12 @@ importFrom(stats,dist) importFrom(stats,hclust) importFrom(stringr,str_c) importFrom(stringr,str_detect) +importFrom(stringr,str_remove) importFrom(stringr,str_replace_all) importFrom(stringr,str_split_fixed) importFrom(stringr,str_sub) importFrom(tibble,as_tibble) +importFrom(tibble,enframe) importFrom(tibble,tibble) importFrom(tidygraph,activate) importFrom(tidygraph,as_tbl_graph) diff --git a/R/parameters.R b/R/parameters.R index 59928d1..315859b 100644 --- a/R/parameters.R +++ b/R/parameters.R @@ -61,6 +61,19 @@ setClass('AssignmentParameters', transformationRules = transformation_rules() )) +# setValidity('AssignmentParameters',function(object){ +# adducts_present <- adducts(object) %in% adductRules(object)$Name +# +# if (FALSE %in% adducts_present){ +# missing_adducts <- adducts(object)[adducts_present] %>% +# str_c(collapse = ', ') +# +# str_c('Specified adducts ',missing_adducts,' not present in adduct rules.') +# } else { +# TRUE +# } +# }) + #' @importFrom methods show #' @importFrom crayon yellow #' @importFrom purrr map @@ -103,6 +116,15 @@ setMethod('show',signature = 'AssignmentParameters', #' @examples #' assignment_parameters <- assignmentParameters('FIE') #' +#' ## Return technique +#' technique(assignment_parameters) +#' +#' ## Return limit +#' limit(assignment_parameters) +#' +#' ## Set limit +#' limit(assignment_parameters) <- 0.002 +#' #' ## Return isotopes #' isotopes(assignment_parameters) #' @@ -115,7 +137,70 @@ setMethod('show',signature = 'AssignmentParameters', #' ## Set adducts #' adducts(assignment_parameters) <- list(n = c('[M-H]1-','[M+Cl]1-'), #' p = c('[M+H]1+','[M+K]1+')) +#' +#' ## Return transformations +#' transformations(assignment_parameters) +#' +#' ## Set transformations +#' transformations(assignment_parameters) <- "M - [O] + [NH2]" +#' +#' ## Return adduct rules +#' adductRules(assignment_parameters) +#' +#' ## Set adduct rules +#' adductRules(assignment_parameters) <- mzAnnotation::adduct_rules()) +#' +#' ## Return isotope rules +#' isotopeRules(assignment_parameters) #' +#' ## Set isotope rules +#' isotopeRules(assignment_parameters) <- mzAnnotation::isotope_rules()) +#' +#' ## Return transformation rules +#' transformationRules(assignment_parameters) +#' +#' ## Set transformation rules +#' transformationRules(assignment_parameters) <- mzAnnotation::transformation_rules()) +#' @export + +setGeneric('technique',function(x) + standardGeneric('technique')) + +#' @rdname parameters + +setMethod('technique',signature = 'AssignmentParameters', + function(x){ + x@technique + }) + +#' @rdname parameters +#' @export + +setGeneric('limit',function(x) + standardGeneric('limit')) + +#' @rdname parameters + +setMethod('limit',signature = 'AssignmentParameters', + function(x){ + x@limit + }) + +#' @rdname parameters +#' @export + +setGeneric('limit<-',function(x,value) + standardGeneric('limit<-')) + +#' @rdname parameters + +setMethod('limit<-',signature = 'AssignmentParameters', + function(x,value){ + x@limit <- value + return(x) + }) + +#' @rdname parameters #' @export setGeneric('isotopes',function(x) @@ -168,3 +253,111 @@ setMethod('adducts<-',signature = 'AssignmentParameters', x@adducts <- value return(x) }) + +#' @rdname parameters +#' @export + +setGeneric('transformations',function(x) + standardGeneric('transformations')) + +#' @rdname parameters + +setMethod('transformations',signature = 'AssignmentParameters', + function(x){ + x@transformations + }) + +#' @rdname parameters +#' @export + +setGeneric('transformations<-',function(x,value) + standardGeneric('transformations<-')) + +#' @rdname parameters + +setMethod('transformations<-',signature = 'AssignmentParameters', + function(x,value){ + x@transformations <- value + return(x) + }) + +#' @rdname parameters +#' @export + +setGeneric('adductRules',function(x) + standardGeneric('adductRules')) + +#' @rdname parameters + +setMethod('adductRules',signature = 'AssignmentParameters', + function(x){ + x@adductRules + }) + +#' @rdname parameters +#' @export + +setGeneric('adductRules<-',function(x,value) + standardGeneric('adductRules<-')) + +#' @rdname parameters + +setMethod('adductRules<-',signature = 'AssignmentParameters', + function(x,value){ + x@adductRules <- value + return(x) + }) + +#' @rdname parameters +#' @export + +setGeneric('isotopeRules',function(x) + standardGeneric('isotopeRules')) + +#' @rdname parameters + +setMethod('isotopeRules',signature = 'AssignmentParameters', + function(x){ + x@isotopeRules + }) + +#' @rdname parameters +#' @export + +setGeneric('isotopeRules<-',function(x,value) + standardGeneric('isotopeRules<-')) + +#' @rdname parameters + +setMethod('isotopeRules<-',signature = 'AssignmentParameters', + function(x,value){ + x@isotopeRules <- value + return(x) + }) + +#' @rdname parameters +#' @export + +setGeneric('transformationRules',function(x) + standardGeneric('transformationRules')) + +#' @rdname parameters + +setMethod('transformationRules',signature = 'AssignmentParameters', + function(x){ + x@isotopeRules + }) + +#' @rdname parameters +#' @export + +setGeneric('transformationRules<-',function(x,value) + standardGeneric('transformationRules<-')) + +#' @rdname parameters + +setMethod('transformationRules<-',signature = 'AssignmentParameters', + function(x,value){ + x@transformationRules <- value + return(x) + }) \ No newline at end of file diff --git a/tests/testthat/test-parameters.R b/tests/testthat/test-parameters.R index f497d02..e61cca2 100644 --- a/tests/testthat/test-parameters.R +++ b/tests/testthat/test-parameters.R @@ -1,15 +1,19 @@ p <- assignmentParameters('FIE') -test_that("isotopes can be returned", { - expect_type(isotopes(p),'character') +test_that("technique can be returned", { + expect_type(technique(p),'character') }) -test_that("isotopes can be set", { - new_isotopes <- '13C' - isotopes(p) <- new_isotopes +test_that("limit can be returned", { + expect_type(limit(p),'double') +}) - expect_identical(isotopes(p),new_isotopes) +test_that("limit can be set", { + new_limit <- 0.002 + limit(p) <- new_limit + + expect_identical(limit(p),new_limit) }) test_that("adducts can be returned", { @@ -23,3 +27,25 @@ test_that("adducts can be set", { expect_identical(adducts(p),new_adducts) }) + +test_that("isotopes can be returned", { + expect_type(isotopes(p),'character') +}) + +test_that("isotopes can be set", { + new_isotopes <- '13C' + isotopes(p) <- new_isotopes + + expect_identical(isotopes(p),new_isotopes) +}) + +test_that("transformations can be returned", { + expect_type(transformations(p),'character') +}) + +test_that("transformations can be set", { + new_transformations <- "M - [O] + [NH2]" + transformations(p) <- new_transformations + + expect_identical(transformations(p),new_transformations) +}) \ No newline at end of file From 4554266dd8776225ce9cd42053fca5507786f737 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Tue, 23 Nov 2021 12:56:42 +0000 Subject: [PATCH 057/226] moved assignmentParameters to parameters file --- DESCRIPTION | 1 - R/assignmentParameters.R | 32 -------------------------------- R/parameters.R | 35 ++++++++++++++++++++++++++++++++++- 3 files changed, 34 insertions(+), 34 deletions(-) diff --git a/DESCRIPTION b/DESCRIPTION index 436d2a8..b6488b6 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -36,7 +36,6 @@ Collate: parameters.R assignment.R allGenerics.R prepCorrelations-method.R addIsoAssign.R transformationAssign-method.R relationships.R graph.R assignMFs.R MFgen.R - assignmentParameters.R 'MFscore.R' 'addIsoScore.R' 'addMFs.R' diff --git a/R/assignmentParameters.R b/R/assignmentParameters.R index 2ea315e..e69de29 100644 --- a/R/assignmentParameters.R +++ b/R/assignmentParameters.R @@ -1,32 +0,0 @@ -#' annotationParameters -#' @description Return assignment parameters for a specified technique. -#' @param technique technique to use for assignment. \code{NULL} prints available techniques -#' @importFrom parallel detectCores -#' @importFrom methods new -#' @export - -assignmentParameters <- function(technique = NULL){ - availTechniques <- c('FIE','RP-LC','NP-LC') - if (is.null(technique)) { - cat('\nAvailable Techniques:',str_c('\n\t\t\t',str_c(availTechniques,collapse = '\n\t\t\t'),'\n')) - p <- NULL - } else { - - if (technique == 'FIE') { - p <- new('AssignmentParameters') - } - if (technique == 'RP-LC') { - p <- new('AssignmentParameters', - technique = 'RP-LC', - RTwindow = 1/60 - ) - } - if (technique == 'NP-LC') { - p <- new('AssignmentParameters', - technique = 'NP-LC', - RTwindow = 1/60 - ) - } - } - return(p) -} \ No newline at end of file diff --git a/R/parameters.R b/R/parameters.R index 315859b..1c154ad 100644 --- a/R/parameters.R +++ b/R/parameters.R @@ -360,4 +360,37 @@ setMethod('transformationRules<-',signature = 'AssignmentParameters', function(x,value){ x@transformationRules <- value return(x) - }) \ No newline at end of file + }) + +#' Assignment parameters +#' @description Return default assignment parameters for a given technique. +#' @param technique technique to use for assignment. \code{NULL} prints available techniques +#' @importFrom parallel detectCores +#' @importFrom methods new +#' @export + +assignmentParameters <- function(technique = NULL){ + availTechniques <- c('FIE','RP-LC','NP-LC') + if (is.null(technique)) { + cat('\nAvailable Techniques:',str_c('\n\t\t\t',str_c(availTechniques,collapse = '\n\t\t\t'),'\n')) + p <- NULL + } else { + + if (technique == 'FIE') { + p <- new('AssignmentParameters') + } + if (technique == 'RP-LC') { + p <- new('AssignmentParameters', + technique = 'RP-LC', + RTwindow = 1/60 + ) + } + if (technique == 'NP-LC') { + p <- new('AssignmentParameters', + technique = 'NP-LC', + RTwindow = 1/60 + ) + } + } + return(p) +} \ No newline at end of file From f887731b2282c58d1e423e33904216285b52b8bf Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Tue, 23 Nov 2021 13:02:54 +0000 Subject: [PATCH 058/226] removed sysdata --- R/sysdata.rda | Bin 1729 -> 0 bytes 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100644 R/sysdata.rda diff --git a/R/sysdata.rda b/R/sysdata.rda deleted file mode 100644 index 8f377efe8f54470a381db459b612015af2922796..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 1729 zcmV;y20r;8iwFP!000001MOIQY*SSjzkR^kvaQ8|AUJI#KA^O$x04}Z>*>0UOGvFrv`}V>06F52Hk5LJY=WqM+G^K?I`4@W*`2L}M@-!oz?O zB3nJ@_MZD{aT_2ivB}*%-|v3k@B5wa+4lfJ5mJ3eC4!_M6U^-nk0hj>+%0{XolCsGm0}7)gyS#%$ z07*l~P7MB$iwpL15~vH8F=-QZQ*S@)M^h< zF1ao;pAzypB^d%pNtgj)KFK!mcC}MNj0lm_@GeM|l0-&&6I8XTmupUONf;@AQi|)P z!W#TRT8^P&kUqQ0OWh%}ERW1}M!x=b6{JdA(xK=$8V^Ok%lPVhDHp9Mm$DWpN>K{L zs`Pi-97-J&KU69Rj-ayll)cF#AsW9(=<=hE+2vzOF{~V$fv_e|fg3CdDZ|jHDZ~7> zR%ICKZhcDWqDqFeDuWQ>Q)DX5*H)F?Z}Y~LQQo+#MwzTYvfpWUNH(mtN-lCI}T z?Pxgpd4iui6qk0Am*zimX@!2_{uX;aS)S`ri(+GNB|PP*zhLQD?aL?cX$MPMPK3@| zv%tEC9$0W&zcH?MEI;X$y#v}14M!TFeHsA}7f-j1VdK(j{6eDHOf$m88a9bWrN3uxF> zd22Fj7I{g-Tb~V7>O>uFy3MB-pFRd!KmN{*1R{=wB^ve zOYiI=gx?_6=ihqhRP}2sf$$tuU)(-&AnFsJuX9(74ljKH1owYYLNDA`;9sA8rAujPRA-V3{ z(|OA&I*IRt+^M|i+hGZ?Trqt5pQgyO|5X(QqshdrvgvJR>E6$=VZE4 zWO6{TY_3xsA`?sxIz;l5>~sOt2Ox+C+#6+5-PqD@#Jg^tCltaQfp9#`;@B2=Dpe&h zrnn6boCvL6+9&fX#wThuY@F%EYIImZx+}gu6v26+h4;rHCe1h^DI}I4#)T6wUNHV;FAMaWm+uCi1&0gZpgR`}+@DjsZfr8)ogAyXYk+ zuwdM<@4j|Rmpgav`ES2#|Eev}T301Col=vOnvzh_7Ydc) zd{Q%5Ck(eXr>bcQJR_#LBpz0?AC}$G5Q{{@sc?b~7mlSary9Bod0ek%p5ka3h44~5 z@3f|vL@(15OEBpem$2d*SUf#FTq4F;4kzT`d{3O^qFmgX=BzA} z>f$zL<1yCSo#HY{e3J5q)6r~P9;HrADpG7zIvWuv2X4s|s!}p+41XnMUICUznSz;k zGAc*R%~7s58Rb&gQCXjIztwK-pgXNLYk(p;$&onCE9b_YGKV&^3*AhJa(*z+SqnA1oOQjhsDI2T1KcbL5Tt zLG49$lzR9$XdHic@Y~e~L2zuvL)us8!24HgKRrSU?|Ugx_|r^);W&J7)1r;H%q9d( z+&Bw3j?)l@If~^}3frK?aNPQTH&9uM!_aj>9s;k1sh$EGHg1W!X*$N5z-|2ck@^zo)DMmiifX+WTr$COQgfyS0?3umaAm>M?SI%<(nn> z-I*}l;!Q$4j@3ga98eMpN0>}JtxAJGMgw$RpZ_2cT>+)I{b53(44cNRhFE?#gzfS) X+6hFsR1aQ)d9ptNbp~Q7lNkU27|~On From 97829b30db5adca579b58664fb4ba7adf2db8a4f Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Tue, 23 Nov 2021 13:06:33 +0000 Subject: [PATCH 059/226] removed assignmentParameters file --- R/assignmentParameters.R | 0 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100644 R/assignmentParameters.R diff --git a/R/assignmentParameters.R b/R/assignmentParameters.R deleted file mode 100644 index e69de29..0000000 From 6a10e5b31f818d7c2cf4311ccffe559f88ca7a0c Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Tue, 23 Nov 2021 13:07:20 +0000 Subject: [PATCH 060/226] fixed example data --- DESCRIPTION | 2 +- R/feature_data.R | 5 +++++ R/peakData.R | 5 ----- man/feature_data.Rd | 16 ++++++++++++++++ man/peakData.Rd | 16 ---------------- 5 files changed, 22 insertions(+), 22 deletions(-) create mode 100644 R/feature_data.R delete mode 100644 R/peakData.R create mode 100644 man/feature_data.Rd delete mode 100644 man/peakData.Rd diff --git a/DESCRIPTION b/DESCRIPTION index b6488b6..c386a6c 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -41,7 +41,7 @@ Collate: parameters.R assignment.R allGenerics.R 'addMFs.R' components.R 'assignMethods.R' - 'peakData.R' + feature_data.R 'LCassignment.R' 'MFassign.R' 'FIEassignment.R' diff --git a/R/feature_data.R b/R/feature_data.R new file mode 100644 index 0000000..15ac94f --- /dev/null +++ b/R/feature_data.R @@ -0,0 +1,5 @@ +#' Example feature data +#' @description Example mass spectral feature intensity table. +#' @format A tibble containing 60 rows and 1003 variables. + +'feature_data' \ No newline at end of file diff --git a/R/peakData.R b/R/peakData.R deleted file mode 100644 index 9af722b..0000000 --- a/R/peakData.R +++ /dev/null @@ -1,5 +0,0 @@ -#' peakData -#' @description example peak intensity table of sample data from the example FIE-HRMS B. distachyon ecotype data in the metaboData package. -#' @format A tibble containining 60 rows and 1003 variables - -'peakData' \ No newline at end of file diff --git a/man/feature_data.Rd b/man/feature_data.Rd new file mode 100644 index 0000000..d0d8326 --- /dev/null +++ b/man/feature_data.Rd @@ -0,0 +1,16 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/feature_data.R +\docType{data} +\name{feature_data} +\alias{feature_data} +\title{Example feature data} +\format{ +A tibble containing 60 rows and 1003 variables. +} +\usage{ +feature_data +} +\description{ +Example mass spectral feature intensity table. +} +\keyword{datasets} diff --git a/man/peakData.Rd b/man/peakData.Rd deleted file mode 100644 index 566ce05..0000000 --- a/man/peakData.Rd +++ /dev/null @@ -1,16 +0,0 @@ -% Generated by roxygen2: do not edit by hand -% Please edit documentation in R/peakData.R -\docType{data} -\name{peakData} -\alias{peakData} -\title{peakData} -\format{ -A tibble containining 60 rows and 1003 variables -} -\usage{ -peakData -} -\description{ -example peak intensity table of sample data from the example FIE-HRMS B. distachyon ecotype data in the metaboData package. -} -\keyword{datasets} From c7a374c6cd32f9e77b03cc42b4fdfaea161d6a4a Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Tue, 23 Nov 2021 13:08:03 +0000 Subject: [PATCH 061/226] added availableTechniques() --- NAMESPACE | 1 + R/parameters.R | 59 ++++++++++++++++++++++++-------------- man/availableTechniques.Rd | 17 +++++++++++ 3 files changed, 55 insertions(+), 22 deletions(-) create mode 100644 man/availableTechniques.Rd diff --git a/NAMESPACE b/NAMESPACE index 204de6c..22451a6 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -14,6 +14,7 @@ export(assignedData) export(assignmentData) export(assignmentParameters) export(assignments) +export(availableTechniques) export(continueAssignment) export(edges) export(isotopeRules) diff --git a/R/parameters.R b/R/parameters.R index 1c154ad..caecf02 100644 --- a/R/parameters.R +++ b/R/parameters.R @@ -362,35 +362,50 @@ setMethod('transformationRules<-',signature = 'AssignmentParameters', return(x) }) +#' Available techniques +#' @description Available techniques for molecular formula assignment. +#' @return A `character` vector of technique names. +#' @examples +#' availableTechniques() +#' @export + +availableTechniques <- function(){ + c('FIE','RP-LC','NP-LC') +} + #' Assignment parameters #' @description Return default assignment parameters for a given technique. -#' @param technique technique to use for assignment. \code{NULL} prints available techniques +#' @param technique technique to use for assignment #' @importFrom parallel detectCores #' @importFrom methods new #' @export -assignmentParameters <- function(technique = NULL){ - availTechniques <- c('FIE','RP-LC','NP-LC') - if (is.null(technique)) { - cat('\nAvailable Techniques:',str_c('\n\t\t\t',str_c(availTechniques,collapse = '\n\t\t\t'),'\n')) - p <- NULL - } else { +assignmentParameters <- function(technique){ + + if (!(technique %in% availableTechniques())) { + techniques <- availableTechniques() %>% + str_c(collapse = ', ') - if (technique == 'FIE') { - p <- new('AssignmentParameters') - } - if (technique == 'RP-LC') { - p <- new('AssignmentParameters', - technique = 'RP-LC', - RTwindow = 1/60 - ) - } - if (technique == 'NP-LC') { - p <- new('AssignmentParameters', - technique = 'NP-LC', - RTwindow = 1/60 - ) - } + stop(str_c('Argument `technique` should be one of ',techniques,'.'),call. = FALSE) + } + + if (technique == 'FIE') { + p <- new('AssignmentParameters') + } + + if (technique == 'RP-LC') { + p <- new('AssignmentParameters', + technique = 'RP-LC', + RTwindow = 1/60 + ) + } + + if (technique == 'NP-LC') { + p <- new('AssignmentParameters', + technique = 'NP-LC', + RTwindow = 1/60 + ) } + return(p) } \ No newline at end of file diff --git a/man/availableTechniques.Rd b/man/availableTechniques.Rd new file mode 100644 index 0000000..8774430 --- /dev/null +++ b/man/availableTechniques.Rd @@ -0,0 +1,17 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/parameters.R +\name{availableTechniques} +\alias{availableTechniques} +\title{Available techniques} +\usage{ +availableTechniques() +} +\value{ +A \code{character} vector of technique names. +} +\description{ +Available techniques for molecular formula assignment. +} +\examples{ +availableTechniques() +} From 89028c77e035d447a136d4e1113f400b44a53916 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Tue, 23 Nov 2021 13:08:16 +0000 Subject: [PATCH 062/226] Updated documentation --- man/assignmentParameters.Rd | 10 ++-- man/parameters.Rd | 100 +++++++++++++++++++++++++++++++++++- 2 files changed, 104 insertions(+), 6 deletions(-) diff --git a/man/assignmentParameters.Rd b/man/assignmentParameters.Rd index f84a9f9..f1fb715 100644 --- a/man/assignmentParameters.Rd +++ b/man/assignmentParameters.Rd @@ -1,14 +1,14 @@ % Generated by roxygen2: do not edit by hand -% Please edit documentation in R/assignmentParameters.R +% Please edit documentation in R/parameters.R \name{assignmentParameters} \alias{assignmentParameters} -\title{annotationParameters} +\title{Assignment parameters} \usage{ -assignmentParameters(technique = NULL) +assignmentParameters(technique) } \arguments{ -\item{technique}{technique to use for assignment. \code{NULL} prints available techniques} +\item{technique}{technique to use for assignment} } \description{ -Return assignment parameters for a specified technique. +Return default assignment parameters for a given technique. } diff --git a/man/parameters.Rd b/man/parameters.Rd index 7e446fc..cf0ea40 100644 --- a/man/parameters.Rd +++ b/man/parameters.Rd @@ -1,6 +1,12 @@ % Generated by roxygen2: do not edit by hand % Please edit documentation in R/parameters.R -\name{isotopes} +\name{technique} +\alias{technique} +\alias{technique,AssignmentParameters-method} +\alias{limit} +\alias{limit,AssignmentParameters-method} +\alias{limit<-} +\alias{limit<-,AssignmentParameters-method} \alias{isotopes} \alias{isotopes,AssignmentParameters-method} \alias{isotopes<-} @@ -9,8 +15,36 @@ \alias{adducts,AssignmentParameters-method} \alias{adducts<-} \alias{adducts<-,AssignmentParameters-method} +\alias{transformations} +\alias{transformations,AssignmentParameters-method} +\alias{transformations<-} +\alias{transformations<-,AssignmentParameters-method} +\alias{adductRules} +\alias{adductRules,AssignmentParameters-method} +\alias{adductRules<-} +\alias{adductRules<-,AssignmentParameters-method} +\alias{isotopeRules} +\alias{isotopeRules,AssignmentParameters-method} +\alias{isotopeRules<-} +\alias{isotopeRules<-,AssignmentParameters-method} +\alias{transformationRules} +\alias{transformationRules,AssignmentParameters-method} +\alias{transformationRules<-} +\alias{transformationRules<-,AssignmentParameters-method} \title{Parameter get and set methods} \usage{ +technique(x) + +\S4method{technique}{AssignmentParameters}(x) + +limit(x) + +\S4method{limit}{AssignmentParameters}(x) + +limit(x) <- value + +\S4method{limit}{AssignmentParameters}(x) <- value + isotopes(x) \S4method{isotopes}{AssignmentParameters}(x) @@ -26,6 +60,38 @@ adducts(x) adducts(x) <- value \S4method{adducts}{AssignmentParameters}(x) <- value + +transformations(x) + +\S4method{transformations}{AssignmentParameters}(x) + +transformations(x) <- value + +\S4method{transformations}{AssignmentParameters}(x) <- value + +adductRules(x) + +\S4method{adductRules}{AssignmentParameters}(x) + +adductRules(x) <- value + +\S4method{adductRules}{AssignmentParameters}(x) <- value + +isotopeRules(x) + +\S4method{isotopeRules}{AssignmentParameters}(x) + +isotopeRules(x) <- value + +\S4method{isotopeRules}{AssignmentParameters}(x) <- value + +transformationRules(x) + +\S4method{transformationRules}{AssignmentParameters}(x) + +transformationRules(x) <- value + +\S4method{transformationRules}{AssignmentParameters}(x) <- value } \arguments{ \item{x}{S4 object of class \code{AssignmentParameters}} @@ -38,6 +104,15 @@ Get and set methods for the \code{AssignmentParameters} S4 class. \examples{ assignment_parameters <- assignmentParameters('FIE') +## Return technique +technique(assignment_parameters) + +## Return limit +limit(assignment_parameters) + +## Set limit +limit(assignment_parameters) <- 0.002 + ## Return isotopes isotopes(assignment_parameters) @@ -50,5 +125,28 @@ adducts(assignment_parameters) ## Set adducts adducts(assignment_parameters) <- list(n = c('[M-H]1-','[M+Cl]1-'), p = c('[M+H]1+','[M+K]1+')) + +## Return transformations +transformations(assignment_parameters) + +## Set transformations +transformations(assignment_parameters) <- "M - [O] + [NH2]" + +## Return adduct rules +adductRules(assignment_parameters) + +## Set adduct rules +adductRules(assignment_parameters) <- mzAnnotation::adduct_rules()) + +## Return isotope rules +isotopeRules(assignment_parameters) + +## Set isotope rules +isotopeRules(assignment_parameters) <- mzAnnotation::isotope_rules()) + +## Return transformation rules +transformationRules(assignment_parameters) +## Set transformation rules +transformationRules(assignment_parameters) <- mzAnnotation::transformation_rules()) } From d0a4a37ac2331918b603a9daf91d28ad323a4497 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Tue, 23 Nov 2021 13:12:10 +0000 Subject: [PATCH 063/226] fixed assignment test --- tests/testthat/test-assignment.R | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/tests/testthat/test-assignment.R b/tests/testthat/test-assignment.R index 1f2c4df..1ea5743 100644 --- a/tests/testthat/test-assignment.R +++ b/tests/testthat/test-assignment.R @@ -1,12 +1,10 @@ context('assignMFs') -p <- assignmentParameters('FIE') +assignment_parameters <- assignmentParameters('FIE') -plan(future::multisession,workers = 2) - -assignment <- assignMFs(peakData, - p, +assignment <- assignMFs(feature_data, + assignment_parameters, verbose = TRUE) test_that('assignMFs works',{ From c2493b5bee230969fd7a8451d0af60849674a378 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Tue, 23 Nov 2021 13:16:10 +0000 Subject: [PATCH 064/226] relationships fixes --- R/relationships.R | 34 +++++++++++++++++----------------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/R/relationships.R b/R/relationships.R index 0df6519..5af56c6 100644 --- a/R/relationships.R +++ b/R/relationships.R @@ -4,11 +4,11 @@ setGeneric("relationships", function(assignment,transformations = TRUE) #' @importFrom furrr future_map #' @importFrom dplyr mutate bind_rows filter vars contains -#' @importFrom dplyr inner_join semi_join select mutate_at -#' @importFrom stringr str_sub str_replace_all +#' @importFrom dplyr inner_join semi_join select mutate_at relocate +#' @importFrom stringr str_sub str_replace_all str_remove #' @importFrom mzAnnotation relationshipCalculator #' @importFrom magrittr %>% -#' @importFrom tibble tibble +#' @importFrom tibble tibble enframe setMethod('relationships',signature = 'Assignment', function(assignment,transformations = T){ @@ -23,7 +23,7 @@ setMethod('relationships',signature = 'Assignment', cors <- assignment@preparedCorrelations if (isTRUE(transformations)) { - trans <- c(NA,parameters@transformations) + trans <- c(NA,transformations(assignment)) } else { trans <- NA } @@ -36,39 +36,39 @@ setMethod('relationships',signature = 'Assignment', mzs <- bind_rows( .x %>% select(contains('1')) %>% - setNames(stringr::str_remove(names(.),'1')), + setNames(str_remove(names(.),'1')), .x %>% select(contains('2')) %>% - setNames(stringr::str_remove(names(.),'2')) + setNames(str_remove(names(.),'2')) ) modes <- mzs$Mode %>% unique() if (length(modes) > 1){ - adducts <- parameters@adducts %>% + specified_adducts <- adducts(assignment) %>% unlist() } else { - adducts <- parameters@adducts[[modes]] + specified_adducts <- adducts(assignment)[[modes]] } relationships <- relationshipCalculator(mzs$`m/z`, - limit = parameters@limit, - adducts = adducts, - isotopes = c(NA,parameters@isotopes), + limit = limit(assignment), + adducts = specified_adducts, + isotopes = c(NA,isotopes(assignment)), transformations = trans, - adductTable = parameters@adductRules, - isotopeTable = parameters@isotopeRules, - transformationTable = parameters@transformationRules) %>% + adduct_rules_table = adductRules(assignment), + isotope_rules_table = isotopeRules(assignment), + transformation_rules_table = transformationRules(assignment)) %>% left_join(mzs,by = c('m/z1' = 'm/z')) %>% rename(Mode1 = Mode) %>% left_join(mzs,by = c('m/z2' = 'm/z')) %>% rename(Mode2 = Mode) %>% - dplyr::relocate(contains('Mode'),.after = `m/z2`) + relocate(contains('Mode'),.after = `m/z2`) if (length(modes) > 1){ - adduct_modes <- parameters@adducts %>% - map(tibble::enframe,value = 'Adduct') %>% + adduct_modes <- adducts(assignment) %>% + map(enframe,value = 'Adduct') %>% bind_rows(.id = 'Mode') %>% select(-name) From 22341992fb339d52f5212d8e9a65477ab723d512 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Tue, 23 Nov 2021 13:38:37 +0000 Subject: [PATCH 065/226] added tests for LC routines --- tests/testthat/test-assignment.R | 37 +++++++++++++++++++++++--------- 1 file changed, 27 insertions(+), 10 deletions(-) diff --git a/tests/testthat/test-assignment.R b/tests/testthat/test-assignment.R index 1ea5743..62c4db9 100644 --- a/tests/testthat/test-assignment.R +++ b/tests/testthat/test-assignment.R @@ -1,18 +1,35 @@ context('assignMFs') -assignment_parameters <- assignmentParameters('FIE') +assignment_parameters_FIE <- assignmentParameters('FIE') +assignment_parameters_LC <- assignmentParameters('RP-LC') -assignment <- assignMFs(feature_data, - assignment_parameters, +LC_features <- feature_data +colnames(LC_features) <- str_c(colnames(LC_features),'@1.00') + +assignment_FIE <- assignMFs(feature_data, + assignment_parameters_FIE, verbose = TRUE) -test_that('assignMFs works',{ - expect_s4_class(assignment,"Assignment") +assignment_LC <- assignMFs(LC_features, + assignment_parameters_LC, + verbose = TRUE) + +test_that('assignment works for FIE technique',{ + expect_s4_class(assignment_FIE,"Assignment") +}) + +test_that('assignment works for LC techniques',{ + expect_s4_class(assignment_LC,"Assignment") +}) + +test_that('Assignment class show method works',{ + expect_output(print(assignment_FIE), + 'Assignment:') }) test_that('feature solutions can be plotted',{ - pl <- plotFeatureSolutions(assignment, + pl <- plotFeatureSolutions(assignment_FIE, 'n191.01962', maxComponents = 2) @@ -20,24 +37,24 @@ test_that('feature solutions can be plotted',{ }) test_that('feature solutions plotting throws an error if an incorrect feature is provided',{ - expect_error(plotFeatureSolutions(assignment, + expect_error(plotFeatureSolutions(assignment_FIE, 'test')) }) test_that('assignment network can be plotted',{ - pl <- plotNetwork(assignment) + pl <- plotNetwork(assignment_FIE) expect_s3_class(pl,'ggraph') }) test_that('adduct distributions can be plotted',{ - pl <- plotAdductDist(assignment) + pl <- plotAdductDist(assignment_FIE) expect_s3_class(pl,'patchwork') }) test_that('assignment spectrum can be plotted',{ - pl <- plotSpectrum(assignment,'C6H8O7') + pl <- plotSpectrum(assignment_FIE,'C6H8O7') expect_s3_class(pl,'ggplot') }) From b9973fd3aac427765c8db828f212823f795d8c5c Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Tue, 23 Nov 2021 13:38:55 +0000 Subject: [PATCH 066/226] added rules tests --- R/parameters.R | 2 +- tests/testthat/test-parameters.R | 33 ++++++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/R/parameters.R b/R/parameters.R index caecf02..8f96751 100644 --- a/R/parameters.R +++ b/R/parameters.R @@ -345,7 +345,7 @@ setGeneric('transformationRules',function(x) setMethod('transformationRules',signature = 'AssignmentParameters', function(x){ - x@isotopeRules + x@transformationRules }) #' @rdname parameters diff --git a/tests/testthat/test-parameters.R b/tests/testthat/test-parameters.R index e61cca2..87fc8b8 100644 --- a/tests/testthat/test-parameters.R +++ b/tests/testthat/test-parameters.R @@ -48,4 +48,37 @@ test_that("transformations can be set", { transformations(p) <- new_transformations expect_identical(transformations(p),new_transformations) +}) + +test_that("adduct rules can be returned", { + expect_s3_class(adductRules(p),'tbl_df') +}) + +test_that("adducts rules can be set", { + new_adduct_rules <- mzAnnotation::adduct_rules()[1,] + adductRules(p) <- new_adduct_rules + + expect_identical(adductRules(p),new_adduct_rules) +}) + +test_that("isotope rules can be returned", { + expect_s3_class(isotopeRules(p),'tbl_df') +}) + +test_that("isotope rules can be set", { + new_isotope_rules <- mzAnnotation::isotope_rules()[1,] + isotopeRules(p) <- new_isotope_rules + + expect_identical(isotopeRules(p),new_isotope_rules) +}) + +test_that("transformation rules can be returned", { + expect_s3_class(transformationRules(p),'tbl_df') +}) + +test_that("transformation rules can be set", { + new_transformation_rules <- mzAnnotation::transformation_rules()[1,] + transformationRules(p) <- new_transformation_rules + + expect_identical(transformationRules(p),new_transformation_rules) }) \ No newline at end of file From e75783822cff8c9417704907fe04f67ab522b59e Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Tue, 23 Nov 2021 13:41:31 +0000 Subject: [PATCH 067/226] moved summariseAssignment() method to assignment file along with its generic --- DESCRIPTION | 1 - R/allGenerics.R | 4 ---- R/assignment.R | 30 ++++++++++++++++++++++++++++++ R/summariseAssignment-method.R | 24 ------------------------ 4 files changed, 30 insertions(+), 29 deletions(-) delete mode 100644 R/summariseAssignment-method.R diff --git a/DESCRIPTION b/DESCRIPTION index c386a6c..4f76407 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -46,7 +46,6 @@ Collate: parameters.R assignment.R allGenerics.R 'MFassign.R' 'FIEassignment.R' 'continueAssignment.R' - 'summariseAssignment-method.R' plotNetwork.R 'addNames.R' 'eliminate.R' diff --git a/R/allGenerics.R b/R/allGenerics.R index 2d0dbb8..ccc492e 100644 --- a/R/allGenerics.R +++ b/R/allGenerics.R @@ -9,7 +9,3 @@ setGeneric('prepCorrelations', function(assignment) setGeneric("transformationAssign", function(assignment) standardGeneric("transformationAssign")) - -#' @rdname summariseAssignment -setGeneric('summariseAssignment',function(assignment) - standardGeneric('summariseAssignment')) diff --git a/R/assignment.R b/R/assignment.R index 3eb564e..bcf4c3b 100644 --- a/R/assignment.R +++ b/R/assignment.R @@ -146,3 +146,33 @@ setMethod('assignedData', signature = 'Assignment', return(d) }) + +#' Summarise assignments +#' @rdname summariseAssignment +#' @description Summarise features assigned to molecular formulas. +#' @param assignment S4 object of class Assignment +#' @importFrom dplyr desc +#' @export + +setGeneric('summariseAssignment',function(assignment) + standardGeneric('summariseAssignment')) + +#' @rdname summariseAssignment + +setMethod('summariseAssignment',signature = 'Assignment', + function(assignment){ + assigned <- assignment %>% + assignments() %>% + split(.$MF) %>% + map(~{ + d <- . + d$Isotope[is.na(d$Isotope)] <- '' + d <- d %>% + mutate(IIP = str_c(Isotope,Adduct,sep = ' ')) %>% + arrange(`Measured m/z`) + tibble(MF = d$MF[1],Features = str_c(d$Feature,collapse = '; '),`Isotopes & Ionisation Products` = str_c(d$IIP,collapse = '; '),Count = nrow(d)) + }) %>% + bind_rows() %>% + arrange(desc(Count)) + return(assigned) + }) \ No newline at end of file diff --git a/R/summariseAssignment-method.R b/R/summariseAssignment-method.R deleted file mode 100644 index 2363339..0000000 --- a/R/summariseAssignment-method.R +++ /dev/null @@ -1,24 +0,0 @@ -#' summariseAssignment-Assignment -#' @rdname summariseAssignment -#' @description Summarise features assigned to moleuclar formulas. -#' @param assignment S4 object of class Assignment -#' @importFrom dplyr desc -#' @export - -setMethod('summariseAssignment',signature = 'Assignment', - function(assignment){ - assigned <- assignment %>% - assignments() %>% - split(.$MF) %>% - map(~{ - d <- . - d$Isotope[is.na(d$Isotope)] <- '' - d <- d %>% - mutate(IIP = str_c(Isotope,Adduct,sep = ' ')) %>% - arrange(`Measured m/z`) - tibble(MF = d$MF[1],Features = str_c(d$Feature,collapse = '; '),`Isotopes & Ionisation Products` = str_c(d$IIP,collapse = '; '),Count = nrow(d)) - }) %>% - bind_rows() %>% - arrange(desc(Count)) - return(assigned) -}) From 3095ed911adde50664a9a18d98bdd80328ee7b42 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Tue, 23 Nov 2021 13:44:34 +0000 Subject: [PATCH 068/226] moved assignMethods() to assignMFs file --- DESCRIPTION | 1 - R/assignMFs.R | 15 +++++++++++++++ R/assignMethods.R | 15 --------------- 3 files changed, 15 insertions(+), 16 deletions(-) delete mode 100644 R/assignMethods.R diff --git a/DESCRIPTION b/DESCRIPTION index 4f76407..d258cd6 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -40,7 +40,6 @@ Collate: parameters.R assignment.R allGenerics.R 'addIsoScore.R' 'addMFs.R' components.R - 'assignMethods.R' feature_data.R 'LCassignment.R' 'MFassign.R' diff --git a/R/assignMFs.R b/R/assignMFs.R index 905ca45..0f6721f 100644 --- a/R/assignMFs.R +++ b/R/assignMFs.R @@ -1,4 +1,19 @@ +assignMethods <- function(method = NULL) { + methods <- list( + FIE = FIEassignment, + `RP-LC` = LCassignment, + `NP-LC` = LCassignment + ) + + if (is.null(method)) { + method <- methods + } else { + method <- methods[[method]] + } + return(method) +} + setGeneric('doAssignment',function(assignment){ standardGeneric('doAssignment') }) diff --git a/R/assignMethods.R b/R/assignMethods.R deleted file mode 100644 index d192ab4..0000000 --- a/R/assignMethods.R +++ /dev/null @@ -1,15 +0,0 @@ - -assignMethods <- function(method = NULL) { - methods <- list( - FIE = FIEassignment, - `RP-LC` = LCassignment, - `NP-LC` = LCassignment - ) - - if (is.null(method)) { - method <- methods - } else { - method <- methods[[method]] - } - return(method) -} \ No newline at end of file From be75ff5bf949556c671ae26badc22a464f76e6ff Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Tue, 23 Nov 2021 13:48:50 +0000 Subject: [PATCH 069/226] update NAMESPACE --- NAMESPACE | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/NAMESPACE b/NAMESPACE index 22451a6..d1d30a7 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -26,12 +26,12 @@ export(plotAdductDist) export(plotFeatureSolutions) export(plotNetwork) export(plotSpectrum) +export(summariseAssignment) export(technique) export(transformationRules) export(transformations) exportClasses(Assignment) exportClasses(AssignmentParameters) -exportMethods(summariseAssignment) importFrom(CHNOSZ,count.elements) importFrom(cli,console_width) importFrom(crayon,blue) From 84330245502ca79680005b1f04898b457e160812 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Tue, 23 Nov 2021 13:49:29 +0000 Subject: [PATCH 070/226] moved continueAssignment() to assign file --- R/continueAssignment.R | 8 -------- man/{assignMFs.Rd => assign.Rd} | 5 ++++- man/continueAssignment.Rd | 14 -------------- 3 files changed, 4 insertions(+), 23 deletions(-) delete mode 100644 R/continueAssignment.R rename man/{assignMFs.Rd => assign.Rd} (87%) delete mode 100644 man/continueAssignment.Rd diff --git a/R/continueAssignment.R b/R/continueAssignment.R deleted file mode 100644 index afeb391..0000000 --- a/R/continueAssignment.R +++ /dev/null @@ -1,8 +0,0 @@ -#' continueAssignment -#' @description continue a failed assignment -#' @param assignment an S4 object of class Assignment -#' @export - -continueAssignment <- function(assignment){ - doAssignment(assignment) -} \ No newline at end of file diff --git a/man/assignMFs.Rd b/man/assign.Rd similarity index 87% rename from man/assignMFs.Rd rename to man/assign.Rd index 61edc99..2bc989a 100644 --- a/man/assignMFs.Rd +++ b/man/assign.Rd @@ -2,9 +2,12 @@ % Please edit documentation in R/assignMFs.R \name{assignMFs} \alias{assignMFs} -\title{assignMFs} +\alias{continueAssignment} +\title{Assign molecular formulas} \usage{ assignMFs(dat, parameters, verbose = TRUE) + +continueAssignment(assignment) } \arguments{ \item{dat}{tibble containing the peak intensities of m/z for which to assign molecular formulas} diff --git a/man/continueAssignment.Rd b/man/continueAssignment.Rd deleted file mode 100644 index d46928c..0000000 --- a/man/continueAssignment.Rd +++ /dev/null @@ -1,14 +0,0 @@ -% Generated by roxygen2: do not edit by hand -% Please edit documentation in R/continueAssignment.R -\name{continueAssignment} -\alias{continueAssignment} -\title{continueAssignment} -\usage{ -continueAssignment(assignment) -} -\arguments{ -\item{assignment}{an S4 object of class Assignment} -} -\description{ -continue a failed assignment -} From 093b2dd1b9aad8e0038f4e9f2c2d68a585b671c4 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Tue, 23 Nov 2021 13:49:57 +0000 Subject: [PATCH 071/226] renamed assignMFs file --- R/{assignMFs.R => assign.R} | 22 ++++++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) rename R/{assignMFs.R => assign.R} (87%) diff --git a/R/assignMFs.R b/R/assign.R similarity index 87% rename from R/assignMFs.R rename to R/assign.R index 0f6721f..3fbddf9 100644 --- a/R/assignMFs.R +++ b/R/assign.R @@ -14,9 +14,9 @@ assignMethods <- function(method = NULL) { return(method) } -setGeneric('doAssignment',function(assignment){ +setGeneric('doAssignment',function(assignment) standardGeneric('doAssignment') -}) +) setMethod('doAssignment',signature = 'Assignment', function(assignment){ @@ -36,7 +36,8 @@ setMethod('doAssignment',signature = 'Assignment', return(assignment) }) -#' assignMFs +#' Assign molecular formulas +#' @rdname assign #' @description assign molecular formulas to a set of given m/z. #' @param dat tibble containing the peak intensities of m/z for which to assign molecular formulas #' @param parameters an S4 object of class AssignmentParamters containing the parameters for molecular formula assignment @@ -94,4 +95,17 @@ assignMFs <- function(dat,parameters,verbose = TRUE) { } return(assignment) -} \ No newline at end of file +} + +#' @rdname assign +#' @export + +setGeneric('continueAssignment',function(assignment) + standardGeneric('continueAssignment') +) + + +setMethod('continueAssignment',signature = 'Assignment', + function(assignment){ + doAssignment(assignment) + }) \ No newline at end of file From 5fbace7cfcc4592a8f6c9a5aafcbfcc9ce23538b Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Tue, 23 Nov 2021 13:50:10 +0000 Subject: [PATCH 072/226] Updated documentation --- man/summariseAssignment.Rd | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/man/summariseAssignment.Rd b/man/summariseAssignment.Rd index 43dd149..774eb01 100644 --- a/man/summariseAssignment.Rd +++ b/man/summariseAssignment.Rd @@ -1,9 +1,9 @@ % Generated by roxygen2: do not edit by hand -% Please edit documentation in R/allGenerics.R, R/summariseAssignment-method.R +% Please edit documentation in R/assignment.R \name{summariseAssignment} \alias{summariseAssignment} \alias{summariseAssignment,Assignment-method} -\title{summariseAssignment-Assignment} +\title{Summarise assignments} \usage{ summariseAssignment(assignment) @@ -13,5 +13,5 @@ summariseAssignment(assignment) \item{assignment}{S4 object of class Assignment} } \description{ -Summarise features assigned to moleuclar formulas. +Summarise features assigned to molecular formulas. } From 0c3fee1816dd0fd9cbdc1e8c6af1d23c49632bcb Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Tue, 23 Nov 2021 13:50:49 +0000 Subject: [PATCH 073/226] moved miscellaneous functions to internals file --- DESCRIPTION | 7 +--- R/addIsoScore.R | 22 ----------- R/addMFs.R | 51 ------------------------ R/addNames.R | 13 ------ R/eliminate.R | 15 ------- R/internals.R | 103 ++++++++++++++++++++++++++++++++++++++++++++++++ 6 files changed, 104 insertions(+), 107 deletions(-) delete mode 100644 R/addIsoScore.R delete mode 100644 R/addMFs.R delete mode 100644 R/addNames.R delete mode 100644 R/eliminate.R create mode 100644 R/internals.R diff --git a/DESCRIPTION b/DESCRIPTION index d258cd6..4e02cea 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -35,19 +35,14 @@ RoxygenNote: 7.1.2 Collate: parameters.R assignment.R allGenerics.R prepCorrelations-method.R addIsoAssign.R transformationAssign-method.R relationships.R - graph.R assignMFs.R MFgen.R + graph.R assignMFs.R MFgen.R internals.R 'MFscore.R' - 'addIsoScore.R' - 'addMFs.R' components.R feature_data.R 'LCassignment.R' 'MFassign.R' 'FIEassignment.R' - 'continueAssignment.R' plotNetwork.R - 'addNames.R' - 'eliminate.R' plotAdductDist.R plotFeatureSolutions.R 'calcCorrelations-method.R' diff --git a/R/addIsoScore.R b/R/addIsoScore.R deleted file mode 100644 index 2719ab9..0000000 --- a/R/addIsoScore.R +++ /dev/null @@ -1,22 +0,0 @@ -#' @importFrom purrr map_lgl - -addIsoScore <- function(add,iso,addRank,isoRank){ - add <- tibble(Adduct = add) - iso <- tibble(Isotope = iso) - iso$Isotope[is.na(iso$Isotope)] <- 'NA' - addRank <- addRank[map_lgl(addRank,~{add %in% .})] %>% - .[[1]] %>% - {tibble(Adduct = ., - Rank = (length(.) - 1):0)} - isoRank <- tibble(Isotope = c('NA',isoRank), Rank = length(isoRank):0) - - add <- left_join(add, addRank,by = 'Adduct') %>% - .$Rank - iso <- left_join(iso, isoRank,by = 'Isotope') %>% - .$Rank - - maxScore <- max(addRank$Rank) + max(isoRank$Rank) - score <- (add + iso)/maxScore - - return(score) -} diff --git a/R/addMFs.R b/R/addMFs.R deleted file mode 100644 index e810a70..0000000 --- a/R/addMFs.R +++ /dev/null @@ -1,51 +0,0 @@ -#' @importFrom dplyr rename - -addMFs <- function(rel,MF,identMF = T){ - - if (identMF == T) { - relations <- rel %>% - filter(Feature1 %in% MF$Feature, Feature2 %in% MF$Feature) - } else { - relations <- rel %>% - filter(Feature1 %in% MF$Feature | Feature2 %in% MF$Feature) - } - relations <- relations %>% - left_join(MF %>% - select(Feature,MF,Isotope,Adduct,`Measured m/z`),by = c('Feature1' = 'Feature')) %>% - rename(MF1 = MF) - - chr_columns <- relations %>% - map_lgl(is.character) - - relations[,chr_columns] <- relations[,chr_columns] %>% - { - .[is.na(.)] <- '' - . - } - - relations <- relations %>% - filter(Isotope1 == Isotope & Adduct1 == Adduct) %>% - select(-(Isotope:`Measured m/z`)) %>% - left_join(MF %>% - select(Feature,MF,Isotope,Adduct,`Measured m/z`),by = c('Feature2' = 'Feature')) %>% - rename(MF2 = MF) - - chr_columns <- relations %>% - map_lgl(is.character) - - relations[,chr_columns] <- relations[,chr_columns] %>% - { - .[is.na(.)] <- '' - . - } - - relations <- relations %>% - filter(Isotope2 == Isotope & Adduct2 == Adduct) %>% - select(-(Isotope:`Measured m/z`)) - - if (nrow(relations) > 0) { - relations[relations == ''] <- NA - } - - return(relations) -} \ No newline at end of file diff --git a/R/addNames.R b/R/addNames.R deleted file mode 100644 index 63a76dd..0000000 --- a/R/addNames.R +++ /dev/null @@ -1,13 +0,0 @@ - -addNames <- function(rel){ - iso <- rel - iso$Isotope1[is.na(iso$Isotope1)] <- '' - iso$Isotope2[is.na(iso$Isotope2)] <- '' - iso <- iso %>% - mutate(Name1 = str_c(Feature1,MF1,Isotope1,Adduct1,sep = ' '), - Name2 = str_c(Feature2,MF2,Isotope2,Adduct2,sep = ' ')) - rel %>% - bind_cols(iso %>% - select(Name1,Name2)) %>% - select(Name1,Name2,Feature1:MF2) -} \ No newline at end of file diff --git a/R/eliminate.R b/R/eliminate.R deleted file mode 100644 index 69520e8..0000000 --- a/R/eliminate.R +++ /dev/null @@ -1,15 +0,0 @@ -#' @importFrom dplyr bind_cols - -eliminate <- function(MFs,by,direction){ - MFs %>% - bind_cols(MFs %>% select(by = by)) %>% - split(.$Feature) %>% - map(~{ - d <- . - direct <- get(direction) - d %>% - filter(by == direct(by)) - }) %>% - bind_rows() %>% - select(-by) -} \ No newline at end of file diff --git a/R/internals.R b/R/internals.R new file mode 100644 index 0000000..5f0de4f --- /dev/null +++ b/R/internals.R @@ -0,0 +1,103 @@ +#' @importFrom purrr map_lgl + +addIsoScore <- function(add,iso,addRank,isoRank){ + add <- tibble(Adduct = add) + iso <- tibble(Isotope = iso) + iso$Isotope[is.na(iso$Isotope)] <- 'NA' + addRank <- addRank[map_lgl(addRank,~{add %in% .})] %>% + .[[1]] %>% + {tibble(Adduct = ., + Rank = (length(.) - 1):0)} + isoRank <- tibble(Isotope = c('NA',isoRank), Rank = length(isoRank):0) + + add <- left_join(add, addRank,by = 'Adduct') %>% + .$Rank + iso <- left_join(iso, isoRank,by = 'Isotope') %>% + .$Rank + + maxScore <- max(addRank$Rank) + max(isoRank$Rank) + score <- (add + iso)/maxScore + + return(score) +} + +#' @importFrom dplyr bind_cols + +eliminate <- function(MFs,by,direction){ + MFs %>% + bind_cols(MFs %>% select(by = by)) %>% + split(.$Feature) %>% + map(~{ + d <- . + direct <- get(direction) + d %>% + filter(by == direct(by)) + }) %>% + bind_rows() %>% + select(-by) +} + +#' @importFrom dplyr rename + +addMFs <- function(rel,MF,identMF = T){ + + if (identMF == T) { + relations <- rel %>% + filter(Feature1 %in% MF$Feature, Feature2 %in% MF$Feature) + } else { + relations <- rel %>% + filter(Feature1 %in% MF$Feature | Feature2 %in% MF$Feature) + } + relations <- relations %>% + left_join(MF %>% + select(Feature,MF,Isotope,Adduct,`Measured m/z`),by = c('Feature1' = 'Feature')) %>% + rename(MF1 = MF) + + chr_columns <- relations %>% + map_lgl(is.character) + + relations[,chr_columns] <- relations[,chr_columns] %>% + { + .[is.na(.)] <- '' + . + } + + relations <- relations %>% + filter(Isotope1 == Isotope & Adduct1 == Adduct) %>% + select(-(Isotope:`Measured m/z`)) %>% + left_join(MF %>% + select(Feature,MF,Isotope,Adduct,`Measured m/z`),by = c('Feature2' = 'Feature')) %>% + rename(MF2 = MF) + + chr_columns <- relations %>% + map_lgl(is.character) + + relations[,chr_columns] <- relations[,chr_columns] %>% + { + .[is.na(.)] <- '' + . + } + + relations <- relations %>% + filter(Isotope2 == Isotope & Adduct2 == Adduct) %>% + select(-(Isotope:`Measured m/z`)) + + if (nrow(relations) > 0) { + relations[relations == ''] <- NA + } + + return(relations) +} + +addNames <- function(rel){ + iso <- rel + iso$Isotope1[is.na(iso$Isotope1)] <- '' + iso$Isotope2[is.na(iso$Isotope2)] <- '' + iso <- iso %>% + mutate(Name1 = str_c(Feature1,MF1,Isotope1,Adduct1,sep = ' '), + Name2 = str_c(Feature2,MF2,Isotope2,Adduct2,sep = ' ')) + rel %>% + bind_cols(iso %>% + select(Name1,Name2)) %>% + select(Name1,Name2,Feature1:MF2) +} \ No newline at end of file From 61907d13ecb6645a5bcf9d1d6e2f7d665a9d8cff Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Tue, 23 Nov 2021 13:55:04 +0000 Subject: [PATCH 074/226] moved correlations methods to correlations file --- DESCRIPTION | 6 +- R/allGenerics.R | 8 -- R/calcCorrelations-method.R | 71 ------------- R/correlations.R | 189 ++++++++++++++++++++++++++++++++++ R/filterCorrelations-method.R | 57 ---------- R/prepCorrelations-method.R | 50 --------- man/assign.Rd | 2 +- 7 files changed, 192 insertions(+), 191 deletions(-) delete mode 100644 R/calcCorrelations-method.R create mode 100644 R/correlations.R delete mode 100644 R/filterCorrelations-method.R delete mode 100644 R/prepCorrelations-method.R diff --git a/DESCRIPTION b/DESCRIPTION index 4e02cea..730a0fb 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -33,9 +33,9 @@ LazyData: true Roxygen: list(markdown = TRUE) RoxygenNote: 7.1.2 Collate: parameters.R assignment.R allGenerics.R - prepCorrelations-method.R addIsoAssign.R + correlations.R addIsoAssign.R transformationAssign-method.R relationships.R - graph.R assignMFs.R MFgen.R internals.R + graph.R assign.R MFgen.R internals.R 'MFscore.R' components.R feature_data.R @@ -45,8 +45,6 @@ Collate: parameters.R assignment.R allGenerics.R plotNetwork.R plotAdductDist.R plotFeatureSolutions.R - 'calcCorrelations-method.R' - 'filterCorrelations-method.R' plotSpectrum.R reexports.R Suggests: testthat, diff --git a/R/allGenerics.R b/R/allGenerics.R index ccc492e..707ada4 100644 --- a/R/allGenerics.R +++ b/R/allGenerics.R @@ -1,11 +1,3 @@ -setGeneric('calcCorrelations', function(assignment) - standardGeneric('calcCorrelations')) - -setGeneric('filterCorrelations', function(assignment) - standardGeneric('filterCorrelations')) - -setGeneric('prepCorrelations', function(assignment) - standardGeneric('prepCorrelations')) setGeneric("transformationAssign", function(assignment) standardGeneric("transformationAssign")) diff --git a/R/calcCorrelations-method.R b/R/calcCorrelations-method.R deleted file mode 100644 index 1218f97..0000000 --- a/R/calcCorrelations-method.R +++ /dev/null @@ -1,71 +0,0 @@ -#' @importFrom metabolyseR analysisParameters metabolyse analysisResults keepFeatures analysisData dat sinfo -#' @importFrom magrittr set_rownames -#' @importFrom stats cutree dist hclust - -setMethod('calcCorrelations',signature = 'Assignment',function(assignment){ - if (assignment@log$verbose == T) { - startTime <- proc.time() - message(blue('Calculating correlations '),cli::symbol$continue,'\r',appendLF = FALSE) - } - - p <- analysisParameters('correlations') - parameters <- as(assignment,'AssignmentParameters') - - p@correlations <- parameters@correlations_parameters - - if (str_detect(parameters@technique,'LC')) { - feat <- tibble(Feature = colnames(assignment@data)) %>% - mutate(RT = str_split_fixed(Feature,'@',2)[,2] %>% - as.numeric()) - RTgroups <- feat %>% - data.frame() %>% - set_rownames(.$Feature) %>% - select(-Feature) %>% - dist() %>% - hclust() %>% - cutree(h = parameters@RTwindow) %>% - {tibble(Feature = names(.),Group = .)} - - RTsum <- RTgroups %>% - group_by(Group) %>% - summarise(N = n()) - - RTgroups <- RTgroups %>% - filter(Group %in% {RTsum %>% - filter(N > 1) %>% - .$Group}) - - cors <- RTgroups %>% - split(.$Group) %>% - future_map(~{ - analysisData(assignment@data,tibble(ID = 1:nrow(assignment@data))) %>% - keepFeatures(features = .x$Feature) %>% - {metabolyse(dat(.),sinfo(.),p,verbose = FALSE)} %>% - analysisResults(element = 'correlations') - }) %>% - bind_rows(.id = 'RT Group') - - } else { - cors <- metabolyse(assignment@data, - tibble(ID = 1:nrow(assignment@data)), - p, - verbose = FALSE) %>% - analysisResults(element = 'correlations') - } - - assignment@correlations <- cors - - if (assignment@log$verbose == T) { - endTime <- proc.time() - elapsed <- {endTime - startTime} %>% - .[3] %>% - round(1) %>% - seconds_to_period() %>% - str_c('[',.,']') - ncors <- nrow(assignment@correlations) %>% - str_c('[',.,' correlations',']') - message(blue('Calculating correlations '),'\t',green(cli::symbol$tick),' ',ncors,' ',elapsed) - } - - return(assignment) -}) \ No newline at end of file diff --git a/R/correlations.R b/R/correlations.R new file mode 100644 index 0000000..b34bd39 --- /dev/null +++ b/R/correlations.R @@ -0,0 +1,189 @@ + +setGeneric('calcCorrelations', function(assignment) + standardGeneric('calcCorrelations')) + +#' @importFrom metabolyseR analysisParameters metabolyse analysisResults keepFeatures analysisData dat sinfo +#' @importFrom magrittr set_rownames +#' @importFrom stats cutree dist hclust + +setMethod('calcCorrelations',signature = 'Assignment',function(assignment){ + if (assignment@log$verbose == T) { + startTime <- proc.time() + message(blue('Calculating correlations '),cli::symbol$continue,'\r',appendLF = FALSE) + } + + p <- analysisParameters('correlations') + parameters <- as(assignment,'AssignmentParameters') + + p@correlations <- parameters@correlations_parameters + + if (str_detect(parameters@technique,'LC')) { + feat <- tibble(Feature = colnames(assignment@data)) %>% + mutate(RT = str_split_fixed(Feature,'@',2)[,2] %>% + as.numeric()) + RTgroups <- feat %>% + data.frame() %>% + set_rownames(.$Feature) %>% + select(-Feature) %>% + dist() %>% + hclust() %>% + cutree(h = parameters@RTwindow) %>% + {tibble(Feature = names(.),Group = .)} + + RTsum <- RTgroups %>% + group_by(Group) %>% + summarise(N = n()) + + RTgroups <- RTgroups %>% + filter(Group %in% {RTsum %>% + filter(N > 1) %>% + .$Group}) + + cors <- RTgroups %>% + split(.$Group) %>% + future_map(~{ + analysisData(assignment@data,tibble(ID = 1:nrow(assignment@data))) %>% + keepFeatures(features = .x$Feature) %>% + {metabolyse(dat(.),sinfo(.),p,verbose = FALSE)} %>% + analysisResults(element = 'correlations') + }) %>% + bind_rows(.id = 'RT Group') + + } else { + cors <- metabolyse(assignment@data, + tibble(ID = 1:nrow(assignment@data)), + p, + verbose = FALSE) %>% + analysisResults(element = 'correlations') + } + + assignment@correlations <- cors + + if (assignment@log$verbose == T) { + endTime <- proc.time() + elapsed <- {endTime - startTime} %>% + .[3] %>% + round(1) %>% + seconds_to_period() %>% + str_c('[',.,']') + ncors <- nrow(assignment@correlations) %>% + str_c('[',.,' correlations',']') + message(blue('Calculating correlations '),'\t',green(cli::symbol$tick),' ',ncors,' ',elapsed) + } + + return(assignment) +}) + + +filterCors <- function(correlations, rthresh = 0.7, n = 100000, rIncrement = 0.01, nIncrement = 20000){ + filCors <- function(cors,rthresh,n){ + while (nrow(cors) > n) { + cors <- correlations %>% + filter(r > rthresh | r < -rthresh) + rthresh <- rthresh + rIncrement + } + return(cors) + } + + while (TRUE) { + cors <- filCors(correlations,rthresh,n) + if (nrow(cors) > 0) { + break() + } else { + n <- n + nIncrement + } + } + return(cors) +} + +setGeneric('prepCorrelations', function(assignment) + standardGeneric('prepCorrelations')) + +setMethod('prepCorrelations',signature = 'Assignment', + function(assignment){ + + if (assignment@log$verbose == T) { + startTime <- proc.time() + message(blue('Preparing correlations '),cli::symbol$continue,'\r',appendLF = FALSE) + } + + correlations <- assignment@preparedCorrelations + + correlations <- correlations %>% + mutate(Mode1 = str_split_fixed(Feature1,'@',2) %>% + .[,1] %>% + str_sub(1,1), + Mode2 = str_split_fixed(Feature2,'@',2) %>% + .[,1] %>% + str_sub(1,1), + `m/z1` = str_split_fixed(Feature1,'@',2) %>% + .[,1] %>% + str_replace_all('[:alpha:]','') %>% + as.numeric(), + `m/z2` = str_split_fixed(Feature2,'@',2) %>% + .[,1] %>% + str_replace_all('[:alpha:]','') %>% + as.numeric(), + RetentionTime1 = str_split_fixed(Feature1,'@',2) %>% + .[,2] %>% + as.numeric(), + RetentionTime2 = str_split_fixed(Feature2,'@',2) %>% + .[,2] %>% + as.numeric(), + ID = 1:nrow(.) + ) %>% + select(Feature1,Feature2,Mode1:RetentionTime2,log2IntensityRatio,r,ID) + + assignment@preparedCorrelations <- correlations + + if (assignment@log$verbose == T) { + endTime <- proc.time() + elapsed <- {endTime - startTime} %>% + .[3] %>% + round(1) %>% + seconds_to_period() %>% + str_c('[',.,']') + message(blue('Preparing correlations '),'\t\t',green(cli::symbol$tick),' ',elapsed) + } + + return(assignment) + }) + +setGeneric('filterCorrelations', function(assignment) + standardGeneric('filterCorrelations')) + +setMethod('filterCorrelations',signature = 'Assignment',function(assignment){ + if (assignment@log$verbose == T) { + startTime <- proc.time() + message(blue('Filtering correlations '),cli::symbol$continue,'\r',appendLF = FALSE) + } + + parameters <- as(assignment,'AssignmentParameters') + + if (str_detect(parameters@technique,'LC')) { + cors <- assignment@correlations %>% + filter(r < -(parameters@filter$rthresh) | r > parameters@filter$rthresh) + } else { + cors <- assignment@correlations %>% + filterCors(rthresh = parameters@filter$rthresh, + n = parameters@filter$n, + rIncrement = parameters@filter$rIncrement, + nIncrement = parameters@filter$nIncrement + ) + } + + assignment@preparedCorrelations <- cors + + if (assignment@log$verbose == T) { + endTime <- proc.time() + elapsed <- {endTime - startTime} %>% + .[3] %>% + round(1) %>% + seconds_to_period() %>% + str_c('[',.,']') + ncors <- nrow(assignment@preparedCorrelations) %>% + str_c('[',.,' correlations',']') + message(blue('Filtering correlations '),'\t\t',green(cli::symbol$tick),' ',ncors,' ',elapsed) + } + return(assignment) +}) \ No newline at end of file diff --git a/R/filterCorrelations-method.R b/R/filterCorrelations-method.R deleted file mode 100644 index 5f8ea77..0000000 --- a/R/filterCorrelations-method.R +++ /dev/null @@ -1,57 +0,0 @@ - -filterCors <- function(correlations, rthresh = 0.7, n = 100000, rIncrement = 0.01, nIncrement = 20000){ - filCors <- function(cors,rthresh,n){ - while (nrow(cors) > n) { - cors <- correlations %>% - filter(r > rthresh | r < -rthresh) - rthresh <- rthresh + rIncrement - } - return(cors) - } - - while (TRUE) { - cors <- filCors(correlations,rthresh,n) - if (nrow(cors) > 0) { - break() - } else { - n <- n + nIncrement - } - } - return(cors) -} - -setMethod('filterCorrelations',signature = 'Assignment',function(assignment){ - if (assignment@log$verbose == T) { - startTime <- proc.time() - message(blue('Filtering correlations '),cli::symbol$continue,'\r',appendLF = FALSE) - } - - parameters <- as(assignment,'AssignmentParameters') - - if (str_detect(parameters@technique,'LC')) { - cors <- assignment@correlations %>% - filter(r < -(parameters@filter$rthresh) | r > parameters@filter$rthresh) - } else { - cors <- assignment@correlations %>% - filterCors(rthresh = parameters@filter$rthresh, - n = parameters@filter$n, - rIncrement = parameters@filter$rIncrement, - nIncrement = parameters@filter$nIncrement - ) - } - - assignment@preparedCorrelations <- cors - - if (assignment@log$verbose == T) { - endTime <- proc.time() - elapsed <- {endTime - startTime} %>% - .[3] %>% - round(1) %>% - seconds_to_period() %>% - str_c('[',.,']') - ncors <- nrow(assignment@preparedCorrelations) %>% - str_c('[',.,' correlations',']') - message(blue('Filtering correlations '),'\t\t',green(cli::symbol$tick),' ',ncors,' ',elapsed) - } - return(assignment) -}) \ No newline at end of file diff --git a/R/prepCorrelations-method.R b/R/prepCorrelations-method.R deleted file mode 100644 index e256345..0000000 --- a/R/prepCorrelations-method.R +++ /dev/null @@ -1,50 +0,0 @@ - -setMethod('prepCorrelations',signature = 'Assignment', - function(assignment){ - - if (assignment@log$verbose == T) { - startTime <- proc.time() - message(blue('Preparing correlations '),cli::symbol$continue,'\r',appendLF = FALSE) - } - - correlations <- assignment@preparedCorrelations - - correlations <- correlations %>% - mutate(Mode1 = str_split_fixed(Feature1,'@',2) %>% - .[,1] %>% - str_sub(1,1), - Mode2 = str_split_fixed(Feature2,'@',2) %>% - .[,1] %>% - str_sub(1,1), - `m/z1` = str_split_fixed(Feature1,'@',2) %>% - .[,1] %>% - str_replace_all('[:alpha:]','') %>% - as.numeric(), - `m/z2` = str_split_fixed(Feature2,'@',2) %>% - .[,1] %>% - str_replace_all('[:alpha:]','') %>% - as.numeric(), - RetentionTime1 = str_split_fixed(Feature1,'@',2) %>% - .[,2] %>% - as.numeric(), - RetentionTime2 = str_split_fixed(Feature2,'@',2) %>% - .[,2] %>% - as.numeric(), - ID = 1:nrow(.) - ) %>% - select(Feature1,Feature2,Mode1:RetentionTime2,log2IntensityRatio,r,ID) - - assignment@preparedCorrelations <- correlations - - if (assignment@log$verbose == T) { - endTime <- proc.time() - elapsed <- {endTime - startTime} %>% - .[3] %>% - round(1) %>% - seconds_to_period() %>% - str_c('[',.,']') - message(blue('Preparing correlations '),'\t\t',green(cli::symbol$tick),' ',elapsed) - } - - return(assignment) - }) \ No newline at end of file diff --git a/man/assign.Rd b/man/assign.Rd index 2bc989a..e745b8e 100644 --- a/man/assign.Rd +++ b/man/assign.Rd @@ -1,5 +1,5 @@ % Generated by roxygen2: do not edit by hand -% Please edit documentation in R/assignMFs.R +% Please edit documentation in R/assign.R \name{assignMFs} \alias{assignMFs} \alias{continueAssignment} From 50e4976bc4a08ac9e4b1f24f6beaf3f880eab043 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Tue, 23 Nov 2021 14:06:51 +0000 Subject: [PATCH 075/226] moved transformationAssign() generic alongside its method --- DESCRIPTION | 5 ++--- R/allGenerics.R | 3 --- R/{transformationAssign-method.R => transformationAssign.R} | 4 ++++ 3 files changed, 6 insertions(+), 6 deletions(-) delete mode 100644 R/allGenerics.R rename R/{transformationAssign-method.R => transformationAssign.R} (98%) diff --git a/DESCRIPTION b/DESCRIPTION index 730a0fb..7412036 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -32,9 +32,8 @@ Encoding: UTF-8 LazyData: true Roxygen: list(markdown = TRUE) RoxygenNote: 7.1.2 -Collate: parameters.R assignment.R allGenerics.R - correlations.R addIsoAssign.R - transformationAssign-method.R relationships.R +Collate: parameters.R assignment.R correlations.R + addIsoAssign.R transformationAssign.R relationships.R graph.R assign.R MFgen.R internals.R 'MFscore.R' components.R diff --git a/R/allGenerics.R b/R/allGenerics.R deleted file mode 100644 index 707ada4..0000000 --- a/R/allGenerics.R +++ /dev/null @@ -1,3 +0,0 @@ - -setGeneric("transformationAssign", function(assignment) - standardGeneric("transformationAssign")) diff --git a/R/transformationAssign-method.R b/R/transformationAssign.R similarity index 98% rename from R/transformationAssign-method.R rename to R/transformationAssign.R index 04bb565..14fc807 100644 --- a/R/transformationAssign-method.R +++ b/R/transformationAssign.R @@ -1,4 +1,8 @@ #' @importFrom stringr str_c + +setGeneric("transformationAssign", function(assignment) + standardGeneric("transformationAssign")) + #' @importFrom dplyr full_join select distinct #' @importFrom mzAnnotation transformMF From 6b2b57068254f88885c120cfa6de8f6f8b7a4cd8 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Tue, 23 Nov 2021 14:40:51 +0000 Subject: [PATCH 076/226] renamed relationships method --- DESCRIPTION | 15 ++++----------- R/FIEassignment.R | 2 +- R/LCassignment.R | 2 +- R/assignment.R | 30 ++++++++++++++++++++++++++---- 4 files changed, 32 insertions(+), 17 deletions(-) diff --git a/DESCRIPTION b/DESCRIPTION index 7412036..f87e7ce 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -35,17 +35,10 @@ RoxygenNote: 7.1.2 Collate: parameters.R assignment.R correlations.R addIsoAssign.R transformationAssign.R relationships.R graph.R assign.R MFgen.R internals.R - 'MFscore.R' - components.R - feature_data.R - 'LCassignment.R' - 'MFassign.R' - 'FIEassignment.R' - plotNetwork.R - plotAdductDist.R - plotFeatureSolutions.R - plotSpectrum.R - reexports.R + MFscore.R components.R + feature_data.R LCassignment.R MFassign.R + FIEassignment.R plotNetwork.R plotAdductDist.R + plotFeatureSolutions.R plotSpectrum.R reexports.R Suggests: testthat, covr Remotes: jasenfinch/mzAnnotation@tmp, diff --git a/R/FIEassignment.R b/R/FIEassignment.R index f2e36da..29efc86 100644 --- a/R/FIEassignment.R +++ b/R/FIEassignment.R @@ -15,7 +15,7 @@ FIEassignment <- function(element = NULL) { }, relationships = function(assignment){ assignment %>% - relationships() + calcRelationships() }, `adduct and isotope assignment` = function(assignment){ assignment %>% diff --git a/R/LCassignment.R b/R/LCassignment.R index e9a5309..303cdd4 100644 --- a/R/LCassignment.R +++ b/R/LCassignment.R @@ -15,7 +15,7 @@ LCassignment <- function(element = NULL){ }, relationships = function(assignment){ assignment %>% - relationships(transformations = FALSE) + calcRelationships(transformations = FALSE) }, `adduct and isotope assignment` = function(assignment){ assignment %>% diff --git a/R/assignment.R b/R/assignment.R index bcf4c3b..3262956 100644 --- a/R/assignment.R +++ b/R/assignment.R @@ -79,16 +79,38 @@ setMethod('show',signature = 'Assignment', } ) -#' assignments-Assignment -#' @rdname assignments -#' @description Get table of assigned features from an Assignment +#' Assignment accessors +#' @rdname accessors +#' @description Access methods for Assignment S4 class #' @param assignment S4 object of class Assignment #' @export +setGeneric('relationships',function(assignment) + standardGeneric('relationships')) + +#' @rdname accessors + +setMethod('relationships',signature = 'Assignment', + function(assignment){ + assignment@relationships + }) + +setGeneric('relationships<-',function(assignment,value) + standardGeneric('relationships<-')) + +setMethod('relationships<-',signature = 'Assignment', + function(assignment,value){ + assignment@relationships <- value + return(assignment) + }) + +#' @rdname accessors +#' @export + setGeneric('assignments',function(assignment) standardGeneric('assignments')) -#' @rdname assignments +#' @rdname accessors setMethod('assignments',signature = 'Assignment', function(assignment){ From 0c5d1d1493eef0b56b64d2c2255bfa09ea3119a6 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Tue, 23 Nov 2021 14:41:20 +0000 Subject: [PATCH 077/226] added relationships accessor method --- NAMESPACE | 1 + R/relationships.R | 6 +++--- man/{assignments.Rd => accessors.Rd} | 12 +++++++++--- 3 files changed, 13 insertions(+), 6 deletions(-) rename man/{assignments.Rd => accessors.Rd} (57%) diff --git a/NAMESPACE b/NAMESPACE index d1d30a7..4d89659 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -26,6 +26,7 @@ export(plotAdductDist) export(plotFeatureSolutions) export(plotNetwork) export(plotSpectrum) +export(relationships) export(summariseAssignment) export(technique) export(transformationRules) diff --git a/R/relationships.R b/R/relationships.R index 5af56c6..a669526 100644 --- a/R/relationships.R +++ b/R/relationships.R @@ -1,6 +1,6 @@ -setGeneric("relationships", function(assignment,transformations = TRUE) - standardGeneric("relationships")) +setGeneric("calcRelationships", function(assignment,transformations = TRUE) + standardGeneric("calcRelationships")) #' @importFrom furrr future_map #' @importFrom dplyr mutate bind_rows filter vars contains @@ -10,7 +10,7 @@ setGeneric("relationships", function(assignment,transformations = TRUE) #' @importFrom magrittr %>% #' @importFrom tibble tibble enframe -setMethod('relationships',signature = 'Assignment', +setMethod('calcRelationships',signature = 'Assignment', function(assignment,transformations = T){ if (assignment@log$verbose == T) { diff --git a/man/assignments.Rd b/man/accessors.Rd similarity index 57% rename from man/assignments.Rd rename to man/accessors.Rd index 34b6986..aaf76d7 100644 --- a/man/assignments.Rd +++ b/man/accessors.Rd @@ -1,10 +1,16 @@ % Generated by roxygen2: do not edit by hand % Please edit documentation in R/assignment.R -\name{assignments} +\name{relationships} +\alias{relationships} +\alias{relationships,Assignment-method} \alias{assignments} \alias{assignments,Assignment-method} -\title{assignments-Assignment} +\title{Assignment accessors} \usage{ +relationships(assignment) + +\S4method{relationships}{Assignment}(assignment) + assignments(assignment) \S4method{assignments}{Assignment}(assignment) @@ -13,5 +19,5 @@ assignments(assignment) \item{assignment}{S4 object of class Assignment} } \description{ -Get table of assigned features from an Assignment +Access methods for Assignment S4 class } From b58d76487ff9bfa9c901691c3a3b15a1c95d9740 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Tue, 23 Nov 2021 15:35:49 +0000 Subject: [PATCH 078/226] added parameters get and set methods --- NAMESPACE | 12 ++-- R/parameters.R | 99 ++++++++++++++++++++++++++++++++ man/parameters.Rd | 54 +++++++++++++++++ tests/testthat/test-parameters.R | 34 +++++++++++ 4 files changed, 195 insertions(+), 4 deletions(-) diff --git a/NAMESPACE b/NAMESPACE index 4d89659..7e69997 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -5,6 +5,9 @@ export("adducts<-") export("isotopeRules<-") export("isotopes<-") export("limit<-") +export("maxM<-") +export("maxMFscore<-") +export("ppm<-") export("transformationRules<-") export("transformations<-") export(adductRules) @@ -20,12 +23,15 @@ export(edges) export(isotopeRules) export(isotopes) export(limit) +export(maxM) +export(maxMFscore) export(nodes) export(plan) export(plotAdductDist) export(plotFeatureSolutions) export(plotNetwork) export(plotSpectrum) +export(ppm) export(relationships) export(summariseAssignment) export(technique) @@ -33,7 +39,6 @@ export(transformationRules) export(transformations) exportClasses(Assignment) exportClasses(AssignmentParameters) -importFrom(CHNOSZ,count.elements) importFrom(cli,console_width) importFrom(crayon,blue) importFrom(crayon,green) @@ -118,12 +123,11 @@ importFrom(metabolyseR,sinfo) importFrom(methods,as) importFrom(methods,new) importFrom(methods,show) +importFrom(mzAnnotation,MFscore) importFrom(mzAnnotation,adduct_rules) importFrom(mzAnnotation,calcM) -importFrom(mzAnnotation,calcMZ) -importFrom(mzAnnotation,generateMF) +importFrom(mzAnnotation,ipMF) importFrom(mzAnnotation,isotope_rules) -importFrom(mzAnnotation,ppmError) importFrom(mzAnnotation,relationshipCalculator) importFrom(mzAnnotation,transformMF) importFrom(mzAnnotation,transformation_rules) diff --git a/R/parameters.R b/R/parameters.R index 8f96751..0ad26cd 100644 --- a/R/parameters.R +++ b/R/parameters.R @@ -125,6 +125,24 @@ setMethod('show',signature = 'AssignmentParameters', #' ## Set limit #' limit(assignment_parameters) <- 0.002 #' +#' ## Return max M +#' maxM(assignment_parameters) +#' +#' ## Set max M +#' maxM(assignment_parameters) <- 500 +#' +#' ## Return max MF score +#' maxMFscore(assignment_parameters) +#' +#' ## Set max MF score +#' maxMFscore(assignment_parameters) <- 3 +#' +#' ## Return ppm +#' ppm(assignment_parameters) +#' +#' ## Set ppm +#' ppm(assignment_parameters) <- 3 +#' #' ## Return isotopes #' isotopes(assignment_parameters) #' @@ -203,6 +221,87 @@ setMethod('limit<-',signature = 'AssignmentParameters', #' @rdname parameters #' @export +setGeneric('maxM',function(x) + standardGeneric('maxM')) + +#' @rdname parameters + +setMethod('maxM',signature = 'AssignmentParameters', + function(x){ + x@maxM + }) + +#' @rdname parameters +#' @export + +setGeneric('maxM<-',function(x,value) + standardGeneric('maxM<-')) + +#' @rdname parameters + +setMethod('maxM<-',signature = 'AssignmentParameters', + function(x,value){ + x@maxM <- value + return(x) + }) + +#' @rdname parameters +#' @export + +setGeneric('maxMFscore',function(x) + standardGeneric('maxMFscore')) + +#' @rdname parameters + +setMethod('maxMFscore',signature = 'AssignmentParameters', + function(x){ + x@maxMFscore + }) + +#' @rdname parameters +#' @export + +setGeneric('maxMFscore<-',function(x,value) + standardGeneric('maxMFscore<-')) + +#' @rdname parameters + +setMethod('maxMFscore<-',signature = 'AssignmentParameters', + function(x,value){ + x@maxMFscore <- value + return(x) + }) + +#' @rdname parameters +#' @export + +setGeneric('ppm',function(x) + standardGeneric('ppm')) + +#' @rdname parameters + +setMethod('ppm',signature = 'AssignmentParameters', + function(x){ + x@ppm + }) + +#' @rdname parameters +#' @export + +setGeneric('ppm<-',function(x,value) + standardGeneric('ppm<-')) + +#' @rdname parameters + +setMethod('ppm<-',signature = 'AssignmentParameters', + function(x,value){ + x@ppm <- value + return(x) + }) + +#' @rdname parameters +#' @export + setGeneric('isotopes',function(x) standardGeneric('isotopes')) diff --git a/man/parameters.Rd b/man/parameters.Rd index cf0ea40..02d551d 100644 --- a/man/parameters.Rd +++ b/man/parameters.Rd @@ -7,6 +7,18 @@ \alias{limit,AssignmentParameters-method} \alias{limit<-} \alias{limit<-,AssignmentParameters-method} +\alias{maxM} +\alias{maxM,AssignmentParameters-method} +\alias{maxM<-} +\alias{maxM<-,AssignmentParameters-method} +\alias{maxMFscore} +\alias{maxMFscore,AssignmentParameters-method} +\alias{maxMFscore<-} +\alias{maxMFscore<-,AssignmentParameters-method} +\alias{ppm} +\alias{ppm,AssignmentParameters-method} +\alias{ppm<-} +\alias{ppm<-,AssignmentParameters-method} \alias{isotopes} \alias{isotopes,AssignmentParameters-method} \alias{isotopes<-} @@ -45,6 +57,30 @@ limit(x) <- value \S4method{limit}{AssignmentParameters}(x) <- value +maxM(x) + +\S4method{maxM}{AssignmentParameters}(x) + +maxM(x) <- value + +\S4method{maxM}{AssignmentParameters}(x) <- value + +maxMFscore(x) + +\S4method{maxMFscore}{AssignmentParameters}(x) + +maxMFscore(x) <- value + +\S4method{maxMFscore}{AssignmentParameters}(x) <- value + +ppm(x) + +\S4method{ppm}{AssignmentParameters}(x) + +ppm(x) <- value + +\S4method{ppm}{AssignmentParameters}(x) <- value + isotopes(x) \S4method{isotopes}{AssignmentParameters}(x) @@ -113,6 +149,24 @@ limit(assignment_parameters) ## Set limit limit(assignment_parameters) <- 0.002 +## Return max M +maxM(assignment_parameters) + +## Set max M +maxM(assignment_parameters) <- 500 + +## Return max MF score +maxMFscore(assignment_parameters) + +## Set max MF score +maxMFscore(assignment_parameters) <- 3 + +## Return ppm +ppm(assignment_parameters) + +## Set ppm +ppm(assignment_parameters) <- 3 + ## Return isotopes isotopes(assignment_parameters) diff --git a/tests/testthat/test-parameters.R b/tests/testthat/test-parameters.R index 87fc8b8..c3c4699 100644 --- a/tests/testthat/test-parameters.R +++ b/tests/testthat/test-parameters.R @@ -16,6 +16,40 @@ test_that("limit can be set", { expect_identical(limit(p),new_limit) }) +test_that("max M can be returned", { + expect_type(maxM(p),'double') +}) + +test_that("max M can be set", { + new_maxM <- 500 + maxM(p) <- new_maxM + + expect_identical(maxM(p),new_maxM) +}) + +test_that("max MF score can be returned", { + expect_type(maxMFscore(p),'double') +}) + +test_that("max MF score can be set", { + new_maxMFscore <- 3 + maxMFscore(p) <- new_maxMFscore + + expect_identical(maxMFscore(p),new_maxMFscore) +}) + + +test_that("ppm can be returned", { + expect_type(ppm(p),'double') +}) + +test_that("ppm can be set", { + new_ppm <- 3 + ppm(p) <- new_ppm + + expect_identical(ppm(p),new_ppm) +}) + test_that("adducts can be returned", { expect_type(adducts(p),'list') }) From 6d79b34ab8590504d1b2abaf6d0a8fdfed8cd1bd Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Tue, 23 Nov 2021 15:36:18 +0000 Subject: [PATCH 079/226] MF generation now handled by mzAnnotation::ipMF() --- DESCRIPTION | 3 +- R/MFgen.R | 46 ------------------------ R/MFscore.R | 93 ------------------------------------------------ R/addIsoAssign.R | 36 ++++++++++--------- 4 files changed, 21 insertions(+), 157 deletions(-) delete mode 100644 R/MFgen.R delete mode 100644 R/MFscore.R diff --git a/DESCRIPTION b/DESCRIPTION index f87e7ce..1faf239 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -34,8 +34,7 @@ Roxygen: list(markdown = TRUE) RoxygenNote: 7.1.2 Collate: parameters.R assignment.R correlations.R addIsoAssign.R transformationAssign.R relationships.R - graph.R assign.R MFgen.R internals.R - MFscore.R components.R + graph.R assign.R internals.R components.R feature_data.R LCassignment.R MFassign.R FIEassignment.R plotNetwork.R plotAdductDist.R plotFeatureSolutions.R plotSpectrum.R reexports.R diff --git a/R/MFgen.R b/R/MFgen.R deleted file mode 100644 index 63285b7..0000000 --- a/R/MFgen.R +++ /dev/null @@ -1,46 +0,0 @@ -maxElementFrequencies <- function(M){ - carb <- round(M/12) - Hs <- round(carb * 2) - NO <- round(carb / 2) - PS <- round(carb / 4) - - maxi <- c(C = carb, - H = Hs, - N = NO, - O = NO, - P = PS, - S = PS) - - return(maxi) -} - - -#' @importFrom mzAnnotation generateMF -#' @importFrom tibble as_tibble - -MFgen <- function(M,mz,ppm = 6){ - - max_element_frequencies <- maxElementFrequencies(M) - - if (M < 100) { - ppm <- 10 - } else { - ppm <- ppm - } - - ppm <- (ppm/10^6 * mz)/M * 10^6 - - if (M < 200) { - gr <- FALSE - } else { - gr <- TRUE - } - - res <- generateMF(M,ppm = ppm, - charge = 0, - validation = gr, - element_max = max_element_frequencies) %>% - rename(`Theoretical M` = Mass) %>% - mutate(`Measured M` = M, `Measured m/z` = mz) - return(res) -} \ No newline at end of file diff --git a/R/MFscore.R b/R/MFscore.R deleted file mode 100644 index 3755b58..0000000 --- a/R/MFscore.R +++ /dev/null @@ -1,93 +0,0 @@ -#' @importFrom CHNOSZ count.elements - -MFscore <- function(mf){ - elements <- c('C','H','N','O','P','S') - eleFreq <- as.vector(count.elements(mf)) - ele <- names(count.elements(mf)) - - if (length(which(!(elements %in% ele))) > 0) { - eleFreq <- c(eleFreq,rep(0,length(which(!(elements %in% ele))))) - ele <- c(ele,elements[!(elements %in% ele)]) - } - - colnames(eleFreq) <- NULL - - eleRatios <- c( - `H/C` = if ('H' %in% ele & 'C' %in% ele) { - eleFreq[ele == 'H']/eleFreq[ele == 'C'] - }, - `N/C` = if ('N' %in% ele & 'C' %in% ele) { - eleFreq[ele == 'N']/eleFreq[ele == 'C'] - }, - `O/C` = if ('O' %in% ele & 'C' %in% ele) { - eleFreq[ele == 'O']/eleFreq[ele == 'C'] - }, - `P/C` = if ('P' %in% ele & 'C' %in% ele) { - eleFreq[ele == 'P']/eleFreq[ele == 'C'] - }, - `S/C` = if ('S' %in% ele & 'C' %in% ele) { - eleFreq[ele == 'S']/eleFreq[ele == 'C'] - }, - `N/O` = if ('N' %in% ele & 'O' %in% ele) { - eleFreq[ele == 'N']/eleFreq[ele == 'O'] - }, - `P/O` = if ('P' %in% ele & 'O' %in% ele) { - eleFreq[ele == 'P']/eleFreq[ele == 'O'] - }, - `S/O` = if ('S' %in% ele & 'O' %in% ele) { - eleFreq[ele == 'S']/eleFreq[ele == 'O'] - }, - `O/P` = if ('O' %in% ele & 'P' %in% ele) { - eleFreq[ele == 'O']/eleFreq[ele == 'P'] - }, - `S/P` = if ('S' %in% ele & 'P' %in% ele) { - eleFreq[ele == 'S']/eleFreq[ele == 'P'] - } - ) - if (!is.null(eleRatios)) { - if ('H/C' %in% names(eleRatios)) { - eleRatios['H/C'] <- abs(eleRatios['H/C'] - 1.6) - } - if ('O/C' %in% names(eleRatios)) { - eleRatios['O/C'] <- abs(eleRatios['O/C'] - 0.3) - } - if (is.nan(eleRatios['N/O'])) { - eleRatios['N/O'] <- 0 - } - if (is.infinite(eleRatios['N/O'])) { - eleRatios['N/O'] <- eleFreq[ele == 'N'] - } - if (is.nan(eleRatios['P/O'])) { - eleRatios['P/O'] <- 0 - } - if (is.infinite(eleRatios['P/O'])) { - eleRatios['P/O'] <- eleFreq[ele == 'P'] - } - if (is.nan(eleRatios['S/O'])) { - eleRatios['S/O'] <- 0 - } - if (is.infinite(eleRatios['S/O'])) { - eleRatios['S/O'] <- eleFreq[ele == 'S'] - } - if (is.nan(eleRatios['O/P'])) { - eleRatios['O/P'] <- 0 - } - if ('O/P' %in% names(eleRatios) & eleRatios['O/P'] >= 3) { - eleRatios['O/P'] <- 0 - } - if (is.nan(eleRatios['P/S'])) { - eleRatios['P/S'] <- 0 - } - if (is.nan(eleRatios['S/P'])) { - eleRatios['S/P'] <- 0 - } - if (is.infinite(eleRatios['S/P'])) { - eleRatios['S/P'] <- eleFreq[ele == 'S'] - } - score <- sum(eleRatios) - } else { - score <- NA - } - - return(score) -} diff --git a/R/addIsoAssign.R b/R/addIsoAssign.R index fa8ffe4..5d07c0a 100644 --- a/R/addIsoAssign.R +++ b/R/addIsoAssign.R @@ -5,7 +5,7 @@ setGeneric("addIsoAssign", function(assignment) #' @importFrom dplyr arrange rowwise slice_sample left_join ungroup #' @importFrom stringr str_detect -#' @importFrom mzAnnotation calcM calcMZ ppmError +#' @importFrom mzAnnotation calcM ipMF MFscore #' @importFrom igraph vertex.attributes V #' @importFrom furrr furrr_options #' @importFrom methods as @@ -18,9 +18,8 @@ setMethod('addIsoAssign',signature = 'Assignment', message(blue('Adduct & isotope assignment '),cli::symbol$continue,'\r',appendLF = FALSE) } - parameters <- as(assignment,'AssignmentParameters') - - rel <- assignment@relationships %>% + rel <- assignment %>% + relationships() %>% filter(is.na(Transformation1) & is.na(Transformation2) & r > 0) %>% @@ -51,7 +50,7 @@ setMethod('addIsoAssign',signature = 'Assignment', adduct = Adduct, isotope = Isotope)) %>% arrange(M) %>% - filter(M <= parameters@maxM) + filter(M <= maxM(assignment)) nM <- nrow(M) @@ -60,26 +59,31 @@ setMethod('addIsoAssign',signature = 'Assignment', slice_sample(n = nM) %>% split(1:nrow(.)) %>% future_map(~{ - mf <- MFgen(.x$M,.x$mz,ppm = parameters@ppm) + mf <- ipMF(mz = .x$mz, + adduct = .x$Adduct, + isotope = .x$Isotope, + ppm = ppm(assignment)) if (nrow(mf) > 0) { mf %>% - left_join(M,by = c('Measured M' = 'M','Measured m/z' = 'mz')) %>% + left_join(select(M, + Feature, + RetentionTime, + M, + mz), + by = c('Measured M' = 'M','Measured m/z' = 'mz')) %>% rowwise() %>% - mutate(`Theoretical m/z` = calcMZ(`Theoretical M`,Adduct,Isotope), - `PPM Error` = ppmError(`Measured m/z`,`Theoretical m/z`)) %>% select(Feature,RetentionTime,MF,Isotope,Adduct,`Theoretical M`, - `Measured M`,`Theoretical m/z`,`Measured m/z`, `PPM Error`) %>% + `Measured M`,`Theoretical m/z`,`Measured m/z`, `PPM Error`, + Score) %>% rowwise() %>% - mutate(Score = MFscore(MF), - `PPM Error` = abs(`PPM Error`), - AddIsoScore = addIsoScore(Adduct, + mutate(AddIsoScore = addIsoScore(Adduct, Isotope, - parameters@adducts, - parameters@isotopes)) %>% + adducts(assignment), + isotopes(assignment))) %>% ungroup() %>% filter(Score == min(Score,na.rm = TRUE)) %>% - filter(Score < parameters@maxMFscore) + filter(Score < maxMFscore(assignment)) } else { return(NULL) } From 57ea474d982b05581e9041e1231e7da557cb9d5c Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Tue, 23 Nov 2021 15:36:28 +0000 Subject: [PATCH 080/226] fixed function import --- R/graph.R | 1 + 1 file changed, 1 insertion(+) diff --git a/R/graph.R b/R/graph.R index 8adc0fc..40829fb 100644 --- a/R/graph.R +++ b/R/graph.R @@ -1,6 +1,7 @@ #' nodes #' @description extract node table from tbl_graph object. #' @param graph object of class tbl_graph +#' @importFrom tibble as_tibble #' @export nodes <- function(graph){ From 583d05d7c4273e3a8d6765aa7d092952785eabd1 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Tue, 23 Nov 2021 16:02:31 +0000 Subject: [PATCH 081/226] removed redundant tests --- tests/testthat/test-MFgen.R | 14 -------------- tests/testthat/test-MFscore.R | 7 ------- tests/testthat/test-assignment.R | 2 -- 3 files changed, 23 deletions(-) delete mode 100644 tests/testthat/test-MFgen.R delete mode 100644 tests/testthat/test-MFscore.R diff --git a/tests/testthat/test-MFgen.R b/tests/testthat/test-MFgen.R deleted file mode 100644 index 2da4bc0..0000000 --- a/tests/testthat/test-MFgen.R +++ /dev/null @@ -1,14 +0,0 @@ - -context('MFgen') - -test_that('MFgen returns correctly',{ - res <- MFassign:::MFgen(117.07898,118.08626) - - expect_false(F %in% (class(res) == c('tbl_df','tbl','data.frame'))) - expect_false(F %in% (colnames(res) == c('MF','Theoretical M','PPM Error','Measured M','Measured m/z'))) - expect_true(class(res$MF) == 'character') - expect_true(class(res$`Theoretical M`) == 'numeric') - expect_true(class(res$`PPM Error`) == 'numeric') - expect_true(class(res$`Measured M`) == 'numeric') - expect_true(class(res$`Measured m/z`) == 'numeric') -}) \ No newline at end of file diff --git a/tests/testthat/test-MFscore.R b/tests/testthat/test-MFscore.R deleted file mode 100644 index ab558be..0000000 --- a/tests/testthat/test-MFscore.R +++ /dev/null @@ -1,7 +0,0 @@ - -context('MFscore') - -test_that('MFscore returns correctly',{ - res <- MFassign:::MFscore('C4H6O5PS') - expect_true(class(res) == 'numeric') -}) \ No newline at end of file diff --git a/tests/testthat/test-assignment.R b/tests/testthat/test-assignment.R index 62c4db9..02e452c 100644 --- a/tests/testthat/test-assignment.R +++ b/tests/testthat/test-assignment.R @@ -1,6 +1,4 @@ -context('assignMFs') - assignment_parameters_FIE <- assignmentParameters('FIE') assignment_parameters_LC <- assignmentParameters('RP-LC') From f07d9d77a9e47f67e8d71b130fcff31be8699aa9 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Tue, 23 Nov 2021 16:07:21 +0000 Subject: [PATCH 082/226] fixed transformation assignment --- R/transformationAssign.R | 39 +++++++++++++++++++++++---------------- 1 file changed, 23 insertions(+), 16 deletions(-) diff --git a/R/transformationAssign.R b/R/transformationAssign.R index 14fc807..bdb0f4d 100644 --- a/R/transformationAssign.R +++ b/R/transformationAssign.R @@ -9,7 +9,6 @@ setGeneric("transformationAssign", function(assignment) setMethod('transformationAssign',signature = 'Assignment', function(assignment){ - parameters <- as(assignment,'AssignmentParameters') count <- length(assignment@transAssign) assigned <- assignment@assignments @@ -38,7 +37,7 @@ setMethod('transformationAssign',signature = 'Assignment', rowwise() %>% mutate(M = calcM(mz,Adduct,Isotope)) %>% arrange(M) %>% - filter(M <= parameters@maxM) %>% + filter(M <= maxM(assignment)) %>% filter(!(mz %in% assigned$`Measured m/z`)) nM <- nrow(M) @@ -48,26 +47,31 @@ setMethod('transformationAssign',signature = 'Assignment', slice_sample(n = nM) %>% split(1:nrow(.)) %>% future_map(~{ - mf <- MFgen(.x$M,.x$mz,ppm = parameters@ppm) + mf <- ipMF(mz = .x$mz, + adduct = .x$Adduct, + isotope = .x$Isotope, + ppm = ppm(assignment)) if (nrow(mf) > 0) { mf %>% - left_join(M,by = c('Measured M' = 'M','Measured m/z' = 'mz')) %>% + left_join(select(M, + Feature, + RetentionTime, + M, + mz), + by = c('Measured M' = 'M','Measured m/z' = 'mz')) %>% rowwise() %>% - mutate(`Theoretical m/z` = calcMZ(`Theoretical M`,Adduct,Isotope), - `PPM Error` = ppmError(`Measured m/z`,`Theoretical m/z`)) %>% select(Feature,RetentionTime,MF,Isotope,Adduct,`Theoretical M`, - `Measured M`,`Theoretical m/z`,`Measured m/z`, `PPM Error`) %>% + `Measured M`,`Theoretical m/z`,`Measured m/z`, `PPM Error`, + Score) %>% rowwise() %>% - mutate(Score = MFscore(MF), - `PPM Error` = abs(`PPM Error`), - AddIsoScore = addIsoScore(Adduct, + mutate(AddIsoScore = addIsoScore(Adduct, Isotope, - parameters@adducts, - parameters@isotopes)) %>% + adducts(assignment), + isotopes(assignment))) %>% ungroup() %>% filter(Score == min(Score,na.rm = TRUE)) %>% - filter(Score < parameters@maxMFscore) + filter(Score < maxMFscore(assignment)) } else { return(NULL) } @@ -80,7 +84,10 @@ setMethod('transformationAssign',signature = 'Assignment', bind_rows(assigned %>% select(names(MF)[!(names(MF) == 'AddIsoScore')]) %>% rowwise() %>% - mutate(AddIsoScore = addIsoScore(Adduct,Isotope,parameters@adducts,parameters@isotopes))) + mutate(AddIsoScore = addIsoScore(Adduct, + Isotope, + adducts(assignment), + isotopes(assignment)))) rel <- rel %>% addMFs(MF,identMF = F) %>% mutate(RetentionTime1 = as.numeric(RetentionTime1),RetentionTime2 = as.numeric(RetentionTime2)) %>% @@ -96,7 +103,7 @@ setMethod('transformationAssign',signature = 'Assignment', distinct() %>% mutate(ID = 1:nrow(.)) - graph <- calcComponents(MFs,rel,parameters) + graph <- calcComponents(MFs,rel,assignment) filters <- tibble(Measure = c('Plausibility','Size','AIS','Score','PPM Error'), Direction = c(rep('max',3),rep('min',2))) @@ -114,7 +121,7 @@ setMethod('transformationAssign',signature = 'Assignment', .$name}) if (V(filteredGraph) %>% length() > 0) { filteredGraph <- filteredGraph %>% - recalcComponents(parameters) + recalcComponents(assignment) } else { break() } From da578045b4e4ada75eb156c9de5b6346d7240180 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Tue, 23 Nov 2021 16:07:37 +0000 Subject: [PATCH 083/226] added transformation assignment feature to example data --- data/feature_data.RData | Bin 4342 -> 4361 bytes 1 file changed, 0 insertions(+), 0 deletions(-) diff --git a/data/feature_data.RData b/data/feature_data.RData index 14e4ead6dd969eba0c48a24a53226e00d69421ed..c03b259a974bf24ede0b2da6a2d6669de98c82e9 100644 GIT binary patch literal 4361 zcmV+k5%%sMiwFP!000001MOJ(Kh zRg+^Y2Ll5GGXo1F69Y5r@|JNY3in#( z3oK(l5ArOV0cu_xZl9=UN9FFPQ(J_jQ1daWLXK!d)l#OORnucsMhJ20uy>(S;CT24 z`U386wNP8v@d4$JO&y%_d{AC7(BCNh8dWh%dTf#}QU3M(HIIWcs8nOjrYHxZT-N(t ztAj5puJMTIbJwGyVlZ)s?XS2y$MRq&^JY|Z5bxH{&!W74etbA44HZ6@#mX5-sMsH! z{=h;CrTp9KmKF<8mUH2J{k0FM@@2`NJ{O9+)-Ik)PxDdcShjW0sSg$6)W;S#Z=$>|Zj|3(d15~G9c5+X8w7`oP-5!-DP-F= zlov)nihA%0<>w;INe7PLdX4Vs-5Z8c(HY!D9$t;APqAN~M&3cG)a9K?1)Zq)6r7u| z&Ict{^KL4xGAK7sFt1IXMQJt1xuNK^<-Tt0s>`L~4*gh>^SKWwRcAb}a*K?Lh9J`& zr{AE$G$WZ)RSs2hXWg5tD|BA^Kox=jx z#1~IQA;?ZqbF@lTIM8Tjag-;$hI~;vGkn z_QP?|yoHZMAh47>g1lxPVJcD6iUx7;9@)%U-$X*tY5s|CF9+b$AlZ4ydK>}e*W)rJ z0YCY<$-Jvs2>5YK-1X5Dc)0B@D5dwnS79W=WHAxJYYZpcB?=H|mOPg{co<>V1IGs0 z8sV|;ilD`fYJ?i;O+4PNgJ6%$de?-j%lCXX&8L>VK;qG2X(Q7&w_6j+Cwq< zCE_0d`t3Y=(IBYPpV-^G96>x@?0i>U2%7rl^zS1x&}m&0(LJ34{Wj?!!Mnkr3a^); z&uKyb;mP@{Hk+WcD$0OADFz0q`}s@fc7oEEA0j{I56TYJ=dspoAO`o-csLKk(2w3& zNj(H;2W@43Q3|~yiodA8>V%Q2tzvBba$NatuF`GV&>#v!6SFM<=eDtXAt|7(+0(pD z^D%Ur)xBC+?*Ja6k|UyLpm*Jm$D_{~#E2dP%k@{wd`&4QAqud_H9V$i4*ht)!*PZM z(EB{=bV24CXtr&|C7iE8Rm!azI2;WV`;SteMHN9g%JBQWuT!9T^*opx&;xaEYP)S# zFbMCI=+>mN6`l26(o=-o2cgB4`pofSC^U)re*b|`P-bh-Wm~ob6N943JTB1k%UE}N zcN8{0ziuw3qX)|1b(V0g01zHd&(wqe1eLe3J@DIQ=x@2;7vJ&$a=vAh4|HA_W!_Jz zTnvHnc-;+)EHZR`x~jdcUO>B(;(w~;AZVOSUC*?KVBxN9alP{ysH2{7V~5NhQX1npP+LU-n`gWxZ#eN}i62Buwh zCs}EL-kC(cwP_%VG&QF?_rRp?BK^|I3o!1jtd+=Vhmqt*v-h5XASzV#8;%7*=V6dv zXBN02^Dz*GxHlAi^WdkkumVWpfPFN-P^6t_Yhe6nht>!cBdEdD44P^97g+y6sOgQ^ZES+p5x(Fl-zvdN9}_2BSy6H~6b=0kLyb z#m8<8Ix&_TW-|O?ko);w4!odmSS;6E69bxQ#w*1oCeU`AXpNjQ15v>EW*w6@h>8CC z#qD{}onUKE{P+dh)osKlIsxAG1E(1K$D#ABk9D7 zyPjO{J^_b)?=toIkHbFpd%DT3Bv@Z?UKr=GgM(eQs;c-j9Fm%x1a3sYp4o0xGT{ZR zlzyx$lX(kkuL`GKLPD@KAKjoq%Y*fZ-#H(D1z3K*%I-@theg)AvG09uuo7)PzI5^- z92gTU{U;k?Ip%j;N4*Ya5@8En9XnvI7Un1*X^%~0{R?Z{{b0sqdga)BDomVv^3VRr zhSRs4pf8I~Ft#_gxj&)@6Gz>FFeYmlQwT+2H7A%2Hz=N1-~g?r^&angHW>HNcifYG z2ov(GE8~(QOqeb7n}*V0WKk3MndvMH`-V4M`>_Rf8sl7fJ5ylnnl~9LCj`B3Y1(?DZwFpI^K*&2DbBIZtkOQu*p0x%d|HQmSx!HWOfmDsa|q@=45P|+jyX& zKoM3VH@Rb&BVd)|x;Q1S3QNu-M4~(+oF+}&9+vjNj`le_(N7AFwso7@h0?I;#vg5a zTsFgo^O@hV%yeuONnR}$UkYcvp&Qv{JS#ej40ya}$#RFVwxgq2y&^<7P8SFkI76IN zsB`dbHzb4!+ZwhZV)j$nxf7o3keP`-q2)<|s8wR9X4zB7J;>h9dzb~vrja1 zGmM{7O5O*RD@^0JU$H{wMc=A>Hdc`Bwk#ZW6osrM&sa6F9G5EImiz)B4dlKKjlT@p z$h5gD9d1yv7jB>P>4I<_#|#rg5120b*;wQ?K-xXZnBRR4Bz4|nUt%awoGzRlnW%+2 z8E;En4574-S0TkjWBLB_`Cqd~AeS?!-Hjt49hZ3%@;MhOUbz>woQxoLr{`FnbTR}; zx54}5F>|z6vn@Q3c9*0~_Gvo8{Um-K+M7kHz0FmUp%GG1vAlA~B)zh$x__1rm&?sv?R@X%vT;2T+ zGJeU_PdoZnbatFM`Krdq1XlWcZvQ#<1WpBSzZl<3fWv`<0o0fIuu57-cimh9d#~~5 zMd^WXnSa=ir%SL^Gp3kyu)#(MwMWlc_9AdzE+s7s|zXV{R(?XE|dk%z~-vVSZ9n8Ozi#$wocuEP42gT zpG=Z~skg?q{mBln<JE2-XUC!ouK0qcv%jjVOBFg(#}^nlGa-|}8*7w(7pAH_ zvI$PWMv0q6+>~Hw*f@4HPhS46*_kw%o<)A6-bnYP-p=BVR%X#!N%$lBg zH06xJLbUj%+0iP{I2K|(-IQTDJD;*vBNrB)?i$zlMqxBu-`GwUhAEZrtkk9xASMH5 zXN`Da5$5|nm9GRwy83%+*1d;Wg3N0EvwbjlEqixrP#NX|G|@3p0%pu{h4EOM zX=a!-tPgR{_4n9A^N(@Hv(Ay&)L8PamE$sOS7qwR@}$FdG>S>4JaR>6EpHyTk}ata zwPy>9IAaOQM-pE-Ycf>kT{4W@JfRS|I1;y*4Y`SaUO}Lr7GGIQLC=LBR6twUI<8sK`uo-qW}P z4IlE2c&Q2S7MT160hdXU5^!<7 zGKmm++geD>2J|IWizIkZ9U}v7K4`0%Rj1^+H`HAv>RM%gyo> z0vGd1QF=vS^qF>4-zo>`Rku2as#C$QU=uz<9tZcO4yhvyhaeYVB=$1#CgfWVWcT`= zg23Z!!z4~k$R3FzJ3QnkIttQniF02CiA$u3i>VfCcppZHSl)o3&(Np+)l$TWw2+<*5$z|dx(+5>Wl`DID0 za}X9hsTFNqfM0T62RiFA5|iR;$|@d_VD&iG8$ePgK25WQQ4a+XbG3rAEtN4~4T$Y^ z3a=&>PF{H%v0511r`AhEMQtS}LY?Lv4V1uqFf`nh)J#n5UE>;G+)2z+>nU@0T#4Ar zitA5B27<3PI$c?67L5Cp+Emo&MBk0jM;US|M9dlWm%sHpfRQI}$!M^Jcww)$YTv@W zzw0KRZT3p-xGzq$GBw&>2vl6bu;ytHcN8rqysj2xv?=lf6mBJOp+KU^dC|~Bq6|%?H4j2MD$PCyI2hi5OW=; zS>o&;fF-Hdsatm=(d*OA6y3p1jLZs5nlGLszHIwNwWKzKn8?^PcRqeQ7<}Y~b2_bw z8G*;8=apNCuJ_@sd6aOX_t$>IC$4_r+Nk9FC1meP{@3d#4DuUGiBZwnM~4rtCKmZV zH3nr?5`BISQK1JN!FQ$3WMSU^|K}wCSLP)DF*9S|6M8^B#4FhE=Y!#1Hm2C+-_p`j z(|-|JeS*C9{v`4J?dHUHNkO`+0@$-|Oe$>lN;`qUT#- zKRMUR&`0fyBOQ|stf<=abb70R1ZqDl9m}^3IrXDbl=9g8=53TUe;$6Z zMGh5u2_kaVX}CM|M6NO}1C<6B%@al4P_eCG?r!b^%3Gzz$c)vvQ}E-d(u-%P)I5C5 z!A2Q(zV+un;D|*Tb6JPb@KID|e50tJ?m@*3rYC08-%(yZv59}A7^NoepF*~8M@3Qe zqo@b3P;oB8jCAlQuGi|M?b$Sf%C6vUwUM=`{uKM=Y2+Q0NnGBQRM>^ePr-Q!8+=e| zwcw`YDuoKO1hcy2Ih56~og0o$U#aWn?)p3m?$C}GJD>Z2GFAHXO1IQd*%)N9Gwls3 zO)`_&m1R&ZbJo4Z>nlpG9&0=sm4d2?2!^aKo)sQ^yU61Ws&cZ|`&Uk_`WzOxF1}dqJoN@#zl75rr zltcjEnDz7e4G2CHHNaMukAM>+Ar8M~B8VePzfO??TE(U`zS{)+wl^gzIM#wT-xIwn ziHy+Lf;}3!P4HPTdOpgVi(Rj+ebSff5iIQEZI+Y+n&2q$)vyt}*9~;_ZZ?4Ld!G5+ zMoR=%?s$2fq(FM z=A0eH2wb|mV?=#7Xz^iZ+NFE3tMXR6iw6sQTqSVQEM}i z1Z9ZzNzxlWP+4y~|K76;`aQ~W_AZ97CFVqU;?tjlyN&!(<+@;gq4r;M$QI&NJ zbOf$%70}NBRq9mA*M?T;|4?o3ms13V+7{CJC>I1rPPbhR543aHh7LdXgTb*DafJ~@ z=tW$eZ9irLM9sSLSLwnahMxb_4oQ%^bDPXfC87V_ht=dg4V0x$9&?^KXbr~{l!|@; zXt(oe#Y3RXd}8hBb_DTwsq0-$5vZzLGQN+_Lc48UM9)kL^x7qZ`0oaTBDhhCHm?c2 zho=^<+E_w+O_V-wQVjG{5Ac@F?*h5MAVhZDALO0N&tt7wKnxwAa4MZXP;J{wO4(n7qL5cTcqAIe_8%oa3(JFijPCb)U#CI!>U}Ujs0+%z)DGM1U=ZFZ z(QQfPt3Km$~8go+xa7 ze%(w&TNmV^>rCOA0U$h_o~Z`^2?}>pN8q>1(A#>!FTV8yWPHoXA86b#%(|aawG;xQ ziTWGn*=o@7>8|m%dI7C2vj6GUL!h!VbU)J?hPk_z`Sq@6pp1FOjXx@bfufP-w-=t! z%Y0a+d8!$NVuM_H3OC3D`@ejoH9;>;F4W2`2wJar1@0_d2f(fCLYiP`L?S*muMcSoP7hu#^RVS9)0YmYRrtduiK~yU1H69Ow_QN2*swH|T z{1DOnlqL&`BN02%Cb4o~HmA|Gv4EO)OE3HlJFJrXxOb~hKtJr{w)3``Fc{fp(K1~E zeed(>;U+%70_nZ5*&k`827uaty&LLv9QJN&Ydt*33KEVw}+*g-i3AUelTS)xpI6V6~@lJ1!sTc!0B6V z(3d4A7}*=y+#l72v7^pl7=ty8$b`J0iW5vn8s$$evVmILc8~i#3ygYcJMT$9gt6M3 zEB&$~j2X@KnupV2XkHulnc*x9`bRch`>_>v>JuFKyHa4}nm-jPBLLlR>00?|aWLBL zmT|Yh6GqcD!FGF0U|8FypwVUpLf2U0*5F52H{TrO3YUV-;NDPQg>>lqDmEYDuZLxk zh|QV(3UCOYi8tkvg6%?>oBNm>Y_iTvGwe%;MLD)RnO=lls+UZ^nHntTHy^All!ukj zP0kp`2w3I1E=`Ln!-D-NktjRk>$%vL^Auc_rdMJwO zd{zSKaot8U6-`J*d2w{ScZK-#IBGvF6Qr0Aaw?!e%(&qpOLhz-+l4&;3@wC+LHx8r z@_r~?VVJo6iWyQb`q$jEv4V7uMbU_(Fr+QG#%qX`ycE&)3-|?sU$I& zc&l$ekn8|k9`$b*U5sHHaJNzVL^+I0Y$BznWTC_Ew&u#x6m;!8U(M4CLXDf&Dig9E znhEA_x;s9Av?WME)!{Di?09tH6<<)b4^($|D?@ww#3CJg7NiomV-0ie!bF)%I>8Cp zEOxV)lN=0n8^_L;$!tK&1^WQ9q> z`Y`+aK(9SC{+OUY>l_KorqXw9Y?ooXCQDnID+9J;Q4CTQk*hvydULszZcT--Jxf@` z84Hj)@L8O_Hk#-JC8^1-d+K+f?xS`i zUSbm5g~mTpSN6~LvZ`N3R0d+KK3?QsWa<8Tz;-NhkVR*DHC})6pv#m{DL6P@>OU4O z#oDS|hkV0O^QG-B6b)NG}xFaxy&y-^Bt_ zlx{KTeP$e0x5+?q&8@ECnpE)0*@Ta(O@Q-Kr^HdZ!;lFu6nU9=6SA!bbNc*FgYR*U zK@z(Lq>o0aIXvVgItw#yiE>^Ai9@KFgP{)VxF1FcS=<1>&+w-MH4?wLZ`+6XfBRT)Kloty0)`^%!4niTLa1^GTQyM(p*qqaF^dH>Xb&%kD|#se~m1?5T1^AO}e zr5SBqh+lGF2RiG}6H}rpib@`lVD>oP7eG=aKFzR%Q4R+Y^L6}ltyM8#4v6h@3a=p+ zPhEK%u~rbAr#Fg4MQtM{L!A~J^%cN)C^X!J)Iv<|Tjv^I(nTy#8p!i^T#4Ar@*7V_ z27;$9Izv%n4)psK+LcsjME{M@N0~B8M9dl0m%j}-fSxOV*>I?pcww)yX8+>7zxPc% z+v1hld0&)hV`#Fy5GcRO5@ag~3$KX2$LB2G*YdJicf;^3pp@e3IgAOe1Ou^!fBKM0au$qjP*yW=rRYFWY}nF0IQXCNnMP&&TfoosX<-q3@pAzs0LKNE4T42Ia1*Yfgm^Zy8$eS*C9{S@*1 zUyJ6y@RxA!AP-;vzaqw!=&vc;&(@5p|K63v|C{IU#d!YPwfRdPvPox?s@f(UE%kp9 zbyYQW4K=NQ5sjZjTYHtLt81z1=xFI^{EKL->X5ZGwEjQQQ73EuLo`;_Qd85?`MU-o k8rqtwYMMHmS0x(Sn^%DL%1?B3OFzed0G1Y@)t?do00dlvxc~qF From 6de7fd23be3ed8155cef4d6ae4b7e51d44dca265 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Tue, 23 Nov 2021 17:07:28 +0000 Subject: [PATCH 084/226] fixed plotNetwork() for assignments with only a single transformation assignment iteration --- R/plotNetwork.R | 21 ++++++++++++--------- 1 file changed, 12 insertions(+), 9 deletions(-) diff --git a/R/plotNetwork.R b/R/plotNetwork.R index 725138f..8810ca2 100644 --- a/R/plotNetwork.R +++ b/R/plotNetwork.R @@ -53,10 +53,9 @@ setMethod('plotNetwork',signature = 'Assignment', TA <- assignment@transAssign %>% map(~{.$filteredGraph}) - graph <- AI - if (length(TA) > 0){ - graph <- bind_graphs( + if (length(TA) > 1) { + graph <- bind_graphs(graph, {a <- TA[[1]] for (i in 2:length(TA)) { a <- bind_graphs(a,TA[[i]]) @@ -64,6 +63,9 @@ setMethod('plotNetwork',signature = 'Assignment', a } ) + } else { + graph <- bind_graphs(AI,TA[[1]]) + } } e <- edges(graph) %>% @@ -104,9 +106,10 @@ setMethod('plotNetwork',signature = 'Assignment', .$Assigned %>% table() - networkPlot(network, - layout, - rThreshold, - assignedNodes, - explainedEdges) - }) \ No newline at end of file + networkPlot(network, + layout, + rThreshold, + assignedNodes, + explainedEdges) + }) + \ No newline at end of file From 37fae367ef041b408f1e17024fec6d8390b2169a Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Tue, 23 Nov 2021 17:19:10 +0000 Subject: [PATCH 085/226] formatted transformation assignment --- R/transformationAssign.R | 72 +++++++++++++++++++++++++++++++++------- 1 file changed, 60 insertions(+), 12 deletions(-) diff --git a/R/transformationAssign.R b/R/transformationAssign.R index bdb0f4d..a694caf 100644 --- a/R/transformationAssign.R +++ b/R/transformationAssign.R @@ -14,24 +14,48 @@ setMethod('transformationAssign',signature = 'Assignment', if (assignment@log$verbose == T) { startTime <- proc.time() - message(blue(str_c('Transformation assignment iteration ', count + 1,' ')),cli::symbol$continue,'\r',appendLF = FALSE) + message(blue(str_c('Transformation assignment iteration ', + count + 1,' ')), + cli::symbol$continue, + '\r', + appendLF = FALSE) } - rel <- assignment@relationships %>% - filter((`m/z1` %in% assigned$`Measured m/z` | (`m/z2` %in% assigned$`Measured m/z`)) & !(`m/z1` %in% assigned$`Measured m/z` & (`m/z2` %in% assigned$`Measured m/z`))) + rel <- assignment %>% + relationships() %>% + filter((`m/z1` %in% assigned$`Measured m/z` | + (`m/z2` %in% assigned$`Measured m/z`)) & + !(`m/z1` %in% assigned$`Measured m/z` & + (`m/z2` %in% assigned$`Measured m/z`))) mz1 <- rel %>% - semi_join(assigned,by = c('m/z1' = 'Measured m/z', 'Adduct1' = 'Adduct', 'Isotope1' = 'Isotope')) %>% + semi_join(assigned, + by = c('m/z1' = 'Measured m/z', + 'Adduct1' = 'Adduct', + 'Isotope1' = 'Isotope')) %>% filter(is.na(Transformation1)) mz2 <- rel %>% - semi_join(assigned,by = c('m/z2' = 'Measured m/z', 'Adduct2' = 'Adduct', 'Isotope2' = 'Isotope')) %>% + semi_join(assigned, + by = c('m/z2' = 'Measured m/z', + 'Adduct2' = 'Adduct', + 'Isotope2' = 'Isotope')) %>% filter(is.na(Transformation2)) rel <- bind_rows(mz1,mz2) if (nrow(rel) > 0) { - M <- bind_rows(select(rel,mz = `m/z1`,RetentionTime = RetentionTime1,Isotope = Isotope1, Adduct = Adduct1, Feature = Feature1), - select(rel,mz = `m/z2`,RetentionTime = RetentionTime2,Isotope = Isotope2, Adduct = Adduct2, Feature = Feature2)) %>% + M <- bind_rows(select(rel, + mz = `m/z1`, + RetentionTime = RetentionTime1, + Isotope = Isotope1, + Adduct = Adduct1, + Feature = Feature1), + select(rel, + mz = `m/z2`, + RetentionTime = RetentionTime2, + Isotope = Isotope2, + Adduct = Adduct2, + Feature = Feature2)) %>% distinct() %>% arrange(mz) %>% rowwise() %>% @@ -90,22 +114,46 @@ setMethod('transformationAssign',signature = 'Assignment', isotopes(assignment)))) rel <- rel %>% addMFs(MF,identMF = F) %>% - mutate(RetentionTime1 = as.numeric(RetentionTime1),RetentionTime2 = as.numeric(RetentionTime2)) %>% + mutate(RetentionTime1 = as.numeric(RetentionTime1), + RetentionTime2 = as.numeric(RetentionTime2)) %>% addNames() if (nrow(rel) > 0) { - MFs <- bind_rows(select(rel,Name = Name1,Feature = Feature1,mz = `m/z1`,RetentionTime = RetentionTime1,Isotope = Isotope1, Adduct = Adduct1, MF = MF1), - select(rel,Name = Name2,Feature = Feature2,mz = `m/z2`,RetentionTime = RetentionTime2,Isotope = Isotope2, Adduct = Adduct2,MF = MF2)) %>% + MFs <- bind_rows(select(rel, + Name = Name1, + Feature = Feature1, + mz = `m/z1`, + RetentionTime = RetentionTime1, + Isotope = Isotope1, + Adduct = Adduct1, + MF = MF1), + select(rel, + Name = Name2, + Feature = Feature2, + mz = `m/z2`, + RetentionTime = RetentionTime2, + Isotope = Isotope2, + Adduct = Adduct2, + MF = MF2)) %>% mutate(RetentionTime = as.numeric(RetentionTime)) %>% arrange(mz) %>% select(-mz) %>% - left_join(MF, by = c("Feature", "RetentionTime", "Isotope", "Adduct",'MF')) %>% + left_join(MF, + by = c("Feature", + "RetentionTime", + "Isotope", + "Adduct", + 'MF')) %>% distinct() %>% mutate(ID = 1:nrow(.)) graph <- calcComponents(MFs,rel,assignment) - filters <- tibble(Measure = c('Plausibility','Size','AIS','Score','PPM Error'), + filters <- tibble(Measure = c('Plausibility', + 'Size', + 'AIS', + 'Score', + 'PPM Error'), Direction = c(rep('max',3),rep('min',2))) filteredGraph <- graph From 0cc8ec3d510e3f420513c3bba19ff4e56f86a5a8 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Tue, 23 Nov 2021 17:20:52 +0000 Subject: [PATCH 086/226] added tests for assignment class accessors --- tests/testthat/test-assignment.R | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/tests/testthat/test-assignment.R b/tests/testthat/test-assignment.R index 02e452c..243150c 100644 --- a/tests/testthat/test-assignment.R +++ b/tests/testthat/test-assignment.R @@ -21,11 +21,22 @@ test_that('assignment works for LC techniques',{ expect_s4_class(assignment_LC,"Assignment") }) -test_that('Assignment class show method works',{ +test_that('assignment class show method works',{ expect_output(print(assignment_FIE), 'Assignment:') }) +test_that('assignment data can be returned',{ + expect_s3_class(assignmentData(assignment_FIE),'tbl_df') +}) + +test_that('data with assigned feature names can be returned',{ + expect_s3_class(assignedData(assignment_FIE),'tbl_df') +}) + +test_that('a summary of assignments can be returned',{ + expect_s3_class(summariseAssignment(assignment_FIE),'tbl_df') +}) test_that('feature solutions can be plotted',{ pl <- plotFeatureSolutions(assignment_FIE, 'n191.01962', From ed8a193c90bf7163ed790ad0585754a2b6304bc7 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Tue, 23 Nov 2021 17:21:09 +0000 Subject: [PATCH 087/226] example feature data now includes a positive mode feature --- data/feature_data.RData | Bin 4361 -> 4363 bytes 1 file changed, 0 insertions(+), 0 deletions(-) diff --git a/data/feature_data.RData b/data/feature_data.RData index c03b259a974bf24ede0b2da6a2d6669de98c82e9..138d1dee404b40f3f002f36456de0972bcac768d 100644 GIT binary patch literal 4363 zcmV+m5%lgKiwFP!000001MQgkKbBkD#*I5O8OuD}#*q0oUdMf#MP@3LS?-LLO3GA{ zPloyxZkIrpPdl=9f}=53TU ze;$6ZSq>Eji6U|~r*U`aiCkrT1}cp%S|*9Qqhf2p+}+#-l($Nakr}ITr{Kp^r5Ddo zsdeb6qpdRTeCyADz!8Ts=CTf<;UlQb_(st<)q{!~OiwJPzoWc-LY;r47^P+&pF+27 zLq$={qv!{(P;oBOf^^^ruGi|F-mN}@%C3-ZwUM=`{uKA+Y1AE*NnGBUT-b%mPa%1U z8+=h}z2L6oCWQ)%M2otVIh56~og0oxU#Y8hcYPiOcWB3oUCw<#nJWExrCVyKYz#Kr zarzA^%`#Kim1R&ZbJnB9`zuPW9&J1uor*H8o~DR%6kSKv0F6z-5Jrt2#JhS4&0sz+Kcwhv##+7E@R<&+w=toN?y+PeQiN7 zE^!pjG=TPfUEXBP8HDPlrKJRQBc#kDG5ZM_!CXEXZ986oM$9gbiHBg2dxIMsqS z-xISlnT)Wwg58?AP4HbXc|OXUi=D4+eAAcf5hCpCW09N#n&2q$)wmJ6)(v#^Y8%1t zJ_Z2NPHKfo*I%rT<}n-N6zxl3|+3ZGYpIWEPV zK|siP=A7-t2wJ+keMDmyXbItG+NFE3v+`EEt0xP5-Ref3C!au2kI;LUrNf}nL_3ct z?1$5kMJo@9Ku{THq}sX#geyhQ$Q#DPXLK`rLo*4%r+Fv8y&QyZqj=XLn+XI~T#wHZ z2mEE{r}D36Bk;#DQMX4=;OV}*u#DCVKe^FJ)1@SYtTUSQ5GzEGdCGjs&|!pM4;mk0 zX@cjzEBux>Y7l0uKlymOE7xUmIFs_(Qe5UrrGeYFlXMqg)UiIo zP%8QXpxw@=6%Ti+X=+urLK21MWCu~&iFn$3*EMLkv%i1Fld(y=D!;Pir_{m z+PoGF9-dsdYP$)#YoZN#lVf3+wx73bekaKN1);Lz0U+;CejaDT0%B-Cm5co_jQnX$ zRg^=3PViR77iG{tBL9o(t1cM3*~!N>tmKvL;V9dt0}Y}mEGfqlaA_aE7n%y{x;-u1 zG#^8+Mb*2N`3~SIEIulH2Kv|ixjg$_K#c0sFs7<&KIPvfoj)YQp)}s6otI%!NV~yb@(XpSy&$AqjbOD`#KG(ckhGwL48p6rghk5 zhk)=&jcH3RU-j9*H6vBPV+dLtY0sQ4hC!297zh{)19`6QT#i)-FgYZg!sQAr|I7`y zcSl3}`E?5sU44*;t}{hw1%mK&ex@4oCn(%a9YNnN!(ht=|Af{Lknt-gf1q*0IO~3D z)lw)-ChBikW~)KZx4Xv2`UP~l$N{HX4}!|h(EUtj7?vJ7me;$UfimV5KmMo;Mv5j{ z-(GmZAoF3B*2!iNiVbq*soWqB?ECVO)&zsoa$(l)!O(fdD{yDwItbqKx>rR9VQAKE zf0CIB=$}dAS)UG~SW|PRYY$B8FVZfZya1EFsyeaU4j7AnG=J|E1fo*epz&BRbRP!$ zS1r*);fILUr_-{aI1zCZZ4xW@Mf)^e8w;p;w+tfQu){i~k9(KK1PsGZY&~z638Rs% zRxQ&dF!VW}9%1GSERfy{TP(ti-+h0wxjeM>Z!1fZ!=XK1{9ve41jdhkZwyf00%GTw zlCS+ZbYrd5XEOs}nD_Z!F1%r2R3g(-8w;vg<}3MS22gjLXp5RQ2T@4>W&?u`h{=J5 zrS199n`G%o`uGJpHSNSF8UgN&gQw^RCZPMRpLw6S6DXYAmet?9R(*Em+4aSL#1oEm zyPjO{IRVFg@3IVdkHaDEdxq()WY}DAS)AaqhogOsva;w59Fv=!`EEqQfzf_UJn;pr z6@F|emwF2u?@H%g0s^qI7*p4v=EG*x|D11t9IQTHW%VOjz%u*Y`1gKySPQotUq1N| zj`WFE0aHz|8u!1gt6C3pvGB$2&KucIDVY8cbb!3(o$? zf%CWA;4e$gFmW)ky+5iCQzyN_a0VNgkO_G~6=#@_G|Hb?WCOLf?H>1g7MS$XcHEPG z2vfB=H~M8Km@--#G!Li4*s?bMGs9UJ^^d4u`>_S~8WSA(J5yoemOm9HBLMwx={otR z<6*MPJ>zbH7fhyWLhN^&!ML_hL9@*ogubc7t-+75X}&qg6(I%N!98Jq3h6NPQ*1uS zUyn^iBDQDtDZnveCc&Ib3U&+O?jB?Au+2Iz&9FBeR^`~{Y<>~;Y2GsZ7HZfuuYI7h zP#)GoH#uV&BVnEEwlpoO3@i2{M3O8$oTp6PAC~pPp87c_$zK9acJ-S&1k$nT#vko_ zTsOm({h9xrTzD9#8G3Wr7s@K~4n}h?zD#WXX<&WV?{ppJ9a% zF-n+LNZALaD-092Uok`KMgN+6w$_mDu__vI5{9%D*LV%Fl9wXdp7H`94d%TLOSlZ_ zsPy?Oo$gR@5bT)u?S^1I+bjcJFBmTQ+gj!~LeeAJgx6ypBvtNXUt-CSpDCIfoveeZ z8s3(<8bM(nw_K{J#>)T87JSVag-q^{P7jWNbX@99=;u5rdFNf!ayEv@o!(>lk}2RL z=?RE69)Kc4ia~5Z5lFRbJ}XJ=g%DS0>0v`J@cnwtP(&>Zq;S^t8KWhT~!>a)}A$yc?;rm!~HbNkQnCvYx&`^Ds5A{-AK45Yj)fOYZ)n%m}5ICxJy zFU|;p>%zkUJY9yJiV4}YlLfXq16LCmo8|-go#uz2vfQ5G^b(6&;TvgQ` ziI-HuCR`_0WK01zSqBn6?rVeDhWgObzOQhA_+oj`ENrhzjd#Tw!_@wd5Sui0Z1TAE z`&6{`y3%uJXeY_l|CALx0Q?k%wcVBa5X$t!GUa#iq1);`G zYn2II53NMYH{Bf{K-wIvpz3%Rcy=tN@QNR(y8ElUyOp6keSDFQJquEa+;PS^cVVW? zC7tLDXp7w}<|Kze!`7*@WilI(w5;8u(g5QPzZc%Kr~p-Nr%NwE4=qE{JoclPVcz`A zvpIJhmck`B&5u@t%C;Ei<*o>;xrNmA8hNnv^3b@(GX~?4hNcdhAj~K{XC*eB05KIf zH)qTZ%W%K%X*{Jc)-%{syWu^|6Q$Pjp6!R>Yw5ewLyEBAqY94;6EK$?JpPq!Jxs>i z&9cHJVRMLmexTO@ntx2tpLL1Crl!(&ZETlew2xq^+Ev?PXQJjHnF6Sbe?8zsS=4^?>bY)F6xA^lH5R!~xeSp;B;g zyfl0)T8gz*Cs{AeGybEWu21|;&yASly&M&o6ht)dzu3VjdI8drQTk!7Q;=RLu;XNU z3cia4q-gzO(EH9fscw~lE(m9vc)Rht0krA~<>bcY}lXe{zF=_X`b59IXu zp90_G9HV4*O-LV!R&#vFOLP`y+!E!y3KEAYKic_RJ;nqw^;H=~yPrbTeM)Cnx+Wxs8vHmN5?0SIej;`FyIciG3WB77j%3Ji zdYwut%9PN<{1#)tA2wID(!lf7y7bm3ZNxvS#1n zy}!>*JlpJ@)_Gr)Xk%!yyAUM5%HutL+ma{GM!d9c;~3stK#U%xQRe?pC*Gc8woU0e zzN(v|@|-eIzD)GS)R<~q*tp8S+@Cjg5)mgR2!n@|P;v0l<@kpV3J?R64zAWCe8ha` zX{LCG2VhF>bMDd8Ci;AP7-Bj(iP1T}DT}3Z#FuTqD3{h{5|f#m=FcZ=2c561U~ZQU zG0XS3?7U(t(fvN6EuS1g^!++u^u)~{9NG$gUqbh;?*Dq@q+vl*88Ie2_vrA!wZsz7 zr>5YnDx%-tF*@v^6L_xFn=URm{C}V1|4N_aKYC`Yd%_N=hI)ti|GY4qD}y0!<+Z%L z-27icX5V1%y+1`f|J#cD7yKo{C)m?3;ID{rCHia1_Ok`28n9<2@qg#}do!MYb?5$) zhpOwTtE#E%>1g~L(NI;>&{Wg;H=_BI=<2Q#4GkStJv|*g&3_}hs(NG{O`ZQFdKzS{ ze~9MFUTSJOdVkj-R8v<=RZUAzdsU*TtGxnr|5+5Sp{Bb+wAFQ2qNShXe*nRQYw4L3 F006(qh4lac literal 4361 zcmV+k5%%sMiwFP!000001MOJ(Kh zRg+^Y2Ll5GGXo1F69Y5r@|JNY3in#( z3oK(l5ArOV0cu_xZl9=UN9FFPQ(J_jQ1daWLXK!d)l#OORnucsMhJ20uy>(S;CT24 z`U386wNP8v@d4$JO&y%_d{AC7(BCNh8dWh%dTf#}QU3M(HIIWcs8nOjrYHxZT-N(t ztAj5puJMTIbJwGyVlZ)s?XS2y$MRq&^JY|Z5bxH{&!W74etbA44HZ6@#mX5-sMsH! z{=h;CrTp9KmKF<8mUH2J{k0FM@@2`NJ{O9+)-Ik)PxDdcShjW0sSg$6)W;S#Z=$>|Zj|3(d15~G9c5+X8w7`oP-5!-DP-F= zlov)nihA%0<>w;INe7PLdX4Vs-5Z8c(HY!D9$t;APqAN~M&3cG)a9K?1)Zq)6r7u| z&Ict{^KL4xGAK7sFt1IXMQJt1xuNK^<-Tt0s>`L~4*gh>^SKWwRcAb}a*K?Lh9J`& zr{AE$G$WZ)RSs2hXWg5tD|BA^Kox=jx z#1~IQA;?ZqbF@lTIM8Tjag-;$hI~;vGkn z_QP?|yoHZMAh47>g1lxPVJcD6iUx7;9@)%U-$X*tY5s|CF9+b$AlZ4ydK>}e*W)rJ z0YCY<$-Jvs2>5YK-1X5Dc)0B@D5dwnS79W=WHAxJYYZpcB?=H|mOPg{co<>V1IGs0 z8sV|;ilD`fYJ?i;O+4PNgJ6%$de?-j%lCXX&8L>VK;qG2X(Q7&w_6j+Cwq< zCE_0d`t3Y=(IBYPpV-^G96>x@?0i>U2%7rl^zS1x&}m&0(LJ34{Wj?!!Mnkr3a^); z&uKyb;mP@{Hk+WcD$0OADFz0q`}s@fc7oEEA0j{I56TYJ=dspoAO`o-csLKk(2w3& zNj(H;2W@43Q3|~yiodA8>V%Q2tzvBba$NatuF`GV&>#v!6SFM<=eDtXAt|7(+0(pD z^D%Ur)xBC+?*Ja6k|UyLpm*Jm$D_{~#E2dP%k@{wd`&4QAqud_H9V$i4*ht)!*PZM z(EB{=bV24CXtr&|C7iE8Rm!azI2;WV`;SteMHN9g%JBQWuT!9T^*opx&;xaEYP)S# zFbMCI=+>mN6`l26(o=-o2cgB4`pofSC^U)re*b|`P-bh-Wm~ob6N943JTB1k%UE}N zcN8{0ziuw3qX)|1b(V0g01zHd&(wqe1eLe3J@DIQ=x@2;7vJ&$a=vAh4|HA_W!_Jz zTnvHnc-;+)EHZR`x~jdcUO>B(;(w~;AZVOSUC*?KVBxN9alP{ysH2{7V~5NhQX1npP+LU-n`gWxZ#eN}i62Buwh zCs}EL-kC(cwP_%VG&QF?_rRp?BK^|I3o!1jtd+=Vhmqt*v-h5XASzV#8;%7*=V6dv zXBN02^Dz*GxHlAi^WdkkumVWpfPFN-P^6t_Yhe6nht>!cBdEdD44P^97g+y6sOgQ^ZES+p5x(Fl-zvdN9}_2BSy6H~6b=0kLyb z#m8<8Ix&_TW-|O?ko);w4!odmSS;6E69bxQ#w*1oCeU`AXpNjQ15v>EW*w6@h>8CC z#qD{}onUKE{P+dh)osKlIsxAG1E(1K$D#ABk9D7 zyPjO{J^_b)?=toIkHbFpd%DT3Bv@Z?UKr=GgM(eQs;c-j9Fm%x1a3sYp4o0xGT{ZR zlzyx$lX(kkuL`GKLPD@KAKjoq%Y*fZ-#H(D1z3K*%I-@theg)AvG09uuo7)PzI5^- z92gTU{U;k?Ip%j;N4*Ya5@8En9XnvI7Un1*X^%~0{R?Z{{b0sqdga)BDomVv^3VRr zhSRs4pf8I~Ft#_gxj&)@6Gz>FFeYmlQwT+2H7A%2Hz=N1-~g?r^&angHW>HNcifYG z2ov(GE8~(QOqeb7n}*V0WKk3MndvMH`-V4M`>_Rf8sl7fJ5ylnnl~9LCj`B3Y1(?DZwFpI^K*&2DbBIZtkOQu*p0x%d|HQmSx!HWOfmDsa|q@=45P|+jyX& zKoM3VH@Rb&BVd)|x;Q1S3QNu-M4~(+oF+}&9+vjNj`le_(N7AFwso7@h0?I;#vg5a zTsFgo^O@hV%yeuONnR}$UkYcvp&Qv{JS#ej40ya}$#RFVwxgq2y&^<7P8SFkI76IN zsB`dbHzb4!+ZwhZV)j$nxf7o3keP`-q2)<|s8wR9X4zB7J;>h9dzb~vrja1 zGmM{7O5O*RD@^0JU$H{wMc=A>Hdc`Bwk#ZW6osrM&sa6F9G5EImiz)B4dlKKjlT@p z$h5gD9d1yv7jB>P>4I<_#|#rg5120b*;wQ?K-xXZnBRR4Bz4|nUt%awoGzRlnW%+2 z8E;En4574-S0TkjWBLB_`Cqd~AeS?!-Hjt49hZ3%@;MhOUbz>woQxoLr{`FnbTR}; zx54}5F>|z6vn@Q3c9*0~_Gvo8{Um-K+M7kHz0FmUp%GG1vAlA~B)zh$x__1rm&?sv?R@X%vT;2T+ zGJeU_PdoZnbatFM`Krdq1XlWcZvQ#<1WpBSzZl<3fWv`<0o0fIuu57-cimh9d#~~5 zMd^WXnSa=ir%SL^Gp3kyu)#(MwMWlc_9AdzE+s7s|zXV{R(?XE|dk%z~-vVSZ9n8Ozi#$wocuEP42gT zpG=Z~skg?q{mBln<JE2-XUC!ouK0qcv%jjVOBFg(#}^nlGa-|}8*7w(7pAH_ zvI$PWMv0q6+>~Hw*f@4HPhS46*_kw%o<)A6-bnYP-p=BVR%X#!N%$lBg zH06xJLbUj%+0iP{I2K|(-IQTDJD;*vBNrB)?i$zlMqxBu-`GwUhAEZrtkk9xASMH5 zXN`Da5$5|nm9GRwy83%+*1d;Wg3N0EvwbjlEqixrP#NX|G|@3p0%pu{h4EOM zX=a!-tPgR{_4n9A^N(@Hv(Ay&)L8PamE$sOS7qwR@}$FdG>S>4JaR>6EpHyTk}ata zwPy>9IAaOQM-pE-Ycf>kT{4W@JfRS|I1;y*4Y`SaUO}Lr7GGIQLC=LBR6twUI<8sK`uo-qW}P z4IlE2c&Q2S7MT160hdXU5^!<7 zGKmm++geD>2J|IWizIkZ9U}v7K4`0%Rj1^+H`HAv>RM%gyo> z0vGd1QF=vS^qF>4-zo>`Rku2as#C$QU=uz<9tZcO4yhvyhaeYVB=$1#CgfWVWcT`= zg23Z!!z4~k$R3FzJ3QnkIttQniF02CiA$u3i>VfCcppZHSl)o3&(Np+)l$TWw2+<*5$z|dx(+5>Wl`DID0 za}X9hsTFNqfM0T62RiFA5|iR;$|@d_VD&iG8$ePgK25WQQ4a+XbG3rAEtN4~4T$Y^ z3a=&>PF{H%v0511r`AhEMQtS}LY?Lv4V1uqFf`nh)J#n5UE>;G+)2z+>nU@0T#4Ar zitA5B27<3PI$c?67L5Cp+Emo&MBk0jM;US|M9dlWm%sHpfRQI}$!M^Jcww)$YTv@W zzw0KRZT3p-xGzq$GBw&>2vl6bu;ytHcN8rqysj2xv?=lf6mBJOp+KU^dC|~Bq6|%?H4j2MD$PCyI2hi5OW=; zS>o&;fF-Hdsatm=(d*OA6y3p1jLZs5nlGLszHIwNwWKzKn8?^PcRqeQ7<}Y~b2_bw z8G*;8=apNCuJ_@sd6aOX_t$>IC$4_r+Nk9FC1meP{@3d#4DuUGiBZwnM~4rtCKmZV zH3nr?5`BISQK1JN!FQ$3WMSU^|K}wCSLP)DF*9S|6M8^B#4FhE=Y!#1Hm2C+-_p`j z(|-|JeS*C9{v`4J? Date: Tue, 23 Nov 2021 17:21:27 +0000 Subject: [PATCH 088/226] various fixes --- R/assign.R | 9 +++------ R/assignment.R | 2 +- R/relationships.R | 2 +- 3 files changed, 5 insertions(+), 8 deletions(-) diff --git a/R/assign.R b/R/assign.R index 3fbddf9..b305397 100644 --- a/R/assign.R +++ b/R/assign.R @@ -1,16 +1,13 @@ -assignMethods <- function(method = NULL) { +assignMethods <- function(method) { methods <- list( FIE = FIEassignment, `RP-LC` = LCassignment, `NP-LC` = LCassignment ) - if (is.null(method)) { - method <- methods - } else { - method <- methods[[method]] - } + method <- methods[[method]] + return(method) } diff --git a/R/assignment.R b/R/assignment.R index 3262956..e284971 100644 --- a/R/assignment.R +++ b/R/assignment.R @@ -48,7 +48,7 @@ setMethod('show',signature = 'Assignment', cat(yellow('Assignment:'),'\n') cat('\t','Features:\t\t',ncol(object@data),'\n') cat('\t','Correlations:\t\t',nrow(object@correlations),'\n') - cat('\t','Relationships:\t\t',nrow(object@relationships),'\n') + cat('\t','Relationships:\t\t',nrow(relationships(object)),'\n') cat('\n') if (length(object@addIsoAssign) > 0) { cat('\t',green('Adduct & isotope assignment:'),'\n') diff --git a/R/relationships.R b/R/relationships.R index a669526..65b2c1a 100644 --- a/R/relationships.R +++ b/R/relationships.R @@ -98,7 +98,7 @@ setMethod('calcRelationships',signature = 'Assignment', ID) %>% mutate_at(vars(RetentionTime1,RetentionTime2),as.numeric) - assignment@relationships <- rel + relationships(assignment) <- rel if (assignment@log$verbose == T) { endTime <- proc.time() From cdd2f6cc6a7278c97fcbd57826b2fe8ca50298e1 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Fri, 18 Feb 2022 15:52:35 +0000 Subject: [PATCH 089/226] Fixed renaming of PPM error column --- R/MFassign.R | 4 ++-- R/transformationAssign.R | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/R/MFassign.R b/R/MFassign.R index 925f6fe..aa3837f 100644 --- a/R/MFassign.R +++ b/R/MFassign.R @@ -6,9 +6,9 @@ globalVariables(c( 'EdgeWeight2','Degree','Measured M','Cluster', 'Average AddIsoScore', 'Transformation1','Transformation2','log2IntensityRatio','m/z1', 'm/z2','RetentionTime1','RetentionTime2','mz','Theoretical M', - 'Theoretical m/z','PPM Error','name','Mode','V1','V2','Mode1', + 'Theoretical m/z','PPM error','name','Mode','V1','V2','Mode1', 'Mode2','ID','Adducts','Isotopes','Transformations','Error', 'Count','TransformedMF1', 'TransformedMF2','Plausibility','absPPM', 'Name1','Name2','Size','AverageAddIsoScore','nodes','rtDiff', 'Component','Weight','AIS','Name','Assigned','Intensity','Label','Relative Abundance','m/z','Group','N' -)) \ No newline at end of file +)) diff --git a/R/transformationAssign.R b/R/transformationAssign.R index a694caf..c43d114 100644 --- a/R/transformationAssign.R +++ b/R/transformationAssign.R @@ -86,7 +86,7 @@ setMethod('transformationAssign',signature = 'Assignment', by = c('Measured M' = 'M','Measured m/z' = 'mz')) %>% rowwise() %>% select(Feature,RetentionTime,MF,Isotope,Adduct,`Theoretical M`, - `Measured M`,`Theoretical m/z`,`Measured m/z`, `PPM Error`, + `Measured M`,`Theoretical m/z`,`Measured m/z`, `PPM error`, Score) %>% rowwise() %>% mutate(AddIsoScore = addIsoScore(Adduct, @@ -153,7 +153,7 @@ setMethod('transformationAssign',signature = 'Assignment', 'Size', 'AIS', 'Score', - 'PPM Error'), + 'PPM error'), Direction = c(rep('max',3),rep('min',2))) filteredGraph <- graph From ee73e3e07a0efe7eaf362e57061e24dad1ed9920 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Fri, 18 Feb 2022 16:25:19 +0000 Subject: [PATCH 090/226] replaced max MF score parameter with the MF rank threshold --- NAMESPACE | 5 +- R/parameters.R | 82 +++++++++++++++---------------- man/AssignmentParameters-class.Rd | 12 ++--- man/parameters.Rd | 24 ++++----- tests/testthat/test-parameters.R | 12 ++--- 5 files changed, 67 insertions(+), 68 deletions(-) diff --git a/NAMESPACE b/NAMESPACE index 7e69997..bf68519 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -1,15 +1,16 @@ # Generated by roxygen2: do not edit by hand +export("MFrankThreshold<-") export("adductRules<-") export("adducts<-") export("isotopeRules<-") export("isotopes<-") export("limit<-") export("maxM<-") -export("maxMFscore<-") export("ppm<-") export("transformationRules<-") export("transformations<-") +export(MFrankThreshold) export(adductRules) export(adducts) export(assignMFs) @@ -24,7 +25,6 @@ export(isotopeRules) export(isotopes) export(limit) export(maxM) -export(maxMFscore) export(nodes) export(plan) export(plotAdductDist) @@ -123,7 +123,6 @@ importFrom(metabolyseR,sinfo) importFrom(methods,as) importFrom(methods,new) importFrom(methods,show) -importFrom(mzAnnotation,MFscore) importFrom(mzAnnotation,adduct_rules) importFrom(mzAnnotation,calcM) importFrom(mzAnnotation,ipMF) diff --git a/R/parameters.R b/R/parameters.R index 0ad26cd..2b8ee61 100644 --- a/R/parameters.R +++ b/R/parameters.R @@ -4,18 +4,18 @@ #' @slot technique assignment technique to use #' @slot correlations_parameters list of correlation parameters to be passed to metabolyseR correlation analysis #' @slot filter list of r and n thresholds for filtering correlations -#' @slot maxM maximum M for which to assign molecular formulas -#' @slot maxMFscore threshold for molecular formula score +#' @slot max_M maximum M for which to assign molecular formulas +#' @slot MF_rank_threshold rank threshold for molecular formula selection #' @slot ppm ppm threshold #' #' @slot adducts named list of character vectors containing the adducuts to use for each mode #' @slot limit amu deviation limit for relationship prediction -#' @slot RTwindow retention time window for chromatographic associations +#' @slot RT_window retention time window for chromatographic associations #' @slot adducts list of character vectors containing the adducts to use. List element names should denote ionisation mode. #' @slot isotopes character vector of isotopes to use #' @slot transformations character vector of transformations to use -#' @slot adductRules tibble containing adduct formation rules as returned by mzAnnotation::adducts() -#' @slot isotopeRules tibble containing isotope rules as returned by mzAnnotation::isotopes() -#' @slot transformationRules tibble containing transformation rules as returned by mzAnnotation::transformations() +#' @slot adduct_rules tibble containing adduct formation rules as returned by mzAnnotation::adducts() +#' @slot isotope_rules tibble containing isotope rules as returned by mzAnnotation::isotopes() +#' @slot transformation_rules tibble containing transformation rules as returned by mzAnnotation::transformations() #' @importFrom mzAnnotation adduct_rules isotope_rules transformation_rules #' @export @@ -24,17 +24,17 @@ setClass('AssignmentParameters', technique = 'character', correlations_parameters = 'list', filter = 'list', - maxM = 'numeric', - maxMFscore = 'numeric', + max_M = 'numeric', + MF_rank_threshold = 'numeric', ppm = 'numeric', limit = 'numeric', - RTwindow = 'numeric', + RT_window = 'numeric', adducts = 'list', isotopes = 'character', transformations = 'character', - adductRules = 'tbl_df', - isotopeRules = 'tbl_df', - transformationRules = 'tbl_df' + adduct_rules = 'tbl_df', + isotope_rules = 'tbl_df', + transformation_rules = 'tbl_df' ), prototype = list( technique = 'FIE', @@ -45,20 +45,20 @@ setClass('AssignmentParameters', n = 200000, rIncrement = 0.01, nIncrement = 20000), - maxM = 1000, - maxMFscore = 5, + max_M = 1000, + MF_rank_threshold = 1, ppm = 5, limit = 0.001, - RTwindow = numeric(), + RT_window = numeric(), isotopes = c('13C','18O','13C2'), adducts = list(n = c("[M-H]1-", "[M+Cl]1-", "[M+K-2H]1-", "[M-2H]2-", "[M+Cl37]1-","[2M-H]1-"), p = c('[M+H]1+','[M+K]1+','[M+Na]1+','[M+K41]1+', '[M+NH4]1+','[M+2H]2+','[2M+H]1+')), transformations = transformation_rules()$`MF Change`, - adductRules = adduct_rules(), - isotopeRules = isotope_rules(), - transformationRules = transformation_rules() + adduct_rules = adduct_rules(), + isotope_rules = isotope_rules(), + transformation_rules = transformation_rules() )) # setValidity('AssignmentParameters',function(object){ @@ -83,13 +83,13 @@ setMethod('show',signature = 'AssignmentParameters', cat(yellow('\nAssignment Parameters:'),'\n') cat('\n') cat('\t','Technique:\t\t',object@technique,'\n') - cat('\t','Max M:\t\t\t',object@maxM,'\n') - cat('\t','Max MF score:\t\t',object@maxMFscore,'\n') + cat('\t','Max M:\t\t\t',object@max_M,'\n') + cat('\t','MF rank threshold:\t\t',object@MF_rank_threshold,'\n') cat('\t','PPM threshold:\t\t',object@ppm,'\n') cat('\t','Relationship limit:\t',object@limit,'\n') if (object@technique != 'FIE') { - cat('\t','RT window:\t\t',object@RTwindow,'\n') + cat('\t','RT window:\t\t',object@RT_window,'\n') } cat('\n\t','Adducts:','\n') @@ -131,11 +131,11 @@ setMethod('show',signature = 'AssignmentParameters', #' ## Set max M #' maxM(assignment_parameters) <- 500 #' -#' ## Return max MF score -#' maxMFscore(assignment_parameters) +#' ## Return MF rank threshold +#' MFrankThreshold(assignment_parameters) #' -#' ## Set max MF score -#' maxMFscore(assignment_parameters) <- 3 +#' ## Set MF rank threshold +#' MFrankThreshold(assignment_parameters) <- 3 #' #' ## Return ppm #' ppm(assignment_parameters) @@ -228,7 +228,7 @@ setGeneric('maxM',function(x) setMethod('maxM',signature = 'AssignmentParameters', function(x){ - x@maxM + x@max_M }) #' @rdname parameters @@ -241,34 +241,34 @@ setGeneric('maxM<-',function(x,value) setMethod('maxM<-',signature = 'AssignmentParameters', function(x,value){ - x@maxM <- value + x@max_M <- value return(x) }) #' @rdname parameters #' @export -setGeneric('maxMFscore',function(x) - standardGeneric('maxMFscore')) +setGeneric('MFrankThreshold',function(x) + standardGeneric('MFrankThreshold')) #' @rdname parameters -setMethod('maxMFscore',signature = 'AssignmentParameters', +setMethod('MFrankThreshold',signature = 'AssignmentParameters', function(x){ - x@maxMFscore + x@MF_rank_threshold }) #' @rdname parameters #' @export -setGeneric('maxMFscore<-',function(x,value) - standardGeneric('maxMFscore<-')) +setGeneric('MFrankThreshold<-',function(x,value) + standardGeneric('MFrankThreshold<-')) #' @rdname parameters -setMethod('maxMFscore<-',signature = 'AssignmentParameters', +setMethod('MFrankThreshold<-',signature = 'AssignmentParameters', function(x,value){ - x@maxMFscore <- value + x@MF_rank_threshold <- value return(x) }) @@ -390,7 +390,7 @@ setGeneric('adductRules',function(x) setMethod('adductRules',signature = 'AssignmentParameters', function(x){ - x@adductRules + x@adduct_rules }) #' @rdname parameters @@ -403,7 +403,7 @@ setGeneric('adductRules<-',function(x,value) setMethod('adductRules<-',signature = 'AssignmentParameters', function(x,value){ - x@adductRules <- value + x@adduct_rules <- value return(x) }) @@ -417,7 +417,7 @@ setGeneric('isotopeRules',function(x) setMethod('isotopeRules',signature = 'AssignmentParameters', function(x){ - x@isotopeRules + x@isotope_rules }) #' @rdname parameters @@ -430,7 +430,7 @@ setGeneric('isotopeRules<-',function(x,value) setMethod('isotopeRules<-',signature = 'AssignmentParameters', function(x,value){ - x@isotopeRules <- value + x@isotope_rules <- value return(x) }) @@ -444,7 +444,7 @@ setGeneric('transformationRules',function(x) setMethod('transformationRules',signature = 'AssignmentParameters', function(x){ - x@transformationRules + x@transformation_rules }) #' @rdname parameters @@ -457,7 +457,7 @@ setGeneric('transformationRules<-',function(x,value) setMethod('transformationRules<-',signature = 'AssignmentParameters', function(x,value){ - x@transformationRules <- value + x@transformation_rules <- value return(x) }) diff --git a/man/AssignmentParameters-class.Rd b/man/AssignmentParameters-class.Rd index ee1f808..a93ff82 100644 --- a/man/AssignmentParameters-class.Rd +++ b/man/AssignmentParameters-class.Rd @@ -16,16 +16,16 @@ An S4 class to store assignment parameters. \item{\code{filter}}{list of r and n thresholds for filtering correlations} -\item{\code{maxM}}{maximum M for which to assign molecular formulas} +\item{\code{max_M}}{maximum M for which to assign molecular formulas} -\item{\code{maxMFscore}}{threshold for molecular formula score} +\item{\code{MF_rank_threshold}}{rank threshold for molecular formula selection} \item{\code{ppm}}{ppm threshold #' @slot adducts named list of character vectors containing the adducuts to use for each mode} \item{\code{limit}}{amu deviation limit for relationship prediction} -\item{\code{RTwindow}}{retention time window for chromatographic associations} +\item{\code{RT_window}}{retention time window for chromatographic associations} \item{\code{adducts}}{list of character vectors containing the adducts to use. List element names should denote ionisation mode.} @@ -33,10 +33,10 @@ An S4 class to store assignment parameters. \item{\code{transformations}}{character vector of transformations to use} -\item{\code{adductRules}}{tibble containing adduct formation rules as returned by mzAnnotation::adducts()} +\item{\code{adduct_rules}}{tibble containing adduct formation rules as returned by mzAnnotation::adducts()} -\item{\code{isotopeRules}}{tibble containing isotope rules as returned by mzAnnotation::isotopes()} +\item{\code{isotope_rules}}{tibble containing isotope rules as returned by mzAnnotation::isotopes()} -\item{\code{transformationRules}}{tibble containing transformation rules as returned by mzAnnotation::transformations()} +\item{\code{transformation_rules}}{tibble containing transformation rules as returned by mzAnnotation::transformations()} }} diff --git a/man/parameters.Rd b/man/parameters.Rd index 02d551d..a20aaf0 100644 --- a/man/parameters.Rd +++ b/man/parameters.Rd @@ -11,10 +11,10 @@ \alias{maxM,AssignmentParameters-method} \alias{maxM<-} \alias{maxM<-,AssignmentParameters-method} -\alias{maxMFscore} -\alias{maxMFscore,AssignmentParameters-method} -\alias{maxMFscore<-} -\alias{maxMFscore<-,AssignmentParameters-method} +\alias{MFrankThreshold} +\alias{MFrankThreshold,AssignmentParameters-method} +\alias{MFrankThreshold<-} +\alias{MFrankThreshold<-,AssignmentParameters-method} \alias{ppm} \alias{ppm,AssignmentParameters-method} \alias{ppm<-} @@ -65,13 +65,13 @@ maxM(x) <- value \S4method{maxM}{AssignmentParameters}(x) <- value -maxMFscore(x) +MFrankThreshold(x) -\S4method{maxMFscore}{AssignmentParameters}(x) +\S4method{MFrankThreshold}{AssignmentParameters}(x) -maxMFscore(x) <- value +MFrankThreshold(x) <- value -\S4method{maxMFscore}{AssignmentParameters}(x) <- value +\S4method{MFrankThreshold}{AssignmentParameters}(x) <- value ppm(x) @@ -155,11 +155,11 @@ maxM(assignment_parameters) ## Set max M maxM(assignment_parameters) <- 500 -## Return max MF score -maxMFscore(assignment_parameters) +## Return MF rank threshold +MFrankThreshold(assignment_parameters) -## Set max MF score -maxMFscore(assignment_parameters) <- 3 +## Set MF rank threshold +MFrankThreshold(assignment_parameters) <- 3 ## Return ppm ppm(assignment_parameters) diff --git a/tests/testthat/test-parameters.R b/tests/testthat/test-parameters.R index c3c4699..fc96e87 100644 --- a/tests/testthat/test-parameters.R +++ b/tests/testthat/test-parameters.R @@ -27,15 +27,15 @@ test_that("max M can be set", { expect_identical(maxM(p),new_maxM) }) -test_that("max MF score can be returned", { - expect_type(maxMFscore(p),'double') +test_that("MF rank threshold can be returned", { + expect_type(MFrankThreshold(p),'double') }) -test_that("max MF score can be set", { - new_maxMFscore <- 3 - maxMFscore(p) <- new_maxMFscore +test_that("MF rank threshold can be set", { + new_MFrankThreshold <- 3 + MFrankThreshold(p) <- new_MFrankThreshold - expect_identical(maxMFscore(p),new_maxMFscore) + expect_identical(MFrankThreshold(p),new_MFrankThreshold) }) From 2c914679b604c4164486f38fbeb59ba0a93f50d4 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Mon, 21 Feb 2022 15:41:47 +0000 Subject: [PATCH 091/226] begin fixing addIsoAssign --- R/addIsoAssign.R | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/R/addIsoAssign.R b/R/addIsoAssign.R index 5d07c0a..5c379fc 100644 --- a/R/addIsoAssign.R +++ b/R/addIsoAssign.R @@ -5,7 +5,7 @@ setGeneric("addIsoAssign", function(assignment) #' @importFrom dplyr arrange rowwise slice_sample left_join ungroup #' @importFrom stringr str_detect -#' @importFrom mzAnnotation calcM ipMF MFscore +#' @importFrom mzAnnotation calcM ipMF #' @importFrom igraph vertex.attributes V #' @importFrom furrr furrr_options #' @importFrom methods as @@ -74,16 +74,16 @@ setMethod('addIsoAssign',signature = 'Assignment', by = c('Measured M' = 'M','Measured m/z' = 'mz')) %>% rowwise() %>% select(Feature,RetentionTime,MF,Isotope,Adduct,`Theoretical M`, - `Measured M`,`Theoretical m/z`,`Measured m/z`, `PPM Error`, - Score) %>% + `Measured M`,`Theoretical m/z`,`Measured m/z`, `PPM error`, + `MF Plausability (%)` = `Plausability (%)`) %>% + rowwise() %>% mutate(AddIsoScore = addIsoScore(Adduct, Isotope, adducts(assignment), isotopes(assignment))) %>% ungroup() %>% - filter(Score == min(Score,na.rm = TRUE)) %>% - filter(Score < maxMFscore(assignment)) + filter(`MF Plausability (%)` == max(`MF Plausability (%)`)) } else { return(NULL) } @@ -132,7 +132,7 @@ setMethod('addIsoAssign',signature = 'Assignment', 'Size', 'AIS', 'Score', - 'PPM Error'), + 'PPM error'), Direction = c(rep('max',3),rep('min',2))) filteredGraph <- graph From 26bcf2e854226c389917e988894fa6a7d19af966 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Mon, 21 Feb 2022 15:59:47 +0000 Subject: [PATCH 092/226] Fix RT window parameter for LC methods and rank threshold in AssignmentParameters class show method --- R/parameters.R | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/R/parameters.R b/R/parameters.R index 2b8ee61..8706c8c 100644 --- a/R/parameters.R +++ b/R/parameters.R @@ -84,7 +84,7 @@ setMethod('show',signature = 'AssignmentParameters', cat('\n') cat('\t','Technique:\t\t',object@technique,'\n') cat('\t','Max M:\t\t\t',object@max_M,'\n') - cat('\t','MF rank threshold:\t\t',object@MF_rank_threshold,'\n') + cat('\t','MF rank threshold:\t',object@MF_rank_threshold,'\n') cat('\t','PPM threshold:\t\t',object@ppm,'\n') cat('\t','Relationship limit:\t',object@limit,'\n') @@ -495,14 +495,14 @@ assignmentParameters <- function(technique){ if (technique == 'RP-LC') { p <- new('AssignmentParameters', technique = 'RP-LC', - RTwindow = 1/60 + RT_window = 1/60 ) } if (technique == 'NP-LC') { p <- new('AssignmentParameters', technique = 'NP-LC', - RTwindow = 1/60 + RT_window = 1/60 ) } From f36bd26744a580087fcfeb34111884b2d35f6405 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Mon, 21 Feb 2022 19:25:38 +0000 Subject: [PATCH 093/226] MF rank threshold now used to filter generated MFs --- NAMESPACE | 3 + R/addIsoAssign.R | 141 ++++---------------------- R/assignment.R | 2 +- R/components.R | 59 ++++++++--- R/correlations.R | 2 +- R/internals.R | 208 ++++++++++++++++++++++++++++++++------- R/transformationAssign.R | 156 +++++++---------------------- 7 files changed, 280 insertions(+), 291 deletions(-) diff --git a/NAMESPACE b/NAMESPACE index bf68519..855527f 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -69,6 +69,7 @@ importFrom(dplyr,ungroup) importFrom(dplyr,vars) importFrom(furrr,furrr_options) importFrom(furrr,future_map) +importFrom(furrr,future_map_dfr) importFrom(future,plan) importFrom(ggplot2,aes) importFrom(ggplot2,coord_fixed) @@ -134,6 +135,7 @@ importFrom(parallel,detectCores) importFrom(patchwork,plot_annotation) importFrom(patchwork,plot_layout) importFrom(patchwork,wrap_plots) +importFrom(purrr,flatten_chr) importFrom(purrr,map) importFrom(purrr,map_dbl) importFrom(purrr,map_lgl) @@ -158,6 +160,7 @@ importFrom(tidygraph,morph) importFrom(tidygraph,tbl_graph) importFrom(tidygraph,to_components) importFrom(tidygraph,unmorph) +importFrom(tidyr,expand_grid) importFrom(tidyr,gather) importFrom(tidyr,replace_na) importFrom(utils,capture.output) diff --git a/R/addIsoAssign.R b/R/addIsoAssign.R index 5c379fc..dcbaf8a 100644 --- a/R/addIsoAssign.R +++ b/R/addIsoAssign.R @@ -13,7 +13,7 @@ setGeneric("addIsoAssign", function(assignment) setMethod('addIsoAssign',signature = 'Assignment', function(assignment){ - if (assignment@log$verbose == T) { + if (isTRUE(assignment@log$verbose)) { startTime <- proc.time() message(blue('Adduct & isotope assignment '),cli::symbol$continue,'\r',appendLF = FALSE) } @@ -31,144 +31,45 @@ setMethod('addIsoAssign',signature = 'Assignment', is.na(Isotope2) & Adduct1 == Adduct2)) - M <- bind_rows(select(rel, - mz = `m/z1`, - RetentionTime = RetentionTime1, - Isotope = Isotope1, - Adduct = Adduct1, - Feature = Feature1), - select(rel, - mz = `m/z2`, - RetentionTime = RetentionTime2, - Isotope = Isotope2, - Adduct = Adduct2, - Feature = Feature2)) %>% - filter(!duplicated(.)) %>% - arrange(mz) %>% - rowwise() %>% - mutate(M = calcM(mz, - adduct = Adduct, - isotope = Isotope)) %>% - arrange(M) %>% - filter(M <= maxM(assignment)) + M <- collateM(rel, + maxM(assignment)) - nM <- nrow(M) - - MF <- M %>% - ungroup() %>% - slice_sample(n = nM) %>% - split(1:nrow(.)) %>% - future_map(~{ - mf <- ipMF(mz = .x$mz, - adduct = .x$Adduct, - isotope = .x$Isotope, - ppm = ppm(assignment)) - - if (nrow(mf) > 0) { - mf %>% - left_join(select(M, - Feature, - RetentionTime, - M, - mz), - by = c('Measured M' = 'M','Measured m/z' = 'mz')) %>% - rowwise() %>% - select(Feature,RetentionTime,MF,Isotope,Adduct,`Theoretical M`, - `Measured M`,`Theoretical m/z`,`Measured m/z`, `PPM error`, - `MF Plausability (%)` = `Plausability (%)`) %>% - - rowwise() %>% - mutate(AddIsoScore = addIsoScore(Adduct, - Isotope, - adducts(assignment), - isotopes(assignment))) %>% - ungroup() %>% - filter(`MF Plausability (%)` == max(`MF Plausability (%)`)) - } else { - return(NULL) - } - },.options = furrr_options(seed = 1234)) %>% - bind_rows() + MFs <- generateMFs(M, + ppm(assignment), + MFrankThreshold(assignment), + adducts(assignment), + isotopes(assignment)) - rel <- rel %>% - addMFs(MF) %>% + graph_edges <- rel %>% + addMFs(MFs) %>% filter(MF1 == MF2) %>% mutate(RetentionTime1 = as.numeric(RetentionTime1), RetentionTime2 = as.numeric(RetentionTime2)) %>% addNames() - MFs <- bind_rows(select(rel, - Name = Name1, - Feature = Feature1, - mz = `m/z1`, - RetentionTime = RetentionTime1, - Isotope = Isotope1, - Adduct = Adduct1, - MF = MF1), - select(rel, - Name = Name2, - Feature = Feature2, - mz = `m/z2`, - RetentionTime = RetentionTime2, - Isotope = Isotope2, - Adduct = Adduct2, - MF = MF2)) %>% - mutate(RetentionTime = as.numeric(RetentionTime)) %>% - arrange(mz) %>% - select(-mz) %>% - left_join(MF, by = c("Feature", - "RetentionTime", - "Isotope", - "Adduct", - 'MF')) %>% - distinct() %>% - mutate(ID = 1:nrow(.)) + graph_nodes <- collateMFs(graph_edges,MFs) - graph <- calcComponents(MFs, - rel, - parameters) + graph <- calcComponents(graph_nodes, + graph_edges, + assignment) - filters <- tibble(Measure = c('Plausibility', - 'Size', - 'AIS', - 'Score', - 'PPM error'), - Direction = c(rep('max',3),rep('min',2))) - - filteredGraph <- graph - - for (i in 1:nrow(filters)) { - f <- filters[i,] - filteredGraph <- filteredGraph %>% - activate(nodes) %>% - filter(name %in% {filteredGraph %>% - vertex.attributes() %>% - as_tibble() %>% - eliminate(f$Measure,f$Direction) %>% - .$name}) - if (V(filteredGraph) %>% length() > 0) { - filteredGraph <- filteredGraph %>% - recalcComponents(parameters) - } else { - break() - } - } + filtered_graph <- filterComponents(graph, + assignment) assignment@addIsoAssign <- list( graph = graph, - filteredGraph = filteredGraph, - assigned = filteredGraph %>% - vertex.attributes() %>% - as_tibble() %>% + filtered_graph = filtered_graph, + assigned = filtered_graph %>% + nodes() %>% rename(Name = name) %>% mutate(Mode = str_sub(Feature,1,1)) ) assignment@assignments <- assignment@addIsoAssign$assigned %>% - select(Name:Score,Mode) %>% + select(Name:`MF Plausibility (%)`,Mode) %>% mutate(Iteration = 'A&I') - if (assignment@log$verbose == T) { + if (assignment@log$verbose == TRUE) { endTime <- proc.time() elapsed <- {endTime - startTime} %>% .[3] %>% diff --git a/R/assignment.R b/R/assignment.R index e284971..e3fc706 100644 --- a/R/assignment.R +++ b/R/assignment.R @@ -53,7 +53,7 @@ setMethod('show',signature = 'Assignment', if (length(object@addIsoAssign) > 0) { cat('\t',green('Adduct & isotope assignment:'),'\n') cat('\t\t','MFs:\t\t',length(unique(object@addIsoAssign$assigned$MF)),'\n') - cat('\t\t','Relationships:\t',object@addIsoAssign$filteredGraph %>% E() %>% length(),'\n') + cat('\t\t','Relationships:\t',object@addIsoAssign$filtered_graph %>% E() %>% length(),'\n') cat('\t\t','Assigned:\t',nrow(object@addIsoAssign$assigned),'\n') cat('\n') } diff --git a/R/components.R b/R/components.R index 2860687..900db21 100644 --- a/R/components.R +++ b/R/components.R @@ -4,31 +4,39 @@ degree <- function(n_nodes,n_edges){ } plausibility <- function(AIS,degree,weight){ - AIS + weight + degree/10 + AIS + weight } -componentMetrics <- function(component){ +componentMetrics <- function(component,max_add_iso_total){ component %>% mutate(Size = graph_size(), Nodes = n(), Degree = degree(Nodes,Size),, Density = (2 * Size) / (Nodes * (Nodes - 1)), Weight = sum(Weight) / Nodes, - AIS = sum(AddIsoScore) / Nodes, - Plausibility = plausibility(AIS,Degree,Weight)) + AIS = Size * sum(AddIsoScore) / max_add_iso_total, + `Component Plausibility` = plausibility(AIS,Degree,Weight)) +} + +componentFilters <- function(){ + tibble(Measure = c('Component Plausibility', + 'Degree', + 'AIS', + 'MF Plausibility (%)', + 'PPM error'), + Direction = c(rep('max',4),'min')) } #' @importFrom tidygraph as_tbl_graph activate morph unmorph graph_size group_components tbl_graph #' @importFrom magrittr set_names -calcComponents <- function(MFs,rel,parameters) { - no <- MFs +calcComponents <- function(graph_nodes, + graph_edges, + assignment) { - ed <- rel - - graph <- as_tbl_graph(ed,directed = F) %>% + graph <- as_tbl_graph(graph_edges,directed = FALSE) %>% activate(nodes) %>% - left_join(no,by = c('name' = 'Name')) %>% + left_join(graph_nodes,by = c('name' = 'Name')) %>% mutate(Component = group_components()) comp <- graph %>% @@ -52,7 +60,7 @@ calcComponents <- function(MFs,rel,parameters) { graph <- graph %>% left_join(weights,by = 'Component') %>% morph(to_components) %>% - componentMetrics() %>% + componentMetrics(max_add_iso_total = maxAddIsoScore(assignment)) %>% unmorph() return(graph) @@ -61,7 +69,8 @@ calcComponents <- function(MFs,rel,parameters) { #' @importFrom tidygraph to_components #' @importFrom dplyr n -recalcComponents <- function(graph,parameters){ +recalcComponents <- function(graph, + assignment){ g <- graph %>% activate(nodes) @@ -87,6 +96,30 @@ recalcComponents <- function(graph,parameters){ select(-Weight) %>% left_join(weights,by = 'Component') %>% morph(to_components) %>% - componentMetrics() %>% + componentMetrics(max_add_iso_total = maxAddIsoScore(assignment)) %>% unmorph() +} + +filterComponents <- function(graph, + assignment, + filters = componentFilters()){ + filtered_graph <- graph + + for (i in 1:nrow(filters)) { + f <- filters[i,] + filtered_graph <- filtered_graph %>% + activate(nodes) %>% + filter(name %in% {filtered_graph %>% + nodes() %>% + eliminate(f$Measure,f$Direction) %>% + .$name}) + if (V(filtered_graph) %>% length() > 0) { + filteredGraph <- filtered_graph %>% + recalcComponents(assignment) + } else { + break() + } + } + + return(filtered_graph) } \ No newline at end of file diff --git a/R/correlations.R b/R/correlations.R index b34bd39..4501605 100644 --- a/R/correlations.R +++ b/R/correlations.R @@ -27,7 +27,7 @@ setMethod('calcCorrelations',signature = 'Assignment',function(assignment){ select(-Feature) %>% dist() %>% hclust() %>% - cutree(h = parameters@RTwindow) %>% + cutree(h = parameters@RT_window) %>% {tibble(Feature = names(.),Group = .)} RTsum <- RTgroups %>% diff --git a/R/internals.R b/R/internals.R index 5f0de4f..70318cf 100644 --- a/R/internals.R +++ b/R/internals.R @@ -1,40 +1,14 @@ -#' @importFrom purrr map_lgl - -addIsoScore <- function(add,iso,addRank,isoRank){ - add <- tibble(Adduct = add) - iso <- tibble(Isotope = iso) - iso$Isotope[is.na(iso$Isotope)] <- 'NA' - addRank <- addRank[map_lgl(addRank,~{add %in% .})] %>% - .[[1]] %>% - {tibble(Adduct = ., - Rank = (length(.) - 1):0)} - isoRank <- tibble(Isotope = c('NA',isoRank), Rank = length(isoRank):0) - - add <- left_join(add, addRank,by = 'Adduct') %>% - .$Rank - iso <- left_join(iso, isoRank,by = 'Isotope') %>% - .$Rank - - maxScore <- max(addRank$Rank) + max(isoRank$Rank) - score <- (add + iso)/maxScore - - return(score) -} - #' @importFrom dplyr bind_cols eliminate <- function(MFs,by,direction){ + direct <- get(direction) + MFs %>% bind_cols(MFs %>% select(by = by)) %>% - split(.$Feature) %>% - map(~{ - d <- . - direct <- get(direction) - d %>% - filter(by == direct(by)) - }) %>% - bind_rows() %>% - select(-by) + group_by(Feature) %>% + filter(by == direct(by)) %>% + select(-by) %>% + ungroup() } #' @importFrom dplyr rename @@ -100,4 +74,172 @@ addNames <- function(rel){ bind_cols(iso %>% select(Name1,Name2)) %>% select(Name1,Name2,Feature1:MF2) -} \ No newline at end of file +} + +collateM <- function(rel,max_M){ + bind_rows(select(rel, + mz = `m/z1`, + RetentionTime = RetentionTime1, + Isotope = Isotope1, + Adduct = Adduct1, + Feature = Feature1), + select(rel, + mz = `m/z2`, + RetentionTime = RetentionTime2, + Isotope = Isotope2, + Adduct = Adduct2, + Feature = Feature2)) %>% + distinct() %>% + arrange(mz) %>% + rowwise() %>% + mutate(M = calcM(mz, + adduct = Adduct, + isotope = Isotope)) %>% + arrange(M) %>% + filter(M <= max_M) +} + +collateMFs <- function(rel,MF){ + bind_rows(select(rel, + Name = Name1, + Feature = Feature1, + mz = `m/z1`, + RetentionTime = RetentionTime1, + Isotope = Isotope1, + Adduct = Adduct1, + MF = MF1), + select(rel, + Name = Name2, + Feature = Feature2, + mz = `m/z2`, + RetentionTime = RetentionTime2, + Isotope = Isotope2, + Adduct = Adduct2, + MF = MF2)) %>% + mutate(RetentionTime = as.numeric(RetentionTime)) %>% + arrange(mz) %>% + select(-mz) %>% + left_join(MF, by = c("Feature", + "RetentionTime", + "Isotope", + "Adduct", + 'MF')) %>% + distinct() %>% + mutate(ID = 1:nrow(.)) +} + +#' @importFrom purrr map_lgl + +addIsoScore <- function(add,iso,addRank,isoRank){ + add <- tibble(Adduct = add) + iso <- tibble(Isotope = iso) + iso$Isotope[is.na(iso$Isotope)] <- 'NA' + addRank <- addRank[map_lgl(addRank,~{add %in% .})] %>% + .[[1]] %>% + {tibble(Adduct = ., + Rank = (length(.) - 1):0)} + isoRank <- tibble(Isotope = c('NA',isoRank), Rank = length(isoRank):0) + + add <- left_join(add, addRank,by = 'Adduct') %>% + .$Rank + iso <- left_join(iso, isoRank,by = 'Isotope') %>% + .$Rank + + maxScore <- max(addRank$Rank) + max(isoRank$Rank) + score <- (add + iso)/maxScore + + return(score) +} + +#' @importFrom tidyr expand_grid +#' @importFrom purrr flatten_chr + +maxAddIsoScore <- function(assignment){ + + assignment_adducts <- adducts(assignment) + assignment_isotopes <- isotopes(assignment) + + adduct_scores <- assignment_adducts %>% + map(~tibble(adduct = .) %>% + mutate(adduct_rank = (nrow(.) - 1):0)) %>% + bind_rows(.id = 'mode') + + isotope_scores <- assignment_isotopes %>% + c('NA',.) %>% + tibble(isotope = .) %>% + mutate(isotope_rank = (nrow(.) - 1):0) + + max_total <- assignment_adducts %>% + map_dfr(~tibble(max_total = length(.x) - 1), + .id = 'mode') %>% + mutate(max_total = max_total + + length(assignment_isotopes)) + + add_iso_combs <- expand_grid(adduct = assignment_adducts %>% + flatten_chr(), + isotope = c('NA',assignment_isotopes) + ) + + add_iso_scores <- add_iso_combs %>% + left_join(adduct_scores, + by = "adduct") %>% + left_join(isotope_scores, + by = "isotope") %>% + mutate(total = adduct_rank + + isotope_rank) %>% + left_join(max_total,by = 'mode') %>% + mutate(score = total / max_total) + + max_score <- sum(add_iso_scores$score) + + return(max_score) +} + + +#' @importFrom furrr future_map_dfr + +generateMFs <- function(M, + ppm, + rank_threshold, + adducts, + isotopes){ + nM <- nrow(M) + + M %>% + ungroup() %>% + slice_sample(n = nM) %>% + split(1:nrow(.)) %>% + future_map_dfr(~{ + mf <- ipMF(mz = .x$mz, + adduct = .x$Adduct, + isotope = .x$Isotope, + ppm = ppm) %>% + mutate(Rank = rank(100 - `Plausibility (%)`, + ties.method = 'min')) %>% + filter(Rank <= rank_threshold) + + if (nrow(mf) > 0) { + mf %>% + left_join(select(M, + Feature, + RetentionTime, + M, + mz), + by = c('Measured M' = 'M','Measured m/z' = 'mz')) %>% + rowwise() %>% + select(Feature,RetentionTime,MF,Isotope,Adduct,`Theoretical M`, + `Measured M`,`Theoretical m/z`,`Measured m/z`, `PPM error`, + `MF Plausibility (%)` = `Plausibility (%)`) %>% + + rowwise() %>% + mutate(AddIsoScore = addIsoScore(Adduct, + Isotope, + adducts(assignment), + isotopes(assignment))) %>% + ungroup() + } else { + return(NULL) + } + }, + .options = furrr_options(seed = 1234)) +} diff --git a/R/transformationAssign.R b/R/transformationAssign.R index c43d114..90cc44a 100644 --- a/R/transformationAssign.R +++ b/R/transformationAssign.R @@ -44,67 +44,19 @@ setMethod('transformationAssign',signature = 'Assignment', rel <- bind_rows(mz1,mz2) if (nrow(rel) > 0) { - M <- bind_rows(select(rel, - mz = `m/z1`, - RetentionTime = RetentionTime1, - Isotope = Isotope1, - Adduct = Adduct1, - Feature = Feature1), - select(rel, - mz = `m/z2`, - RetentionTime = RetentionTime2, - Isotope = Isotope2, - Adduct = Adduct2, - Feature = Feature2)) %>% - distinct() %>% - arrange(mz) %>% - rowwise() %>% - mutate(M = calcM(mz,Adduct,Isotope)) %>% - arrange(M) %>% - filter(M <= maxM(assignment)) %>% + M <- collateM(rel, + maxM(assignment))%>% filter(!(mz %in% assigned$`Measured m/z`)) - nM <- nrow(M) - - MF <- M %>% - ungroup() %>% - slice_sample(n = nM) %>% - split(1:nrow(.)) %>% - future_map(~{ - mf <- ipMF(mz = .x$mz, - adduct = .x$Adduct, - isotope = .x$Isotope, - ppm = ppm(assignment)) - - if (nrow(mf) > 0) { - mf %>% - left_join(select(M, - Feature, - RetentionTime, - M, - mz), - by = c('Measured M' = 'M','Measured m/z' = 'mz')) %>% - rowwise() %>% - select(Feature,RetentionTime,MF,Isotope,Adduct,`Theoretical M`, - `Measured M`,`Theoretical m/z`,`Measured m/z`, `PPM error`, - Score) %>% - rowwise() %>% - mutate(AddIsoScore = addIsoScore(Adduct, - Isotope, - adducts(assignment), - isotopes(assignment))) %>% - ungroup() %>% - filter(Score == min(Score,na.rm = TRUE)) %>% - filter(Score < maxMFscore(assignment)) - } else { - return(NULL) - } - },.options = furrr_options(seed = 1234)) %>% - bind_rows() + MFs <- generateMFs(M, + ppm(assignment), + MFrankThreshold(assignment), + adducts(assignment), + isotopes(assignment)) if (nrow(MF) > 0) { - MF <- MF %>% + MFs <- MFs %>% bind_rows(assigned %>% select(names(MF)[!(names(MF) == 'AddIsoScore')]) %>% rowwise() %>% @@ -112,102 +64,60 @@ setMethod('transformationAssign',signature = 'Assignment', Isotope, adducts(assignment), isotopes(assignment)))) - rel <- rel %>% + graph_edges <- rel %>% addMFs(MF,identMF = F) %>% mutate(RetentionTime1 = as.numeric(RetentionTime1), RetentionTime2 = as.numeric(RetentionTime2)) %>% addNames() - if (nrow(rel) > 0) { - MFs <- bind_rows(select(rel, - Name = Name1, - Feature = Feature1, - mz = `m/z1`, - RetentionTime = RetentionTime1, - Isotope = Isotope1, - Adduct = Adduct1, - MF = MF1), - select(rel, - Name = Name2, - Feature = Feature2, - mz = `m/z2`, - RetentionTime = RetentionTime2, - Isotope = Isotope2, - Adduct = Adduct2, - MF = MF2)) %>% - mutate(RetentionTime = as.numeric(RetentionTime)) %>% - arrange(mz) %>% - select(-mz) %>% - left_join(MF, - by = c("Feature", - "RetentionTime", - "Isotope", - "Adduct", - 'MF')) %>% - distinct() %>% - mutate(ID = 1:nrow(.)) + if (nrow(graph_edges) > 0) { + graph_nodes <- collateMFs(rel, + MF) - graph <- calcComponents(MFs,rel,assignment) + graph <- calcComponents(graph_nodes, + graph_edges, + assignment) - filters <- tibble(Measure = c('Plausibility', - 'Size', - 'AIS', - 'Score', - 'PPM error'), - Direction = c(rep('max',3),rep('min',2))) + filtered_graph <- filterComponents(graph, + assignment) - filteredGraph <- graph - - for (i in 1:nrow(filters)) { - f <- filters[i,] - filteredGraph <- filteredGraph %>% - activate(nodes) %>% - filter(name %in% {filteredGraph %>% - vertex.attributes() %>% - as_tibble() %>% - eliminate(f$Measure,f$Direction) %>% - .$name}) - if (V(filteredGraph) %>% length() > 0) { - filteredGraph <- filteredGraph %>% - recalcComponents(assignment) - } else { - break() - } - } - - newlyAssigned <- filteredGraph %>% - vertex.attributes() %>% - as_tibble() %>% + newly_assigned <- filtered_graph %>% + nodes() %>% rename(Name = name) %>% mutate(Mode = str_sub(Feature,1,1)) %>% filter(!(Name %in% assigned$Name)) %>% - select(Name:Score,Mode) %>% + select(Name:`MF Plausibility (%)`,Mode) %>% mutate(Iteration = str_c('T',count + 1)) outputs <- list( graph = graph, - filteredGraph = filteredGraph, - assigned = newlyAssigned) + filtered_graph = filtered_graph, + assigned = newly_assigned) - assignment@assignments <- bind_rows(assignment@assignments,newlyAssigned) + assignment@assignments <- bind_rows(assignment@assignments, + newly_assigned) if (count == 0) { assignment@transAssign <- list(`1` = outputs) } else { - assignment@transAssign <- c(assignment@transAssign,list(outputs)) + assignment@transAssign <- c(assignment@transAssign, + list(outputs)) } } else { - assignment@transAssign <- c(assignment@transAssign,list(list())) + assignment@transAssign <- c(assignment@transAssign, + list(list())) } } else { - assignment@transAssign <- c(assignment@transAssign,list(list())) + assignment@transAssign <- c(assignment@transAssign, + list(list())) } } else { - assignment@transAssign <- c(assignment@transAssign,list(list())) + assignment@transAssign <- c(assignment@transAssign, + list(list())) } names(assignment@transAssign)[count + 1] <- count + 1 - if (assignment@log$verbose == T) { + if (assignment@log$verbose == TRUE) { endTime <- proc.time() elapsed <- {endTime - startTime} %>% .[3] %>% From beb4df17bd84fc01bbe1f00613f770fa4b100241 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Mon, 21 Feb 2022 19:30:58 +0000 Subject: [PATCH 094/226] fixed plotFeatureSolutions --- R/plotFeatureSolutions.R | 10 +++++----- R/plotNetwork.R | 4 ++-- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/R/plotFeatureSolutions.R b/R/plotFeatureSolutions.R index 473ac82..c97025b 100644 --- a/R/plotFeatureSolutions.R +++ b/R/plotFeatureSolutions.R @@ -6,7 +6,7 @@ plotSolutions <- function(graph,selectedComp,feature){ graph %>% map(~{ stats <- nodes(.) %>% - select(Component:Plausibility) %>% + select(Component:`Component Plausibility`) %>% .[1,] if (stats$Component[1] == selectedComp){ @@ -36,7 +36,7 @@ plotSolutions <- function(graph,selectedComp,feature){ caption = str_c('Degree = ',stats$Degree %>% round(2),'; ', 'Weight = ',stats$Weight %>% round(2),'; ', 'AIS = ',stats$AIS %>% round(2),'; ', - 'Plausibility = ',stats$Plausibility %>% round(2))) + + 'Plausibility = ',stats$`Component Plausibility` %>% round(2))) + xlim(min(g$x) - (max(g$x) - min(g$x)) * 0.05, max(g$x) + (max(g$x) - min(g$x)) * 0.05) + ylim(min(g$y) - (max(g$y) - min(g$y)) * 0.05, @@ -78,7 +78,7 @@ setMethod('plotFeatureSolutions',signature = 'Assignment', comp <- n %>% filter(Feature == feature) %>% - select(Component,Plausibility) %>% + select(Component,`Component Plausibility`) %>% distinct() %>% arrange(Component) @@ -95,7 +95,7 @@ setMethod('plotFeatureSolutions',signature = 'Assignment', }) comp <- comp %>% - arrange(desc(Plausibility)) %>% + arrange(desc(`Component Plausibility`)) %>% .$Component graph <- graph %>% @@ -106,7 +106,7 @@ setMethod('plotFeatureSolutions',signature = 'Assignment', graph <- graph[1:maxComponents] } - selectedComp <- assignment@addIsoAssign$filteredGraph %>% + selectedComp <- assignment@addIsoAssign$filtered_graph %>% nodes() %>% select(Feature,Component) %>% filter(Feature == feature) %>% diff --git a/R/plotNetwork.R b/R/plotNetwork.R index 8810ca2..ab33074 100644 --- a/R/plotNetwork.R +++ b/R/plotNetwork.R @@ -49,7 +49,7 @@ setGeneric('plotNetwork',function(assignment, layout = 'stress', rThreshold = 0. setMethod('plotNetwork',signature = 'Assignment', function(assignment, layout = 'stress', rThreshold = 0.7){ - AI <- assignment@addIsoAssign$filteredGraph + AI <- assignment@addIsoAssign$filtered_graph TA <- assignment@transAssign %>% map(~{.$filteredGraph}) @@ -71,7 +71,7 @@ setMethod('plotNetwork',signature = 'Assignment', e <- edges(graph) %>% mutate(Explained = 'Explained') n <- nodes(graph) %>% - select(name:Score) %>% + select(name:`MF Plausibility (%)`) %>% distinct() %>% mutate(Assigned = 'Assigned') From 9e05af5e2944fdc7533876e0911dfee6831d2fb5 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Tue, 22 Feb 2022 10:40:01 +0000 Subject: [PATCH 095/226] test fixes --- R/internals.R | 8 ++++---- R/plotNetwork.R | 2 +- R/transformationAssign.R | 9 ++++----- 3 files changed, 9 insertions(+), 10 deletions(-) diff --git a/R/internals.R b/R/internals.R index 70318cf..c074d4f 100644 --- a/R/internals.R +++ b/R/internals.R @@ -201,8 +201,8 @@ maxAddIsoScore <- function(assignment){ generateMFs <- function(M, ppm, rank_threshold, - adducts, - isotopes){ + assignment_adducts, + assignment_isotopes){ nM <- nrow(M) M %>% @@ -234,8 +234,8 @@ generateMFs <- function(M, rowwise() %>% mutate(AddIsoScore = addIsoScore(Adduct, Isotope, - adducts(assignment), - isotopes(assignment))) %>% + assignment_adducts, + assignment_isotopes)) %>% ungroup() } else { return(NULL) diff --git a/R/plotNetwork.R b/R/plotNetwork.R index ab33074..139fda9 100644 --- a/R/plotNetwork.R +++ b/R/plotNetwork.R @@ -51,7 +51,7 @@ setMethod('plotNetwork',signature = 'Assignment', AI <- assignment@addIsoAssign$filtered_graph TA <- assignment@transAssign %>% - map(~{.$filteredGraph}) + map(~{.$filtered_graph}) if (length(TA) > 0){ if (length(TA) > 1) { diff --git a/R/transformationAssign.R b/R/transformationAssign.R index 90cc44a..9fdc247 100644 --- a/R/transformationAssign.R +++ b/R/transformationAssign.R @@ -54,25 +54,24 @@ setMethod('transformationAssign',signature = 'Assignment', adducts(assignment), isotopes(assignment)) - if (nrow(MF) > 0) { + if (nrow(MFs) > 0) { MFs <- MFs %>% bind_rows(assigned %>% - select(names(MF)[!(names(MF) == 'AddIsoScore')]) %>% + select(names(MFs)[!(names(MFs) == 'AddIsoScore')]) %>% rowwise() %>% mutate(AddIsoScore = addIsoScore(Adduct, Isotope, adducts(assignment), isotopes(assignment)))) graph_edges <- rel %>% - addMFs(MF,identMF = F) %>% + addMFs(MFs,identMF = F) %>% mutate(RetentionTime1 = as.numeric(RetentionTime1), RetentionTime2 = as.numeric(RetentionTime2)) %>% addNames() if (nrow(graph_edges) > 0) { - graph_nodes <- collateMFs(rel, - MF) + graph_nodes <- collateMFs(graph_edges,MFs) graph <- calcComponents(graph_nodes, graph_edges, From 7a8b3f8ff877cd5b4e7b06cc1c5b80b42753abbb Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Tue, 22 Feb 2022 14:41:45 +0000 Subject: [PATCH 096/226] function import fix --- NAMESPACE | 1 + R/internals.R | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/NAMESPACE b/NAMESPACE index 855527f..8fa0b58 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -138,6 +138,7 @@ importFrom(patchwork,wrap_plots) importFrom(purrr,flatten_chr) importFrom(purrr,map) importFrom(purrr,map_dbl) +importFrom(purrr,map_dfr) importFrom(purrr,map_lgl) importFrom(stats,cutree) importFrom(stats,dist) diff --git a/R/internals.R b/R/internals.R index c074d4f..26ecf64 100644 --- a/R/internals.R +++ b/R/internals.R @@ -152,7 +152,7 @@ addIsoScore <- function(add,iso,addRank,isoRank){ } #' @importFrom tidyr expand_grid -#' @importFrom purrr flatten_chr +#' @importFrom purrr flatten_chr map_dfr maxAddIsoScore <- function(assignment){ From de74ebb9207a537c7ca94a02affe8d6b85fe94f1 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Tue, 22 Feb 2022 14:42:04 +0000 Subject: [PATCH 097/226] documentation fixes --- R/assign.R | 4 +++- R/parameters.R | 6 +++--- man/assign.Rd | 7 ++++++- man/parameters.Rd | 6 +++--- 4 files changed, 15 insertions(+), 8 deletions(-) diff --git a/R/assign.R b/R/assign.R index b305397..b2826db 100644 --- a/R/assign.R +++ b/R/assign.R @@ -37,6 +37,7 @@ setMethod('doAssignment',signature = 'Assignment', #' @rdname assign #' @description assign molecular formulas to a set of given m/z. #' @param dat tibble containing the peak intensities of m/z for which to assign molecular formulas +#' @param assignment an S4 object of class `Assignment` #' @param parameters an S4 object of class AssignmentParamters containing the parameters for molecular formula assignment #' @param verbose should output be printed to the console #' @importFrom tibble tibble @@ -48,7 +49,7 @@ setMethod('doAssignment',signature = 'Assignment', #' plan(future::sequential) #' p <- assignmentParameters('FIE') #' -#' assignment <- assignMFs(peakData,p) +#' assignment <- assignMFs(feature_data,p) #' #' @export @@ -101,6 +102,7 @@ setGeneric('continueAssignment',function(assignment) standardGeneric('continueAssignment') ) +#' @rdname assign setMethod('continueAssignment',signature = 'Assignment', function(assignment){ diff --git a/R/parameters.R b/R/parameters.R index 8706c8c..8034ac3 100644 --- a/R/parameters.R +++ b/R/parameters.R @@ -166,19 +166,19 @@ setMethod('show',signature = 'AssignmentParameters', #' adductRules(assignment_parameters) #' #' ## Set adduct rules -#' adductRules(assignment_parameters) <- mzAnnotation::adduct_rules()) +#' adductRules(assignment_parameters) <- mzAnnotation::adduct_rules() #' #' ## Return isotope rules #' isotopeRules(assignment_parameters) #' #' ## Set isotope rules -#' isotopeRules(assignment_parameters) <- mzAnnotation::isotope_rules()) +#' isotopeRules(assignment_parameters) <- mzAnnotation::isotope_rules() #' #' ## Return transformation rules #' transformationRules(assignment_parameters) #' #' ## Set transformation rules -#' transformationRules(assignment_parameters) <- mzAnnotation::transformation_rules()) +#' transformationRules(assignment_parameters) <- mzAnnotation::transformation_rules() #' @export setGeneric('technique',function(x) diff --git a/man/assign.Rd b/man/assign.Rd index e745b8e..ae2d2a6 100644 --- a/man/assign.Rd +++ b/man/assign.Rd @@ -3,11 +3,14 @@ \name{assignMFs} \alias{assignMFs} \alias{continueAssignment} +\alias{continueAssignment,Assignment-method} \title{Assign molecular formulas} \usage{ assignMFs(dat, parameters, verbose = TRUE) continueAssignment(assignment) + +\S4method{continueAssignment}{Assignment}(assignment) } \arguments{ \item{dat}{tibble containing the peak intensities of m/z for which to assign molecular formulas} @@ -15,6 +18,8 @@ continueAssignment(assignment) \item{parameters}{an S4 object of class AssignmentParamters containing the parameters for molecular formula assignment} \item{verbose}{should output be printed to the console} + +\item{assignment}{an S4 object of class \code{Assignment}} } \description{ assign molecular formulas to a set of given m/z. @@ -23,6 +28,6 @@ assign molecular formulas to a set of given m/z. plan(future::sequential) p <- assignmentParameters('FIE') -assignment <- assignMFs(peakData,p) +assignment <- assignMFs(feature_data,p) } diff --git a/man/parameters.Rd b/man/parameters.Rd index a20aaf0..a7dc180 100644 --- a/man/parameters.Rd +++ b/man/parameters.Rd @@ -190,17 +190,17 @@ transformations(assignment_parameters) <- "M - [O] + [NH2]" adductRules(assignment_parameters) ## Set adduct rules -adductRules(assignment_parameters) <- mzAnnotation::adduct_rules()) +adductRules(assignment_parameters) <- mzAnnotation::adduct_rules() ## Return isotope rules isotopeRules(assignment_parameters) ## Set isotope rules -isotopeRules(assignment_parameters) <- mzAnnotation::isotope_rules()) +isotopeRules(assignment_parameters) <- mzAnnotation::isotope_rules() ## Return transformation rules transformationRules(assignment_parameters) ## Set transformation rules -transformationRules(assignment_parameters) <- mzAnnotation::transformation_rules()) +transformationRules(assignment_parameters) <- mzAnnotation::transformation_rules() } From 9cfbc10044fb5beaa450f0afa63ebc5ee5699c2b Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Tue, 22 Feb 2022 14:46:45 +0000 Subject: [PATCH 098/226] check fixes --- R/MFassign.R | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/R/MFassign.R b/R/MFassign.R index aa3837f..555c7f4 100644 --- a/R/MFassign.R +++ b/R/MFassign.R @@ -10,5 +10,7 @@ globalVariables(c( 'Mode2','ID','Adducts','Isotopes','Transformations','Error', 'Count','TransformedMF1', 'TransformedMF2','Plausibility','absPPM', 'Name1','Name2','Size','AverageAddIsoScore','nodes','rtDiff', - 'Component','Weight','AIS','Name','Assigned','Intensity','Label','Relative Abundance','m/z','Group','N' + 'Component','Weight','AIS','Name','Assigned','Intensity','Label', + 'Relative Abundance','m/z','Group','N','M','adduct_rank','isotope_rank', + 'total','MF Plausibility (%)','Component Plausibility' )) From 9b40a10c44600d685691de9e20558afc63e75582 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Thu, 3 Mar 2022 16:05:20 +0000 Subject: [PATCH 099/226] digits option now set to 10 if below 10 upon package load --- DESCRIPTION | 1 + R/zzz.R | 5 +++++ 2 files changed, 6 insertions(+) create mode 100644 R/zzz.R diff --git a/DESCRIPTION b/DESCRIPTION index 1faf239..5b52b1c 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -38,6 +38,7 @@ Collate: parameters.R assignment.R correlations.R feature_data.R LCassignment.R MFassign.R FIEassignment.R plotNetwork.R plotAdductDist.R plotFeatureSolutions.R plotSpectrum.R reexports.R + zzz.R Suggests: testthat, covr Remotes: jasenfinch/mzAnnotation@tmp, diff --git a/R/zzz.R b/R/zzz.R new file mode 100644 index 0000000..130e16e --- /dev/null +++ b/R/zzz.R @@ -0,0 +1,5 @@ +.onLoad <- function(libname, pkgname) { + if (options()$digits < 10) options(digits = 10) + + invisible() +} \ No newline at end of file From fab0bbfb1b2fb24b0d064941b76cb438f47211c2 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Thu, 3 Mar 2022 16:40:06 +0000 Subject: [PATCH 100/226] added unit tests for package onLoad --- R/zzz.R | 2 +- tests/testthat/test-onload.R | 15 +++++++++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) create mode 100644 tests/testthat/test-onload.R diff --git a/R/zzz.R b/R/zzz.R index 130e16e..606e9fc 100644 --- a/R/zzz.R +++ b/R/zzz.R @@ -1,5 +1,5 @@ .onLoad <- function(libname, pkgname) { - if (options()$digits < 10) options(digits = 10) + if (getOption('digits') < 10) options(digits = 10) invisible() } \ No newline at end of file diff --git a/tests/testthat/test-onload.R b/tests/testthat/test-onload.R new file mode 100644 index 0000000..8021614 --- /dev/null +++ b/tests/testthat/test-onload.R @@ -0,0 +1,15 @@ +test_that("Digits correctly set upon package load", { + options('digits' = 7) + + MFassign:::.onLoad() + + expect_equal(getOption('digits'),10) +}) + +test_that('Digits not set upon package load if already above 10', { + options('digits' = 11) + + MFassign:::.onLoad() + + expect_equal(getOption('digits'),11) +}) From 7e57ff43e2954b033888a6373dd8a82e46e7ff3a Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Thu, 3 Mar 2022 16:40:30 +0000 Subject: [PATCH 101/226] added assignMF methods for AnalysisData and Analysis classes from metabolyseR --- NAMESPACE | 2 + R/assign.R | 63 ++++++++++++++++++++++++++++---- man/assign.Rd | 44 +++++++++++++++++++--- tests/testthat/test-assignment.R | 25 +++++++++---- 4 files changed, 113 insertions(+), 21 deletions(-) diff --git a/NAMESPACE b/NAMESPACE index 855527f..9148261 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -120,6 +120,8 @@ importFrom(metabolyseR,analysisResults) importFrom(metabolyseR,dat) importFrom(metabolyseR,keepFeatures) importFrom(metabolyseR,metabolyse) +importFrom(metabolyseR,preTreated) +importFrom(metabolyseR,raw) importFrom(metabolyseR,sinfo) importFrom(methods,as) importFrom(methods,new) diff --git a/R/assign.R b/R/assign.R index b305397..7b91d68 100644 --- a/R/assign.R +++ b/R/assign.R @@ -36,9 +36,13 @@ setMethod('doAssignment',signature = 'Assignment', #' Assign molecular formulas #' @rdname assign #' @description assign molecular formulas to a set of given m/z. -#' @param dat tibble containing the peak intensities of m/z for which to assign molecular formulas -#' @param parameters an S4 object of class AssignmentParamters containing the parameters for molecular formula assignment -#' @param verbose should output be printed to the console +#' @param feature_data a tibble or an object of S4 class `AnalysisData` or `Analysis` containing the feature intensity matrix of m/z for which to assign molecular formulas. See details. +#' @param parameters an S4 object of class `AssignmentParamters` containing the parameters for molecular formula assignment +#' @param verbose should progress output be printed to the console +#' @param type `raw` or `pre-treated` data on which to perform assignment when argument `feature_data` is of class `Analysis` +#' @param ... arguments to pass to the relevant method +#' @details +#' If argument `feature_data` is specified as a tibble, this should be a feature intensity matrix where the columns are the `m/z` features to assign and the rows are the individual observations, with the cells as abundance values. #' @importFrom tibble tibble #' @importFrom stringr str_split_fixed #' @importFrom cli console_width @@ -48,12 +52,23 @@ setMethod('doAssignment',signature = 'Assignment', #' plan(future::sequential) #' p <- assignmentParameters('FIE') #' -#' assignment <- assignMFs(peakData,p) +#' assignment <- assignMFs(feature_data,p) #' #' @export -assignMFs <- function(dat,parameters,verbose = TRUE) { - options(digits = 10) +setGeneric('assignMFs',function(feature_data, + parameters = assignmentParameters('FIE'), + verbose = TRUE, + ...) + standardGeneric('assignMFs') +) + +#' @rdname assign + +setMethod('assignMFs',signature = 'tbl_df', + function(feature_data, + parameters = assignmentParameters('FIE'), + verbose = TRUE) { if (verbose == TRUE) { startTime <- proc.time() @@ -74,7 +89,7 @@ assignMFs <- function(dat,parameters,verbose = TRUE) { assignment <- new('Assignment', parameters, - data = dat) + data = feature_data) assignment@log$verbose <- verbose assignment <- assignment %>% @@ -92,7 +107,39 @@ assignMFs <- function(dat,parameters,verbose = TRUE) { } return(assignment) -} +}) + +#' @rdname assign + +setMethod('assignMFs',signature = 'AnalysisData', + function(feature_data, + parameters = assignmentParameters('FIE'), + verbose = TRUE){ + feature_data %>% + dat() %>% + assignMFs(parameters = parameters, + verbose = verbose) + }) + +#' @rdname assign +#' @importFrom metabolyseR raw preTreated + +setMethod('assignMFs',signature = 'Analysis', + function(feature_data, + parameters = assignmentParameters('FIE'), + verbose = TRUE, + type = c('raw','pre-treated')){ + + type <- match.arg(type, + choices = c('raw','pre-treated')) + + if (type == 'raw') feature_data <- raw(feature_data) + if (type == 'pre-treated') feature_data <- preTreated(feature_data) + + feature_data %>% + assignMFs(parameters = parameters, + verbose = verbose) + }) #' @rdname assign #' @export diff --git a/man/assign.Rd b/man/assign.Rd index e745b8e..6673c0e 100644 --- a/man/assign.Rd +++ b/man/assign.Rd @@ -2,27 +2,61 @@ % Please edit documentation in R/assign.R \name{assignMFs} \alias{assignMFs} +\alias{assignMFs,tbl_df-method} +\alias{assignMFs,AnalysisData-method} +\alias{assignMFs,Analysis-method} \alias{continueAssignment} \title{Assign molecular formulas} \usage{ -assignMFs(dat, parameters, verbose = TRUE) +assignMFs( + feature_data, + parameters = assignmentParameters("FIE"), + verbose = TRUE, + ... +) + +\S4method{assignMFs}{tbl_df}( + feature_data, + parameters = assignmentParameters("FIE"), + verbose = TRUE +) + +\S4method{assignMFs}{AnalysisData}( + feature_data, + parameters = assignmentParameters("FIE"), + verbose = TRUE +) + +\S4method{assignMFs}{Analysis}( + feature_data, + parameters = assignmentParameters("FIE"), + verbose = TRUE, + type = c("raw", "pre-treated") +) continueAssignment(assignment) } \arguments{ -\item{dat}{tibble containing the peak intensities of m/z for which to assign molecular formulas} +\item{feature_data}{a tibble or an object of S4 class \code{AnalysisData} or \code{Analysis} containing the feature intensity matrix of m/z for which to assign molecular formulas. See details.} -\item{parameters}{an S4 object of class AssignmentParamters containing the parameters for molecular formula assignment} +\item{parameters}{an S4 object of class \code{AssignmentParamters} containing the parameters for molecular formula assignment} -\item{verbose}{should output be printed to the console} +\item{verbose}{should progress output be printed to the console} + +\item{...}{arguments to pass to the relevant method} + +\item{type}{\code{raw} or \code{pre-treated} data on which to perform assignment when argument \code{feature_data} is of class \code{Analysis}} } \description{ assign molecular formulas to a set of given m/z. } +\details{ +If argument \code{feature_data} is specified as a tibble, this should be a feature intensity matrix where the columns are the \code{m/z} features to assign and the rows are the individual observations, with the cells as abundance values. +} \examples{ plan(future::sequential) p <- assignmentParameters('FIE') -assignment <- assignMFs(peakData,p) +assignment <- assignMFs(feature_data,p) } diff --git a/tests/testthat/test-assignment.R b/tests/testthat/test-assignment.R index 243150c..691ca7c 100644 --- a/tests/testthat/test-assignment.R +++ b/tests/testthat/test-assignment.R @@ -2,16 +2,25 @@ assignment_parameters_FIE <- assignmentParameters('FIE') assignment_parameters_LC <- assignmentParameters('RP-LC') -LC_features <- feature_data -colnames(LC_features) <- str_c(colnames(LC_features),'@1.00') +LC_features <- new('Analysis') +metabolyseR::raw(LC_features) <- metabolyseR::analysisData( + feature_data %>% + {magrittr::set_colnames(., + paste0(colnames(.), + '@1.00'))}, + info = tibble::tibble( + ID = feature_data %>% + nrow() %>% + seq_len())) + assignment_FIE <- assignMFs(feature_data, - assignment_parameters_FIE, - verbose = TRUE) + assignment_parameters_FIE, + verbose = TRUE) assignment_LC <- assignMFs(LC_features, - assignment_parameters_LC, - verbose = TRUE) + assignment_parameters_LC, + verbose = TRUE) test_that('assignment works for FIE technique',{ expect_s4_class(assignment_FIE,"Assignment") @@ -47,12 +56,12 @@ test_that('feature solutions can be plotted',{ test_that('feature solutions plotting throws an error if an incorrect feature is provided',{ expect_error(plotFeatureSolutions(assignment_FIE, - 'test')) + 'test')) }) test_that('assignment network can be plotted',{ pl <- plotNetwork(assignment_FIE) - + expect_s3_class(pl,'ggraph') }) From 4675e5a7a0c1446a1d789a8edfb5dccd03a4ca94 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Thu, 3 Mar 2022 16:46:41 +0000 Subject: [PATCH 102/226] removed continueAssignment() --- NAMESPACE | 2 +- R/assign.R | 13 ------------- man/assign.Rd | 3 --- 3 files changed, 1 insertion(+), 17 deletions(-) diff --git a/NAMESPACE b/NAMESPACE index 9148261..29696e2 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -19,7 +19,6 @@ export(assignmentData) export(assignmentParameters) export(assignments) export(availableTechniques) -export(continueAssignment) export(edges) export(isotopeRules) export(isotopes) @@ -140,6 +139,7 @@ importFrom(patchwork,wrap_plots) importFrom(purrr,flatten_chr) importFrom(purrr,map) importFrom(purrr,map_dbl) +importFrom(purrr,map_dfr) importFrom(purrr,map_lgl) importFrom(stats,cutree) importFrom(stats,dist) diff --git a/R/assign.R b/R/assign.R index 7b91d68..2d819a4 100644 --- a/R/assign.R +++ b/R/assign.R @@ -140,16 +140,3 @@ setMethod('assignMFs',signature = 'Analysis', assignMFs(parameters = parameters, verbose = verbose) }) - -#' @rdname assign -#' @export - -setGeneric('continueAssignment',function(assignment) - standardGeneric('continueAssignment') -) - - -setMethod('continueAssignment',signature = 'Assignment', - function(assignment){ - doAssignment(assignment) - }) \ No newline at end of file diff --git a/man/assign.Rd b/man/assign.Rd index 6673c0e..569a0b8 100644 --- a/man/assign.Rd +++ b/man/assign.Rd @@ -5,7 +5,6 @@ \alias{assignMFs,tbl_df-method} \alias{assignMFs,AnalysisData-method} \alias{assignMFs,Analysis-method} -\alias{continueAssignment} \title{Assign molecular formulas} \usage{ assignMFs( @@ -33,8 +32,6 @@ assignMFs( verbose = TRUE, type = c("raw", "pre-treated") ) - -continueAssignment(assignment) } \arguments{ \item{feature_data}{a tibble or an object of S4 class \code{AnalysisData} or \code{Analysis} containing the feature intensity matrix of m/z for which to assign molecular formulas. See details.} From beab373bf0e80bf11efd54b618f2df821dd92741 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Thu, 3 Mar 2022 16:51:18 +0000 Subject: [PATCH 103/226] check fixes --- R/MFassign.R | 8 +++++--- R/internals.R | 2 +- R/parameters.R | 6 +++--- man/parameters.Rd | 6 +++--- 4 files changed, 12 insertions(+), 10 deletions(-) diff --git a/R/MFassign.R b/R/MFassign.R index aa3837f..e7c30c3 100644 --- a/R/MFassign.R +++ b/R/MFassign.R @@ -2,13 +2,15 @@ globalVariables(c( 'Mass','.','Feature1','Feature2','Feature','Isotope','Adduct', 'Measured m/z','Isotope1','Adduct1','Isotope2','Adduct2','MF1', - 'MF2','Nodes','AddIsoScore','RetentionTime','Score','r','EdgeWeight1', + 'MF2','Nodes','AddIsoScore','RetentionTime','MF Plausibility (%)','r','EdgeWeight1', 'EdgeWeight2','Degree','Measured M','Cluster', 'Average AddIsoScore', 'Transformation1','Transformation2','log2IntensityRatio','m/z1', 'm/z2','RetentionTime1','RetentionTime2','mz','Theoretical M', 'Theoretical m/z','PPM error','name','Mode','V1','V2','Mode1', 'Mode2','ID','Adducts','Isotopes','Transformations','Error', - 'Count','TransformedMF1', 'TransformedMF2','Plausibility','absPPM', + 'Count','TransformedMF1', 'TransformedMF2','Component Plausibility','absPPM', 'Name1','Name2','Size','AverageAddIsoScore','nodes','rtDiff', - 'Component','Weight','AIS','Name','Assigned','Intensity','Label','Relative Abundance','m/z','Group','N' + 'Component','Weight','AIS','Name','Assigned','Intensity','Label', + 'Relative Abundance','m/z','Group','N','adduct_rank','isotope_rank', + 'M','total' )) diff --git a/R/internals.R b/R/internals.R index c074d4f..26ecf64 100644 --- a/R/internals.R +++ b/R/internals.R @@ -152,7 +152,7 @@ addIsoScore <- function(add,iso,addRank,isoRank){ } #' @importFrom tidyr expand_grid -#' @importFrom purrr flatten_chr +#' @importFrom purrr flatten_chr map_dfr maxAddIsoScore <- function(assignment){ diff --git a/R/parameters.R b/R/parameters.R index 8706c8c..8034ac3 100644 --- a/R/parameters.R +++ b/R/parameters.R @@ -166,19 +166,19 @@ setMethod('show',signature = 'AssignmentParameters', #' adductRules(assignment_parameters) #' #' ## Set adduct rules -#' adductRules(assignment_parameters) <- mzAnnotation::adduct_rules()) +#' adductRules(assignment_parameters) <- mzAnnotation::adduct_rules() #' #' ## Return isotope rules #' isotopeRules(assignment_parameters) #' #' ## Set isotope rules -#' isotopeRules(assignment_parameters) <- mzAnnotation::isotope_rules()) +#' isotopeRules(assignment_parameters) <- mzAnnotation::isotope_rules() #' #' ## Return transformation rules #' transformationRules(assignment_parameters) #' #' ## Set transformation rules -#' transformationRules(assignment_parameters) <- mzAnnotation::transformation_rules()) +#' transformationRules(assignment_parameters) <- mzAnnotation::transformation_rules() #' @export setGeneric('technique',function(x) diff --git a/man/parameters.Rd b/man/parameters.Rd index a20aaf0..a7dc180 100644 --- a/man/parameters.Rd +++ b/man/parameters.Rd @@ -190,17 +190,17 @@ transformations(assignment_parameters) <- "M - [O] + [NH2]" adductRules(assignment_parameters) ## Set adduct rules -adductRules(assignment_parameters) <- mzAnnotation::adduct_rules()) +adductRules(assignment_parameters) <- mzAnnotation::adduct_rules() ## Return isotope rules isotopeRules(assignment_parameters) ## Set isotope rules -isotopeRules(assignment_parameters) <- mzAnnotation::isotope_rules()) +isotopeRules(assignment_parameters) <- mzAnnotation::isotope_rules() ## Return transformation rules transformationRules(assignment_parameters) ## Set transformation rules -transformationRules(assignment_parameters) <- mzAnnotation::transformation_rules()) +transformationRules(assignment_parameters) <- mzAnnotation::transformation_rules() } From d14ba9bb4d8b5e4cb35102d7db76161c0a5b7f19 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Tue, 8 Mar 2022 10:18:18 +0000 Subject: [PATCH 104/226] removed redundant import --- NAMESPACE | 1 - 1 file changed, 1 deletion(-) diff --git a/NAMESPACE b/NAMESPACE index 29696e2..d8979d0 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -132,7 +132,6 @@ importFrom(mzAnnotation,isotope_rules) importFrom(mzAnnotation,relationshipCalculator) importFrom(mzAnnotation,transformMF) importFrom(mzAnnotation,transformation_rules) -importFrom(parallel,detectCores) importFrom(patchwork,plot_annotation) importFrom(patchwork,plot_layout) importFrom(patchwork,wrap_plots) From 5856ce50d7d3eb6bcdadfa23c51c0752e11ffc88 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Tue, 8 Mar 2022 10:19:10 +0000 Subject: [PATCH 105/226] tidied technique names --- R/assign.R | 19 +++------ R/parameters.R | 70 +++++++++++++------------------- man/assign.Rd | 2 +- man/assignmentParameters.Rd | 2 +- tests/testthat/test-assignment.R | 4 +- 5 files changed, 38 insertions(+), 59 deletions(-) diff --git a/R/assign.R b/R/assign.R index 2d819a4..2e467cf 100644 --- a/R/assign.R +++ b/R/assign.R @@ -1,16 +1,4 @@ -assignMethods <- function(method) { - methods <- list( - FIE = FIEassignment, - `RP-LC` = LCassignment, - `NP-LC` = LCassignment - ) - - method <- methods[[method]] - - return(method) -} - setGeneric('doAssignment',function(assignment) standardGeneric('doAssignment') ) @@ -19,7 +7,10 @@ setMethod('doAssignment',signature = 'Assignment', function(assignment){ parameters <- as(assignment,'AssignmentParameters') - assignmentMethod <- assignMethods(parameters@technique) + assignmentMethod <- switch(technique(assignment), + `FIE-HRMS` = FIEassignment, + `RP-LC-HRMS` = LCassignment, + `NP-LC-HRMS` = LCassignment) elements <- names(assignmentMethod()) elements <- elements[!(elements %in% assignment@flags)] @@ -50,7 +41,7 @@ setMethod('doAssignment',signature = 'Assignment', #' @importFrom utils capture.output #' @examples #' plan(future::sequential) -#' p <- assignmentParameters('FIE') +#' p <- assignmentParameters('FIE-HRMS') #' #' assignment <- assignMFs(feature_data,p) #' diff --git a/R/parameters.R b/R/parameters.R index 8034ac3..18f4a47 100644 --- a/R/parameters.R +++ b/R/parameters.R @@ -37,7 +37,7 @@ setClass('AssignmentParameters', transformation_rules = 'tbl_df' ), prototype = list( - technique = 'FIE', + technique = 'FIE-HRMS', correlations_parameters = list(method = 'pearson', pAdjustMethod = 'bonferroni', corPvalue = 0.05), @@ -54,25 +54,23 @@ setClass('AssignmentParameters', adducts = list(n = c("[M-H]1-", "[M+Cl]1-", "[M+K-2H]1-", "[M-2H]2-", "[M+Cl37]1-","[2M-H]1-"), p = c('[M+H]1+','[M+K]1+','[M+Na]1+','[M+K41]1+', - '[M+NH4]1+','[M+2H]2+','[2M+H]1+')), + '[M+2H]2+','[2M+H]1+')), transformations = transformation_rules()$`MF Change`, adduct_rules = adduct_rules(), isotope_rules = isotope_rules(), transformation_rules = transformation_rules() )) -# setValidity('AssignmentParameters',function(object){ -# adducts_present <- adducts(object) %in% adductRules(object)$Name -# -# if (FALSE %in% adducts_present){ -# missing_adducts <- adducts(object)[adducts_present] %>% -# str_c(collapse = ', ') -# -# str_c('Specified adducts ',missing_adducts,' not present in adduct rules.') -# } else { -# TRUE -# } -# }) +setValidity('AssignmentParameters',function(object){ + technique_correct <- technique(object) %in% availableTechniques() + + if (isFALSE(technique_correct)) { + availableTechniques() %>% + paste(collapse = ', ') %>% + paste0('Technique should be one of ',.) + } + else TRUE +}) #' @importFrom methods show #' @importFrom crayon yellow @@ -469,42 +467,32 @@ setMethod('transformationRules<-',signature = 'AssignmentParameters', #' @export availableTechniques <- function(){ - c('FIE','RP-LC','NP-LC') + c('FIE-HRMS','RP-LC-HRMS','NP-LC-HRMS') } #' Assignment parameters #' @description Return default assignment parameters for a given technique. #' @param technique technique to use for assignment -#' @importFrom parallel detectCores #' @importFrom methods new #' @export -assignmentParameters <- function(technique){ - - if (!(technique %in% availableTechniques())) { - techniques <- availableTechniques() %>% - str_c(collapse = ', ') - - stop(str_c('Argument `technique` should be one of ',techniques,'.'),call. = FALSE) - } - - if (technique == 'FIE') { - p <- new('AssignmentParameters') - } +assignmentParameters <- function(technique = availableTechniques()){ - if (technique == 'RP-LC') { - p <- new('AssignmentParameters', - technique = 'RP-LC', - RT_window = 1/60 - ) - } + technique <- match.arg(technique, + choices = availableTechniques()) - if (technique == 'NP-LC') { - p <- new('AssignmentParameters', - technique = 'NP-LC', - RT_window = 1/60 - ) - } + parameters <- switch(technique, + `FIE-HRMS` = new('AssignmentParameters'), + `RP-LC-HRMS` = new('AssignmentParameters', + technique = 'RP-LC-HRMS', + RT_window = 1/60), + `NP-LC-HRMS` = new('AssignmentParameters', + technique = 'NP-LC-HRMS', + RT_window = 1/60, + adducts = list(n = c("[M-H]1-", "[M+Cl]1-", "[M+K-2H]1-", + "[M-2H]2-", "[M+Cl37]1-","[2M-H]1-"), + p = c('[M+H]1+','[M+K]1+','[M+Na]1+','[M+K41]1+', + '[M+NH4]1+','[M+2H]2+','[2M+H]1+')))) - return(p) + return(parameters) } \ No newline at end of file diff --git a/man/assign.Rd b/man/assign.Rd index 569a0b8..39d86da 100644 --- a/man/assign.Rd +++ b/man/assign.Rd @@ -52,7 +52,7 @@ If argument \code{feature_data} is specified as a tibble, this should be a featu } \examples{ plan(future::sequential) -p <- assignmentParameters('FIE') +p <- assignmentParameters('FIE-HRMS') assignment <- assignMFs(feature_data,p) diff --git a/man/assignmentParameters.Rd b/man/assignmentParameters.Rd index f1fb715..ec1cd3a 100644 --- a/man/assignmentParameters.Rd +++ b/man/assignmentParameters.Rd @@ -4,7 +4,7 @@ \alias{assignmentParameters} \title{Assignment parameters} \usage{ -assignmentParameters(technique) +assignmentParameters(technique = availableTechniques()) } \arguments{ \item{technique}{technique to use for assignment} diff --git a/tests/testthat/test-assignment.R b/tests/testthat/test-assignment.R index 691ca7c..0101775 100644 --- a/tests/testthat/test-assignment.R +++ b/tests/testthat/test-assignment.R @@ -1,6 +1,6 @@ -assignment_parameters_FIE <- assignmentParameters('FIE') -assignment_parameters_LC <- assignmentParameters('RP-LC') +assignment_parameters_FIE <- assignmentParameters() +assignment_parameters_LC <- assignmentParameters('RP-LC-HRMS') LC_features <- new('Analysis') metabolyseR::raw(LC_features) <- metabolyseR::analysisData( From ad8ff3a693a24bf96d646dbd69971fa6484794c9 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Tue, 8 Mar 2022 10:47:02 +0000 Subject: [PATCH 106/226] reduced computation during tests --- tests/testthat/test-assignment.R | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/tests/testthat/test-assignment.R b/tests/testthat/test-assignment.R index 0101775..96e1d52 100644 --- a/tests/testthat/test-assignment.R +++ b/tests/testthat/test-assignment.R @@ -2,6 +2,17 @@ assignment_parameters_FIE <- assignmentParameters() assignment_parameters_LC <- assignmentParameters('RP-LC-HRMS') +test_adducts <- list( + n = c("[M-H]1-", + "[M+Cl]1-", + "[M+K-2H]1-", + "[2M-H]1-", + "[M+Cl37]1-"), + p = c("[M+H]1+")) + +adducts(assignment_parameters_FIE) <- test_adducts +adducts(assignment_parameters_LC) <- test_adducts + LC_features <- new('Analysis') metabolyseR::raw(LC_features) <- metabolyseR::analysisData( feature_data %>% From a1e4c48a9a90eb25953e0ccf0d282079f82cca53 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Tue, 8 Mar 2022 11:24:18 +0000 Subject: [PATCH 107/226] console output fixes --- R/addIsoAssign.R | 4 ++-- R/assign.R | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/R/addIsoAssign.R b/R/addIsoAssign.R index dcbaf8a..abb2d2b 100644 --- a/R/addIsoAssign.R +++ b/R/addIsoAssign.R @@ -15,7 +15,7 @@ setMethod('addIsoAssign',signature = 'Assignment', if (isTRUE(assignment@log$verbose)) { startTime <- proc.time() - message(blue('Adduct & isotope assignment '),cli::symbol$continue,'\r',appendLF = FALSE) + message(blue('Adduct & isotopic assignment '),cli::symbol$continue,'\r',appendLF = FALSE) } rel <- assignment %>% @@ -76,7 +76,7 @@ setMethod('addIsoAssign',signature = 'Assignment', round(1) %>% seconds_to_period() %>% str_c('[',.,']') - message(blue('Adduct & isotope assignment '),'\t',green(cli::symbol$tick),' ',elapsed) + message(blue('Adduct & isotopic assignment '),'\t',green(cli::symbol$tick),' ',elapsed) } return(assignment) diff --git a/R/assign.R b/R/assign.R index 2e467cf..10ced15 100644 --- a/R/assign.R +++ b/R/assign.R @@ -48,7 +48,7 @@ setMethod('doAssignment',signature = 'Assignment', #' @export setGeneric('assignMFs',function(feature_data, - parameters = assignmentParameters('FIE'), + parameters = assignmentParameters('FIE-HRMS'), verbose = TRUE, ...) standardGeneric('assignMFs') @@ -58,7 +58,7 @@ setGeneric('assignMFs',function(feature_data, setMethod('assignMFs',signature = 'tbl_df', function(feature_data, - parameters = assignmentParameters('FIE'), + parameters = assignmentParameters('FIE-HRMS'), verbose = TRUE) { if (verbose == TRUE) { @@ -75,7 +75,7 @@ setMethod('assignMFs',signature = 'tbl_df', str_c(collapse = '\n') message(params) message(rep('_',console_width()),'\n') - message('No. m/z:\t',ncol(dat),'\n') + message('No. m/z:\t',ncol(feature_data),'\n') } assignment <- new('Assignment', From 4ea02f93a2ff60177cc75d1833c9162b3d4bcfa4 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Tue, 8 Mar 2022 13:25:34 +0000 Subject: [PATCH 108/226] Retain only components that contain at least one non-isotopic assignment --- NAMESPACE | 1 + R/addIsoAssign.R | 3 ++- R/internals.R | 11 +++++++++++ R/transformationAssign.R | 13 ++++++++++--- man/assign.Rd | 4 ++-- 5 files changed, 26 insertions(+), 6 deletions(-) diff --git a/NAMESPACE b/NAMESPACE index d8979d0..e8632e6 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -52,6 +52,7 @@ importFrom(dplyr,distinct) importFrom(dplyr,filter) importFrom(dplyr,full_join) importFrom(dplyr,group_by) +importFrom(dplyr,group_split) importFrom(dplyr,inner_join) importFrom(dplyr,left_join) importFrom(dplyr,mutate) diff --git a/R/addIsoAssign.R b/R/addIsoAssign.R index abb2d2b..a9fc53d 100644 --- a/R/addIsoAssign.R +++ b/R/addIsoAssign.R @@ -62,7 +62,8 @@ setMethod('addIsoAssign',signature = 'Assignment', assigned = filtered_graph %>% nodes() %>% rename(Name = name) %>% - mutate(Mode = str_sub(Feature,1,1)) + mutate(Mode = str_sub(Feature,1,1)) %>% + clean() ) assignment@assignments <- assignment@addIsoAssign$assigned %>% diff --git a/R/internals.R b/R/internals.R index 26ecf64..c84ae3f 100644 --- a/R/internals.R +++ b/R/internals.R @@ -243,3 +243,14 @@ generateMFs <- function(M, }, .options = furrr_options(seed = 1234)) } + +#' @importFrom dplyr group_split + +clean <- function(assigned){ + assigned %>% + group_split(MF) %>% + map_dfr(~{ + if (NA %in% .x$Isotope) return(.x) + else NULL + }) +} \ No newline at end of file diff --git a/R/transformationAssign.R b/R/transformationAssign.R index 9fdc247..26cb0e6 100644 --- a/R/transformationAssign.R +++ b/R/transformationAssign.R @@ -65,7 +65,8 @@ setMethod('transformationAssign',signature = 'Assignment', adducts(assignment), isotopes(assignment)))) graph_edges <- rel %>% - addMFs(MFs,identMF = F) %>% + addMFs(MFs, + identMF = FALSE) %>% mutate(RetentionTime1 = as.numeric(RetentionTime1), RetentionTime2 = as.numeric(RetentionTime2)) %>% addNames() @@ -86,7 +87,8 @@ setMethod('transformationAssign',signature = 'Assignment', mutate(Mode = str_sub(Feature,1,1)) %>% filter(!(Name %in% assigned$Name)) %>% select(Name:`MF Plausibility (%)`,Mode) %>% - mutate(Iteration = str_c('T',count + 1)) + mutate(Iteration = str_c('T',count + 1)) %>% + clean() outputs <- list( graph = graph, @@ -123,7 +125,12 @@ setMethod('transformationAssign',signature = 'Assignment', round(1) %>% seconds_to_period() %>% str_c('[',.,']') - message(blue(str_c('Transformation assignment iteration ', count + 1,' ')),'\t',green(cli::symbol$tick),' ',elapsed) + message(blue(str_c('Transformation assignment iteration ', + count + 1,' ')), + '\t', + green(cli::symbol$tick), + ' ', + elapsed) } return(assignment) diff --git a/man/assign.Rd b/man/assign.Rd index 39d86da..675cdb7 100644 --- a/man/assign.Rd +++ b/man/assign.Rd @@ -9,14 +9,14 @@ \usage{ assignMFs( feature_data, - parameters = assignmentParameters("FIE"), + parameters = assignmentParameters("FIE-HRMS"), verbose = TRUE, ... ) \S4method{assignMFs}{tbl_df}( feature_data, - parameters = assignmentParameters("FIE"), + parameters = assignmentParameters("FIE-HRMS"), verbose = TRUE ) From 1407736734911c244c9acbad94f47dbb0794ec15 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Tue, 8 Mar 2022 14:46:24 +0000 Subject: [PATCH 109/226] reduced the default max M to 800 --- R/parameters.R | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/R/parameters.R b/R/parameters.R index 18f4a47..77337d9 100644 --- a/R/parameters.R +++ b/R/parameters.R @@ -45,7 +45,7 @@ setClass('AssignmentParameters', n = 200000, rIncrement = 0.01, nIncrement = 20000), - max_M = 1000, + max_M = 800, MF_rank_threshold = 1, ppm = 5, limit = 0.001, From 9943e122f8d6a597d6ce3ee164ceb99a24ebc3c3 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Tue, 15 Mar 2022 17:05:10 +0000 Subject: [PATCH 110/226] adduct and isotopic rules now passed to mzAnnotation::ipMF --- R/internals.R | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/R/internals.R b/R/internals.R index c84ae3f..e8a9e36 100644 --- a/R/internals.R +++ b/R/internals.R @@ -202,7 +202,9 @@ generateMFs <- function(M, ppm, rank_threshold, assignment_adducts, - assignment_isotopes){ + adduct_rules, + assignment_isotopes, + isotope_rules){ nM <- nrow(M) M %>% @@ -213,7 +215,9 @@ generateMFs <- function(M, mf <- ipMF(mz = .x$mz, adduct = .x$Adduct, isotope = .x$Isotope, - ppm = ppm) %>% + ppm = ppm, + adduct_rules_table = adduct_rules, + isotope_rules_table = isotope_rules) %>% mutate(Rank = rank(100 - `Plausibility (%)`, ties.method = 'min')) %>% filter(Rank <= rank_threshold) @@ -253,4 +257,6 @@ clean <- function(assigned){ if (NA %in% .x$Isotope) return(.x) else NULL }) -} \ No newline at end of file +} + +isotopicCheck <- function(){} \ No newline at end of file From 1147cd29eb175216790f47279103a4e64caf6c9d Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Tue, 15 Mar 2022 19:10:16 +0000 Subject: [PATCH 111/226] fixed arguments for generateMFs usage --- R/addIsoAssign.R | 4 +++- R/transformationAssign.R | 4 +++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/R/addIsoAssign.R b/R/addIsoAssign.R index a9fc53d..d9a24a0 100644 --- a/R/addIsoAssign.R +++ b/R/addIsoAssign.R @@ -38,7 +38,9 @@ setMethod('addIsoAssign',signature = 'Assignment', ppm(assignment), MFrankThreshold(assignment), adducts(assignment), - isotopes(assignment)) + adductRules(assignment), + isotopes(assignment), + isotopeRules(assignment)) graph_edges <- rel %>% addMFs(MFs) %>% diff --git a/R/transformationAssign.R b/R/transformationAssign.R index 26cb0e6..2dc35e9 100644 --- a/R/transformationAssign.R +++ b/R/transformationAssign.R @@ -52,7 +52,9 @@ setMethod('transformationAssign',signature = 'Assignment', ppm(assignment), MFrankThreshold(assignment), adducts(assignment), - isotopes(assignment)) + adductRules(assignment), + isotopes(assignment), + isotopeRules(assignment)) if (nrow(MFs) > 0) { From b0728e0cb3556d3c59cedf1808dfc5f05febd35a Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Wed, 16 Mar 2022 11:25:04 +0000 Subject: [PATCH 112/226] Directly remove components containing only isotopic features --- R/addIsoAssign.R | 3 +-- R/components.R | 18 +++++++++++++++++- R/internals.R | 13 ------------- R/transformationAssign.R | 3 +-- 4 files changed, 19 insertions(+), 18 deletions(-) diff --git a/R/addIsoAssign.R b/R/addIsoAssign.R index d9a24a0..703bcda 100644 --- a/R/addIsoAssign.R +++ b/R/addIsoAssign.R @@ -64,8 +64,7 @@ setMethod('addIsoAssign',signature = 'Assignment', assigned = filtered_graph %>% nodes() %>% rename(Name = name) %>% - mutate(Mode = str_sub(Feature,1,1)) %>% - clean() + mutate(Mode = str_sub(Feature,1,1)) ) assignment@assignments <- assignment@addIsoAssign$assigned %>% diff --git a/R/components.R b/R/components.R index 900db21..7660f56 100644 --- a/R/components.R +++ b/R/components.R @@ -7,6 +7,21 @@ plausibility <- function(AIS,degree,weight){ AIS + weight } +#' @importFrom purrr compact + +clean <- function(graph){ + graph %>% + morph(to_components) %>% + map(~{ + component_nodes <- nodes(.x) + + if (NA %in% component_nodes$Isotope) return(.x) + else NULL + }) %>% + compact() %>% + bind_graphs() +} + componentMetrics <- function(component,max_add_iso_total){ component %>% mutate(Size = graph_size(), @@ -37,7 +52,8 @@ calcComponents <- function(graph_nodes, graph <- as_tbl_graph(graph_edges,directed = FALSE) %>% activate(nodes) %>% left_join(graph_nodes,by = c('name' = 'Name')) %>% - mutate(Component = group_components()) + mutate(Component = group_components()) %>% + clean() comp <- graph %>% nodes() %>% diff --git a/R/internals.R b/R/internals.R index e8a9e36..332d20d 100644 --- a/R/internals.R +++ b/R/internals.R @@ -247,16 +247,3 @@ generateMFs <- function(M, }, .options = furrr_options(seed = 1234)) } - -#' @importFrom dplyr group_split - -clean <- function(assigned){ - assigned %>% - group_split(MF) %>% - map_dfr(~{ - if (NA %in% .x$Isotope) return(.x) - else NULL - }) -} - -isotopicCheck <- function(){} \ No newline at end of file diff --git a/R/transformationAssign.R b/R/transformationAssign.R index 2dc35e9..6b00219 100644 --- a/R/transformationAssign.R +++ b/R/transformationAssign.R @@ -89,8 +89,7 @@ setMethod('transformationAssign',signature = 'Assignment', mutate(Mode = str_sub(Feature,1,1)) %>% filter(!(Name %in% assigned$Name)) %>% select(Name:`MF Plausibility (%)`,Mode) %>% - mutate(Iteration = str_c('T',count + 1)) %>% - clean() + mutate(Iteration = str_c('T',count + 1)) outputs <- list( graph = graph, From e75d1f9ff99368517f9e0f120e34f9208e4531e6 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Wed, 16 Mar 2022 11:43:17 +0000 Subject: [PATCH 113/226] retain only components with at least one non-isotopic feature when recalculating components after component filtering --- R/components.R | 3 +++ 1 file changed, 3 insertions(+) diff --git a/R/components.R b/R/components.R index 7660f56..91527b1 100644 --- a/R/components.R +++ b/R/components.R @@ -87,6 +87,9 @@ calcComponents <- function(graph_nodes, recalcComponents <- function(graph, assignment){ + graph <- graph %>% + clean() + g <- graph %>% activate(nodes) From 549c883e9cd8f179b79400b5337f05c41d3808de Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Wed, 16 Mar 2022 12:04:15 +0000 Subject: [PATCH 114/226] remove single node components --- R/components.R | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/R/components.R b/R/components.R index 91527b1..32e458b 100644 --- a/R/components.R +++ b/R/components.R @@ -15,7 +15,8 @@ clean <- function(graph){ map(~{ component_nodes <- nodes(.x) - if (NA %in% component_nodes$Isotope) return(.x) + if (nrow(component_nodes) > 1 & + NA %in% component_nodes$Isotope) return(.x) else NULL }) %>% compact() %>% From 1813d457c4af124891eebaf540252485ae94e03e Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Wed, 16 Mar 2022 12:45:09 +0000 Subject: [PATCH 115/226] update namespace --- NAMESPACE | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/NAMESPACE b/NAMESPACE index e8632e6..426e4e5 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -52,7 +52,6 @@ importFrom(dplyr,distinct) importFrom(dplyr,filter) importFrom(dplyr,full_join) importFrom(dplyr,group_by) -importFrom(dplyr,group_split) importFrom(dplyr,inner_join) importFrom(dplyr,left_join) importFrom(dplyr,mutate) @@ -136,6 +135,7 @@ importFrom(mzAnnotation,transformation_rules) importFrom(patchwork,plot_annotation) importFrom(patchwork,plot_layout) importFrom(patchwork,wrap_plots) +importFrom(purrr,compact) importFrom(purrr,flatten_chr) importFrom(purrr,map) importFrom(purrr,map_dbl) From f2022f4a1ef324cbb865b8a692c7f968cef1418c Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Wed, 16 Mar 2022 13:19:31 +0000 Subject: [PATCH 116/226] fix for empty graphs returned after cleaning components --- R/components.R | 102 ++++++++++++++++++++++++++----------------------- 1 file changed, 54 insertions(+), 48 deletions(-) diff --git a/R/components.R b/R/components.R index 32e458b..c052f04 100644 --- a/R/components.R +++ b/R/components.R @@ -56,29 +56,31 @@ calcComponents <- function(graph_nodes, mutate(Component = group_components()) %>% clean() - comp <- graph %>% - nodes() %>% - .$Component %>% - unique() - - weights <- comp %>% - future_map(~{ - graph %>% - filter(Component == .x) %>% - edges() %>% - .$r %>% - mean() %>% - tibble(Weight = .) + if (length(graph) > 0){ + comp <- graph %>% + nodes() %>% + .$Component %>% + unique() + + weights <- comp %>% + future_map(~{ + graph %>% + filter(Component == .x) %>% + edges() %>% + .$r %>% + mean() %>% + tibble(Weight = .) },graph = graph) %>% - set_names(comp) %>% - bind_rows(.id = 'Component') %>% - mutate(Component = as.numeric(Component)) - - graph <- graph %>% - left_join(weights,by = 'Component') %>% - morph(to_components) %>% - componentMetrics(max_add_iso_total = maxAddIsoScore(assignment)) %>% - unmorph() + set_names(comp) %>% + bind_rows(.id = 'Component') %>% + mutate(Component = as.numeric(Component)) + + graph <- graph %>% + left_join(weights,by = 'Component') %>% + morph(to_components) %>% + componentMetrics(max_add_iso_total = maxAddIsoScore(assignment)) %>% + unmorph() + } return(graph) } @@ -91,33 +93,37 @@ recalcComponents <- function(graph, graph <- graph %>% clean() - g <- graph %>% - activate(nodes) - - comp <- g %>% - nodes() %>% - .$Component %>% - unique() - - weights <- comp %>% - future_map(~{ - graph %>% - filter(Component == .x) %>% - edges() %>% - .$r %>% - mean() %>% - tibble(Weight = .) - },graph = g) %>% - set_names(comp) %>% - bind_rows(.id = 'Component') %>% - mutate(Component = as.numeric(Component)) + if (length(graph) > 0){ + g <- graph %>% + activate(nodes) + + comp <- g %>% + nodes() %>% + .$Component %>% + unique() + + weights <- comp %>% + future_map(~{ + graph %>% + filter(Component == .x) %>% + edges() %>% + .$r %>% + mean() %>% + tibble(Weight = .) + },graph = g) %>% + set_names(comp) %>% + bind_rows(.id = 'Component') %>% + mutate(Component = as.numeric(Component)) + + graph <- g %>% + select(-Weight) %>% + left_join(weights,by = 'Component') %>% + morph(to_components) %>% + componentMetrics(max_add_iso_total = maxAddIsoScore(assignment)) %>% + unmorph() + } - g %>% - select(-Weight) %>% - left_join(weights,by = 'Component') %>% - morph(to_components) %>% - componentMetrics(max_add_iso_total = maxAddIsoScore(assignment)) %>% - unmorph() + return(graph) } filterComponents <- function(graph, From 0375a98d432fb7c78fb9f63db8c36e1ca7a91f42 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Wed, 16 Mar 2022 17:21:27 +0000 Subject: [PATCH 117/226] prefer pre-treated data in assignMFs method for Analysis class --- R/assign.R | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/R/assign.R b/R/assign.R index 10ced15..45841b8 100644 --- a/R/assign.R +++ b/R/assign.R @@ -119,10 +119,10 @@ setMethod('assignMFs',signature = 'Analysis', function(feature_data, parameters = assignmentParameters('FIE'), verbose = TRUE, - type = c('raw','pre-treated')){ + type = c('pre-treated','raw')){ type <- match.arg(type, - choices = c('raw','pre-treated')) + choices = c('pre-treated','raw')) if (type == 'raw') feature_data <- raw(feature_data) if (type == 'pre-treated') feature_data <- preTreated(feature_data) From cdd6fbe5cc2b572f21e44e6b7a883950627f879d Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Wed, 16 Mar 2022 17:21:57 +0000 Subject: [PATCH 118/226] Show filtered correlation numbers --- R/assignment.R | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/R/assignment.R b/R/assignment.R index e3fc706..8ed7470 100644 --- a/R/assignment.R +++ b/R/assignment.R @@ -47,7 +47,7 @@ setMethod('show',signature = 'Assignment', cat(blue('\nMFassign'),red(str_c('v',packageVersion('MFassign') %>% as.character())),'\n') cat(yellow('Assignment:'),'\n') cat('\t','Features:\t\t',ncol(object@data),'\n') - cat('\t','Correlations:\t\t',nrow(object@correlations),'\n') + cat('\t','Correlations:\t\t',nrow(object@preparedCorrelations),'\n') cat('\t','Relationships:\t\t',nrow(relationships(object)),'\n') cat('\n') if (length(object@addIsoAssign) > 0) { From 1b71a889aeabe69130a45b654bf6efe9968b3d7d Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Wed, 16 Mar 2022 17:22:43 +0000 Subject: [PATCH 119/226] fix component filtering logic --- R/components.R | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/R/components.R b/R/components.R index c052f04..96c90cc 100644 --- a/R/components.R +++ b/R/components.R @@ -23,6 +23,12 @@ clean <- function(graph){ bind_graphs() } +nComponents <- function(graph){ + graph %>% + morph(to_components) %>% + length() +} + componentMetrics <- function(component,max_add_iso_total){ component %>% mutate(Size = graph_size(), @@ -56,7 +62,7 @@ calcComponents <- function(graph_nodes, mutate(Component = group_components()) %>% clean() - if (length(graph) > 0){ + if (nComponents(graph) > 0){ comp <- graph %>% nodes() %>% .$Component %>% @@ -90,10 +96,11 @@ calcComponents <- function(graph_nodes, recalcComponents <- function(graph, assignment){ + graph <- graph %>% clean() - if (length(graph) > 0){ + if (nComponents(graph) > 0){ g <- graph %>% activate(nodes) @@ -121,7 +128,7 @@ recalcComponents <- function(graph, morph(to_components) %>% componentMetrics(max_add_iso_total = maxAddIsoScore(assignment)) %>% unmorph() - } + } return(graph) } @@ -140,7 +147,7 @@ filterComponents <- function(graph, eliminate(f$Measure,f$Direction) %>% .$name}) if (V(filtered_graph) %>% length() > 0) { - filteredGraph <- filtered_graph %>% + filtered_graph <- filtered_graph %>% recalcComponents(assignment) } else { break() From ce70b97e8914d902735c7d7c060b21a9e6b4f6a2 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Wed, 16 Mar 2022 17:23:04 +0000 Subject: [PATCH 120/226] remove MFs with only an isotopic assignment --- NAMESPACE | 1 + R/transformationAssign.R | 9 +++++++-- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/NAMESPACE b/NAMESPACE index 426e4e5..24543f9 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -52,6 +52,7 @@ importFrom(dplyr,distinct) importFrom(dplyr,filter) importFrom(dplyr,full_join) importFrom(dplyr,group_by) +importFrom(dplyr,group_split) importFrom(dplyr,inner_join) importFrom(dplyr,left_join) importFrom(dplyr,mutate) diff --git a/R/transformationAssign.R b/R/transformationAssign.R index 6b00219..ee31fa5 100644 --- a/R/transformationAssign.R +++ b/R/transformationAssign.R @@ -3,7 +3,7 @@ setGeneric("transformationAssign", function(assignment) standardGeneric("transformationAssign")) -#' @importFrom dplyr full_join select distinct +#' @importFrom dplyr full_join select distinct group_split #' @importFrom mzAnnotation transformMF setMethod('transformationAssign',signature = 'Assignment', @@ -89,7 +89,12 @@ setMethod('transformationAssign',signature = 'Assignment', mutate(Mode = str_sub(Feature,1,1)) %>% filter(!(Name %in% assigned$Name)) %>% select(Name:`MF Plausibility (%)`,Mode) %>% - mutate(Iteration = str_c('T',count + 1)) + mutate(Iteration = str_c('T',count + 1)) %>% + group_split(MF) %>% + map_dfr(~{ + if (NA %in% .x$Isotope) return(.x) + else NULL + }) outputs <- list( graph = graph, From 5e9265217f88db2e2772bfcb2737c6768444f835 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Wed, 16 Mar 2022 17:24:04 +0000 Subject: [PATCH 121/226] increase default correlations n parameter --- R/parameters.R | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/R/parameters.R b/R/parameters.R index 77337d9..77a92e2 100644 --- a/R/parameters.R +++ b/R/parameters.R @@ -42,7 +42,7 @@ setClass('AssignmentParameters', pAdjustMethod = 'bonferroni', corPvalue = 0.05), filter = list(rthresh = 0.7, - n = 200000, + n = 500000, rIncrement = 0.01, nIncrement = 20000), max_M = 800, From 9f06263a2dac9b5ebb800cb8f0748655b6b5de3c Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Wed, 16 Mar 2022 17:42:43 +0000 Subject: [PATCH 122/226] increased default ppm threshold --- R/parameters.R | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/R/parameters.R b/R/parameters.R index 77a92e2..0d03f2f 100644 --- a/R/parameters.R +++ b/R/parameters.R @@ -47,7 +47,7 @@ setClass('AssignmentParameters', nIncrement = 20000), max_M = 800, MF_rank_threshold = 1, - ppm = 5, + ppm = 6, limit = 0.001, RT_window = numeric(), isotopes = c('13C','18O','13C2'), From 8c570183ff4e8bd76863685be5ec53b17f1678ac Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Fri, 18 Mar 2022 12:13:28 +0000 Subject: [PATCH 123/226] parallise the calculation of M prior to MF generation --- R/internals.R | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/R/internals.R b/R/internals.R index 332d20d..d141e6c 100644 --- a/R/internals.R +++ b/R/internals.R @@ -92,9 +92,12 @@ collateM <- function(rel,max_M){ distinct() %>% arrange(mz) %>% rowwise() %>% - mutate(M = calcM(mz, - adduct = Adduct, - isotope = Isotope)) %>% + group_split() %>% + furrr::future_map_dfr(~.x %>% + mutate(M = calcM(mz, + adduct = Adduct, + isotope = Isotope)) + ) %>% arrange(M) %>% filter(M <= max_M) } From df6df785d9d5d2582054ce9c448f2e27562165cf Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Wed, 23 Mar 2022 12:22:02 +0000 Subject: [PATCH 124/226] change default correlation method to spearmans --- R/parameters.R | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/R/parameters.R b/R/parameters.R index 0d03f2f..6369b0b 100644 --- a/R/parameters.R +++ b/R/parameters.R @@ -38,7 +38,7 @@ setClass('AssignmentParameters', ), prototype = list( technique = 'FIE-HRMS', - correlations_parameters = list(method = 'pearson', + correlations_parameters = list(method = 'spearman', pAdjustMethod = 'bonferroni', corPvalue = 0.05), filter = list(rthresh = 0.7, From 9c8ade70c0075fd8186989590ce53a890e0d4b8a Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Wed, 23 Mar 2022 12:22:19 +0000 Subject: [PATCH 125/226] fixed assignment tests for LC --- tests/testthat/test-assignment.R | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/testthat/test-assignment.R b/tests/testthat/test-assignment.R index 96e1d52..d1ce8c1 100644 --- a/tests/testthat/test-assignment.R +++ b/tests/testthat/test-assignment.R @@ -14,7 +14,7 @@ adducts(assignment_parameters_FIE) <- test_adducts adducts(assignment_parameters_LC) <- test_adducts LC_features <- new('Analysis') -metabolyseR::raw(LC_features) <- metabolyseR::analysisData( +metabolyseR::preTreated(LC_features) <- metabolyseR::analysisData( feature_data %>% {magrittr::set_colnames(., paste0(colnames(.), From 88259ea5f5f83df438d10bdf5da317964f4a16a7 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Wed, 30 Mar 2022 21:29:17 +0000 Subject: [PATCH 126/226] simplify correlations --- NAMESPACE | 8 -------- R/correlations.R | 50 ++++++------------------------------------------ 2 files changed, 6 insertions(+), 52 deletions(-) diff --git a/NAMESPACE b/NAMESPACE index 24543f9..febe8e5 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -113,16 +113,11 @@ importFrom(igraph,vertex.attributes) importFrom(lubridate,seconds_to_period) importFrom(magrittr,"%>%") importFrom(magrittr,set_names) -importFrom(magrittr,set_rownames) -importFrom(metabolyseR,analysisData) importFrom(metabolyseR,analysisParameters) importFrom(metabolyseR,analysisResults) -importFrom(metabolyseR,dat) -importFrom(metabolyseR,keepFeatures) importFrom(metabolyseR,metabolyse) importFrom(metabolyseR,preTreated) importFrom(metabolyseR,raw) -importFrom(metabolyseR,sinfo) importFrom(methods,as) importFrom(methods,new) importFrom(methods,show) @@ -142,9 +137,6 @@ importFrom(purrr,map) importFrom(purrr,map_dbl) importFrom(purrr,map_dfr) importFrom(purrr,map_lgl) -importFrom(stats,cutree) -importFrom(stats,dist) -importFrom(stats,hclust) importFrom(stringr,str_c) importFrom(stringr,str_detect) importFrom(stringr,str_remove) diff --git a/R/correlations.R b/R/correlations.R index 4501605..32205fc 100644 --- a/R/correlations.R +++ b/R/correlations.R @@ -2,9 +2,7 @@ setGeneric('calcCorrelations', function(assignment) standardGeneric('calcCorrelations')) -#' @importFrom metabolyseR analysisParameters metabolyse analysisResults keepFeatures analysisData dat sinfo -#' @importFrom magrittr set_rownames -#' @importFrom stats cutree dist hclust +#' @importFrom metabolyseR analysisParameters metabolyse analysisResults setMethod('calcCorrelations',signature = 'Assignment',function(assignment){ if (assignment@log$verbose == T) { @@ -17,47 +15,11 @@ setMethod('calcCorrelations',signature = 'Assignment',function(assignment){ p@correlations <- parameters@correlations_parameters - if (str_detect(parameters@technique,'LC')) { - feat <- tibble(Feature = colnames(assignment@data)) %>% - mutate(RT = str_split_fixed(Feature,'@',2)[,2] %>% - as.numeric()) - RTgroups <- feat %>% - data.frame() %>% - set_rownames(.$Feature) %>% - select(-Feature) %>% - dist() %>% - hclust() %>% - cutree(h = parameters@RT_window) %>% - {tibble(Feature = names(.),Group = .)} - - RTsum <- RTgroups %>% - group_by(Group) %>% - summarise(N = n()) - - RTgroups <- RTgroups %>% - filter(Group %in% {RTsum %>% - filter(N > 1) %>% - .$Group}) - - cors <- RTgroups %>% - split(.$Group) %>% - future_map(~{ - analysisData(assignment@data,tibble(ID = 1:nrow(assignment@data))) %>% - keepFeatures(features = .x$Feature) %>% - {metabolyse(dat(.),sinfo(.),p,verbose = FALSE)} %>% - analysisResults(element = 'correlations') - }) %>% - bind_rows(.id = 'RT Group') - - } else { - cors <- metabolyse(assignment@data, - tibble(ID = 1:nrow(assignment@data)), - p, - verbose = FALSE) %>% - analysisResults(element = 'correlations') - } - - assignment@correlations <- cors + assignment@correlations <- metabolyse(assignment@data, + tibble(ID = 1:nrow(assignment@data)), + p, + verbose = FALSE) %>% + analysisResults(element = 'correlations') if (assignment@log$verbose == T) { endTime <- proc.time() From c5c2c1d0ce66acc97e90721472378982854d4f7d Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Wed, 30 Mar 2022 21:29:30 +0000 Subject: [PATCH 127/226] update documentation --- man/assign.Rd | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/man/assign.Rd b/man/assign.Rd index 675cdb7..5c24a53 100644 --- a/man/assign.Rd +++ b/man/assign.Rd @@ -30,7 +30,7 @@ assignMFs( feature_data, parameters = assignmentParameters("FIE"), verbose = TRUE, - type = c("raw", "pre-treated") + type = c("pre-treated", "raw") ) } \arguments{ From bfd40f238518d5265e4781dfdb6738f3dd5cc659 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Wed, 30 Mar 2022 21:38:43 +0000 Subject: [PATCH 128/226] function import fix --- NAMESPACE | 1 + R/assign.R | 1 + 2 files changed, 2 insertions(+) diff --git a/NAMESPACE b/NAMESPACE index febe8e5..ad76498 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -115,6 +115,7 @@ importFrom(magrittr,"%>%") importFrom(magrittr,set_names) importFrom(metabolyseR,analysisParameters) importFrom(metabolyseR,analysisResults) +importFrom(metabolyseR,dat) importFrom(metabolyseR,metabolyse) importFrom(metabolyseR,preTreated) importFrom(metabolyseR,raw) diff --git a/R/assign.R b/R/assign.R index 45841b8..ac78dd8 100644 --- a/R/assign.R +++ b/R/assign.R @@ -101,6 +101,7 @@ setMethod('assignMFs',signature = 'tbl_df', }) #' @rdname assign +#' @importFrom metabolyseR dat setMethod('assignMFs',signature = 'AnalysisData', function(feature_data, From 8d7896d3b67a6d460e80350577c6cecf3b60b7b3 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Wed, 30 Mar 2022 21:39:00 +0000 Subject: [PATCH 129/226] calculate retention time difference --- R/correlations.R | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/R/correlations.R b/R/correlations.R index 32205fc..523d808 100644 --- a/R/correlations.R +++ b/R/correlations.R @@ -92,9 +92,12 @@ setMethod('prepCorrelations',signature = 'Assignment', RetentionTime2 = str_split_fixed(Feature2,'@',2) %>% .[,2] %>% as.numeric(), + RetentionTimeDiff = abs(RetentionTime1 - RetentionTime2), ID = 1:nrow(.) ) %>% - select(Feature1,Feature2,Mode1:RetentionTime2,log2IntensityRatio,r,ID) + select(Feature1,Feature2, + Mode1:RetentionTimeDiff, + log2IntensityRatio,r,ID) assignment@preparedCorrelations <- correlations From 94d269481728a5a86859de24a6e8028df5f83eb8 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Wed, 30 Mar 2022 21:47:20 +0000 Subject: [PATCH 130/226] limit RT difference in adduct and isotopic assignment --- R/addIsoAssign.R | 15 +++++++++++++-- R/parameters.R | 12 ++++++------ 2 files changed, 19 insertions(+), 8 deletions(-) diff --git a/R/addIsoAssign.R b/R/addIsoAssign.R index 703bcda..59a744c 100644 --- a/R/addIsoAssign.R +++ b/R/addIsoAssign.R @@ -15,11 +15,22 @@ setMethod('addIsoAssign',signature = 'Assignment', if (isTRUE(assignment@log$verbose)) { startTime <- proc.time() - message(blue('Adduct & isotopic assignment '),cli::symbol$continue,'\r',appendLF = FALSE) + message(blue('Adduct & isotopic assignment '), + cli::symbol$continue,'\r', + appendLF = FALSE) } + assignment_technique <- technique(assignment) + rel <- assignment %>% - relationships() %>% + relationships() + + if (str_detect(assignment_technique,'LC')){ + rel <- rel %>% + filter(RetentiontimeDiff <= assignment@RT_diff_limit) + } + + rel <- rel %>% filter(is.na(Transformation1) & is.na(Transformation2) & r > 0) %>% diff --git a/R/parameters.R b/R/parameters.R index 6369b0b..9fb8dac 100644 --- a/R/parameters.R +++ b/R/parameters.R @@ -9,7 +9,7 @@ #' @slot ppm ppm threshold #' #' @slot adducts named list of character vectors containing the adducuts to use for each mode #' @slot limit amu deviation limit for relationship prediction -#' @slot RT_window retention time window for chromatographic associations +#' @slot RT_diff_limit limit for retention time differences for correlated features in adduct and isotopic assignment #' @slot adducts list of character vectors containing the adducts to use. List element names should denote ionisation mode. #' @slot isotopes character vector of isotopes to use #' @slot transformations character vector of transformations to use @@ -28,7 +28,7 @@ setClass('AssignmentParameters', MF_rank_threshold = 'numeric', ppm = 'numeric', limit = 'numeric', - RT_window = 'numeric', + RT_diff_limit = 'numeric', adducts = 'list', isotopes = 'character', transformations = 'character', @@ -49,7 +49,7 @@ setClass('AssignmentParameters', MF_rank_threshold = 1, ppm = 6, limit = 0.001, - RT_window = numeric(), + RT_diff_limit = numeric(), isotopes = c('13C','18O','13C2'), adducts = list(n = c("[M-H]1-", "[M+Cl]1-", "[M+K-2H]1-", "[M-2H]2-", "[M+Cl37]1-","[2M-H]1-"), @@ -87,7 +87,7 @@ setMethod('show',signature = 'AssignmentParameters', cat('\t','Relationship limit:\t',object@limit,'\n') if (object@technique != 'FIE') { - cat('\t','RT window:\t\t',object@RT_window,'\n') + cat('\t','RT limit:\t\t',object@RT_diff_limit,'\n') } cat('\n\t','Adducts:','\n') @@ -485,10 +485,10 @@ assignmentParameters <- function(technique = availableTechniques()){ `FIE-HRMS` = new('AssignmentParameters'), `RP-LC-HRMS` = new('AssignmentParameters', technique = 'RP-LC-HRMS', - RT_window = 1/60), + RT_diff_limit = 1/60), `NP-LC-HRMS` = new('AssignmentParameters', technique = 'NP-LC-HRMS', - RT_window = 1/60, + RT_diff_limit = 1/60, adducts = list(n = c("[M-H]1-", "[M+Cl]1-", "[M+K-2H]1-", "[M-2H]2-", "[M+Cl37]1-","[2M-H]1-"), p = c('[M+H]1+','[M+K]1+','[M+Na]1+','[M+K41]1+', From 7d07c3fe486269b9cb8f99784b09388ecb73d631 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Wed, 30 Mar 2022 21:51:25 +0000 Subject: [PATCH 131/226] Variable name fix --- R/addIsoAssign.R | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/R/addIsoAssign.R b/R/addIsoAssign.R index 59a744c..f70d04e 100644 --- a/R/addIsoAssign.R +++ b/R/addIsoAssign.R @@ -27,7 +27,7 @@ setMethod('addIsoAssign',signature = 'Assignment', if (str_detect(assignment_technique,'LC')){ rel <- rel %>% - filter(RetentiontimeDiff <= assignment@RT_diff_limit) + filter(RetentionTimeDiff <= assignment@RT_diff_limit) } rel <- rel %>% From 457cc90a21f488e26cd8b5cd1e37415e4be164df Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Wed, 30 Mar 2022 22:00:08 +0000 Subject: [PATCH 132/226] removed flags slot from Assignment class --- R/assignment.R | 2 -- 1 file changed, 2 deletions(-) diff --git a/R/assignment.R b/R/assignment.R index 8ed7470..d18ce96 100644 --- a/R/assignment.R +++ b/R/assignment.R @@ -16,7 +16,6 @@ setClass('Assignment', contains = 'AssignmentParameters', slots = list( log = 'list', - flags = 'character', data = 'tbl_df', correlations = 'tbl_df', preparedCorrelations = 'tbl_df', @@ -27,7 +26,6 @@ setClass('Assignment', ), prototype = list( log = list(date = date(),verbose = TRUE), - flags = character(), data = tibble(), correlations = tibble(), preparedCorrelations = tibble(), From 59905b2b8ce0b7725d6f0c99f37a6bbaa57e1c20 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Wed, 30 Mar 2022 22:00:42 +0000 Subject: [PATCH 133/226] Remove seperate LC and FIE methods --- DESCRIPTION | 7 +++---- R/FIEassignment.R | 48 ----------------------------------------------- R/LCassignment.R | 47 ---------------------------------------------- R/assign.R | 31 ++++++++++++++++++------------ 4 files changed, 22 insertions(+), 111 deletions(-) delete mode 100644 R/FIEassignment.R delete mode 100644 R/LCassignment.R diff --git a/DESCRIPTION b/DESCRIPTION index 5b52b1c..bc948f9 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -35,10 +35,9 @@ RoxygenNote: 7.1.2 Collate: parameters.R assignment.R correlations.R addIsoAssign.R transformationAssign.R relationships.R graph.R assign.R internals.R components.R - feature_data.R LCassignment.R MFassign.R - FIEassignment.R plotNetwork.R plotAdductDist.R - plotFeatureSolutions.R plotSpectrum.R reexports.R - zzz.R + feature_data.R MFassign.R plotNetwork.R + plotAdductDist.R plotFeatureSolutions.R + plotSpectrum.R reexports.R zzz.R Suggests: testthat, covr Remotes: jasenfinch/mzAnnotation@tmp, diff --git a/R/FIEassignment.R b/R/FIEassignment.R deleted file mode 100644 index 29efc86..0000000 --- a/R/FIEassignment.R +++ /dev/null @@ -1,48 +0,0 @@ - -FIEassignment <- function(element = NULL) { - methods <- list( - `calculate correlations` = function(assignment){ - assignment %>% - calcCorrelations() - }, - `filter correlations` = function(assignment){ - assignment %>% - filterCorrelations() - }, - `prepare correlations` = function(assignment){ - assignment %>% - prepCorrelations() - }, - relationships = function(assignment){ - assignment %>% - calcRelationships() - }, - `adduct and isotope assignment` = function(assignment){ - assignment %>% - addIsoAssign() - }, - `transformation assignment` = function(assignment){ - count <- 0 - while (T) { - count <- count + 1 - assignment <- suppressWarnings(transformationAssign(assignment)) - if (length(assignment@transAssign[[count]]) == 0) { - assignment@transAssign <- assignment@transAssign[-count] - break() - } - if (nrow(assignment@transAssign[[count]]$assigned) == 0) { - assignment@transAssign <- assignment@transAssign[-count] - break() - } - - } - return(assignment) - } - ) - - if (!is.null(element)) { - return(methods[[element]]) - } else { - return(methods) - } -} \ No newline at end of file diff --git a/R/LCassignment.R b/R/LCassignment.R deleted file mode 100644 index 303cdd4..0000000 --- a/R/LCassignment.R +++ /dev/null @@ -1,47 +0,0 @@ - -LCassignment <- function(element = NULL){ - methods <- list( - `calculate correlations` = function(assignment){ - assignment %>% - calcCorrelations() - }, - `filter correlations` = function(assignment){ - assignment %>% - filterCorrelations() - }, - `prepare correlations` = function(assignment){ - assignment %>% - prepCorrelations() - }, - relationships = function(assignment){ - assignment %>% - calcRelationships(transformations = FALSE) - }, - `adduct and isotope assignment` = function(assignment){ - assignment %>% - addIsoAssign() - }#, - # `transformation assignment` = function(assignment){ - # count <- 0 - # while (T) { - # count <- count + 1 - # assignment <- suppressWarnings(transformationAssign(assignment)) - # if (length(assignment@transAssign[[count]]) == 0) { - # break() - # } - # if (nrow(assignment@transAssign[[count]]$assigned) == 0) { - # assignment@transAssign <- assignment@transAssign[-count] - # break() - # } - # - # } - # return(assignment) - # } - ) - - if (!is.null(element)) { - return(methods[[element]]) - } else { - return(methods) - } -} \ No newline at end of file diff --git a/R/assign.R b/R/assign.R index ac78dd8..4b3c8ed 100644 --- a/R/assign.R +++ b/R/assign.R @@ -5,20 +5,27 @@ setGeneric('doAssignment',function(assignment) setMethod('doAssignment',signature = 'Assignment', function(assignment){ - parameters <- as(assignment,'AssignmentParameters') - assignmentMethod <- switch(technique(assignment), - `FIE-HRMS` = FIEassignment, - `RP-LC-HRMS` = LCassignment, - `NP-LC-HRMS` = LCassignment) + assignment <- assignment %>% + calcCorrelations() %>% + filterCorrelations() %>% + prepCorrelations() %>% + relationships() %>% + addIsoAssign() - elements <- names(assignmentMethod()) - elements <- elements[!(elements %in% assignment@flags)] - - for(i in elements){ - method <- assignmentMethod(i) - assignment <- method(assignment) - assignment@flags <- c(assignment@flags,i) + count <- 0 + while (TRUE) { + count <- count + 1 + assignment <- suppressWarnings(transformationAssign(assignment)) + if (length(assignment@transAssign[[count]]) == 0) { + assignment@transAssign <- assignment@transAssign[-count] + break() + } + if (nrow(assignment@transAssign[[count]]$assigned) == 0) { + assignment@transAssign <- assignment@transAssign[-count] + break() + } + } return(assignment) From 289d16f5839392e4c4b29effa679e4c2ac457c20 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Wed, 30 Mar 2022 22:08:43 +0000 Subject: [PATCH 134/226] condensed correlations steps --- R/assign.R | 54 +++++++++++++++++------------------------------- R/correlations.R | 35 +++++++------------------------ 2 files changed, 26 insertions(+), 63 deletions(-) diff --git a/R/assign.R b/R/assign.R index 4b3c8ed..a5d6371 100644 --- a/R/assign.R +++ b/R/assign.R @@ -1,36 +1,3 @@ - -setGeneric('doAssignment',function(assignment) - standardGeneric('doAssignment') -) - -setMethod('doAssignment',signature = 'Assignment', - function(assignment){ - - assignment <- assignment %>% - calcCorrelations() %>% - filterCorrelations() %>% - prepCorrelations() %>% - relationships() %>% - addIsoAssign() - - count <- 0 - while (TRUE) { - count <- count + 1 - assignment <- suppressWarnings(transformationAssign(assignment)) - if (length(assignment@transAssign[[count]]) == 0) { - assignment@transAssign <- assignment@transAssign[-count] - break() - } - if (nrow(assignment@transAssign[[count]]$assigned) == 0) { - assignment@transAssign <- assignment@transAssign[-count] - break() - } - - } - - return(assignment) - }) - #' Assign molecular formulas #' @rdname assign #' @description assign molecular formulas to a set of given m/z. @@ -90,8 +57,25 @@ setMethod('assignMFs',signature = 'tbl_df', data = feature_data) assignment@log$verbose <- verbose - assignment <- assignment %>% - doAssignment() + assignment <- assignment %>% + calcCorrelations() %>% + relationships() %>% + addIsoAssign() + + count <- 0 + while (TRUE) { + count <- count + 1 + assignment <- suppressWarnings(transformationAssign(assignment)) + if (length(assignment@transAssign[[count]]) == 0) { + assignment@transAssign <- assignment@transAssign[-count] + break() + } + if (nrow(assignment@transAssign[[count]]$assigned) == 0) { + assignment@transAssign <- assignment@transAssign[-count] + break() + } + + } if (verbose == TRUE) { endTime <- proc.time() diff --git a/R/correlations.R b/R/correlations.R index 523d808..c2c8c15 100644 --- a/R/correlations.R +++ b/R/correlations.R @@ -21,14 +21,18 @@ setMethod('calcCorrelations',signature = 'Assignment',function(assignment){ verbose = FALSE) %>% analysisResults(element = 'correlations') - if (assignment@log$verbose == T) { + assignment <- assignment %>% + filterCorrelations() %>% + prepCorrelations() + + if (assignment@log$verbose == TRUE) { endTime <- proc.time() elapsed <- {endTime - startTime} %>% .[3] %>% round(1) %>% seconds_to_period() %>% str_c('[',.,']') - ncors <- nrow(assignment@correlations) %>% + ncors <- nrow(assignment@preparedCorrelations) %>% str_c('[',.,' correlations',']') message(blue('Calculating correlations '),'\t',green(cli::symbol$tick),' ',ncors,' ',elapsed) } @@ -101,16 +105,6 @@ setMethod('prepCorrelations',signature = 'Assignment', assignment@preparedCorrelations <- correlations - if (assignment@log$verbose == T) { - endTime <- proc.time() - elapsed <- {endTime - startTime} %>% - .[3] %>% - round(1) %>% - seconds_to_period() %>% - str_c('[',.,']') - message(blue('Preparing correlations '),'\t\t',green(cli::symbol$tick),' ',elapsed) - } - return(assignment) }) @@ -118,11 +112,7 @@ setGeneric('filterCorrelations', function(assignment) standardGeneric('filterCorrelations')) setMethod('filterCorrelations',signature = 'Assignment',function(assignment){ - if (assignment@log$verbose == T) { - startTime <- proc.time() - message(blue('Filtering correlations '),cli::symbol$continue,'\r',appendLF = FALSE) - } - + parameters <- as(assignment,'AssignmentParameters') if (str_detect(parameters@technique,'LC')) { @@ -139,16 +129,5 @@ setMethod('filterCorrelations',signature = 'Assignment',function(assignment){ assignment@preparedCorrelations <- cors - if (assignment@log$verbose == T) { - endTime <- proc.time() - elapsed <- {endTime - startTime} %>% - .[3] %>% - round(1) %>% - seconds_to_period() %>% - str_c('[',.,']') - ncors <- nrow(assignment@preparedCorrelations) %>% - str_c('[',.,' correlations',']') - message(blue('Filtering correlations '),'\t\t',green(cli::symbol$tick),' ',ncors,' ',elapsed) - } return(assignment) }) \ No newline at end of file From 9058d7c2f4a2c87e7d1d8ad75987bb878571c5fc Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Wed, 30 Mar 2022 22:15:25 +0000 Subject: [PATCH 135/226] assignMFs fix --- R/assign.R | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/R/assign.R b/R/assign.R index a5d6371..6981e79 100644 --- a/R/assign.R +++ b/R/assign.R @@ -59,7 +59,7 @@ setMethod('assignMFs',signature = 'tbl_df', assignment <- assignment %>% calcCorrelations() %>% - relationships() %>% + calcRelationships() %>% addIsoAssign() count <- 0 From c9d717d970d22ee535880a6c00dd29f1190a7087 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Thu, 31 Mar 2022 10:00:18 +0100 Subject: [PATCH 136/226] removed prepared correlations slot to reduce the memory footprint of Assignment class objects --- R/assignment.R | 5 +---- R/correlations.R | 10 +++++----- R/plotNetwork.R | 2 +- R/relationships.R | 2 +- man/Assignment.Rd | 2 -- man/AssignmentParameters-class.Rd | 2 +- 6 files changed, 9 insertions(+), 14 deletions(-) diff --git a/R/assignment.R b/R/assignment.R index d18ce96..9b2f5d0 100644 --- a/R/assignment.R +++ b/R/assignment.R @@ -5,7 +5,6 @@ #' @slot flags charactor vector containing completed assignment elements #' @slot data A tibble containing the peak intensity matrix #' @slot correlations A tibble containing the correlations -#' @slot preparedCorrelations A tibble containing the prepared correlations ready for analysis #' @slot relationships A tibble containing the predicted relationships #' @slot addIsoAssign A list containing the results of the adduct and isotope assignment #' @slot transAssign A list containing the results of the transformation assignment @@ -18,7 +17,6 @@ setClass('Assignment', log = 'list', data = 'tbl_df', correlations = 'tbl_df', - preparedCorrelations = 'tbl_df', relationships = 'tbl_df', addIsoAssign = 'list', transAssign = 'list', @@ -28,7 +26,6 @@ setClass('Assignment', log = list(date = date(),verbose = TRUE), data = tibble(), correlations = tibble(), - preparedCorrelations = tibble(), relationships = tibble(), addIsoAssign = list(), transAssign = list(), @@ -45,7 +42,7 @@ setMethod('show',signature = 'Assignment', cat(blue('\nMFassign'),red(str_c('v',packageVersion('MFassign') %>% as.character())),'\n') cat(yellow('Assignment:'),'\n') cat('\t','Features:\t\t',ncol(object@data),'\n') - cat('\t','Correlations:\t\t',nrow(object@preparedCorrelations),'\n') + cat('\t','Correlations:\t\t',nrow(object@correlations),'\n') cat('\t','Relationships:\t\t',nrow(relationships(object)),'\n') cat('\n') if (length(object@addIsoAssign) > 0) { diff --git a/R/correlations.R b/R/correlations.R index c2c8c15..f8c7564 100644 --- a/R/correlations.R +++ b/R/correlations.R @@ -32,7 +32,7 @@ setMethod('calcCorrelations',signature = 'Assignment',function(assignment){ round(1) %>% seconds_to_period() %>% str_c('[',.,']') - ncors <- nrow(assignment@preparedCorrelations) %>% + ncors <- nrow(assignment@correlations) %>% str_c('[',.,' correlations',']') message(blue('Calculating correlations '),'\t',green(cli::symbol$tick),' ',ncors,' ',elapsed) } @@ -68,12 +68,12 @@ setGeneric('prepCorrelations', function(assignment) setMethod('prepCorrelations',signature = 'Assignment', function(assignment){ - if (assignment@log$verbose == T) { + if (assignment@log$verbose == TRUE) { startTime <- proc.time() message(blue('Preparing correlations '),cli::symbol$continue,'\r',appendLF = FALSE) } - correlations <- assignment@preparedCorrelations + correlations <- assignment@correlations correlations <- correlations %>% mutate(Mode1 = str_split_fixed(Feature1,'@',2) %>% @@ -103,7 +103,7 @@ setMethod('prepCorrelations',signature = 'Assignment', Mode1:RetentionTimeDiff, log2IntensityRatio,r,ID) - assignment@preparedCorrelations <- correlations + assignment@correlations <- correlations return(assignment) }) @@ -127,7 +127,7 @@ setMethod('filterCorrelations',signature = 'Assignment',function(assignment){ ) } - assignment@preparedCorrelations <- cors + assignment@correlations <- cors return(assignment) }) \ No newline at end of file diff --git a/R/plotNetwork.R b/R/plotNetwork.R index 139fda9..2eb365a 100644 --- a/R/plotNetwork.R +++ b/R/plotNetwork.R @@ -76,7 +76,7 @@ setMethod('plotNetwork',signature = 'Assignment', mutate(Assigned = 'Assigned') network <- assignment %>% - .@preparedCorrelations %>% + .@correlations %>% filter(r > rThreshold) %>% as_tbl_graph(directed = F) %>% activate(nodes) %>% diff --git a/R/relationships.R b/R/relationships.R index 65b2c1a..4b38610 100644 --- a/R/relationships.R +++ b/R/relationships.R @@ -20,7 +20,7 @@ setMethod('calcRelationships',signature = 'Assignment', parameters <- as(assignment,'AssignmentParameters') - cors <- assignment@preparedCorrelations + cors <- assignment@correlations if (isTRUE(transformations)) { trans <- c(NA,transformations(assignment)) diff --git a/man/Assignment.Rd b/man/Assignment.Rd index 9df24f0..51bf4b9 100644 --- a/man/Assignment.Rd +++ b/man/Assignment.Rd @@ -18,8 +18,6 @@ An S4 class to store assignment results \item{\code{correlations}}{A tibble containing the correlations} -\item{\code{preparedCorrelations}}{A tibble containing the prepared correlations ready for analysis} - \item{\code{relationships}}{A tibble containing the predicted relationships} \item{\code{addIsoAssign}}{A list containing the results of the adduct and isotope assignment} diff --git a/man/AssignmentParameters-class.Rd b/man/AssignmentParameters-class.Rd index a93ff82..67ca4f9 100644 --- a/man/AssignmentParameters-class.Rd +++ b/man/AssignmentParameters-class.Rd @@ -25,7 +25,7 @@ An S4 class to store assignment parameters. \item{\code{limit}}{amu deviation limit for relationship prediction} -\item{\code{RT_window}}{retention time window for chromatographic associations} +\item{\code{RT_diff_limit}}{limit for retention time differences for correlated features in adduct and isotopic assignment} \item{\code{adducts}}{list of character vectors containing the adducts to use. List element names should denote ionisation mode.} From 483928ea8fd867459f1a2d9d1f63f2b90f9c49c7 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Thu, 31 Mar 2022 10:02:32 +0100 Subject: [PATCH 137/226] apply filter for the numbers of correlations to LC-MS data --- R/correlations.R | 27 ++++++++++----------------- 1 file changed, 10 insertions(+), 17 deletions(-) diff --git a/R/correlations.R b/R/correlations.R index f8c7564..7d2f35b 100644 --- a/R/correlations.R +++ b/R/correlations.R @@ -16,9 +16,9 @@ setMethod('calcCorrelations',signature = 'Assignment',function(assignment){ p@correlations <- parameters@correlations_parameters assignment@correlations <- metabolyse(assignment@data, - tibble(ID = 1:nrow(assignment@data)), - p, - verbose = FALSE) %>% + tibble(ID = 1:nrow(assignment@data)), + p, + verbose = FALSE) %>% analysisResults(element = 'correlations') assignment <- assignment %>% @@ -112,22 +112,15 @@ setGeneric('filterCorrelations', function(assignment) standardGeneric('filterCorrelations')) setMethod('filterCorrelations',signature = 'Assignment',function(assignment){ - - parameters <- as(assignment,'AssignmentParameters') - if (str_detect(parameters@technique,'LC')) { - cors <- assignment@correlations %>% - filter(r < -(parameters@filter$rthresh) | r > parameters@filter$rthresh) - } else { - cors <- assignment@correlations %>% - filterCors(rthresh = parameters@filter$rthresh, - n = parameters@filter$n, - rIncrement = parameters@filter$rIncrement, - nIncrement = parameters@filter$nIncrement - ) - } + parameters <- as(assignment,'AssignmentParameters') - assignment@correlations <- cors + assignment@correlations <- assignment@correlations %>% + filterCors(rthresh = parameters@filter$rthresh, + n = parameters@filter$n, + rIncrement = parameters@filter$rIncrement, + nIncrement = parameters@filter$nIncrement + ) return(assignment) }) \ No newline at end of file From 83d5f9e128c1a85d48efb7e4b7a2abe2e7b4ac31 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Thu, 31 Mar 2022 21:57:25 +0100 Subject: [PATCH 138/226] lowered max M parameter to 600 for LC-MS techniques --- R/parameters.R | 2 ++ 1 file changed, 2 insertions(+) diff --git a/R/parameters.R b/R/parameters.R index 9fb8dac..95b3d99 100644 --- a/R/parameters.R +++ b/R/parameters.R @@ -485,9 +485,11 @@ assignmentParameters <- function(technique = availableTechniques()){ `FIE-HRMS` = new('AssignmentParameters'), `RP-LC-HRMS` = new('AssignmentParameters', technique = 'RP-LC-HRMS', + max_M = 600, RT_diff_limit = 1/60), `NP-LC-HRMS` = new('AssignmentParameters', technique = 'NP-LC-HRMS', + max_M = 600, RT_diff_limit = 1/60, adducts = list(n = c("[M-H]1-", "[M+Cl]1-", "[M+K-2H]1-", "[M-2H]2-", "[M+Cl37]1-","[2M-H]1-"), From ffd24d0c466c8ef6b6559d4c657918b69aae374d Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Thu, 31 Mar 2022 22:55:50 +0100 Subject: [PATCH 139/226] increased max M parameter to 700 for LC-MS --- R/parameters.R | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/R/parameters.R b/R/parameters.R index 95b3d99..692e8d1 100644 --- a/R/parameters.R +++ b/R/parameters.R @@ -485,11 +485,11 @@ assignmentParameters <- function(technique = availableTechniques()){ `FIE-HRMS` = new('AssignmentParameters'), `RP-LC-HRMS` = new('AssignmentParameters', technique = 'RP-LC-HRMS', - max_M = 600, + max_M = 700, RT_diff_limit = 1/60), `NP-LC-HRMS` = new('AssignmentParameters', technique = 'NP-LC-HRMS', - max_M = 600, + max_M = 700, RT_diff_limit = 1/60, adducts = list(n = c("[M-H]1-", "[M+Cl]1-", "[M+K-2H]1-", "[M-2H]2-", "[M+Cl37]1-","[2M-H]1-"), From 8064a2502f94ee4910893c45fb62bf106d2c02d5 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Thu, 14 Apr 2022 15:01:28 +0100 Subject: [PATCH 140/226] removed correlations thresholding parameters and filterCorrelations method --- DESCRIPTION | 2 +- R/correlations.R | 46 +++---------------------- R/parameters.R | 56 +++++++++++++++++-------------- man/AssignmentParameters-class.Rd | 27 ++++++++++----- 4 files changed, 55 insertions(+), 76 deletions(-) diff --git a/DESCRIPTION b/DESCRIPTION index bc948f9..beb2b50 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -41,4 +41,4 @@ Collate: parameters.R assignment.R correlations.R Suggests: testthat, covr Remotes: jasenfinch/mzAnnotation@tmp, - jasenfinch/metabolyseR + jasenfinch/metabolyseR@devel diff --git a/R/correlations.R b/R/correlations.R index 7d2f35b..5c4c059 100644 --- a/R/correlations.R +++ b/R/correlations.R @@ -13,7 +13,11 @@ setMethod('calcCorrelations',signature = 'Assignment',function(assignment){ p <- analysisParameters('correlations') parameters <- as(assignment,'AssignmentParameters') - p@correlations <- parameters@correlations_parameters + p@correlations <- parameters@correlations_parameters[c('method', + 'pAdjustMethod', + 'corPvalue', + 'minCoef', + 'maxCor')] assignment@correlations <- metabolyse(assignment@data, tibble(ID = 1:nrow(assignment@data)), @@ -22,7 +26,6 @@ setMethod('calcCorrelations',signature = 'Assignment',function(assignment){ analysisResults(element = 'correlations') assignment <- assignment %>% - filterCorrelations() %>% prepCorrelations() if (assignment@log$verbose == TRUE) { @@ -40,28 +43,6 @@ setMethod('calcCorrelations',signature = 'Assignment',function(assignment){ return(assignment) }) - -filterCors <- function(correlations, rthresh = 0.7, n = 100000, rIncrement = 0.01, nIncrement = 20000){ - filCors <- function(cors,rthresh,n){ - while (nrow(cors) > n) { - cors <- correlations %>% - filter(r > rthresh | r < -rthresh) - rthresh <- rthresh + rIncrement - } - return(cors) - } - - while (TRUE) { - cors <- filCors(correlations,rthresh,n) - if (nrow(cors) > 0) { - break() - } else { - n <- n + nIncrement - } - } - return(cors) -} - setGeneric('prepCorrelations', function(assignment) standardGeneric('prepCorrelations')) @@ -107,20 +88,3 @@ setMethod('prepCorrelations',signature = 'Assignment', return(assignment) }) - -setGeneric('filterCorrelations', function(assignment) - standardGeneric('filterCorrelations')) - -setMethod('filterCorrelations',signature = 'Assignment',function(assignment){ - - parameters <- as(assignment,'AssignmentParameters') - - assignment@correlations <- assignment@correlations %>% - filterCors(rthresh = parameters@filter$rthresh, - n = parameters@filter$n, - rIncrement = parameters@filter$rIncrement, - nIncrement = parameters@filter$nIncrement - ) - - return(assignment) -}) \ No newline at end of file diff --git a/R/parameters.R b/R/parameters.R index 692e8d1..a0ccbb3 100644 --- a/R/parameters.R +++ b/R/parameters.R @@ -2,20 +2,19 @@ #' @rdname AssignmentParameters-class #' @description An S4 class to store assignment parameters. #' @slot technique assignment technique to use -#' @slot correlations_parameters list of correlation parameters to be passed to metabolyseR correlation analysis -#' @slot filter list of r and n thresholds for filtering correlations +#' @slot correlations_parameters list of correlation parameters to be passed to `metabolyseR::correlation()` #' @slot max_M maximum M for which to assign molecular formulas #' @slot MF_rank_threshold rank threshold for molecular formula selection #' @slot ppm ppm threshold -#' #' @slot adducts named list of character vectors containing the adducuts to use for each mode +#' @slot adducts named list of character vectors containing the adducts to use for each mode #' @slot limit amu deviation limit for relationship prediction #' @slot RT_diff_limit limit for retention time differences for correlated features in adduct and isotopic assignment #' @slot adducts list of character vectors containing the adducts to use. List element names should denote ionisation mode. #' @slot isotopes character vector of isotopes to use #' @slot transformations character vector of transformations to use -#' @slot adduct_rules tibble containing adduct formation rules as returned by mzAnnotation::adducts() -#' @slot isotope_rules tibble containing isotope rules as returned by mzAnnotation::isotopes() -#' @slot transformation_rules tibble containing transformation rules as returned by mzAnnotation::transformations() +#' @slot adduct_rules tibble containing adduct formation rules as returned by `mzAnnotation::adducts()` +#' @slot isotope_rules tibble containing isotope rules as returned by `mzAnnotation::isotopes()` +#' @slot transformation_rules tibble containing transformation rules as returned by `mzAnnotation::transformations()` #' @importFrom mzAnnotation adduct_rules isotope_rules transformation_rules #' @export @@ -23,7 +22,6 @@ setClass('AssignmentParameters', slots = list( technique = 'character', correlations_parameters = 'list', - filter = 'list', max_M = 'numeric', MF_rank_threshold = 'numeric', ppm = 'numeric', @@ -40,11 +38,9 @@ setClass('AssignmentParameters', technique = 'FIE-HRMS', correlations_parameters = list(method = 'spearman', pAdjustMethod = 'bonferroni', - corPvalue = 0.05), - filter = list(rthresh = 0.7, - n = 500000, - rIncrement = 0.01, - nIncrement = 20000), + corPvalue = 0.05, + minCoef = 0.7, + maxCor = 500000), max_M = 800, MF_rank_threshold = 1, ppm = 6, @@ -68,10 +64,18 @@ setValidity('AssignmentParameters',function(object){ availableTechniques() %>% paste(collapse = ', ') %>% paste0('Technique should be one of ',.) - } + } else TRUE }) +# setValidity('AssignmentParameters',function(object){ +# correlations_parameters <- object@correlations_parameters +# +# if (){ +# +# } +# }) + #' @importFrom methods show #' @importFrom crayon yellow #' @importFrom purrr map @@ -482,19 +486,19 @@ assignmentParameters <- function(technique = availableTechniques()){ choices = availableTechniques()) parameters <- switch(technique, - `FIE-HRMS` = new('AssignmentParameters'), - `RP-LC-HRMS` = new('AssignmentParameters', - technique = 'RP-LC-HRMS', - max_M = 700, - RT_diff_limit = 1/60), - `NP-LC-HRMS` = new('AssignmentParameters', - technique = 'NP-LC-HRMS', - max_M = 700, - RT_diff_limit = 1/60, - adducts = list(n = c("[M-H]1-", "[M+Cl]1-", "[M+K-2H]1-", - "[M-2H]2-", "[M+Cl37]1-","[2M-H]1-"), - p = c('[M+H]1+','[M+K]1+','[M+Na]1+','[M+K41]1+', - '[M+NH4]1+','[M+2H]2+','[2M+H]1+')))) + `FIE-HRMS` = new('AssignmentParameters'), + `RP-LC-HRMS` = new('AssignmentParameters', + technique = 'RP-LC-HRMS', + max_M = 700, + RT_diff_limit = 1/60), + `NP-LC-HRMS` = new('AssignmentParameters', + technique = 'NP-LC-HRMS', + max_M = 700, + RT_diff_limit = 1/60, + adducts = list(n = c("[M-H]1-", "[M+Cl]1-", "[M+K-2H]1-", + "[M-2H]2-", "[M+Cl37]1-","[2M-H]1-"), + p = c('[M+H]1+','[M+K]1+','[M+Na]1+','[M+K41]1+', + '[M+NH4]1+','[M+2H]2+','[2M+H]1+')))) return(parameters) } \ No newline at end of file diff --git a/man/AssignmentParameters-class.Rd b/man/AssignmentParameters-class.Rd index 67ca4f9..798c6df 100644 --- a/man/AssignmentParameters-class.Rd +++ b/man/AssignmentParameters-class.Rd @@ -7,21 +7,32 @@ \description{ An S4 class to store assignment parameters. } +\details{ +The correlations parameters should be provided as a list containing the following parameters: +\itemize{ +\item \code{method}: Correlation method to use. See \code{metabolyseR::correlations} for more information. +\item \code{pAdjustMethod} +\item \code{corPvalue} +\item \code{rthresh} +\item \code{n} +\item \code{rIncrement} +\item \code{nIncrement} +} +} \section{Slots}{ \describe{ \item{\code{technique}}{assignment technique to use} -\item{\code{correlations_parameters}}{list of correlation parameters to be passed to metabolyseR correlation analysis} - -\item{\code{filter}}{list of r and n thresholds for filtering correlations} +\item{\code{correlations_parameters}}{list of correlation parameters. See Details.} \item{\code{max_M}}{maximum M for which to assign molecular formulas} \item{\code{MF_rank_threshold}}{rank threshold for molecular formula selection} -\item{\code{ppm}}{ppm threshold -#' @slot adducts named list of character vectors containing the adducuts to use for each mode} +\item{\code{ppm}}{ppm threshold} + +\item{\code{adducts}}{named list of character vectors containing the adducts to use for each mode} \item{\code{limit}}{amu deviation limit for relationship prediction} @@ -33,10 +44,10 @@ An S4 class to store assignment parameters. \item{\code{transformations}}{character vector of transformations to use} -\item{\code{adduct_rules}}{tibble containing adduct formation rules as returned by mzAnnotation::adducts()} +\item{\code{adduct_rules}}{tibble containing adduct formation rules as returned by \code{mzAnnotation::adducts()}} -\item{\code{isotope_rules}}{tibble containing isotope rules as returned by mzAnnotation::isotopes()} +\item{\code{isotope_rules}}{tibble containing isotope rules as returned by \code{mzAnnotation::isotopes()}} -\item{\code{transformation_rules}}{tibble containing transformation rules as returned by mzAnnotation::transformations()} +\item{\code{transformation_rules}}{tibble containing transformation rules as returned by \code{mzAnnotation::transformations()}} }} From 63ce32005209262db1d36af23c887eef3f1811cc Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Thu, 14 Apr 2022 17:23:46 +0100 Subject: [PATCH 141/226] remove preparing correlations console message --- R/correlations.R | 5 ----- 1 file changed, 5 deletions(-) diff --git a/R/correlations.R b/R/correlations.R index 5c4c059..c295fdb 100644 --- a/R/correlations.R +++ b/R/correlations.R @@ -49,11 +49,6 @@ setGeneric('prepCorrelations', function(assignment) setMethod('prepCorrelations',signature = 'Assignment', function(assignment){ - if (assignment@log$verbose == TRUE) { - startTime <- proc.time() - message(blue('Preparing correlations '),cli::symbol$continue,'\r',appendLF = FALSE) - } - correlations <- assignment@correlations correlations <- correlations %>% From f859e5e07990ff8b3c4e6d64643f4b44127f8030 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Thu, 14 Apr 2022 17:43:46 +0100 Subject: [PATCH 142/226] fix renaming of correlation coefficient column --- R/addIsoAssign.R | 2 +- R/components.R | 4 ++-- R/correlations.R | 2 +- R/plotNetwork.R | 4 ++-- R/relationships.R | 2 +- 5 files changed, 7 insertions(+), 7 deletions(-) diff --git a/R/addIsoAssign.R b/R/addIsoAssign.R index f70d04e..214e42f 100644 --- a/R/addIsoAssign.R +++ b/R/addIsoAssign.R @@ -33,7 +33,7 @@ setMethod('addIsoAssign',signature = 'Assignment', rel <- rel %>% filter(is.na(Transformation1) & is.na(Transformation2) & - r > 0) %>% + coefficient > 0) %>% filter(!(is.na(Isotope1) & !is.na(Isotope2) & Adduct1 == Adduct2 & diff --git a/R/components.R b/R/components.R index 96c90cc..10e8ef8 100644 --- a/R/components.R +++ b/R/components.R @@ -73,7 +73,7 @@ calcComponents <- function(graph_nodes, graph %>% filter(Component == .x) %>% edges() %>% - .$r %>% + .$coefficient %>% mean() %>% tibble(Weight = .) },graph = graph) %>% @@ -114,7 +114,7 @@ recalcComponents <- function(graph, graph %>% filter(Component == .x) %>% edges() %>% - .$r %>% + .$coefficient %>% mean() %>% tibble(Weight = .) },graph = g) %>% diff --git a/R/correlations.R b/R/correlations.R index c295fdb..7d41602 100644 --- a/R/correlations.R +++ b/R/correlations.R @@ -77,7 +77,7 @@ setMethod('prepCorrelations',signature = 'Assignment', ) %>% select(Feature1,Feature2, Mode1:RetentionTimeDiff, - log2IntensityRatio,r,ID) + log2IntensityRatio,coefficient,ID) assignment@correlations <- correlations diff --git a/R/plotNetwork.R b/R/plotNetwork.R index 2eb365a..52620ee 100644 --- a/R/plotNetwork.R +++ b/R/plotNetwork.R @@ -77,14 +77,14 @@ setMethod('plotNetwork',signature = 'Assignment', network <- assignment %>% .@correlations %>% - filter(r > rThreshold) %>% + filter(coefficient > rThreshold) %>% as_tbl_graph(directed = F) %>% activate(nodes) %>% rename(Feature = name) %>% mutate(Mode = str_sub(Feature,1,1)) %>% left_join(n, by = "Feature") %>% activate(edges) %>% - left_join(e, by = c("Mode1", "Mode2", "m/z1", "m/z2", "RetentionTime1", "RetentionTime2", "log2IntensityRatio", "r", "ID")) + left_join(e, by = c("Mode1", "Mode2", "m/z1", "m/z2", "RetentionTime1", "RetentionTime2", "log2IntensityRatio", "coefficient", "ID")) assigned <- nodes(network)$Assigned assigned[is.na(assigned)] <- 'Unassigned' diff --git a/R/relationships.R b/R/relationships.R index 4b38610..2a4b5bf 100644 --- a/R/relationships.R +++ b/R/relationships.R @@ -93,7 +93,7 @@ setMethod('calcRelationships',signature = 'Assignment', contains('Isotope'), contains('Transformation'), log2IntensityRatio, - r, + coefficient, Error, ID) %>% mutate_at(vars(RetentionTime1,RetentionTime2),as.numeric) From 8056aea977b378b6f292ca9b192a49717d48fb40 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Wed, 27 Apr 2022 17:20:41 +0100 Subject: [PATCH 143/226] transformation graphs now sanitised to ensure only possible transformations between MFs allowed --- R/internals.R | 32 ++++++++++++++++++++++++++++++++ R/transformationAssign.R | 16 ++++++++++------ 2 files changed, 42 insertions(+), 6 deletions(-) diff --git a/R/internals.R b/R/internals.R index d141e6c..ba46c11 100644 --- a/R/internals.R +++ b/R/internals.R @@ -250,3 +250,35 @@ generateMFs <- function(M, }, .options = furrr_options(seed = 1234)) } + +#' @importFrom mzAnnotation transformationPossible + +sanitiseTransformations <- function(graph_edges,transformation_rules_table){ + transforms <- dplyr::bind_rows( + graph_edges %>% + filter(is.na(Transformation1)) %>% + select( + from = MF1, + to = MF2, + transformation = Transformation2), + graph_edges %>% + filter(is.na(Transformation2)) %>% + select( + from = MF2, + to = MF1, + transformation = Transformation1) + + ) + + transformation_possible <- transforms %>% + rowwise() %>% + group_split() %>% + map_lgl(~mzAnnotation::transformationPossible( + .x$from, + .x$to, + .x$transformation, + transformation_rules_table)) + + graph_edges %>% + filter(transformation_possible) +} diff --git a/R/transformationAssign.R b/R/transformationAssign.R index ee31fa5..d67df57 100644 --- a/R/transformationAssign.R +++ b/R/transformationAssign.R @@ -10,9 +10,9 @@ setMethod('transformationAssign',signature = 'Assignment', function(assignment){ count <- length(assignment@transAssign) - assigned <- assignment@assignments + assigned <- assignments(assignment) - if (assignment@log$verbose == T) { + if (assignment@log$verbose == TRUE) { startTime <- proc.time() message(blue(str_c('Transformation assignment iteration ', count + 1,' ')), @@ -23,10 +23,13 @@ setMethod('transformationAssign',signature = 'Assignment', rel <- assignment %>% relationships() %>% - filter((`m/z1` %in% assigned$`Measured m/z` | - (`m/z2` %in% assigned$`Measured m/z`)) & - !(`m/z1` %in% assigned$`Measured m/z` & - (`m/z2` %in% assigned$`Measured m/z`))) + filter( + (`m/z1` %in% assigned$`Measured m/z` | + (`m/z2` %in% assigned$`Measured m/z`)) & + !(`m/z1` %in% assigned$`Measured m/z` & + (`m/z2` %in% assigned$`Measured m/z`)), + !(is.na(Transformation1) & is.na(Transformation2)) + ) mz1 <- rel %>% semi_join(assigned, @@ -69,6 +72,7 @@ setMethod('transformationAssign',signature = 'Assignment', graph_edges <- rel %>% addMFs(MFs, identMF = FALSE) %>% + sanitiseTransformations(assignment@transformation_rules) %>% mutate(RetentionTime1 = as.numeric(RetentionTime1), RetentionTime2 = as.numeric(RetentionTime2)) %>% addNames() From 1c599be3a92915c103b46f6af852eed12b1eb24b Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Wed, 27 Apr 2022 17:45:28 +0100 Subject: [PATCH 144/226] increased default rank threshold to 10 --- R/parameters.R | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/R/parameters.R b/R/parameters.R index a0ccbb3..769d648 100644 --- a/R/parameters.R +++ b/R/parameters.R @@ -42,7 +42,7 @@ setClass('AssignmentParameters', minCoef = 0.7, maxCor = 500000), max_M = 800, - MF_rank_threshold = 1, + MF_rank_threshold = 10, ppm = 6, limit = 0.001, RT_diff_limit = numeric(), From e36e1e7519706947e3d4703bab2966b6adc019b4 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Thu, 28 Apr 2022 09:11:55 +0100 Subject: [PATCH 145/226] set default MF rank threshold to 3 --- R/parameters.R | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/R/parameters.R b/R/parameters.R index 769d648..369d296 100644 --- a/R/parameters.R +++ b/R/parameters.R @@ -42,7 +42,7 @@ setClass('AssignmentParameters', minCoef = 0.7, maxCor = 500000), max_M = 800, - MF_rank_threshold = 10, + MF_rank_threshold = 3, ppm = 6, limit = 0.001, RT_diff_limit = numeric(), From c9bb05678dec96b513e7a742d6d9b10bca1c7253 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Thu, 28 Apr 2022 14:36:05 +0100 Subject: [PATCH 146/226] remove components containing only isotopic adducts --- R/components.R | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/R/components.R b/R/components.R index 10e8ef8..bb52e77 100644 --- a/R/components.R +++ b/R/components.R @@ -9,7 +9,7 @@ plausibility <- function(AIS,degree,weight){ #' @importFrom purrr compact -clean <- function(graph){ +clean <- function(graph,adduct_rules_table){ graph %>% morph(to_components) %>% map(~{ @@ -20,6 +20,18 @@ clean <- function(graph){ else NULL }) %>% compact() %>% + map(~{ + component_nodes <- nodes(.x) + component_adducts <- component_nodes$Adduct %>% + unique() + + adduct_info <- adduct_rules_table %>% + filter(Name %in% component_adducts) + + if (0 %in% adduct_info$Isotopic) return(.x) + else NULL + }) %>% + compact() %>% bind_graphs() } @@ -60,7 +72,7 @@ calcComponents <- function(graph_nodes, activate(nodes) %>% left_join(graph_nodes,by = c('name' = 'Name')) %>% mutate(Component = group_components()) %>% - clean() + clean(adductRules(assignment)) if (nComponents(graph) > 0){ comp <- graph %>% @@ -98,7 +110,7 @@ recalcComponents <- function(graph, assignment){ graph <- graph %>% - clean() + clean(adductRules(assignment)) if (nComponents(graph) > 0){ g <- graph %>% From 6573c9669aede2c3329b720d01a4b47ea4b626f3 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Sat, 30 Apr 2022 12:34:24 +0100 Subject: [PATCH 147/226] remove components containing only isotopic adducts and isotopic features --- R/components.R | 38 +++++++++++++++++++++----------------- 1 file changed, 21 insertions(+), 17 deletions(-) diff --git a/R/components.R b/R/components.R index bb52e77..eb41078 100644 --- a/R/components.R +++ b/R/components.R @@ -12,26 +12,30 @@ plausibility <- function(AIS,degree,weight){ clean <- function(graph,adduct_rules_table){ graph %>% morph(to_components) %>% - map(~{ - component_nodes <- nodes(.x) + furrr::future_map(~{ + component_adducts <- .x %>% + nodes() %>% + .$Adduct %>% + unique() + + adduct_info <- adduct_rules_table %>% + select(Adduct = Name, + adduct_isotopic = Isotopic) + + component_nodes <- .x %>% + nodes() %>% + left_join(adduct_info, + by = "Adduct") %>% + mutate(isotopic = !is.na(Isotope), + adduct_isotopic = as.logical(adduct_isotopic), + either_isotopic = adduct_isotopic | isotopic) - if (nrow(component_nodes) > 1 & - NA %in% component_nodes$Isotope) return(.x) - else NULL + if (all(component_nodes$isotopic) == TRUE | + all(component_nodes$adduct_isotopic) == TRUE | + all(component_nodes$either_isotopic) == TRUE) NULL + else return(.x) }) %>% compact() %>% - map(~{ - component_nodes <- nodes(.x) - component_adducts <- component_nodes$Adduct %>% - unique() - - adduct_info <- adduct_rules_table %>% - filter(Name %in% component_adducts) - - if (0 %in% adduct_info$Isotopic) return(.x) - else NULL - }) %>% - compact() %>% bind_graphs() } From 1c69e7ae62444567e964e2f0ec5a21e41ee026e8 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Sat, 30 Apr 2022 15:20:18 +0100 Subject: [PATCH 148/226] added correlations accessor methods and check validity of correlations parameters --- NAMESPACE | 5 ++++ R/parameters.R | 50 ++++++++++++++++++++++++++----- man/AssignmentParameters-class.Rd | 14 +-------- man/parameters.Rd | 12 ++++++++ 4 files changed, 61 insertions(+), 20 deletions(-) diff --git a/NAMESPACE b/NAMESPACE index ad76498..2287f27 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -3,6 +3,7 @@ export("MFrankThreshold<-") export("adductRules<-") export("adducts<-") +export("correlations<-") export("isotopeRules<-") export("isotopes<-") export("limit<-") @@ -19,6 +20,7 @@ export(assignmentData) export(assignmentParameters) export(assignments) export(availableTechniques) +export(correlations) export(edges) export(isotopeRules) export(isotopes) @@ -115,6 +117,7 @@ importFrom(magrittr,"%>%") importFrom(magrittr,set_names) importFrom(metabolyseR,analysisParameters) importFrom(metabolyseR,analysisResults) +importFrom(metabolyseR,correlationsParameters) importFrom(metabolyseR,dat) importFrom(metabolyseR,metabolyse) importFrom(metabolyseR,preTreated) @@ -122,12 +125,14 @@ importFrom(metabolyseR,raw) importFrom(methods,as) importFrom(methods,new) importFrom(methods,show) +importFrom(methods,validObject) importFrom(mzAnnotation,adduct_rules) importFrom(mzAnnotation,calcM) importFrom(mzAnnotation,ipMF) importFrom(mzAnnotation,isotope_rules) importFrom(mzAnnotation,relationshipCalculator) importFrom(mzAnnotation,transformMF) +importFrom(mzAnnotation,transformationPossible) importFrom(mzAnnotation,transformation_rules) importFrom(patchwork,plot_annotation) importFrom(patchwork,plot_layout) diff --git a/R/parameters.R b/R/parameters.R index 369d296..4198f44 100644 --- a/R/parameters.R +++ b/R/parameters.R @@ -68,13 +68,22 @@ setValidity('AssignmentParameters',function(object){ else TRUE }) -# setValidity('AssignmentParameters',function(object){ -# correlations_parameters <- object@correlations_parameters -# -# if (){ -# -# } -# }) +#' @importFrom metabolyseR correlationsParameters + +setValidity('AssignmentParameters',function(object){ + + correlations_parameters <- correlationsParameters() %>% + names() + + if (!any(names(object@correlations_parameters) %in% + correlations_parameters)) { + correlations_parameters %>% + paste0('`',.,'`') %>% + paste(collapse = ', ') %>% + paste0('Correlations parameters should only include ',.) + } + else TRUE +}) #' @importFrom methods show #' @importFrom crayon yellow @@ -196,6 +205,33 @@ setMethod('technique',signature = 'AssignmentParameters', #' @rdname parameters #' @export +setGeneric('correlations', + function(x) standardGeneric('correlations')) + +#' @rdname parameters + +setMethod('correlations',signature = 'AssignmentParameters', + function(x) x@correlations_parameters) + +#' @rdname parameters +#' @export + +setGeneric('correlations<-', + function(x,value) standardGeneric('correlations<-')) + +#' @rdname parameters +#' @importFrom methods validObject + +setMethod('correlations<-',signature = c('AssignmentParameters','list'), + function(x,value){ + x@correlations_parameters <- value + validObject(x) + return(x) + }) + +#' @rdname parameters +#' @export + setGeneric('limit',function(x) standardGeneric('limit')) diff --git a/man/AssignmentParameters-class.Rd b/man/AssignmentParameters-class.Rd index 798c6df..b3ae0c3 100644 --- a/man/AssignmentParameters-class.Rd +++ b/man/AssignmentParameters-class.Rd @@ -7,24 +7,12 @@ \description{ An S4 class to store assignment parameters. } -\details{ -The correlations parameters should be provided as a list containing the following parameters: -\itemize{ -\item \code{method}: Correlation method to use. See \code{metabolyseR::correlations} for more information. -\item \code{pAdjustMethod} -\item \code{corPvalue} -\item \code{rthresh} -\item \code{n} -\item \code{rIncrement} -\item \code{nIncrement} -} -} \section{Slots}{ \describe{ \item{\code{technique}}{assignment technique to use} -\item{\code{correlations_parameters}}{list of correlation parameters. See Details.} +\item{\code{correlations_parameters}}{list of correlation parameters to be passed to \code{metabolyseR::correlation()}} \item{\code{max_M}}{maximum M for which to assign molecular formulas} diff --git a/man/parameters.Rd b/man/parameters.Rd index a7dc180..909bba5 100644 --- a/man/parameters.Rd +++ b/man/parameters.Rd @@ -3,6 +3,10 @@ \name{technique} \alias{technique} \alias{technique,AssignmentParameters-method} +\alias{correlations} +\alias{correlations,AssignmentParameters-method} +\alias{correlations<-} +\alias{correlations<-,AssignmentParameters,list-method} \alias{limit} \alias{limit,AssignmentParameters-method} \alias{limit<-} @@ -49,6 +53,14 @@ technique(x) \S4method{technique}{AssignmentParameters}(x) +correlations(x) + +\S4method{correlations}{AssignmentParameters}(x) + +correlations(x) <- value + +\S4method{correlations}{AssignmentParameters,list}(x) <- value + limit(x) \S4method{limit}{AssignmentParameters}(x) From 7a2a7a0a46b948b69b596cab9b83b4ba7a26e321 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Sat, 30 Apr 2022 15:24:31 +0100 Subject: [PATCH 149/226] added correlations parameters to AssignmentParameters class show method --- R/parameters.R | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/R/parameters.R b/R/parameters.R index 4198f44..131a62c 100644 --- a/R/parameters.R +++ b/R/parameters.R @@ -103,6 +103,12 @@ setMethod('show',signature = 'AssignmentParameters', cat('\t','RT limit:\t\t',object@RT_diff_limit,'\n') } + + cat('\t','Correlations:\n') + correlations(object) %>% + paste0('\t\t',names(.),': ',.,'\n') %>% + cat() + cat('\n\t','Adducts:','\n') adducts <- map(names(object@adducts),~{ a <- str_c(object@adducts[[.]],collapse = ', ') From 183fea31ccb8d9f8813badcf090b90dc570b0036 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Sat, 30 Apr 2022 15:26:17 +0100 Subject: [PATCH 150/226] bumped version to 1.0.0 --- DESCRIPTION | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/DESCRIPTION b/DESCRIPTION index beb2b50..20e807b 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -1,6 +1,6 @@ Package: MFassign Title: Molecular formula assignment for high resolution metabolomics -Version: 0.8.0 +Version: 1.0.0 Authors@R: person("Jasen", "Finch", email = "jsf9@aber.ac.uk", role = c("aut", "cre")) Description: Molecular formula assignment for high resolution metabolomics. Depends: R (>= 3.5.0), From b02b675a3df621e347b74bb8ee851c00bd84135f Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Tue, 3 May 2022 20:47:14 +0100 Subject: [PATCH 151/226] moved plotting packages to suggests --- DESCRIPTION | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/DESCRIPTION b/DESCRIPTION index 20e807b..9742428 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -11,17 +11,12 @@ Imports: CHNOSZ, dplyr, furrr, future, - ggplot2, - ggrepel, - ggthemes, - graphlayouts, igraph, lubridate, magrittr, + metabolyseR, methods, mzAnnotation, - metabolyseR, - patchwork, purrr, stringr, tibble, @@ -39,6 +34,12 @@ Collate: parameters.R assignment.R correlations.R plotAdductDist.R plotFeatureSolutions.R plotSpectrum.R reexports.R zzz.R Suggests: testthat, - covr + covr, + ggplot2, + ggrepel, + ggthemes, + graphlayouts, + patchwork + Remotes: jasenfinch/mzAnnotation@tmp, jasenfinch/metabolyseR@devel From ff1b5c157578d3900d4a050b5cc8bfc2a4e63e69 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Tue, 3 May 2022 21:12:16 +0100 Subject: [PATCH 152/226] moved plotting dependencies to Suggests field in DESCRIPTION --- DESCRIPTION | 7 ++-- NAMESPACE | 37 +------------------- R/plotAdductDist.R | 43 ++++++++++++----------- R/plotFeatureSolutions.R | 73 ++++++++++++++++++++++------------------ R/plotNetwork.R | 27 ++++++++------- R/plotSpectrum.R | 40 +++++++++++++--------- 6 files changed, 107 insertions(+), 120 deletions(-) diff --git a/DESCRIPTION b/DESCRIPTION index 9742428..d476690 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -4,9 +4,7 @@ Version: 1.0.0 Authors@R: person("Jasen", "Finch", email = "jsf9@aber.ac.uk", role = c("aut", "cre")) Description: Molecular formula assignment for high resolution metabolomics. Depends: R (>= 3.5.0), - ggraph -Imports: CHNOSZ, - cli, +Imports: cli, crayon, dplyr, furrr, @@ -18,6 +16,7 @@ Imports: CHNOSZ, methods, mzAnnotation, purrr, + rlang, stringr, tibble, tidygraph, @@ -36,10 +35,10 @@ Collate: parameters.R assignment.R correlations.R Suggests: testthat, covr, ggplot2, + ggraph, ggrepel, ggthemes, graphlayouts, patchwork - Remotes: jasenfinch/mzAnnotation@tmp, jasenfinch/metabolyseR@devel diff --git a/NAMESPACE b/NAMESPACE index 2287f27..e3a5e32 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -73,39 +73,6 @@ importFrom(furrr,furrr_options) importFrom(furrr,future_map) importFrom(furrr,future_map_dfr) importFrom(future,plan) -importFrom(ggplot2,aes) -importFrom(ggplot2,coord_fixed) -importFrom(ggplot2,element_blank) -importFrom(ggplot2,element_line) -importFrom(ggplot2,element_text) -importFrom(ggplot2,facet_wrap) -importFrom(ggplot2,geom_bar) -importFrom(ggplot2,geom_segment) -importFrom(ggplot2,ggplot) -importFrom(ggplot2,guides) -importFrom(ggplot2,labs) -importFrom(ggplot2,margin) -importFrom(ggplot2,scale_fill_manual) -importFrom(ggplot2,scale_x_discrete) -importFrom(ggplot2,scale_y_continuous) -importFrom(ggplot2,theme) -importFrom(ggplot2,theme_bw) -importFrom(ggplot2,xlim) -importFrom(ggplot2,ylim) -importFrom(ggraph,create_layout) -importFrom(ggraph,facet_edges) -importFrom(ggraph,geom_edge_link) -importFrom(ggraph,geom_node_label) -importFrom(ggraph,geom_node_point) -importFrom(ggraph,geom_node_text) -importFrom(ggraph,ggraph) -importFrom(ggraph,guide_edge_colourbar) -importFrom(ggraph,scale_edge_color_gradient) -importFrom(ggraph,theme_graph) -importFrom(ggrepel,geom_text_repel) -importFrom(ggthemes,ptol_pal) -importFrom(ggthemes,scale_fill_ptol) -importFrom(graphlayouts,layout_igraph_stress) importFrom(igraph,E) importFrom(igraph,V) importFrom(igraph,edge.attributes) @@ -134,15 +101,13 @@ importFrom(mzAnnotation,relationshipCalculator) importFrom(mzAnnotation,transformMF) importFrom(mzAnnotation,transformationPossible) importFrom(mzAnnotation,transformation_rules) -importFrom(patchwork,plot_annotation) -importFrom(patchwork,plot_layout) -importFrom(patchwork,wrap_plots) importFrom(purrr,compact) importFrom(purrr,flatten_chr) importFrom(purrr,map) importFrom(purrr,map_dbl) importFrom(purrr,map_dfr) importFrom(purrr,map_lgl) +importFrom(rlang,check_installed) importFrom(stringr,str_c) importFrom(stringr,str_detect) importFrom(stringr,str_remove) diff --git a/R/plotAdductDist.R b/R/plotAdductDist.R index bd48d7a..6d4e889 100644 --- a/R/plotAdductDist.R +++ b/R/plotAdductDist.R @@ -1,33 +1,33 @@ -#' @importFrom ggthemes ptol_pal -#' @importFrom ggplot2 ggplot geom_bar theme_bw facet_wrap theme element_text element_line scale_y_continuous scale_x_discrete - plotDist <- function(x){ - ggplot(x,aes(x = Adduct)) + - geom_bar(colour = 'black',fill = ptol_pal()(1)) + - scale_y_continuous(expand = c(0,0)) + - scale_x_discrete(expand = c(0,0)) + - theme_bw() + - facet_wrap(~Isotope, + check_installed(c('ggplot2', + 'ggthemes')) + + ggplot2::ggplot(x,ggplot2::aes(x = Adduct)) + + ggplot2::geom_bar(colour = 'black', + fill = ggthemes::ptol_pal()(1)) + + ggplot2::scale_y_continuous(expand = c(0,0)) + + ggplot2::scale_x_discrete(expand = c(0,0)) + + ggplot2::theme_bw() + + ggplot2::facet_wrap(~Isotope, scales = 'free') + - labs(title = x$Mode[1], + ggplot2::labs(title = x$Mode[1], y = 'Count', caption = str_c('N = ',nrow(x))) + - theme(plot.title = element_text(face = 'bold',hjust = 0.5), - axis.title = element_text(face = 'bold'), - axis.text.x = element_text(angle = 45, hjust = 1), - panel.border = element_blank(), - axis.line = element_line(), - panel.grid = element_blank(), - strip.background = element_blank(), - strip.text = element_text(face = 'bold')) + ggplot2::theme(plot.title = ggplot2::element_text(face = 'bold',hjust = 0.5), + axis.title = ggplot2::element_text(face = 'bold'), + axis.text.x = ggplot2::element_text(angle = 45, hjust = 1), + panel.border = ggplot2::element_blank(), + axis.line = ggplot2::element_line(), + panel.grid = ggplot2::element_blank(), + strip.background = ggplot2::element_blank(), + strip.text = ggplot2::element_text(face = 'bold')) } #' Plot adduct frequency distributions #' @rdname plotAdductDist #' @description Plot adduct frequency distributions. #' @param assignment S4 object of class Assignment -#' @importFrom patchwork wrap_plots #' @importFrom tidyr replace_na #' @export @@ -36,10 +36,13 @@ setGeneric('plotAdductDist',function(assignment){ }) #' @rdname plotAdductDist +#' @importFrom rlang check_installed setMethod('plotAdductDist',signature = 'Assignment', function(assignment){ + check_installed('patchwork') + assign <- assignment %>% assignments() %>% replace_na(list(Isotope = '')) %>% @@ -53,6 +56,6 @@ setMethod('plotAdductDist',signature = 'Assignment', assign %>% split(.$Mode) %>% map(plotDist) %>% - wrap_plots() + patchwork::wrap_plots() } ) \ No newline at end of file diff --git a/R/plotFeatureSolutions.R b/R/plotFeatureSolutions.R index c97025b..a22acc4 100644 --- a/R/plotFeatureSolutions.R +++ b/R/plotFeatureSolutions.R @@ -1,8 +1,8 @@ -#' @importFrom patchwork plot_annotation plot_layout -#' @importFrom ggraph create_layout scale_edge_color_gradient geom_node_label guide_edge_colourbar -#' @importFrom ggplot2 scale_fill_manual margin xlim ylim guides plotSolutions <- function(graph,selectedComp,feature){ + check_installed(c('ggraph', + 'ggplot2', + 'patchwork')) graph %>% map(~{ stats <- nodes(.) %>% @@ -19,36 +19,45 @@ plotSolutions <- function(graph,selectedComp,feature){ g <- g %>% mutate(Feat = Feature == feature) %>% create_layout('nicely') - ggraph(g) + - geom_edge_link(aes(colour = r)) + - scale_edge_color_gradient(low = 'white',high = 'black',limits = c(0.5,1)) + - geom_node_label(aes(label = name,fill = Feat),size = 2,) + - scale_fill_manual(values = c('white','steelblue')) + - theme_graph(base_family = '', - title_size = 12, - title_face = 'plain', - foreground = border, - plot_margin = margin(5, 5, 5, 5)) + - theme(plot.title = element_text(face = 'bold', - hjust = 0.5), - plot.caption = element_text(hjust = 0)) + - labs(title = str_c('Component ',stats$Component), - caption = str_c('Degree = ',stats$Degree %>% round(2),'; ', - 'Weight = ',stats$Weight %>% round(2),'; ', - 'AIS = ',stats$AIS %>% round(2),'; ', - 'Plausibility = ',stats$`Component Plausibility` %>% round(2))) + - xlim(min(g$x) - (max(g$x) - min(g$x)) * 0.05, - max(g$x) + (max(g$x) - min(g$x)) * 0.05) + - ylim(min(g$y) - (max(g$y) - min(g$y)) * 0.05, - max(g$y) + (max(g$y) - min(g$y)) * 0.05) + - guides(fill = 'none') + ggraph::ggraph(g) + + ggraph::geom_edge_link(ggplot2::aes(colour = r)) + + ggraph::scale_edge_color_gradient(low = 'white', + high = 'black', + limits = c(0.5,1)) + + ggraph::geom_node_label(ggplot2::aes(label = name, + fill = Feat), + size = 2,) + + ggplot2::scale_fill_manual(values = c('white','steelblue')) + + ggraph::theme_graph(base_family = '', + title_size = 12, + title_face = 'plain', + foreground = border, + plot_margin = ggplot2::margin(5, 5, 5, 5)) + + ggplot2::theme( + plot.title = ggplot2::element_text(face = 'bold', + hjust = 0.5), + plot.caption = ggplot2::element_text(hjust = 0)) + + ggplot2::labs( + title = str_c('Component ',stats$Component), + caption = str_c('Degree = ',stats$Degree %>% round(2),'; ', + 'Weight = ',stats$Weight %>% round(2),'; ', + 'AIS = ',stats$AIS %>% round(2),'; ', + 'Plausibility = ',stats$`Component Plausibility` %>% + round(2))) + + ggplot2::xlim(min(g$x) - (max(g$x) - min(g$x)) * 0.05, + max(g$x) + (max(g$x) - min(g$x)) * 0.05) + + ggplot2::ylim(min(g$y) - (max(g$y) - min(g$y)) * 0.05, + max(g$y) + (max(g$y) - min(g$y)) * 0.05) + + ggplot2::guides(fill = 'none') }) %>% - wrap_plots() + - plot_layout(guides = 'collect') + - plot_annotation(title = str_c('Solutions for feature ', - feature), - theme = theme(plot.title = element_text(face = 'bold', - hjust = 0.5))) + patchwork::wrap_plots() + + patchwork::plot_layout(guides = 'collect') + + patchwork::plot_annotation( + title = str_c('Solutions for feature ', + feature), + theme = ggplot2::theme( + plot.title = ggplot2::element_text(face = 'bold', + hjust = 0.5))) } #' Plot the solutions for a feature diff --git a/R/plotNetwork.R b/R/plotNetwork.R index 52620ee..7695f27 100644 --- a/R/plotNetwork.R +++ b/R/plotNetwork.R @@ -1,5 +1,10 @@ networkPlot <- function(network,layout,rThreshold,assignedNodes,explainedEdges){ + check_installed(c('ggraph', + 'ggthemes', + 'ggplot2', + 'graphlayouts')) + rt <- str_c('Visualised using threshold of r > ',rThreshold) nn <- str_c('Total nodes = ',sum(assignedNodes)) an <- str_c('Assigned nodes = ', @@ -14,15 +19,15 @@ networkPlot <- function(network,layout,rThreshold,assignedNodes,explainedEdges){ {explainedEdges[1]/sum(explainedEdges) * 100} %>% round(),'%)') - ggraph(network,layout = layout) + - geom_edge_link(alpha = 0.2) + - geom_node_point(aes(fill = Assigned),shape = 21) + - scale_fill_ptol() + - theme_graph() + - theme(legend.title = element_blank()) + - coord_fixed() + - facet_edges(~Explained) + - labs(title = str_c('Assignment correlation network'), + ggraph::ggraph(network,layout = layout) + + ggraph::geom_edge_link(alpha = 0.2) + + ggraph::geom_node_point(ggplot2::aes(fill = Assigned),shape = 21) + + ggthemes::scale_fill_ptol() + + ggraph::theme_graph() + + ggplot2::theme(legend.title = ggplot2::element_blank()) + + ggplot2::coord_fixed() + + ggraph::facet_edges(~Explained) + + ggplot2::labs(title = str_c('Assignment correlation network'), caption = str_c(rt,nn,an,ne,ee,sep = '\n')) } @@ -34,10 +39,6 @@ networkPlot <- function(network,layout,rThreshold,assignedNodes,explainedEdges){ #' @param rThreshold r threhold to use for filtering edge correlation weights #' @importFrom tidygraph as_tbl_graph bind_graphs #' @importFrom igraph set_vertex_attr set_edge_attr -#' @importFrom ggraph ggraph geom_edge_link geom_node_point theme_graph geom_node_text facet_edges -#' @importFrom ggthemes scale_fill_ptol -#' @importFrom ggplot2 labs aes element_blank coord_fixed -#' @importFrom graphlayouts layout_igraph_stress #' @export setGeneric('plotNetwork',function(assignment, layout = 'stress', rThreshold = 0.7){ diff --git a/R/plotSpectrum.R b/R/plotSpectrum.R index 13326e7..c8c9523 100644 --- a/R/plotSpectrum.R +++ b/R/plotSpectrum.R @@ -1,23 +1,35 @@ spectrumPlot <- function(dat,MF){ + check_installed(c('ggplot2', + 'ggrepel', + 'ggthemes')) + dat$Mode[dat$Mode == 'n'] <- 'Negative mode' dat$Mode[dat$Mode == 'n'] <- 'Positive mode' - ggplot(dat) + - geom_segment(aes(x = `m/z`,xend = `m/z`, y = 0, yend = `Relative Abundance`),colour = ptol_pal()(1)) + - geom_text_repel(aes(x = `m/z`,y = `Relative Abundance`,label = Label)) + - theme_bw() + - theme(panel.border = element_blank(), - panel.grid = element_blank(), - axis.line = element_line(), - axis.title = element_text(face = 'bold'), - strip.background = element_blank(), - strip.text = element_text(face = 'bold'), - plot.title = element_text(face = 'bold', + ggplot2::ggplot(dat) + + ggplot2::geom_segment( + ggplot2::aes(x = `m/z`, + xend = `m/z`, + y = 0, + yend = `Relative Abundance`), + colour = ggthemes::ptol_pal()(1)) + + ggrepel::geom_text_repel( + ggplot2::aes(x = `m/z`, + y = `Relative Abundance`, + label = Label)) + + ggplot2::theme_bw() + + ggplot2::theme(panel.border = ggplot2::element_blank(), + panel.grid = ggplot2::element_blank(), + axis.line = ggplot2::element_line(), + axis.title = ggplot2::element_text(face = 'bold'), + strip.background = ggplot2::element_blank(), + strip.text = ggplot2::element_text(face = 'bold'), + plot.title = ggplot2::element_text(face = 'bold', hjust = 0.5)) + - labs(title = MF, + ggplot2::labs(title = MF, y = 'Relative Abundance') + - facet_wrap(~Mode,scales = 'free') + ggplot2::facet_wrap(~Mode,scales = 'free') } #' plotSpectrum @@ -27,8 +39,6 @@ spectrumPlot <- function(dat,MF){ #' @param MF molecular formula #' @importFrom tidyr gather #' @importFrom dplyr group_by summarise -#' @importFrom ggplot2 geom_segment -#' @importFrom ggrepel geom_text_repel #' @export setGeneric('plotSpectrum',function(assignment,MF) From eff5de2518d0e8b4264a4eaba374eb06ffc4e419 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Tue, 3 May 2022 21:17:52 +0100 Subject: [PATCH 153/226] documentation fixes --- R/MFassign.R | 18 +++++++++--------- R/parameters.R | 1 - man/AssignmentParameters-class.Rd | 2 -- 3 files changed, 9 insertions(+), 12 deletions(-) diff --git a/R/MFassign.R b/R/MFassign.R index e7c30c3..2021d2f 100644 --- a/R/MFassign.R +++ b/R/MFassign.R @@ -2,15 +2,15 @@ globalVariables(c( 'Mass','.','Feature1','Feature2','Feature','Isotope','Adduct', 'Measured m/z','Isotope1','Adduct1','Isotope2','Adduct2','MF1', - 'MF2','Nodes','AddIsoScore','RetentionTime','MF Plausibility (%)','r','EdgeWeight1', - 'EdgeWeight2','Degree','Measured M','Cluster', 'Average AddIsoScore', - 'Transformation1','Transformation2','log2IntensityRatio','m/z1', - 'm/z2','RetentionTime1','RetentionTime2','mz','Theoretical M', - 'Theoretical m/z','PPM error','name','Mode','V1','V2','Mode1', - 'Mode2','ID','Adducts','Isotopes','Transformations','Error', - 'Count','TransformedMF1', 'TransformedMF2','Component Plausibility','absPPM', - 'Name1','Name2','Size','AverageAddIsoScore','nodes','rtDiff', + 'MF2','Nodes','AddIsoScore','RetentionTime','MF Plausibility (%)', + 'coefficient','EdgeWeight1','EdgeWeight2','Degree','Measured M', + 'Cluster', 'Average AddIsoScore','Transformation1','Transformation2', + 'log2IntensityRatio','m/z1','m/z2','RetentionTime1','RetentionTime2', + 'mz','Theoretical M','Theoretical m/z','PPM error','name','Mode', + 'V1','V2','Mode1','Mode2','ID','Adducts','Isotopes','Transformations', + 'Error','Count','TransformedMF1', 'TransformedMF2','Component Plausibility', + 'absPPM','Name1','Name2','Size','AverageAddIsoScore','nodes','rtDiff', 'Component','Weight','AIS','Name','Assigned','Intensity','Label', 'Relative Abundance','m/z','Group','N','adduct_rank','isotope_rank', - 'M','total' + 'M','total','MF','RetentionTimeDiff' )) diff --git a/R/parameters.R b/R/parameters.R index 131a62c..def6840 100644 --- a/R/parameters.R +++ b/R/parameters.R @@ -6,7 +6,6 @@ #' @slot max_M maximum M for which to assign molecular formulas #' @slot MF_rank_threshold rank threshold for molecular formula selection #' @slot ppm ppm threshold -#' @slot adducts named list of character vectors containing the adducts to use for each mode #' @slot limit amu deviation limit for relationship prediction #' @slot RT_diff_limit limit for retention time differences for correlated features in adduct and isotopic assignment #' @slot adducts list of character vectors containing the adducts to use. List element names should denote ionisation mode. diff --git a/man/AssignmentParameters-class.Rd b/man/AssignmentParameters-class.Rd index b3ae0c3..dd34540 100644 --- a/man/AssignmentParameters-class.Rd +++ b/man/AssignmentParameters-class.Rd @@ -20,8 +20,6 @@ An S4 class to store assignment parameters. \item{\code{ppm}}{ppm threshold} -\item{\code{adducts}}{named list of character vectors containing the adducts to use for each mode} - \item{\code{limit}}{amu deviation limit for relationship prediction} \item{\code{RT_diff_limit}}{limit for retention time differences for correlated features in adduct and isotopic assignment} From 85f36577754d87d3d62edbd43791a74c00cb6723 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Tue, 3 May 2022 21:35:12 +0100 Subject: [PATCH 154/226] documentation fixes --- NAMESPACE | 2 -- R/assignment.R | 5 ++--- R/parameters.R | 1 - R/plotFeatureSolutions.R | 2 +- man/{Assignment.Rd => Assignment-class.Rd} | 2 +- 5 files changed, 4 insertions(+), 8 deletions(-) rename man/{Assignment.Rd => Assignment-class.Rd} (92%) diff --git a/NAMESPACE b/NAMESPACE index e3a5e32..0124145 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -38,8 +38,6 @@ export(summariseAssignment) export(technique) export(transformationRules) export(transformations) -exportClasses(Assignment) -exportClasses(AssignmentParameters) importFrom(cli,console_width) importFrom(crayon,blue) importFrom(crayon,green) diff --git a/R/assignment.R b/R/assignment.R index 9b2f5d0..13150c8 100644 --- a/R/assignment.R +++ b/R/assignment.R @@ -1,15 +1,14 @@ #' Assignment -#' @rdname Assignment +#' @rdname Assignment-class #' @description An S4 class to store assignment results #' @slot log list containing assignment logs -#' @slot flags charactor vector containing completed assignment elements +#' @slot flags character vector containing completed assignment elements #' @slot data A tibble containing the peak intensity matrix #' @slot correlations A tibble containing the correlations #' @slot relationships A tibble containing the predicted relationships #' @slot addIsoAssign A list containing the results of the adduct and isotope assignment #' @slot transAssign A list containing the results of the transformation assignment #' @slot assignments A tibble containing the assigned molecular formulas -#' @export setClass('Assignment', contains = 'AssignmentParameters', diff --git a/R/parameters.R b/R/parameters.R index def6840..0a61c1a 100644 --- a/R/parameters.R +++ b/R/parameters.R @@ -15,7 +15,6 @@ #' @slot isotope_rules tibble containing isotope rules as returned by `mzAnnotation::isotopes()` #' @slot transformation_rules tibble containing transformation rules as returned by `mzAnnotation::transformations()` #' @importFrom mzAnnotation adduct_rules isotope_rules transformation_rules -#' @export setClass('AssignmentParameters', slots = list( diff --git a/R/plotFeatureSolutions.R b/R/plotFeatureSolutions.R index a22acc4..346aee3 100644 --- a/R/plotFeatureSolutions.R +++ b/R/plotFeatureSolutions.R @@ -18,7 +18,7 @@ plotSolutions <- function(graph,selectedComp,feature){ g <- . g <- g %>% mutate(Feat = Feature == feature) %>% - create_layout('nicely') + ggraph::create_layout('nicely') ggraph::ggraph(g) + ggraph::geom_edge_link(ggplot2::aes(colour = r)) + ggraph::scale_edge_color_gradient(low = 'white', diff --git a/man/Assignment.Rd b/man/Assignment-class.Rd similarity index 92% rename from man/Assignment.Rd rename to man/Assignment-class.Rd index 51bf4b9..bb2c107 100644 --- a/man/Assignment.Rd +++ b/man/Assignment-class.Rd @@ -12,7 +12,7 @@ An S4 class to store assignment results \describe{ \item{\code{log}}{list containing assignment logs} -\item{\code{flags}}{charactor vector containing completed assignment elements} +\item{\code{flags}}{character vector containing completed assignment elements} \item{\code{data}}{A tibble containing the peak intensity matrix} From 3b395b061e15338c535dc918f7cf00f9a4ac8df2 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Wed, 4 May 2022 14:00:42 +0100 Subject: [PATCH 155/226] tidied AIS computation --- R/addIsoAssign.R | 5 +-- R/components.R | 6 +-- R/internals.R | 96 +++++++++++++++------------------------- R/plotFeatureSolutions.R | 4 +- R/transformationAssign.R | 16 +++---- 5 files changed, 49 insertions(+), 78 deletions(-) diff --git a/R/addIsoAssign.R b/R/addIsoAssign.R index 214e42f..5d2e1a7 100644 --- a/R/addIsoAssign.R +++ b/R/addIsoAssign.R @@ -48,10 +48,9 @@ setMethod('addIsoAssign',signature = 'Assignment', MFs <- generateMFs(M, ppm(assignment), MFrankThreshold(assignment), - adducts(assignment), adductRules(assignment), - isotopes(assignment), - isotopeRules(assignment)) + isotopeRules(assignment), + AIS(assignment)) graph_edges <- rel %>% addMFs(MFs) %>% diff --git a/R/components.R b/R/components.R index eb41078..1b99ffa 100644 --- a/R/components.R +++ b/R/components.R @@ -52,7 +52,7 @@ componentMetrics <- function(component,max_add_iso_total){ Degree = degree(Nodes,Size),, Density = (2 * Size) / (Nodes * (Nodes - 1)), Weight = sum(Weight) / Nodes, - AIS = Size * sum(AddIsoScore) / max_add_iso_total, + AIS = Size * sum(AIS) / max_add_iso_total, `Component Plausibility` = plausibility(AIS,Degree,Weight)) } @@ -100,7 +100,7 @@ calcComponents <- function(graph_nodes, graph <- graph %>% left_join(weights,by = 'Component') %>% morph(to_components) %>% - componentMetrics(max_add_iso_total = maxAddIsoScore(assignment)) %>% + componentMetrics(max_add_iso_total = maxAIS(assignment)) %>% unmorph() } @@ -142,7 +142,7 @@ recalcComponents <- function(graph, select(-Weight) %>% left_join(weights,by = 'Component') %>% morph(to_components) %>% - componentMetrics(max_add_iso_total = maxAddIsoScore(assignment)) %>% + componentMetrics(max_add_iso_total = maxAIS(assignment)) %>% unmorph() } diff --git a/R/internals.R b/R/internals.R index ba46c11..d9bd695 100644 --- a/R/internals.R +++ b/R/internals.R @@ -131,69 +131,51 @@ collateMFs <- function(rel,MF){ mutate(ID = 1:nrow(.)) } -#' @importFrom purrr map_lgl - -addIsoScore <- function(add,iso,addRank,isoRank){ - add <- tibble(Adduct = add) - iso <- tibble(Isotope = iso) - iso$Isotope[is.na(iso$Isotope)] <- 'NA' - addRank <- addRank[map_lgl(addRank,~{add %in% .})] %>% - .[[1]] %>% - {tibble(Adduct = ., - Rank = (length(.) - 1):0)} - isoRank <- tibble(Isotope = c('NA',isoRank), Rank = length(isoRank):0) +AIS <- function(assignment){ + possible_products <- expand_grid( + Adduct = adducts(assignment) %>% + flatten_chr(), + Isotope = c(NA,isotopes(assignment)) + ) - add <- left_join(add, addRank,by = 'Adduct') %>% - .$Rank - iso <- left_join(iso, isoRank,by = 'Isotope') %>% - .$Rank + adducts_scores <- assignment %>% + adducts() %>% + map(~tibble(Adduct = .x, + Adduct_Score = (length(.x) -1):0)) %>% + bind_rows() - maxScore <- max(addRank$Rank) + max(isoRank$Rank) - score <- (add + iso)/maxScore + isotopes_scores <- assignment %>% + isotopes() %>% + {c(NA,.)} %>% + {tibble(Isotope = ., + Isotope_Score = (length(.) -1):0)} - return(score) + possible_products %>% + left_join(adducts_scores,by = 'Adduct') %>% + left_join(isotopes_scores,by = 'Isotope') %>% + mutate(AIS = Adduct_Score + Isotope_Score, + AIS = AIS / max(AIS)) %>% + select(-contains('Score')) } #' @importFrom tidyr expand_grid #' @importFrom purrr flatten_chr map_dfr -maxAddIsoScore <- function(assignment){ - +maxAIS <- function(assignment){ assignment_adducts <- adducts(assignment) assignment_isotopes <- isotopes(assignment) - adduct_scores <- assignment_adducts %>% - map(~tibble(adduct = .) %>% - mutate(adduct_rank = (nrow(.) - 1):0)) %>% - bind_rows(.id = 'mode') - - isotope_scores <- assignment_isotopes %>% - c('NA',.) %>% - tibble(isotope = .) %>% - mutate(isotope_rank = (nrow(.) - 1):0) + n_adducts <- assignment %>% + adducts() %>% + flatten_chr() %>% + length() - max_total <- assignment_adducts %>% - map_dfr(~tibble(max_total = length(.x) - 1), - .id = 'mode') %>% - mutate(max_total = max_total + - length(assignment_isotopes)) + n_isotopes <- assignment %>% + isotopes() %>% + {c(NA,.)} %>% + length() - add_iso_combs <- expand_grid(adduct = assignment_adducts %>% - flatten_chr(), - isotope = c('NA',assignment_isotopes) - ) - - add_iso_scores <- add_iso_combs %>% - left_join(adduct_scores, - by = "adduct") %>% - left_join(isotope_scores, - by = "isotope") %>% - mutate(total = adduct_rank + - isotope_rank) %>% - left_join(max_total,by = 'mode') %>% - mutate(score = total / max_total) - - max_score <- sum(add_iso_scores$score) + max_score <- (n_adducts * n_isotopes) / 2 return(max_score) } @@ -204,10 +186,9 @@ maxAddIsoScore <- function(assignment){ generateMFs <- function(M, ppm, rank_threshold, - assignment_adducts, adduct_rules, - assignment_isotopes, - isotope_rules){ + isotope_rules, + AIS){ nM <- nrow(M) M %>% @@ -237,13 +218,8 @@ generateMFs <- function(M, select(Feature,RetentionTime,MF,Isotope,Adduct,`Theoretical M`, `Measured M`,`Theoretical m/z`,`Measured m/z`, `PPM error`, `MF Plausibility (%)` = `Plausibility (%)`) %>% - - rowwise() %>% - mutate(AddIsoScore = addIsoScore(Adduct, - Isotope, - assignment_adducts, - assignment_isotopes)) %>% - ungroup() + left_join(AIS, + by = c('Adduct','Isotope')) } else { return(NULL) } diff --git a/R/plotFeatureSolutions.R b/R/plotFeatureSolutions.R index 346aee3..24dd102 100644 --- a/R/plotFeatureSolutions.R +++ b/R/plotFeatureSolutions.R @@ -5,8 +5,8 @@ plotSolutions <- function(graph,selectedComp,feature){ 'patchwork')) graph %>% map(~{ - stats <- nodes(.) %>% - select(Component:`Component Plausibility`) %>% + stats <- nodes(.x) %>% + select(Component:`Component Plausibility`,AIS) %>% .[1,] if (stats$Component[1] == selectedComp){ diff --git a/R/transformationAssign.R b/R/transformationAssign.R index d67df57..b61a399 100644 --- a/R/transformationAssign.R +++ b/R/transformationAssign.R @@ -54,21 +54,17 @@ setMethod('transformationAssign',signature = 'Assignment', MFs <- generateMFs(M, ppm(assignment), MFrankThreshold(assignment), - adducts(assignment), adductRules(assignment), - isotopes(assignment), - isotopeRules(assignment)) + isotopeRules(assignment), + AIS(assignment)) if (nrow(MFs) > 0) { MFs <- MFs %>% - bind_rows(assigned %>% - select(names(MFs)[!(names(MFs) == 'AddIsoScore')]) %>% - rowwise() %>% - mutate(AddIsoScore = addIsoScore(Adduct, - Isotope, - adducts(assignment), - isotopes(assignment)))) + bind_rows(assigned %>% + select(dplyr::any_of(names(MFs))) %>% + left_join(AIS(assignment), + by = c('Adduct','Isotope'))) graph_edges <- rel %>% addMFs(MFs, identMF = FALSE) %>% From a2bc8de10295399c20541b6bbc614f1b9afae4fa Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Wed, 4 May 2022 14:13:36 +0100 Subject: [PATCH 156/226] correct AIS and component plausibility calculation --- R/components.R | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/R/components.R b/R/components.R index 1b99ffa..cd9a4d8 100644 --- a/R/components.R +++ b/R/components.R @@ -3,8 +3,8 @@ degree <- function(n_nodes,n_edges){ 2 * (n_edges / n_nodes) } -plausibility <- function(AIS,degree,weight){ - AIS + weight +plausibility <- function(size,AIS,weight){ + size * AIS + weight } #' @importFrom purrr compact @@ -52,7 +52,7 @@ componentMetrics <- function(component,max_add_iso_total){ Degree = degree(Nodes,Size),, Density = (2 * Size) / (Nodes * (Nodes - 1)), Weight = sum(Weight) / Nodes, - AIS = Size * sum(AIS) / max_add_iso_total, + AIS = sum(AIS) / max_add_iso_total, `Component Plausibility` = plausibility(AIS,Degree,Weight)) } From 1b5c8ffaa00ecff1e50e1494ef1df11685d51d30 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Wed, 4 May 2022 14:33:14 +0100 Subject: [PATCH 157/226] plotFeatureSolutions fix --- R/plotFeatureSolutions.R | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/R/plotFeatureSolutions.R b/R/plotFeatureSolutions.R index 24dd102..6d867de 100644 --- a/R/plotFeatureSolutions.R +++ b/R/plotFeatureSolutions.R @@ -20,7 +20,7 @@ plotSolutions <- function(graph,selectedComp,feature){ mutate(Feat = Feature == feature) %>% ggraph::create_layout('nicely') ggraph::ggraph(g) + - ggraph::geom_edge_link(ggplot2::aes(colour = r)) + + ggraph::geom_edge_link(ggplot2::aes(colour = coefficient)) + ggraph::scale_edge_color_gradient(low = 'white', high = 'black', limits = c(0.5,1)) + From 209bb36a1accc0b8110d557c6758dd97afeb19aa Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Wed, 4 May 2022 15:08:38 +0100 Subject: [PATCH 158/226] ensure single node components removed when recalculated --- R/components.R | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/R/components.R b/R/components.R index cd9a4d8..1e80e87 100644 --- a/R/components.R +++ b/R/components.R @@ -32,7 +32,8 @@ clean <- function(graph,adduct_rules_table){ if (all(component_nodes$isotopic) == TRUE | all(component_nodes$adduct_isotopic) == TRUE | - all(component_nodes$either_isotopic) == TRUE) NULL + all(component_nodes$either_isotopic) == TRUE | + nrow(component_nodes) < 2) NULL else return(.x) }) %>% compact() %>% From 25662d3fe07ee44aadb6bc8bdd06cb8ddc480f36 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Tue, 10 May 2022 10:24:48 +0100 Subject: [PATCH 159/226] enable feature solutions to be plotted for features that were not selected --- R/plotFeatureSolutions.R | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/R/plotFeatureSolutions.R b/R/plotFeatureSolutions.R index 6d867de..405140b 100644 --- a/R/plotFeatureSolutions.R +++ b/R/plotFeatureSolutions.R @@ -9,14 +9,15 @@ plotSolutions <- function(graph,selectedComp,feature){ select(Component:`Component Plausibility`,AIS) %>% .[1,] - if (stats$Component[1] == selectedComp){ - border <- 'red' + if (length(selectedComp) > 0){ + border <- ifelse(stats$Component[1] == selectedComp, + 'red', + 'black') } else { border <- 'black' } - g <- . - g <- g %>% + g <- .x %>% mutate(Feat = Feature == feature) %>% ggraph::create_layout('nicely') ggraph::ggraph(g) + From 6c03becc6ee8b2d48d12ace63b803ef9b1e6a951 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Wed, 11 May 2022 15:07:24 +0100 Subject: [PATCH 160/226] set max correlations parameter to infinite --- R/parameters.R | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/R/parameters.R b/R/parameters.R index 0a61c1a..f32f457 100644 --- a/R/parameters.R +++ b/R/parameters.R @@ -38,7 +38,7 @@ setClass('AssignmentParameters', pAdjustMethod = 'bonferroni', corPvalue = 0.05, minCoef = 0.7, - maxCor = 500000), + maxCor = Inf), max_M = 800, MF_rank_threshold = 3, ppm = 6, From 431f048a6c0a160e9fc571d6b3ff7cfb09b29540 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Wed, 11 May 2022 15:08:02 +0100 Subject: [PATCH 161/226] use mzAnnotation devel branch --- DESCRIPTION | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/DESCRIPTION b/DESCRIPTION index d476690..cd8d55a 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -40,5 +40,5 @@ Suggests: testthat, ggthemes, graphlayouts, patchwork -Remotes: jasenfinch/mzAnnotation@tmp, +Remotes: jasenfinch/mzAnnotation@devel, jasenfinch/metabolyseR@devel From 9d6344cbfee2e84bc94cd6b6a94464ce3905e16c Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Wed, 11 May 2022 15:29:52 +0100 Subject: [PATCH 162/226] removed M restriction for LC-MS parameters --- R/parameters.R | 2 -- 1 file changed, 2 deletions(-) diff --git a/R/parameters.R b/R/parameters.R index f32f457..5958647 100644 --- a/R/parameters.R +++ b/R/parameters.R @@ -529,11 +529,9 @@ assignmentParameters <- function(technique = availableTechniques()){ `FIE-HRMS` = new('AssignmentParameters'), `RP-LC-HRMS` = new('AssignmentParameters', technique = 'RP-LC-HRMS', - max_M = 700, RT_diff_limit = 1/60), `NP-LC-HRMS` = new('AssignmentParameters', technique = 'NP-LC-HRMS', - max_M = 700, RT_diff_limit = 1/60, adducts = list(n = c("[M-H]1-", "[M+Cl]1-", "[M+K-2H]1-", "[M-2H]2-", "[M+Cl37]1-","[2M-H]1-"), From fe89e2c24e0a4cf81659c303ffc31d7aaaf1be7f Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Tue, 17 May 2022 19:27:54 +0100 Subject: [PATCH 163/226] added multiple iterations to adduct and isotopic assignment iteration --- R/addIsoAssign.R | 75 ++++++++++++++++++++++++++++++++++++------------ 1 file changed, 57 insertions(+), 18 deletions(-) diff --git a/R/addIsoAssign.R b/R/addIsoAssign.R index 5d2e1a7..4a51f2a 100644 --- a/R/addIsoAssign.R +++ b/R/addIsoAssign.R @@ -46,12 +46,12 @@ setMethod('addIsoAssign',signature = 'Assignment', maxM(assignment)) MFs <- generateMFs(M, - ppm(assignment), - MFrankThreshold(assignment), - adductRules(assignment), - isotopeRules(assignment), - AIS(assignment)) - + ppm(assignment), + MFrankThreshold(assignment), + adductRules(assignment), + isotopeRules(assignment), + AIS(assignment)) + graph_edges <- rel %>% addMFs(MFs) %>% filter(MF1 == MF2) %>% @@ -64,22 +64,61 @@ setMethod('addIsoAssign',signature = 'Assignment', graph <- calcComponents(graph_nodes, graph_edges, assignment) - - filtered_graph <- filterComponents(graph, - assignment) - assignment@addIsoAssign <- list( - graph = graph, - filtered_graph = filtered_graph, - assigned = filtered_graph %>% + counter <- 0 + + assignment@addIsoAssign <- list() + + repeat { + + counter <- counter + 1 + + message(paste0('iteration ',counter)) + + if (counter > 1){ + graph <- assignment@addIsoAssign[[counter - 1]]$graph %>% + activate(nodes) %>% + dplyr::anti_join(assignment %>% + assignments() %>% + select(dplyr::any_of(c('Feature','Isotope','Adduct','MF'))), + by = 'Feature') + + if (length(graph) == 0) break() + + graph <- graph %>% + clean(adductRules(assignment)) %>% + recalcComponents(assignment) + } + + filtered_graph <- graph + + filtered_graph <- filtered_graph %>% + filterComponents(assignment, + filters = componentFilters()) + + assigned_features <- filtered_graph %>% nodes() %>% rename(Name = name) %>% mutate(Mode = str_sub(Feature,1,1)) - ) - - assignment@assignments <- assignment@addIsoAssign$assigned %>% - select(Name:`MF Plausibility (%)`,Mode) %>% - mutate(Iteration = 'A&I') + + if (nrow(assigned_features) == 0){ + break() + } + + assignment@addIsoAssign[[counter]] <- list( + graph = graph, + filtered_graph = filtered_graph, + assigned = assigned_features + ) + + assignment@assignments <- bind_rows( + assignment@assignments, + assigned_features %>% + select(Name:`MF Plausibility (%)`,Mode) %>% + mutate(Iteration = paste0('A&I',counter)) + ) + + } if (assignment@log$verbose == TRUE) { endTime <- proc.time() From cee90600c8e66d511873e0822912821f9584288a Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Tue, 17 May 2022 19:38:22 +0100 Subject: [PATCH 164/226] fix assignment class show method --- R/assignment.R | 33 +++++++++++++++++++++++---------- 1 file changed, 23 insertions(+), 10 deletions(-) diff --git a/R/assignment.R b/R/assignment.R index 13150c8..a98ef88 100644 --- a/R/assignment.R +++ b/R/assignment.R @@ -45,22 +45,35 @@ setMethod('show',signature = 'Assignment', cat('\t','Relationships:\t\t',nrow(relationships(object)),'\n') cat('\n') if (length(object@addIsoAssign) > 0) { + addIsoAssigned <- object %>% + assignments() %>% + filter(str_detect(Iteration,'A&I')) cat('\t',green('Adduct & isotope assignment:'),'\n') - cat('\t\t','MFs:\t\t',length(unique(object@addIsoAssign$assigned$MF)),'\n') - cat('\t\t','Relationships:\t',object@addIsoAssign$filtered_graph %>% E() %>% length(),'\n') - cat('\t\t','Assigned:\t',nrow(object@addIsoAssign$assigned),'\n') + cat('\t\t','Iterations:\t',length(object@addIsoAssign),'\n') + cat('\t\t', + 'MFs:\t\t', + addIsoAssigned %>% + select(MF) %>% + distinct() %>% + nrow(), + '\n') + cat('\t\t','Assigned:\t',nrow(addIsoAssigned),'\n') cat('\n') } if (length(object@transAssign) > 0) { + transAssign <- object %>% + assignments() %>% + filter(str_detect(Iteration,'T')) cat('\t',green('Transformation assignment:'),'\n') cat('\t\t','Iterations:\t',length(object@transAssign),'\n') - transAssigned <- object@transAssign %>% - {.[map_dbl(.,length) > 0]} %>% - map_dbl(~{ - return(nrow(.$assigned)) - }) %>% - sum() - cat('\t\t','Assigned:\t',transAssigned,'\n') + cat('\t\t', + 'MFs:\t\t', + transAssign %>% + select(MF) %>% + distinct() %>% + nrow(), + '\n') + cat('\t\t','Assigned:\t',nrow(transAssign),'\n') cat('\n') } if (nrow(object@assignments) > 0) { From 7d7e75a4a78eafe58c5430446c740c018090db84 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Tue, 17 May 2022 21:01:24 +0100 Subject: [PATCH 165/226] ensure only nodes with degree > 0 kept after component elimination --- DESCRIPTION | 2 +- NAMESPACE | 2 +- R/addIsoAssign.R | 2 -- R/components.R | 13 ++++++++----- 4 files changed, 10 insertions(+), 9 deletions(-) diff --git a/DESCRIPTION b/DESCRIPTION index cd8d55a..25341b2 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -25,7 +25,7 @@ License: GPL (>= 3) Encoding: UTF-8 LazyData: true Roxygen: list(markdown = TRUE) -RoxygenNote: 7.1.2 +RoxygenNote: 7.2.0 Collate: parameters.R assignment.R correlations.R addIsoAssign.R transformationAssign.R relationships.R graph.R assign.R internals.R components.R diff --git a/NAMESPACE b/NAMESPACE index 0124145..b564da2 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -73,6 +73,7 @@ importFrom(furrr,future_map_dfr) importFrom(future,plan) importFrom(igraph,E) importFrom(igraph,V) +importFrom(igraph,degree) importFrom(igraph,edge.attributes) importFrom(igraph,set_edge_attr) importFrom(igraph,set_vertex_attr) @@ -104,7 +105,6 @@ importFrom(purrr,flatten_chr) importFrom(purrr,map) importFrom(purrr,map_dbl) importFrom(purrr,map_dfr) -importFrom(purrr,map_lgl) importFrom(rlang,check_installed) importFrom(stringr,str_c) importFrom(stringr,str_detect) diff --git a/R/addIsoAssign.R b/R/addIsoAssign.R index 4a51f2a..09adf7a 100644 --- a/R/addIsoAssign.R +++ b/R/addIsoAssign.R @@ -67,8 +67,6 @@ setMethod('addIsoAssign',signature = 'Assignment', counter <- 0 - assignment@addIsoAssign <- list() - repeat { counter <- counter + 1 diff --git a/R/components.R b/R/components.R index 1e80e87..2c535ca 100644 --- a/R/components.R +++ b/R/components.R @@ -1,5 +1,5 @@ -degree <- function(n_nodes,n_edges){ +avg_degree <- function(n_nodes,n_edges){ 2 * (n_edges / n_nodes) } @@ -50,7 +50,7 @@ componentMetrics <- function(component,max_add_iso_total){ component %>% mutate(Size = graph_size(), Nodes = n(), - Degree = degree(Nodes,Size),, + Degree = avg_degree(Nodes,Size),, Density = (2 * Size) / (Nodes * (Nodes - 1)), Weight = sum(Weight) / Nodes, AIS = sum(AIS) / max_add_iso_total, @@ -150,6 +150,8 @@ recalcComponents <- function(graph, return(graph) } +#' @importFrom igraph degree + filterComponents <- function(graph, assignment, filters = componentFilters()){ @@ -162,8 +164,9 @@ filterComponents <- function(graph, filter(name %in% {filtered_graph %>% nodes() %>% eliminate(f$Measure,f$Direction) %>% - .$name}) - if (V(filtered_graph) %>% length() > 0) { + .$name}) %>% + filter(degree(.) != 0) + if (E(filtered_graph) %>% length() > 0) { filtered_graph <- filtered_graph %>% recalcComponents(assignment) } else { @@ -172,4 +175,4 @@ filterComponents <- function(graph, } return(filtered_graph) -} \ No newline at end of file +} From 271db243206160f207189eb45aa43a2ef23339cd Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Tue, 17 May 2022 21:39:17 +0100 Subject: [PATCH 166/226] set default correlation coefficient cutoff to 0 --- R/parameters.R | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/R/parameters.R b/R/parameters.R index 5958647..794ae6e 100644 --- a/R/parameters.R +++ b/R/parameters.R @@ -37,7 +37,7 @@ setClass('AssignmentParameters', correlations_parameters = list(method = 'spearman', pAdjustMethod = 'bonferroni', corPvalue = 0.05, - minCoef = 0.7, + minCoef = 0, maxCor = Inf), max_M = 800, MF_rank_threshold = 3, From 7c4075b6611ab3f396e64e0f01c74d8a87af2133 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Tue, 17 May 2022 21:44:14 +0100 Subject: [PATCH 167/226] changed package name to assignments --- DESCRIPTION | 4 ++-- R/assign.R | 2 +- R/assignment.R | 2 +- R/{MFassign.R => assignments.R} | 0 README.md | 10 +++++----- tests/testthat.R | 4 ++-- tests/testthat/test-onload.R | 4 ++-- 7 files changed, 13 insertions(+), 13 deletions(-) rename R/{MFassign.R => assignments.R} (100%) diff --git a/DESCRIPTION b/DESCRIPTION index 25341b2..eca8e9e 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -1,4 +1,4 @@ -Package: MFassign +Package: assignments Title: Molecular formula assignment for high resolution metabolomics Version: 1.0.0 Authors@R: person("Jasen", "Finch", email = "jsf9@aber.ac.uk", role = c("aut", "cre")) @@ -29,7 +29,7 @@ RoxygenNote: 7.2.0 Collate: parameters.R assignment.R correlations.R addIsoAssign.R transformationAssign.R relationships.R graph.R assign.R internals.R components.R - feature_data.R MFassign.R plotNetwork.R + feature_data.R assignments.R plotNetwork.R plotAdductDist.R plotFeatureSolutions.R plotSpectrum.R reexports.R zzz.R Suggests: testthat, diff --git a/R/assign.R b/R/assign.R index 6981e79..d491dc3 100644 --- a/R/assign.R +++ b/R/assign.R @@ -37,7 +37,7 @@ setMethod('assignMFs',signature = 'tbl_df', if (verbose == TRUE) { startTime <- proc.time() - message(blue('\nMFassign '),red(str_c('v',packageVersion('MFassign') %>% as.character())),' ',date()) + message(blue('\nassignments '),red(str_c('v',packageVersion('assignments') %>% as.character())),' ',date()) message(rep('_',console_width())) params <- parameters %>% {capture.output(print(.))} %>% diff --git a/R/assignment.R b/R/assignment.R index a98ef88..50497ba 100644 --- a/R/assignment.R +++ b/R/assignment.R @@ -38,7 +38,7 @@ setClass('Assignment', setMethod('show',signature = 'Assignment', function(object){ - cat(blue('\nMFassign'),red(str_c('v',packageVersion('MFassign') %>% as.character())),'\n') + cat(blue('\nassignments'),red(str_c('v',packageVersion('assignments') %>% as.character())),'\n') cat(yellow('Assignment:'),'\n') cat('\t','Features:\t\t',ncol(object@data),'\n') cat('\t','Correlations:\t\t',nrow(object@correlations),'\n') diff --git a/R/MFassign.R b/R/assignments.R similarity index 100% rename from R/MFassign.R rename to R/assignments.R diff --git a/README.md b/README.md index c8e6d1a..d70cefe 100644 --- a/README.md +++ b/README.md @@ -1,10 +1,10 @@ -# MFassign +# assignments [![Lifecycle: experimental](https://img.shields.io/badge/lifecycle-experimental-orange.svg)](https://www.tidyverse.org/lifecycle/#experimental) - [![R build status](https://github.com/jasenfinch/MFassign/workflows/R-CMD-check/badge.svg)](https://github.com/jasenfinch/MFassign/actions) -[![Coverage Status](https://img.shields.io/codecov/c/github/jasenfinch/MFassign/master.svg)](https://codecov.io/github/jasenfinch/MFassign?branch=master) -[![license](https://img.shields.io/badge/license-GNU%20GPL%20v3.0-blue.svg)](https://github.com/jasenfinch/MFassign/blob/master/DESCRIPTION) + [![R build status](https://github.com/jasenfinch/assignments/workflows/R-CMD-check/badge.svg)](https://github.com/jasenfinch/assignments/actions) +[![Coverage Status](https://img.shields.io/codecov/c/github/jasenfinch/assignments/master.svg)](https://codecov.io/github/jasenfinch/assignments?branch=master) +[![license](https://img.shields.io/badge/license-GNU%20GPL%20v3.0-blue.svg)](https://github.com/jasenfinch/assignments/blob/master/DESCRIPTION) An R package for molecular formula assignment in high resolution metabolomics @@ -12,5 +12,5 @@ An R package for molecular formula assignment in high resolution metabolomics ### Installation ``` r -devtools::install_github('jasenfinch/MFassign') +devtools::install_github('jasenfinch/assignments') ``` diff --git a/tests/testthat.R b/tests/testthat.R index ff7878c..4c9e137 100644 --- a/tests/testthat.R +++ b/tests/testthat.R @@ -1,4 +1,4 @@ library(testthat) -library(MFassign) +library(assignments) -test_check("MFassign") +test_check("assignments") diff --git a/tests/testthat/test-onload.R b/tests/testthat/test-onload.R index 8021614..cc2f286 100644 --- a/tests/testthat/test-onload.R +++ b/tests/testthat/test-onload.R @@ -1,7 +1,7 @@ test_that("Digits correctly set upon package load", { options('digits' = 7) - MFassign:::.onLoad() + assignments:::.onLoad() expect_equal(getOption('digits'),10) }) @@ -9,7 +9,7 @@ test_that("Digits correctly set upon package load", { test_that('Digits not set upon package load if already above 10', { options('digits' = 11) - MFassign:::.onLoad() + assignments:::.onLoad() expect_equal(getOption('digits'),11) }) From 1470246840ce75c528c7a1cdc1e14ff34d0bde08 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Tue, 17 May 2022 21:50:14 +0100 Subject: [PATCH 168/226] check fixes --- NAMESPACE | 1 + R/assignments.R | 3 ++- R/internals.R | 1 + 3 files changed, 4 insertions(+), 1 deletion(-) diff --git a/NAMESPACE b/NAMESPACE index b564da2..33f677b 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -105,6 +105,7 @@ importFrom(purrr,flatten_chr) importFrom(purrr,map) importFrom(purrr,map_dbl) importFrom(purrr,map_dfr) +importFrom(purrr,map_lgl) importFrom(rlang,check_installed) importFrom(stringr,str_c) importFrom(stringr,str_detect) diff --git a/R/assignments.R b/R/assignments.R index 2021d2f..978f05b 100644 --- a/R/assignments.R +++ b/R/assignments.R @@ -12,5 +12,6 @@ globalVariables(c( 'absPPM','Name1','Name2','Size','AverageAddIsoScore','nodes','rtDiff', 'Component','Weight','AIS','Name','Assigned','Intensity','Label', 'Relative Abundance','m/z','Group','N','adduct_rank','isotope_rank', - 'M','total','MF','RetentionTimeDiff' + 'M','total','MF','RetentionTimeDiff','Adduct_Score','Isotope_Score', + 'Iteration' )) diff --git a/R/internals.R b/R/internals.R index d9bd695..a3f1aa8 100644 --- a/R/internals.R +++ b/R/internals.R @@ -12,6 +12,7 @@ eliminate <- function(MFs,by,direction){ } #' @importFrom dplyr rename +#' @importFrom purrr map_lgl addMFs <- function(rel,MF,identMF = T){ From 77c56b9bab05daf16216bdfc2b864dd05b21b041 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Wed, 18 May 2022 09:07:27 +0100 Subject: [PATCH 169/226] Rename RStudio project --- MFassign.Rproj => assignments.Rproj | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename MFassign.Rproj => assignments.Rproj (100%) diff --git a/MFassign.Rproj b/assignments.Rproj similarity index 100% rename from MFassign.Rproj rename to assignments.Rproj From a4d5b4d7f9163a00f4a966a4b76c976de4306ee8 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Wed, 18 May 2022 09:12:57 +0100 Subject: [PATCH 170/226] default parameters --- R/parameters.R | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/R/parameters.R b/R/parameters.R index 794ae6e..5958647 100644 --- a/R/parameters.R +++ b/R/parameters.R @@ -37,7 +37,7 @@ setClass('AssignmentParameters', correlations_parameters = list(method = 'spearman', pAdjustMethod = 'bonferroni', corPvalue = 0.05, - minCoef = 0, + minCoef = 0.7, maxCor = Inf), max_M = 800, MF_rank_threshold = 3, From 27d4969c1263465d9b80b2f0d6171c16ad062944 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Thu, 19 May 2022 07:21:35 +0100 Subject: [PATCH 171/226] Renamed summariseAssignment --- R/assignment.R | 10 +++++----- tests/testthat/test-assignment.R | 2 +- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/R/assignment.R b/R/assignment.R index 50497ba..0bb0b32 100644 --- a/R/assignment.R +++ b/R/assignment.R @@ -177,18 +177,18 @@ setMethod('assignedData', signature = 'Assignment', }) #' Summarise assignments -#' @rdname summariseAssignment +#' @rdname summariseAssignments #' @description Summarise features assigned to molecular formulas. #' @param assignment S4 object of class Assignment #' @importFrom dplyr desc #' @export -setGeneric('summariseAssignment',function(assignment) - standardGeneric('summariseAssignment')) +setGeneric('summariseAssignments',function(assignment) + standardGeneric('summariseAssignments')) -#' @rdname summariseAssignment +#' @rdname summariseAssignments -setMethod('summariseAssignment',signature = 'Assignment', +setMethod('summariseAssignments',signature = 'Assignment', function(assignment){ assigned <- assignment %>% assignments() %>% diff --git a/tests/testthat/test-assignment.R b/tests/testthat/test-assignment.R index d1ce8c1..ee714dc 100644 --- a/tests/testthat/test-assignment.R +++ b/tests/testthat/test-assignment.R @@ -55,7 +55,7 @@ test_that('data with assigned feature names can be returned',{ }) test_that('a summary of assignments can be returned',{ - expect_s3_class(summariseAssignment(assignment_FIE),'tbl_df') + expect_s3_class(summariseAssignments(assignment_FIE),'tbl_df') }) test_that('feature solutions can be plotted',{ pl <- plotFeatureSolutions(assignment_FIE, From 6f61511fe29e28bd4bdf3120dabea4e3248dd84e Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Thu, 19 May 2022 07:39:35 +0100 Subject: [PATCH 172/226] renamed correlations accessor method --- R/parameters.R | 24 ++++++++++++++---------- man/parameters.Rd | 22 ++++++++++++++-------- 2 files changed, 28 insertions(+), 18 deletions(-) diff --git a/R/parameters.R b/R/parameters.R index 5958647..9c33c96 100644 --- a/R/parameters.R +++ b/R/parameters.R @@ -66,11 +66,9 @@ setValidity('AssignmentParameters',function(object){ else TRUE }) -#' @importFrom metabolyseR correlationsParameters - setValidity('AssignmentParameters',function(object){ - correlations_parameters <- correlationsParameters() %>% + correlations_parameters <- metabolyseR::correlationsParameters() %>% names() if (!any(names(object@correlations_parameters) %in% @@ -103,7 +101,7 @@ setMethod('show',signature = 'AssignmentParameters', cat('\t','Correlations:\n') - correlations(object) %>% + correlationsParameters(object) %>% paste0('\t\t',names(.),': ',.,'\n') %>% cat() @@ -133,6 +131,12 @@ setMethod('show',signature = 'AssignmentParameters', #' #' ## Return technique #' technique(assignment_parameters) +#' +#' ## Return correlations parameters +#' correlationsParameters(assignment_parameters) +#' +#' ## Set correlations parameters +#' correlationsParameters(assignment_parameters)$minCoef <- 0.75 #' #' ## Return limit #' limit(assignment_parameters) @@ -209,24 +213,24 @@ setMethod('technique',signature = 'AssignmentParameters', #' @rdname parameters #' @export -setGeneric('correlations', - function(x) standardGeneric('correlations')) +setGeneric('correlationsParameters', + function(x) standardGeneric('correlationsParameters')) #' @rdname parameters -setMethod('correlations',signature = 'AssignmentParameters', +setMethod('correlationsParameters',signature = 'AssignmentParameters', function(x) x@correlations_parameters) #' @rdname parameters #' @export -setGeneric('correlations<-', - function(x,value) standardGeneric('correlations<-')) +setGeneric('correlationsParameters<-', + function(x,value) standardGeneric('correlationsParameters<-')) #' @rdname parameters #' @importFrom methods validObject -setMethod('correlations<-',signature = c('AssignmentParameters','list'), +setMethod('correlationsParameters<-',signature = c('AssignmentParameters','list'), function(x,value){ x@correlations_parameters <- value validObject(x) diff --git a/man/parameters.Rd b/man/parameters.Rd index 909bba5..0e98529 100644 --- a/man/parameters.Rd +++ b/man/parameters.Rd @@ -3,10 +3,10 @@ \name{technique} \alias{technique} \alias{technique,AssignmentParameters-method} -\alias{correlations} -\alias{correlations,AssignmentParameters-method} -\alias{correlations<-} -\alias{correlations<-,AssignmentParameters,list-method} +\alias{correlationsParameters} +\alias{correlationsParameters,AssignmentParameters-method} +\alias{correlationsParameters<-} +\alias{correlationsParameters<-,AssignmentParameters,list-method} \alias{limit} \alias{limit,AssignmentParameters-method} \alias{limit<-} @@ -53,13 +53,13 @@ technique(x) \S4method{technique}{AssignmentParameters}(x) -correlations(x) +correlationsParameters(x) -\S4method{correlations}{AssignmentParameters}(x) +\S4method{correlationsParameters}{AssignmentParameters}(x) -correlations(x) <- value +correlationsParameters(x) <- value -\S4method{correlations}{AssignmentParameters,list}(x) <- value +\S4method{correlationsParameters}{AssignmentParameters,list}(x) <- value limit(x) @@ -155,6 +155,12 @@ assignment_parameters <- assignmentParameters('FIE') ## Return technique technique(assignment_parameters) +## Return correlations parameters +correlationsParameters(assignment_parameters) + +## Set correlations parameters +correlationsParameters(assignment_parameters)$minCoef <- 0.75 + ## Return limit limit(assignment_parameters) From 0a520cf6a8ad4cd15772ea0dfb09579b72bbdd9a Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Thu, 19 May 2022 08:08:59 +0100 Subject: [PATCH 173/226] moved transformation assignment iteration control flow to method --- R/assign.R | 18 +--- R/transformationAssign.R | 222 +++++++++++++++++++-------------------- 2 files changed, 109 insertions(+), 131 deletions(-) diff --git a/R/assign.R b/R/assign.R index d491dc3..9b5b2ec 100644 --- a/R/assign.R +++ b/R/assign.R @@ -60,22 +60,8 @@ setMethod('assignMFs',signature = 'tbl_df', assignment <- assignment %>% calcCorrelations() %>% calcRelationships() %>% - addIsoAssign() - - count <- 0 - while (TRUE) { - count <- count + 1 - assignment <- suppressWarnings(transformationAssign(assignment)) - if (length(assignment@transAssign[[count]]) == 0) { - assignment@transAssign <- assignment@transAssign[-count] - break() - } - if (nrow(assignment@transAssign[[count]]$assigned) == 0) { - assignment@transAssign <- assignment@transAssign[-count] - break() - } - - } + addIsoAssign() %>% + transformationAssign() if (verbose == TRUE) { endTime <- proc.time() diff --git a/R/transformationAssign.R b/R/transformationAssign.R index b61a399..dfc9704 100644 --- a/R/transformationAssign.R +++ b/R/transformationAssign.R @@ -9,44 +9,49 @@ setGeneric("transformationAssign", function(assignment) setMethod('transformationAssign',signature = 'Assignment', function(assignment){ - count <- length(assignment@transAssign) - assigned <- assignments(assignment) - - if (assignment@log$verbose == TRUE) { - startTime <- proc.time() - message(blue(str_c('Transformation assignment iteration ', - count + 1,' ')), - cli::symbol$continue, - '\r', - appendLF = FALSE) - } - - rel <- assignment %>% - relationships() %>% - filter( - (`m/z1` %in% assigned$`Measured m/z` | - (`m/z2` %in% assigned$`Measured m/z`)) & - !(`m/z1` %in% assigned$`Measured m/z` & - (`m/z2` %in% assigned$`Measured m/z`)), - !(is.na(Transformation1) & is.na(Transformation2)) - ) - - mz1 <- rel %>% - semi_join(assigned, - by = c('m/z1' = 'Measured m/z', - 'Adduct1' = 'Adduct', - 'Isotope1' = 'Isotope')) %>% - filter(is.na(Transformation1)) - mz2 <- rel %>% - semi_join(assigned, - by = c('m/z2' = 'Measured m/z', - 'Adduct2' = 'Adduct', - 'Isotope2' = 'Isotope')) %>% - filter(is.na(Transformation2)) - - rel <- bind_rows(mz1,mz2) - - if (nrow(rel) > 0) { + if (assignment@log$verbose == TRUE) message(blue('Transformation assignment...')) + count <- 0 + repeat { + count <- count + 1 + + if (assignment@log$verbose == TRUE) { + startTime <- proc.time() + message(blue(str_c('iteration ', + count,' ')), + cli::symbol$continue, + '\r', + appendLF = FALSE) + } + + assigned <- assignments(assignment) + + rel <- assignment %>% + relationships() %>% + filter( + (`m/z1` %in% assigned$`Measured m/z` | + (`m/z2` %in% assigned$`Measured m/z`)) & + !(`m/z1` %in% assigned$`Measured m/z` & + (`m/z2` %in% assigned$`Measured m/z`)), + !(is.na(Transformation1) & is.na(Transformation2)) + ) + + mz1 <- rel %>% + semi_join(assigned, + by = c('m/z1' = 'Measured m/z', + 'Adduct1' = 'Adduct', + 'Isotope1' = 'Isotope')) %>% + filter(is.na(Transformation1)) + mz2 <- rel %>% + semi_join(assigned, + by = c('m/z2' = 'Measured m/z', + 'Adduct2' = 'Adduct', + 'Isotope2' = 'Isotope')) %>% + filter(is.na(Transformation2)) + + rel <- bind_rows(mz1,mz2) + + if (nrow(rel) == 0) break + M <- collateM(rel, maxM(assignment))%>% filter(!(mz %in% assigned$`Measured m/z`)) @@ -58,86 +63,73 @@ setMethod('transformationAssign',signature = 'Assignment', isotopeRules(assignment), AIS(assignment)) - if (nrow(MFs) > 0) { - - MFs <- MFs %>% - bind_rows(assigned %>% - select(dplyr::any_of(names(MFs))) %>% - left_join(AIS(assignment), - by = c('Adduct','Isotope'))) - graph_edges <- rel %>% - addMFs(MFs, - identMF = FALSE) %>% - sanitiseTransformations(assignment@transformation_rules) %>% - mutate(RetentionTime1 = as.numeric(RetentionTime1), - RetentionTime2 = as.numeric(RetentionTime2)) %>% - addNames() - - if (nrow(graph_edges) > 0) { - graph_nodes <- collateMFs(graph_edges,MFs) - - graph <- calcComponents(graph_nodes, - graph_edges, - assignment) - - filtered_graph <- filterComponents(graph, - assignment) - - newly_assigned <- filtered_graph %>% - nodes() %>% - rename(Name = name) %>% - mutate(Mode = str_sub(Feature,1,1)) %>% - filter(!(Name %in% assigned$Name)) %>% - select(Name:`MF Plausibility (%)`,Mode) %>% - mutate(Iteration = str_c('T',count + 1)) %>% - group_split(MF) %>% - map_dfr(~{ - if (NA %in% .x$Isotope) return(.x) - else NULL - }) - - outputs <- list( - graph = graph, - filtered_graph = filtered_graph, - assigned = newly_assigned) - - assignment@assignments <- bind_rows(assignment@assignments, - newly_assigned) - - if (count == 0) { - assignment@transAssign <- list(`1` = outputs) - } else { - assignment@transAssign <- c(assignment@transAssign, - list(outputs)) - } - } else { - assignment@transAssign <- c(assignment@transAssign, - list(list())) - } - } else { - assignment@transAssign <- c(assignment@transAssign, - list(list())) + if (nrow(MFs) == 0) break + + MFs <- MFs %>% + bind_rows(assigned %>% + select(dplyr::any_of(names(MFs))) %>% + left_join(AIS(assignment), + by = c('Adduct','Isotope'))) + graph_edges <- rel %>% + addMFs(MFs, + identMF = FALSE) %>% + sanitiseTransformations(assignment@transformation_rules) %>% + mutate(RetentionTime1 = as.numeric(RetentionTime1), + RetentionTime2 = as.numeric(RetentionTime2)) %>% + addNames() + + if (nrow(graph_edges) == 0) break + + graph_nodes <- collateMFs(graph_edges,MFs) + + graph <- calcComponents(graph_nodes, + graph_edges, + assignment) + + filtered_graph <- filterComponents(graph, + assignment) + + newly_assigned <- filtered_graph %>% + nodes() %>% + rename(Name = name) %>% + mutate(Mode = str_sub(Feature,1,1)) %>% + filter(!(Name %in% assigned$Name)) %>% + select(Name:`MF Plausibility (%)`,Mode) %>% + mutate(Iteration = str_c('T',count + 1)) %>% + group_split(MF) %>% + map_dfr(~{ + if (NA %in% .x$Isotope) return(.x) + else NULL + }) + + if (nrow(newly_assigned) == 0) break + + assignment@transAssign[[count]] <- list( + graph = graph, + filtered_graph = filtered_graph, + assigned = newly_assigned) + + assignment@assignments <- bind_rows(assignment@assignments, + newly_assigned) + + if (assignment@log$verbose == TRUE) { + endTime <- proc.time() + elapsed <- {endTime - startTime} %>% + .[3] %>% + round(1) %>% + seconds_to_period() %>% + str_c('[',.,']') + message(blue(str_c('iteration ', + count,' ')), + '\t', + green(cli::symbol$tick), + ' ', + elapsed) } - } else { - assignment@transAssign <- c(assignment@transAssign, - list(list())) } - names(assignment@transAssign)[count + 1] <- count + 1 - if (assignment@log$verbose == TRUE) { - endTime <- proc.time() - elapsed <- {endTime - startTime} %>% - .[3] %>% - round(1) %>% - seconds_to_period() %>% - str_c('[',.,']') - message(blue(str_c('Transformation assignment iteration ', - count + 1,' ')), - '\t', - green(cli::symbol$tick), - ' ', - elapsed) - } + names(assignment@transAssign) <- paste0('T', + seq_along(assignment@transAssign)) return(assignment) } From fa44b5b22358e1acc92b2ebc24bb139d0132a417 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Thu, 19 May 2022 08:32:35 +0100 Subject: [PATCH 174/226] fixed assignment console output --- R/addIsoAssign.R | 55 ++++++++++++++++++++++++++++++++-------- R/internals.R | 9 +++++++ R/transformationAssign.R | 35 +++++++++++++++---------- 3 files changed, 74 insertions(+), 25 deletions(-) diff --git a/R/addIsoAssign.R b/R/addIsoAssign.R index 09adf7a..79ce00d 100644 --- a/R/addIsoAssign.R +++ b/R/addIsoAssign.R @@ -14,10 +14,9 @@ setMethod('addIsoAssign',signature = 'Assignment', function(assignment){ if (isTRUE(assignment@log$verbose)) { - startTime <- proc.time() + ai_start_time <- proc.time() message(blue('Adduct & isotopic assignment '), - cli::symbol$continue,'\r', - appendLF = FALSE) + cli::symbol$continue) } assignment_technique <- technique(assignment) @@ -45,6 +44,14 @@ setMethod('addIsoAssign',signature = 'Assignment', M <- collateM(rel, maxM(assignment)) + if (isTRUE(assignment@log$verbose)) { + start_time <- proc.time() + message('generating molecular formulas', + cli::symbol$continue, + '\r', + appendLF = FALSE) + } + MFs <- generateMFs(M, ppm(assignment), MFrankThreshold(assignment), @@ -52,6 +59,16 @@ setMethod('addIsoAssign',signature = 'Assignment', isotopeRules(assignment), AIS(assignment)) + if (isTRUE(assignment@log$verbose)) { + end_time <- proc.time() + elapsed <- elapsedTime(start_time,end_time) + message('generating molecular formulas', + '\t', + green(cli::symbol$tick), + ' ', + elapsed) + } + graph_edges <- rel %>% addMFs(MFs) %>% filter(MF1 == MF2) %>% @@ -71,7 +88,13 @@ setMethod('addIsoAssign',signature = 'Assignment', counter <- counter + 1 - message(paste0('iteration ',counter)) + if (isTRUE(assignment@log$verbose)) { + start_time <- proc.time() + message(paste0('iteration ',counter), + cli::symbol$continue, + '\r', + appendLF = FALSE) + } if (counter > 1){ graph <- assignment@addIsoAssign[[counter - 1]]$graph %>% @@ -116,15 +139,25 @@ setMethod('addIsoAssign',signature = 'Assignment', mutate(Iteration = paste0('A&I',counter)) ) + if (isTRUE(assignment@log$verbose)) { + end_time <- proc.time() + elapsed <- elapsedTime(start_time,end_time) + message(paste0('iteration ',counter), + '\t\t\t', + green(cli::symbol$tick), + ' ', + elapsed) + } + } - if (assignment@log$verbose == TRUE) { - endTime <- proc.time() - elapsed <- {endTime - startTime} %>% - .[3] %>% - round(1) %>% - seconds_to_period() %>% - str_c('[',.,']') + names(assignment@addIsoAssign) <- paste0('A&I', + seq_along(assignment@addIsoAssign)) + + if (isTRUE(assignment@log$verbose)) { + ai_end_time <- proc.time() + elapsed <- elapsedTime(ai_start_time, + ai_end_time) message(blue('Adduct & isotopic assignment '),'\t',green(cli::symbol$tick),' ',elapsed) } diff --git a/R/internals.R b/R/internals.R index a3f1aa8..11de69c 100644 --- a/R/internals.R +++ b/R/internals.R @@ -1,3 +1,12 @@ + +elapsedTime <- function(start_time,end_time){ + {end_time - start_time} %>% + .[3] %>% + round(1) %>% + seconds_to_period() %>% + str_c('[',.,']') +} + #' @importFrom dplyr bind_cols eliminate <- function(MFs,by,direction){ diff --git a/R/transformationAssign.R b/R/transformationAssign.R index dfc9704..aeb7384 100644 --- a/R/transformationAssign.R +++ b/R/transformationAssign.R @@ -9,15 +9,19 @@ setGeneric("transformationAssign", function(assignment) setMethod('transformationAssign',signature = 'Assignment', function(assignment){ - if (assignment@log$verbose == TRUE) message(blue('Transformation assignment...')) + if (assignment@log$verbose == TRUE) { + t_start_time <- proc.time() + message(blue('Transformation assignment'), + cli::symbol$continue) + } count <- 0 repeat { count <- count + 1 if (assignment@log$verbose == TRUE) { - startTime <- proc.time() - message(blue(str_c('iteration ', - count,' ')), + start_time <- proc.time() + message(str_c('iteration ', + count,' '), cli::symbol$continue, '\r', appendLF = FALSE) @@ -112,16 +116,12 @@ setMethod('transformationAssign',signature = 'Assignment', assignment@assignments <- bind_rows(assignment@assignments, newly_assigned) - if (assignment@log$verbose == TRUE) { - endTime <- proc.time() - elapsed <- {endTime - startTime} %>% - .[3] %>% - round(1) %>% - seconds_to_period() %>% - str_c('[',.,']') - message(blue(str_c('iteration ', - count,' ')), - '\t', + if (isTRUE(assignment@log$verbose)) { + end_time <- proc.time() + elapsed <- elapsedTime(start_time,end_time) + message(str_c('iteration ', + count,' '), + '\t\t\t', green(cli::symbol$tick), ' ', elapsed) @@ -131,6 +131,13 @@ setMethod('transformationAssign',signature = 'Assignment', names(assignment@transAssign) <- paste0('T', seq_along(assignment@transAssign)) + if (isTRUE(assignment@log$verbose)) { + t_end_time <- proc.time() + elapsed <- elapsedTime(t_start_time, + t_end_time) + message(blue('Transformation assignment '),'\t',green(cli::symbol$tick),' ',elapsed) + } + return(assignment) } ) From d760e33e54d5a01dfa49f37cf6f2d5b3ee71bd5f Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Thu, 19 May 2022 08:47:56 +0100 Subject: [PATCH 175/226] Added accessor methods for the assignment class --- NAMESPACE | 10 +-- R/assignment.R | 128 ++++++++++++++++++++++++++++++++---- man/accessors.Rd | 54 ++++++++++++++- man/assignedData.Rd | 13 ++++ man/assignmentData.Rd | 17 ----- man/summariseAssignment.Rd | 17 ----- man/summariseAssignments.Rd | 30 +++++++++ 7 files changed, 217 insertions(+), 52 deletions(-) delete mode 100644 man/assignmentData.Rd delete mode 100644 man/summariseAssignment.Rd create mode 100644 man/summariseAssignments.Rd diff --git a/NAMESPACE b/NAMESPACE index 33f677b..3bc018e 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -3,7 +3,7 @@ export("MFrankThreshold<-") export("adductRules<-") export("adducts<-") -export("correlations<-") +export("correlationsParameters<-") export("isotopeRules<-") export("isotopes<-") export("limit<-") @@ -16,14 +16,17 @@ export(adductRules) export(adducts) export(assignMFs) export(assignedData) -export(assignmentData) export(assignmentParameters) export(assignments) export(availableTechniques) export(correlations) +export(correlationsParameters) export(edges) +export(featureData) +export(graph) export(isotopeRules) export(isotopes) +export(iterations) export(limit) export(maxM) export(nodes) @@ -34,7 +37,7 @@ export(plotNetwork) export(plotSpectrum) export(ppm) export(relationships) -export(summariseAssignment) +export(summariseAssignments) export(technique) export(transformationRules) export(transformations) @@ -83,7 +86,6 @@ importFrom(magrittr,"%>%") importFrom(magrittr,set_names) importFrom(metabolyseR,analysisParameters) importFrom(metabolyseR,analysisResults) -importFrom(metabolyseR,correlationsParameters) importFrom(metabolyseR,dat) importFrom(metabolyseR,metabolyse) importFrom(metabolyseR,preTreated) diff --git a/R/assignment.R b/R/assignment.R index 0bb0b32..5af8bd7 100644 --- a/R/assignment.R +++ b/R/assignment.R @@ -90,6 +90,57 @@ setMethod('show',signature = 'Assignment', #' @rdname accessors #' @description Access methods for Assignment S4 class #' @param assignment S4 object of class Assignment +#' @param iteration the assignment iteration +#' @param type the graph type to return. `filtered` returns the assignment graph after component selection. `all` returns all assignment components. +#' @examples +#' assignment <- new('Assignment', +#' data = feature_data) +#' +#' ## Return feature data +#' featureData(assignment) +#' +#' ## Return correlations +#' correlations(assignment) +#' +#' ## Return relationships +#' relationships(assignment) +#' +#' ## Return the available iterations +#' iterations(assignment) +#' +#' ## Return a selected graph +#' \dontrun{ +#' graph(assignment,'A&I1') +#' } +#' +#' ## Return assignments +#' assignments(assignment) +#' @export + +setGeneric('featureData',function(assignment) + standardGeneric('featureData')) + +#' @rdname accessors + +setMethod('featureData', signature = 'Assignment', + function(assignment){ + assignment@data + }) + +#' @rdname accessors +#' @export + +setGeneric('correlations',function(assignment) + standardGeneric('correlations')) + +#' @rdname accessors + +setMethod('correlations',signature = 'Assignment', + function(assignment){ + assignment@relationships + }) + +#' @rdname accessors #' @export setGeneric('relationships',function(assignment) @@ -114,36 +165,77 @@ setMethod('relationships<-',signature = 'Assignment', #' @rdname accessors #' @export -setGeneric('assignments',function(assignment) - standardGeneric('assignments')) +setGeneric('iterations',function(assignment) + standardGeneric('iterations')) #' @rdname accessors -setMethod('assignments',signature = 'Assignment', +setMethod('iterations',signature = 'Assignment', function(assignment){ - assignment@assignments + c(names(assignment@addIsoAssign), + names(assignment@transAssign)) }) -#' assignmentData -#' @rdname assignmentData -#' @description Return data table used for assignments. -#' @param assignment S4 object of class Assignment +#' @rdname accessors +#' @export + +setGeneric('graph',function(assignment, + iteration, + type = c('filtered','all')) + standardGeneric('graph')) + +#' @rdname accessors + +setMethod('graph',signature = 'Assignment', + function(assignment, + iteration, + type = c('filtered','all')){ + + if (!iteration %in% iterations(assignment)) { + iters <- assignment %>% + iterations() %>% + paste0('"',.,'"') %>% + paste(collapse = ', ') + stop(paste0('Iteration not recognised. Argument `iteration` should be one of ',iters), + call. = FALSE) + } + + type <- match.arg(type, + choices = c('filtered','all')) + graph <- switch(type, + filtered = assignment@addIsoAssign[[iteration]]$filtered_graph, + all = assignment@addIsoAssign[[iteration]]$graph) + + return(graph) + }) + +#' @rdname accessors #' @export -setGeneric('assignmentData',function(assignment) - standardGeneric('assignmentData')) +setGeneric('assignments',function(assignment) + standardGeneric('assignments')) -#' @rdname assignmentData +#' @rdname accessors -setMethod('assignmentData', signature = 'Assignment', +setMethod('assignments',signature = 'Assignment', function(assignment){ - assignment@data + assignment@assignments }) #' assignedData #' @rdname assignedData #' @description Return data table used for assignments with feature assignments added to column names. #' @param assignment S4 object of class Assignment +#' @return A tibble containing the original feature data with molecular formula assignments added to teh column names. +#' @examples +#' \dontrun{ +#' plan(future::sequential) +#' p <- assignmentParameters('FIE-HRMS') +#' +#' assignment <- assignMFs(feature_data,p) +#' +#' assignedData(assignment) +#' } #' @export setGeneric('assignedData',function(assignment) @@ -180,6 +272,16 @@ setMethod('assignedData', signature = 'Assignment', #' @rdname summariseAssignments #' @description Summarise features assigned to molecular formulas. #' @param assignment S4 object of class Assignment +#' @return A tibble containing the feature assignments summarised by molecular formula. +#' @examples +#' \dontrun{ +#' plan(future::sequential) +#' p <- assignmentParameters('FIE-HRMS') +#' +#' assignment <- assignMFs(feature_data,p) +#' +#' summariseAssignments(assignment) +#' } #' @importFrom dplyr desc #' @export diff --git a/man/accessors.Rd b/man/accessors.Rd index aaf76d7..a044e5d 100644 --- a/man/accessors.Rd +++ b/man/accessors.Rd @@ -1,23 +1,75 @@ % Generated by roxygen2: do not edit by hand % Please edit documentation in R/assignment.R -\name{relationships} +\name{featureData} +\alias{featureData} +\alias{featureData,Assignment-method} +\alias{correlations} +\alias{correlations,Assignment-method} \alias{relationships} \alias{relationships,Assignment-method} +\alias{iterations} +\alias{iterations,Assignment-method} +\alias{graph} +\alias{graph,Assignment-method} \alias{assignments} \alias{assignments,Assignment-method} \title{Assignment accessors} \usage{ +featureData(assignment) + +\S4method{featureData}{Assignment}(assignment) + +correlations(assignment) + +\S4method{correlations}{Assignment}(assignment) + relationships(assignment) \S4method{relationships}{Assignment}(assignment) +iterations(assignment) + +\S4method{iterations}{Assignment}(assignment) + +graph(assignment, iteration, type = c("filtered", "all")) + +\S4method{graph}{Assignment}(assignment, iteration, type = c("filtered", "all")) + assignments(assignment) \S4method{assignments}{Assignment}(assignment) } \arguments{ \item{assignment}{S4 object of class Assignment} + +\item{iteration}{the assignment iteration} + +\item{type}{the graph type to return. \code{filtered} returns the assignment graph after component selection. \code{all} returns all assignment components.} } \description{ Access methods for Assignment S4 class } +\examples{ +assignment <- new('Assignment', + data = feature_data) + +## Return feature data +featureData(assignment) + +## Return correlations +correlations(assignment) + +## Return relationships +relationships(assignment) + +## Return the available iterations +iterations(assignment) + +## Return a selected graph +\dontrun{ +graph(assignment,'A&I1') +} + +## Return assignments +assignments(assignment) +} diff --git a/man/assignedData.Rd b/man/assignedData.Rd index 3555f17..faa4015 100644 --- a/man/assignedData.Rd +++ b/man/assignedData.Rd @@ -12,6 +12,19 @@ assignedData(assignment) \arguments{ \item{assignment}{S4 object of class Assignment} } +\value{ +A tibble containing the original feature data with molecular formula assignments added to teh column names. +} \description{ Return data table used for assignments with feature assignments added to column names. } +\examples{ +\dontrun{ +plan(future::sequential) +p <- assignmentParameters('FIE-HRMS') + +assignment <- assignMFs(feature_data,p) + +assignedData(assignment) +} +} diff --git a/man/assignmentData.Rd b/man/assignmentData.Rd deleted file mode 100644 index 36c0ec7..0000000 --- a/man/assignmentData.Rd +++ /dev/null @@ -1,17 +0,0 @@ -% Generated by roxygen2: do not edit by hand -% Please edit documentation in R/assignment.R -\name{assignmentData} -\alias{assignmentData} -\alias{assignmentData,Assignment-method} -\title{assignmentData} -\usage{ -assignmentData(assignment) - -\S4method{assignmentData}{Assignment}(assignment) -} -\arguments{ -\item{assignment}{S4 object of class Assignment} -} -\description{ -Return data table used for assignments. -} diff --git a/man/summariseAssignment.Rd b/man/summariseAssignment.Rd deleted file mode 100644 index 774eb01..0000000 --- a/man/summariseAssignment.Rd +++ /dev/null @@ -1,17 +0,0 @@ -% Generated by roxygen2: do not edit by hand -% Please edit documentation in R/assignment.R -\name{summariseAssignment} -\alias{summariseAssignment} -\alias{summariseAssignment,Assignment-method} -\title{Summarise assignments} -\usage{ -summariseAssignment(assignment) - -\S4method{summariseAssignment}{Assignment}(assignment) -} -\arguments{ -\item{assignment}{S4 object of class Assignment} -} -\description{ -Summarise features assigned to molecular formulas. -} diff --git a/man/summariseAssignments.Rd b/man/summariseAssignments.Rd new file mode 100644 index 0000000..ecd0cd7 --- /dev/null +++ b/man/summariseAssignments.Rd @@ -0,0 +1,30 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/assignment.R +\name{summariseAssignments} +\alias{summariseAssignments} +\alias{summariseAssignments,Assignment-method} +\title{Summarise assignments} +\usage{ +summariseAssignments(assignment) + +\S4method{summariseAssignments}{Assignment}(assignment) +} +\arguments{ +\item{assignment}{S4 object of class Assignment} +} +\value{ +A tibble containing the feature assignments summarised by molecular formula. +} +\description{ +Summarise features assigned to molecular formulas. +} +\examples{ +\dontrun{ +plan(future::sequential) +p <- assignmentParameters('FIE-HRMS') + +assignment <- assignMFs(feature_data,p) + +summariseAssignments(assignment) +} +} From 28129e9d390a1a5bcf02ff8f1857a54c350f7387 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Thu, 19 May 2022 09:25:56 +0100 Subject: [PATCH 176/226] test fix --- tests/testthat/test-assignment.R | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/testthat/test-assignment.R b/tests/testthat/test-assignment.R index ee714dc..ba58724 100644 --- a/tests/testthat/test-assignment.R +++ b/tests/testthat/test-assignment.R @@ -47,7 +47,7 @@ test_that('assignment class show method works',{ }) test_that('assignment data can be returned',{ - expect_s3_class(assignmentData(assignment_FIE),'tbl_df') + expect_s3_class(featureData(assignment_FIE),'tbl_df') }) test_that('data with assigned feature names can be returned',{ From 5e0b43b6966089c4df7498bd12561a9df4cf66ab Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Thu, 19 May 2022 09:26:24 +0100 Subject: [PATCH 177/226] added component accessor methods --- R/assignment.R | 100 +++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 97 insertions(+), 3 deletions(-) diff --git a/R/assignment.R b/R/assignment.R index 5af8bd7..9cb7784 100644 --- a/R/assignment.R +++ b/R/assignment.R @@ -112,6 +112,21 @@ setMethod('show',signature = 'Assignment', #' \dontrun{ #' graph(assignment,'A&I1') #' } +#' +#' ## Return a component information for a selected graph +#' \dontrun{ +#' components(assignment,'A&I1') +#' } +#' +#' ## Return a component information for a selected feature +#' \dontrun{ +#' featureComponents(assignment,'A&I1') +#' } +#' +#' ## Extract a component graph +#' \dontrun{ +#' component(assignment,1,'A&I1') +#' } #' #' ## Return assignments #' assignments(assignment) @@ -202,9 +217,15 @@ setMethod('graph',signature = 'Assignment', type <- match.arg(type, choices = c('filtered','all')) + + assignment_iteration <- switch( + str_remove(iteration,'[1-9]'), + `A&I` = assignment@addIsoAssign, + `T` = assignment@transAssign) + graph <- switch(type, - filtered = assignment@addIsoAssign[[iteration]]$filtered_graph, - all = assignment@addIsoAssign[[iteration]]$graph) + filtered = assignment_iteration[[iteration]]$filtered_graph, + all = assignment_iteration[[iteration]]$graph) return(graph) }) @@ -212,6 +233,79 @@ setMethod('graph',signature = 'Assignment', #' @rdname accessors #' @export +setGeneric('components',function(assignment, + iteration, + type = c('filtered','all')) + standardGeneric('components')) + +#' @rdname accessors + +setMethod('components',signature = 'Assignment', + function(assignment, + iteration, + type = c('filtered','all')){ + + selected_graph <- graph(assignment,iteration,type) %>% + nodes() %>% + select(Component:Weight) %>% + distinct() + + }) + +#' @rdname accessors +#' @export + +setGeneric('featureComponents',function(assignment, + feature, + type = c('filtered','all')) + standardGeneric('featureComponents')) + +#' @rdname accessors + +setMethod('featureComponents',signature = 'Assignment', + function(assignment, + feature, + type = c('filtered','all')){ + + available_iterations <- iterations(assignment) + + available_iterations %>% + map(graph,assignment = assignment,type = 'all') %>% + set_names(available_iterations) %>% + map_dfr(nodes,.id = 'Iteration') %>% + filter(Feature == feature) + }) + +setGeneric('component',function(assignment, + component, + iteration, + type = c('filtered','all')) + standardGeneric('component')) + +#' @rdname accessors + +setMethod('component',signature = 'Assignment', + function(assignment, + component, + iteration, + type = c('filtered','all')){ + + iteration_components <- components(assignment, + iteration, + type) + + if (!component %in% iteration_components$Component){ + stop(paste0('Component ',component, ' not found in iteration ',iteration,'.')) + } + + graph(assignment,iteration,type) %>% + filter(Component == component) + + }) + +#' @rdname accessors +#' @export + setGeneric('assignments',function(assignment) standardGeneric('assignments')) @@ -247,7 +341,7 @@ setMethod('assignedData', signature = 'Assignment', function(assignment){ d <- assignment %>% - assignmentData() + featureData() assignedFeats <- assignment %>% assignments() %>% From 262c5e9d56fe89cdeb405e9ecb3dc2ad16318144 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Thu, 19 May 2022 09:27:29 +0100 Subject: [PATCH 178/226] renamed plotFeatureSolutions file --- DESCRIPTION | 2 +- ...otFeatureSolutions.R => plot_components.R} | 21 ++++++++++++++++--- 2 files changed, 19 insertions(+), 4 deletions(-) rename R/{plotFeatureSolutions.R => plot_components.R} (86%) diff --git a/DESCRIPTION b/DESCRIPTION index eca8e9e..2664391 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -30,7 +30,7 @@ Collate: parameters.R assignment.R correlations.R addIsoAssign.R transformationAssign.R relationships.R graph.R assign.R internals.R components.R feature_data.R assignments.R plotNetwork.R - plotAdductDist.R plotFeatureSolutions.R + plotAdductDist.R plot_components.R plotSpectrum.R reexports.R zzz.R Suggests: testthat, covr, diff --git a/R/plotFeatureSolutions.R b/R/plot_components.R similarity index 86% rename from R/plotFeatureSolutions.R rename to R/plot_components.R index 405140b..9ec0541 100644 --- a/R/plotFeatureSolutions.R +++ b/R/plot_components.R @@ -79,10 +79,25 @@ setGeneric('plotFeatureSolutions', setMethod('plotFeatureSolutions',signature = 'Assignment', function(assignment,feature,maxComponents = 10){ - n <- nodes(assignment@addIsoAssign$graph) + if (!feature %in% colnames(featureData(assignment))) { + stop('Feature not found in assignment data') + } + + available_iterations <- iterations(assignment) + + graphs <- available_iterations %>% + map(graph,assignment = assignment,type = 'all') %>% + set_names(available_iterations) + + available_nodes <- graphs %>% + map_dfr(nodes,.id = 'Iteration') %>% + select(Feature) %>% + distinct() - if (!(feature %in% n$Feature)){ - stop('Feature not found in assignment graph.', + if (!(feature %in% available_nodes$Feature)){ + stop( + paste0('No assignment solutions available for feature ', + feature), call. = FALSE) } From 8dd54a149e833d4da1585bd3506cc711ed22ae3b Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Thu, 19 May 2022 09:27:55 +0100 Subject: [PATCH 179/226] update documentation --- NAMESPACE | 2 ++ man/accessors.Rd | 30 ++++++++++++++++++++++++++++++ man/plotFeatureSolutions.Rd | 2 +- 3 files changed, 33 insertions(+), 1 deletion(-) diff --git a/NAMESPACE b/NAMESPACE index 3bc018e..efaee18 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -19,9 +19,11 @@ export(assignedData) export(assignmentParameters) export(assignments) export(availableTechniques) +export(components) export(correlations) export(correlationsParameters) export(edges) +export(featureComponents) export(featureData) export(graph) export(isotopeRules) diff --git a/man/accessors.Rd b/man/accessors.Rd index a044e5d..1b7b2ba 100644 --- a/man/accessors.Rd +++ b/man/accessors.Rd @@ -11,6 +11,11 @@ \alias{iterations,Assignment-method} \alias{graph} \alias{graph,Assignment-method} +\alias{components} +\alias{components,Assignment-method} +\alias{featureComponents} +\alias{featureComponents,Assignment-method} +\alias{component,Assignment-method} \alias{assignments} \alias{assignments,Assignment-method} \title{Assignment accessors} @@ -35,6 +40,16 @@ graph(assignment, iteration, type = c("filtered", "all")) \S4method{graph}{Assignment}(assignment, iteration, type = c("filtered", "all")) +components(assignment, iteration, type = c("filtered", "all")) + +\S4method{components}{Assignment}(assignment, iteration, type = c("filtered", "all")) + +featureComponents(assignment, feature, type = c("filtered", "all")) + +\S4method{featureComponents}{Assignment}(assignment, feature, type = c("filtered", "all")) + +\S4method{component}{Assignment}(assignment, component, iteration, type = c("filtered", "all")) + assignments(assignment) \S4method{assignments}{Assignment}(assignment) @@ -70,6 +85,21 @@ iterations(assignment) graph(assignment,'A&I1') } +## Return a component information for a selected graph +\dontrun{ +components(assignment,'A&I1') +} + +## Return a component information for a selected feature +\dontrun{ +featureComponents(assignment,'A&I1') +} + + ## Extract a component graph +\dontrun{ +component(assignment,1,'A&I1') +} + ## Return assignments assignments(assignment) } diff --git a/man/plotFeatureSolutions.Rd b/man/plotFeatureSolutions.Rd index 80e53df..dec952e 100644 --- a/man/plotFeatureSolutions.Rd +++ b/man/plotFeatureSolutions.Rd @@ -1,5 +1,5 @@ % Generated by roxygen2: do not edit by hand -% Please edit documentation in R/plotFeatureSolutions.R +% Please edit documentation in R/plot_components.R \name{plotFeatureSolutions} \alias{plotFeatureSolutions} \alias{plotFeatureSolutions,Assignment-method} From 93dc94c1eb565ce9cd70f3468297ebb47358dbf2 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Thu, 19 May 2022 11:20:11 +0100 Subject: [PATCH 180/226] added plotComponent method --- DESCRIPTION | 1 + NAMESPACE | 2 + R/plot_components.R | 174 ++++++++++++++++++++++++++++--------------- man/plotComponent.Rd | 41 ++++++++++ 4 files changed, 157 insertions(+), 61 deletions(-) create mode 100644 man/plotComponent.Rd diff --git a/DESCRIPTION b/DESCRIPTION index 2664391..7fac27f 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -39,6 +39,7 @@ Suggests: testthat, ggrepel, ggthemes, graphlayouts, + ggtext, patchwork Remotes: jasenfinch/mzAnnotation@devel, jasenfinch/metabolyseR@devel diff --git a/NAMESPACE b/NAMESPACE index efaee18..80bf76a 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -34,6 +34,7 @@ export(maxM) export(nodes) export(plan) export(plotAdductDist) +export(plotComponent) export(plotFeatureSolutions) export(plotNetwork) export(plotSpectrum) @@ -62,6 +63,7 @@ importFrom(dplyr,inner_join) importFrom(dplyr,left_join) importFrom(dplyr,mutate) importFrom(dplyr,mutate_at) +importFrom(dplyr,mutate_if) importFrom(dplyr,n) importFrom(dplyr,relocate) importFrom(dplyr,rename) diff --git a/R/plot_components.R b/R/plot_components.R index 9ec0541..cdcfba9 100644 --- a/R/plot_components.R +++ b/R/plot_components.R @@ -1,66 +1,118 @@ -plotSolutions <- function(graph,selectedComp,feature){ - check_installed(c('ggraph', - 'ggplot2', - 'patchwork')) - graph %>% - map(~{ - stats <- nodes(.x) %>% - select(Component:`Component Plausibility`,AIS) %>% - .[1,] - - if (length(selectedComp) > 0){ - border <- ifelse(stats$Component[1] == selectedComp, - 'red', - 'black') - } else { - border <- 'black' - } - - g <- .x %>% - mutate(Feat = Feature == feature) %>% - ggraph::create_layout('nicely') - ggraph::ggraph(g) + - ggraph::geom_edge_link(ggplot2::aes(colour = coefficient)) + - ggraph::scale_edge_color_gradient(low = 'white', - high = 'black', - limits = c(0.5,1)) + - ggraph::geom_node_label(ggplot2::aes(label = name, - fill = Feat), - size = 2,) + - ggplot2::scale_fill_manual(values = c('white','steelblue')) + - ggraph::theme_graph(base_family = '', - title_size = 12, - title_face = 'plain', - foreground = border, - plot_margin = ggplot2::margin(5, 5, 5, 5)) + - ggplot2::theme( - plot.title = ggplot2::element_text(face = 'bold', - hjust = 0.5), - plot.caption = ggplot2::element_text(hjust = 0)) + - ggplot2::labs( - title = str_c('Component ',stats$Component), - caption = str_c('Degree = ',stats$Degree %>% round(2),'; ', - 'Weight = ',stats$Weight %>% round(2),'; ', - 'AIS = ',stats$AIS %>% round(2),'; ', - 'Plausibility = ',stats$`Component Plausibility` %>% - round(2))) + - ggplot2::xlim(min(g$x) - (max(g$x) - min(g$x)) * 0.05, - max(g$x) + (max(g$x) - min(g$x)) * 0.05) + - ggplot2::ylim(min(g$y) - (max(g$y) - min(g$y)) * 0.05, - max(g$y) + (max(g$y) - min(g$y)) * 0.05) + - ggplot2::guides(fill = 'none') - }) %>% - patchwork::wrap_plots() + - patchwork::plot_layout(guides = 'collect') + - patchwork::plot_annotation( - title = str_c('Solutions for feature ', - feature), - theme = ggplot2::theme( - plot.title = ggplot2::element_text(face = 'bold', - hjust = 0.5))) +graphTheme <- function(){ + ggplot2::theme( + legend.title = ggplot2::element_text(face = 'bold'), + plot.margin = ggplot2::margin(5, 5, 5, 5), + plot.title = ggplot2::element_text(face = 'bold',hjust = 0.5), + plot.caption = ggtext::element_markdown(hjust = 0.5) + ) } +plotGraph <- function(graph,min_coef,label_size = 3,axis_offset = 0.1){ + + g <- graph %>% + activate(nodes) %>% + mutate(name = str_replace_all(name,' ','\n') %>% + str_replace_all(' ','\n')) %>% + ggraph::create_layout('nicely') + + g %>% + ggraph::ggraph() + + ggraph::geom_edge_link(ggplot2::aes(colour = coefficient)) + + ggraph::scale_edge_color_gradient(low = 'lightgrey', + high = 'black', + limits = c(min_coef,1)) + + ggraph::geom_node_label(ggplot2::aes(label = name), + size = label_size) + + ggraph::theme_graph(base_family = '', + base_size = 10) + + graphTheme() + + ggplot2::lims( + x = c( + min(g$x) - (max(g$x) - min(g$x)) * axis_offset, + max(g$x) + (max(g$x) - min(g$x)) * axis_offset + ), + y = c( + min(g$y) - (max(g$y) - min(g$y)) * axis_offset, + max(g$y) + (max(g$y) - min(g$y)) * axis_offset + ) + ) +} + +#' Plot a component +#' @rdname plotComponent +#' @description Plot a molecular formula component graph. +#' @param assignment S4 object of class Assignment +#' @param component component number to extract +#' @param iteration the assignment iteration +#' @param type the graph type to return. `filtered` returns the assignment graph after component selection. `all` returns all assignment components. +#' @param label_size node label size +#' @param axis_offset axis proportion by which to increase axis limits. Prevents cut off of node labels. +#' @examples +#' \dontrun{ +#' plan(future::sequential) +#' p <- assignmentParameters('FIE-HRMS') +#' +#' assignment <- assignMFs(feature_data,p) +#' +#' plotComponent(assignment,1,'A&I1') +#' } +#' @export + +setGeneric('plotComponent', + function(assignment, + component, + iteration, + type = c('filtered','all'), + label_size = 3, + axis_offset = 0.1) + standardGeneric('plotComponent')) + +#' @importFrom dplyr mutate_if + +setMethod('plotComponent',signature = 'Assignment', + function(assignment, + component, + iteration, + type = c('filtered','all'), + label_size = 3, + axis_offset = 0.1 + ){ + + check_installed(c('ggraph', + 'ggplot2', + 'ggtext')) + + component_graph <- component(assignment, + component, + iteration, + type) + + component_stats <- component_graph %>% + nodes() %>% + select(`MF Plausibility (%)`, + AIS, + Component:`Component Plausibility`) %>% + distinct() %>% + mutate_if(is.numeric,signif,digits = 3) + + min_coef <- correlationsParameters(assignment)$minCoef + + plotGraph(component_graph, + min_coef, + label_size, + axis_offset) + + ggplot2::labs( + title = paste0('Component ',component), + caption = glue::glue(' + Pc = {component_stats$`Component Plausibility`}; + Degree = {component_stats$Degree}; + + AISc = {component_stats$AIS}; + PMF = {component_stats$`MF Plausibility (%)`}%') + ) + }) + #' Plot the solutions for a feature #' @rdname plotFeatureSolutions #' @description Plot possible MF solutions for a given feature. @@ -98,7 +150,7 @@ setMethod('plotFeatureSolutions',signature = 'Assignment', stop( paste0('No assignment solutions available for feature ', feature), - call. = FALSE) + call. = FALSE) } comp <- n %>% diff --git a/man/plotComponent.Rd b/man/plotComponent.Rd new file mode 100644 index 0000000..cb775ad --- /dev/null +++ b/man/plotComponent.Rd @@ -0,0 +1,41 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/plot_components.R +\name{plotComponent} +\alias{plotComponent} +\title{Plot a component} +\usage{ +plotComponent( + assignment, + component, + iteration, + type = c("filtered", "all"), + label_size = 3, + axis_offset = 0.1 +) +} +\arguments{ +\item{assignment}{S4 object of class Assignment} + +\item{component}{component number to extract} + +\item{iteration}{the assignment iteration} + +\item{type}{the graph type to return. \code{filtered} returns the assignment graph after component selection. \code{all} returns all assignment components.} + +\item{label_size}{node label size} + +\item{axis_offset}{axis proportion by which to increase axis limits. Prevents cut off of node labels.} +} +\description{ +Plot a molecular formula component graph. +} +\examples{ +\dontrun{ +plan(future::sequential) +p <- assignmentParameters('FIE-HRMS') + +assignment <- assignMFs(feature_data,p) + +plotComponent(assignment,1,'A&I1') +} +} From d003fcc8e34352fd047d1a7594c5b8bf8364dc0a Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Thu, 19 May 2022 11:20:20 +0100 Subject: [PATCH 181/226] documentation fix --- R/assignment.R | 4 +++- man/accessors.Rd | 2 ++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/R/assignment.R b/R/assignment.R index 9cb7784..f8575b9 100644 --- a/R/assignment.R +++ b/R/assignment.R @@ -92,6 +92,7 @@ setMethod('show',signature = 'Assignment', #' @param assignment S4 object of class Assignment #' @param iteration the assignment iteration #' @param type the graph type to return. `filtered` returns the assignment graph after component selection. `all` returns all assignment components. +#' @param component component number to extract #' @examples #' assignment <- new('Assignment', #' data = feature_data) @@ -247,9 +248,10 @@ setMethod('components',signature = 'Assignment', selected_graph <- graph(assignment,iteration,type) %>% nodes() %>% - select(Component:Weight) %>% + select(Component:`Component Plausibility`) %>% distinct() + return(selected_graph) }) #' @rdname accessors diff --git a/man/accessors.Rd b/man/accessors.Rd index 1b7b2ba..73b872b 100644 --- a/man/accessors.Rd +++ b/man/accessors.Rd @@ -60,6 +60,8 @@ assignments(assignment) \item{iteration}{the assignment iteration} \item{type}{the graph type to return. \code{filtered} returns the assignment graph after component selection. \code{all} returns all assignment components.} + +\item{component}{component number to extract} } \description{ Access methods for Assignment S4 class From d7f9f05f334b409582639871a08fbf16cf56e41f Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Thu, 19 May 2022 13:00:20 +0100 Subject: [PATCH 182/226] returned selected component for assigned features --- R/addIsoAssign.R | 4 +++- R/transformationAssign.R | 4 +++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/R/addIsoAssign.R b/R/addIsoAssign.R index 79ce00d..68eacf1 100644 --- a/R/addIsoAssign.R +++ b/R/addIsoAssign.R @@ -135,7 +135,9 @@ setMethod('addIsoAssign',signature = 'Assignment', assignment@assignments <- bind_rows( assignment@assignments, assigned_features %>% - select(Name:`MF Plausibility (%)`,Mode) %>% + select(Name:`MF Plausibility (%)`, + Mode, + Component) %>% mutate(Iteration = paste0('A&I',counter)) ) diff --git a/R/transformationAssign.R b/R/transformationAssign.R index aeb7384..aa33d3f 100644 --- a/R/transformationAssign.R +++ b/R/transformationAssign.R @@ -98,7 +98,9 @@ setMethod('transformationAssign',signature = 'Assignment', rename(Name = name) %>% mutate(Mode = str_sub(Feature,1,1)) %>% filter(!(Name %in% assigned$Name)) %>% - select(Name:`MF Plausibility (%)`,Mode) %>% + select(Name:`MF Plausibility (%)`, + Mode, + Component) %>% mutate(Iteration = str_c('T',count + 1)) %>% group_split(MF) %>% map_dfr(~{ From e86fb07412abb1060bacb3e8a7b3b11b80ee207c Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Thu, 19 May 2022 13:01:03 +0100 Subject: [PATCH 183/226] fix featureComponents method --- R/assignment.R | 4 ++-- man/accessors.Rd | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/R/assignment.R b/R/assignment.R index f8575b9..f098e66 100644 --- a/R/assignment.R +++ b/R/assignment.R @@ -121,7 +121,7 @@ setMethod('show',signature = 'Assignment', #' #' ## Return a component information for a selected feature #' \dontrun{ -#' featureComponents(assignment,'A&I1') +#' featureComponents(assignment,'n191.01962') #' } #' #' ## Extract a component graph @@ -272,7 +272,7 @@ setMethod('featureComponents',signature = 'Assignment', available_iterations <- iterations(assignment) available_iterations %>% - map(graph,assignment = assignment,type = 'all') %>% + map(graph,assignment = assignment,type = type) %>% set_names(available_iterations) %>% map_dfr(nodes,.id = 'Iteration') %>% filter(Feature == feature) diff --git a/man/accessors.Rd b/man/accessors.Rd index 73b872b..8e837e9 100644 --- a/man/accessors.Rd +++ b/man/accessors.Rd @@ -94,7 +94,7 @@ components(assignment,'A&I1') ## Return a component information for a selected feature \dontrun{ -featureComponents(assignment,'A&I1') +featureComponents(assignment,'n191.01962') } ## Extract a component graph From ddce3839ccf378a6f791ab7c53568f3b0b42b4ec Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Thu, 19 May 2022 13:22:04 +0100 Subject: [PATCH 184/226] renamed plotFeatureSolutions and fixed --- DESCRIPTION | 3 +- NAMESPACE | 3 +- R/plot_components.R | 206 ++++++++++++++++++++----------- man/plotComponent.Rd | 20 ++- man/plotFeatureComponents.Rd | 45 +++++++ man/plotFeatureSolutions.Rd | 21 ---- tests/testthat/test-assignment.R | 4 +- 7 files changed, 204 insertions(+), 98 deletions(-) create mode 100644 man/plotFeatureComponents.Rd delete mode 100644 man/plotFeatureSolutions.Rd diff --git a/DESCRIPTION b/DESCRIPTION index 7fac27f..96e0acf 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -37,9 +37,10 @@ Suggests: testthat, ggplot2, ggraph, ggrepel, + ggtext, ggthemes, + glue, graphlayouts, - ggtext, patchwork Remotes: jasenfinch/mzAnnotation@devel, jasenfinch/metabolyseR@devel diff --git a/NAMESPACE b/NAMESPACE index 80bf76a..78bfdb8 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -35,7 +35,7 @@ export(nodes) export(plan) export(plotAdductDist) export(plotComponent) -export(plotFeatureSolutions) +export(plotFeatureComponents) export(plotNetwork) export(plotSpectrum) export(ppm) @@ -70,6 +70,7 @@ importFrom(dplyr,rename) importFrom(dplyr,rowwise) importFrom(dplyr,select) importFrom(dplyr,semi_join) +importFrom(dplyr,slice) importFrom(dplyr,slice_sample) importFrom(dplyr,summarise) importFrom(dplyr,ungroup) diff --git a/R/plot_components.R b/R/plot_components.R index cdcfba9..21d1fda 100644 --- a/R/plot_components.R +++ b/R/plot_components.R @@ -8,7 +8,18 @@ graphTheme <- function(){ ) } -plotGraph <- function(graph,min_coef,label_size = 3,axis_offset = 0.1){ +plotGraph <- function(graph, + min_coef, + label_size = 3, + axis_offset = 0.1, + border = 'black', + highlight = NA){ + + if (!is.na(highlight)){ + graph <- graph %>% + activate(nodes) %>% + mutate(selected = Feature == highlight) + } g <- graph %>% activate(nodes) %>% @@ -16,16 +27,32 @@ plotGraph <- function(graph,min_coef,label_size = 3,axis_offset = 0.1){ str_replace_all(' ','\n')) %>% ggraph::create_layout('nicely') - g %>% + pl <- g %>% ggraph::ggraph() + ggraph::geom_edge_link(ggplot2::aes(colour = coefficient)) + ggraph::scale_edge_color_gradient(low = 'lightgrey', high = 'black', - limits = c(min_coef,1)) + - ggraph::geom_node_label(ggplot2::aes(label = name), - size = label_size) + + limits = c(min_coef,1)) + + if (!is.na(highlight)) { + pl <- pl + + ggraph::geom_node_label( + ggplot2::aes(label = name,fill = selected), + size = label_size) + + ggplot2::scale_fill_manual(values = c('white','lightblue')) + + ggplot2::guides(fill = 'none') + } else { + pl <- pl + + ggraph::geom_node_label( + ggplot2::aes(label = name), + size = label_size) + } + + pl + ggraph::theme_graph(base_family = '', - base_size = 10) + + base_size = 10, + title_size = 11, + foreground = border) + graphTheme() + ggplot2::lims( x = c( @@ -48,6 +75,8 @@ plotGraph <- function(graph,min_coef,label_size = 3,axis_offset = 0.1){ #' @param type the graph type to return. `filtered` returns the assignment graph after component selection. `all` returns all assignment components. #' @param label_size node label size #' @param axis_offset axis proportion by which to increase axis limits. Prevents cut off of node labels. +#' @param border specify a plot border colour +#' @param highlight specify a feature node to highlight #' @examples #' \dontrun{ #' plan(future::sequential) @@ -65,10 +94,13 @@ setGeneric('plotComponent', iteration, type = c('filtered','all'), label_size = 3, - axis_offset = 0.1) + axis_offset = 0.1, + border = NA, + highlight = NA) standardGeneric('plotComponent')) #' @importFrom dplyr mutate_if +#' @rdname plotComponent setMethod('plotComponent',signature = 'Assignment', function(assignment, @@ -76,22 +108,29 @@ setMethod('plotComponent',signature = 'Assignment', iteration, type = c('filtered','all'), label_size = 3, - axis_offset = 0.1 + axis_offset = 0.1, + border = NA, + highlight = NA ){ check_installed(c('ggraph', 'ggplot2', - 'ggtext')) + 'ggtext', + 'glue')) component_graph <- component(assignment, component, iteration, type) + if (!is.na(highlight) & + !highlight %in% nodes(component_graph)$Feature) { + stop(paste0('Highlight feature ',highlight,' not found in component.')) + } + component_stats <- component_graph %>% nodes() %>% - select(`MF Plausibility (%)`, - AIS, + select(AIS, Component:`Component Plausibility`) %>% distinct() %>% mutate_if(is.numeric,signif,digits = 3) @@ -101,95 +140,118 @@ setMethod('plotComponent',signature = 'Assignment', plotGraph(component_graph, min_coef, label_size, - axis_offset) + + axis_offset, + border, + highlight + ) + ggplot2::labs( title = paste0('Component ',component), caption = glue::glue(' Pc = {component_stats$`Component Plausibility`}; Degree = {component_stats$Degree}; - - AISc = {component_stats$AIS}; - PMF = {component_stats$`MF Plausibility (%)`}%') - ) + AISc = {component_stats$AIS}' + )) }) #' Plot the solutions for a feature -#' @rdname plotFeatureSolutions +#' @rdname plotFeatureComponents #' @description Plot possible MF solutions for a given feature. #' @param assignment S4 object of class Assignent #' @param feature name of feature to plot -#' @param maxComponents maximum number of components to plot +#' @param iteration components from which iteration to plot +#' @param type the graph type to return. `all` returns all assignment components. `filtered` returns the assignment graph after component selection. +#' @param max_components maximum number of components to plot +#' @param label_size node label size +#' @param axis_offset axis proportion by which to increase axis limits. Prevents cut off of node labels. #' @export -setGeneric('plotFeatureSolutions', - function(assignment,feature,maxComponents = 10) - standardGeneric('plotFeatureSolutions') +setGeneric('plotFeatureComponents', + function(assignment, + feature, + iteration, + type = c('all','filtered'), + max_components = 6, + label_size = 3, + axis_offset = 0.1) + standardGeneric('plotFeatureComponents') ) -#' @rdname plotFeatureSolutions +#' @rdname plotFeatureComponents +#' @importFrom dplyr slice -setMethod('plotFeatureSolutions',signature = 'Assignment', - function(assignment,feature,maxComponents = 10){ +setMethod('plotFeatureComponents',signature = 'Assignment', + function(assignment, + feature, + iteration, + type = c('all','filtered'), + max_components = 6, + label_size = 2, + axis_offset = 0.05){ + + check_installed(c('ggraph', + 'ggplot2', + 'ggtext', + 'patchwork')) if (!feature %in% colnames(featureData(assignment))) { - stop('Feature not found in assignment data') + stop('Feature not found in assignment data.', + call. = FALSE) } - available_iterations <- iterations(assignment) + type <- match.arg(type, + choices = c('all','filtered')) - graphs <- available_iterations %>% - map(graph,assignment = assignment,type = 'all') %>% - set_names(available_iterations) + selected_component <- assignments(assignment) %>% + filter(Feature == feature, + Iteration == iteration) %>% + .$Component - available_nodes <- graphs %>% - map_dfr(nodes,.id = 'Iteration') %>% - select(Feature) %>% - distinct() + feature_components <- featureComponents(assignment,feature,type) %>% + filter(Iteration == iteration) %>% + select(Component) %>% + arrange(Component) %>% + mutate(border = 'black', + border = border %>% + replace(Component == selected_component, + 'red')) - if (!(feature %in% available_nodes$Feature)){ - stop( - paste0('No assignment solutions available for feature ', - feature), - call. = FALSE) + if (nrow(feature_components) == 0){ + stop(paste0('No components for feature ', + feature, + ' found in iteration ', + iteration,'.'), + call. = FALSE) } - comp <- n %>% - filter(Feature == feature) %>% - select(Component,`Component Plausibility`) %>% - distinct() %>% - arrange(Component) - - graph <- assignment@addIsoAssign$graph %>% - filter(Component %in% comp$Component) %>% - mutate(name = str_replace_all(name,' ','\n')) %>% - mutate(name = str_replace_all(name,' ','\n')) %>% - morph(to_components) - - graphComponents <- graph %>% - map_dbl(~{nodes(.) %>% - .$Component %>% - .[1] - }) - - comp <- comp %>% - arrange(desc(`Component Plausibility`)) %>% - .$Component - - graph <- graph %>% - set_names(graphComponents) %>% - .[comp %>% as.character()] - - if (length(comp) > maxComponents) { - graph <- graph[1:maxComponents] + if (nrow(feature_components) > max_components){ + feature_components <- slice( + feature_components, + seq_len(max_components)) } - selectedComp <- assignment@addIsoAssign$filtered_graph %>% - nodes() %>% - select(Feature,Component) %>% - filter(Feature == feature) %>% - .$Component + pl <- feature_components %>% + rowwise() %>% + group_split() %>% + map(~plotComponent( + assignment, + .x$Component, + iteration, + type, + label_size, + axis_offset, + highlight = feature, + border = .x$border + )) %>% + patchwork::wrap_plots() + + patchwork::plot_layout(guides = 'collect') - pl <- plotSolutions(graph,selectedComp,feature) + if (length(selected_component) > 0){ + pl <- pl + + patchwork::plot_annotation( + caption = 'Red highlighted graph denotes the component selected for assignment.', + theme = ggplot2::theme(plot.caption = ggplot2::element_text(hjust = 0)) + ) + } return(pl) }) diff --git a/man/plotComponent.Rd b/man/plotComponent.Rd index cb775ad..d8bd70f 100644 --- a/man/plotComponent.Rd +++ b/man/plotComponent.Rd @@ -2,6 +2,7 @@ % Please edit documentation in R/plot_components.R \name{plotComponent} \alias{plotComponent} +\alias{plotComponent,Assignment-method} \title{Plot a component} \usage{ plotComponent( @@ -10,7 +11,20 @@ plotComponent( iteration, type = c("filtered", "all"), label_size = 3, - axis_offset = 0.1 + axis_offset = 0.1, + border = NA, + highlight = NA +) + +\S4method{plotComponent}{Assignment}( + assignment, + component, + iteration, + type = c("filtered", "all"), + label_size = 3, + axis_offset = 0.1, + border = NA, + highlight = NA ) } \arguments{ @@ -25,6 +39,10 @@ plotComponent( \item{label_size}{node label size} \item{axis_offset}{axis proportion by which to increase axis limits. Prevents cut off of node labels.} + +\item{border}{specify a plot border colour} + +\item{highlight}{specify a feature node to highlight} } \description{ Plot a molecular formula component graph. diff --git a/man/plotFeatureComponents.Rd b/man/plotFeatureComponents.Rd new file mode 100644 index 0000000..945806f --- /dev/null +++ b/man/plotFeatureComponents.Rd @@ -0,0 +1,45 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/plot_components.R +\name{plotFeatureComponents} +\alias{plotFeatureComponents} +\alias{plotFeatureComponents,Assignment-method} +\title{Plot the solutions for a feature} +\usage{ +plotFeatureComponents( + assignment, + feature, + iteration, + type = c("all", "filtered"), + max_components = 6, + label_size = 3, + axis_offset = 0.1 +) + +\S4method{plotFeatureComponents}{Assignment}( + assignment, + feature, + iteration, + type = c("all", "filtered"), + max_components = 6, + label_size = 2, + axis_offset = 0.05 +) +} +\arguments{ +\item{assignment}{S4 object of class Assignent} + +\item{feature}{name of feature to plot} + +\item{iteration}{components from which iteration to plot} + +\item{type}{the graph type to return. \code{all} returns all assignment components. \code{filtered} returns the assignment graph after component selection.} + +\item{max_components}{maximum number of components to plot} + +\item{label_size}{node label size} + +\item{axis_offset}{axis proportion by which to increase axis limits. Prevents cut off of node labels.} +} +\description{ +Plot possible MF solutions for a given feature. +} diff --git a/man/plotFeatureSolutions.Rd b/man/plotFeatureSolutions.Rd deleted file mode 100644 index dec952e..0000000 --- a/man/plotFeatureSolutions.Rd +++ /dev/null @@ -1,21 +0,0 @@ -% Generated by roxygen2: do not edit by hand -% Please edit documentation in R/plot_components.R -\name{plotFeatureSolutions} -\alias{plotFeatureSolutions} -\alias{plotFeatureSolutions,Assignment-method} -\title{Plot the solutions for a feature} -\usage{ -plotFeatureSolutions(assignment, feature, maxComponents = 10) - -\S4method{plotFeatureSolutions}{Assignment}(assignment, feature, maxComponents = 10) -} -\arguments{ -\item{assignment}{S4 object of class Assignent} - -\item{feature}{name of feature to plot} - -\item{maxComponents}{maximum number of components to plot} -} -\description{ -Plot possible MF solutions for a given feature. -} diff --git a/tests/testthat/test-assignment.R b/tests/testthat/test-assignment.R index ba58724..68d7b2e 100644 --- a/tests/testthat/test-assignment.R +++ b/tests/testthat/test-assignment.R @@ -58,9 +58,9 @@ test_that('a summary of assignments can be returned',{ expect_s3_class(summariseAssignments(assignment_FIE),'tbl_df') }) test_that('feature solutions can be plotted',{ - pl <- plotFeatureSolutions(assignment_FIE, + pl <- plotFeatureComponents(assignment_FIE, 'n191.01962', - maxComponents = 2) + 'A&I1') expect_s3_class(pl,'patchwork') }) From 6a59f71f47dfd03c2b06f9f831f3c33e11329056 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Thu, 19 May 2022 13:22:16 +0100 Subject: [PATCH 185/226] documentation fixes --- R/assignment.R | 1 + R/assignments.R | 2 +- man/accessors.Rd | 2 ++ 3 files changed, 4 insertions(+), 1 deletion(-) diff --git a/R/assignment.R b/R/assignment.R index f098e66..9b366b4 100644 --- a/R/assignment.R +++ b/R/assignment.R @@ -93,6 +93,7 @@ setMethod('show',signature = 'Assignment', #' @param iteration the assignment iteration #' @param type the graph type to return. `filtered` returns the assignment graph after component selection. `all` returns all assignment components. #' @param component component number to extract +#' @param feature feature information to extract #' @examples #' assignment <- new('Assignment', #' data = feature_data) diff --git a/R/assignments.R b/R/assignments.R index 978f05b..6e0c8ff 100644 --- a/R/assignments.R +++ b/R/assignments.R @@ -13,5 +13,5 @@ globalVariables(c( 'Component','Weight','AIS','Name','Assigned','Intensity','Label', 'Relative Abundance','m/z','Group','N','adduct_rank','isotope_rank', 'M','total','MF','RetentionTimeDiff','Adduct_Score','Isotope_Score', - 'Iteration' + 'Iteration','border','selected' )) diff --git a/man/accessors.Rd b/man/accessors.Rd index 8e837e9..5022e22 100644 --- a/man/accessors.Rd +++ b/man/accessors.Rd @@ -61,6 +61,8 @@ assignments(assignment) \item{type}{the graph type to return. \code{filtered} returns the assignment graph after component selection. \code{all} returns all assignment components.} +\item{feature}{feature information to extract} + \item{component}{component number to extract} } \description{ From 0c419173b478d02247ee256edebf324cade46fd6 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Thu, 19 May 2022 13:23:27 +0100 Subject: [PATCH 186/226] removed plotNetwork --- DESCRIPTION | 3 +- R/plotNetwork.R | 116 ------------------------------------------------ 2 files changed, 1 insertion(+), 118 deletions(-) delete mode 100644 R/plotNetwork.R diff --git a/DESCRIPTION b/DESCRIPTION index 96e0acf..5d8dd17 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -29,8 +29,7 @@ RoxygenNote: 7.2.0 Collate: parameters.R assignment.R correlations.R addIsoAssign.R transformationAssign.R relationships.R graph.R assign.R internals.R components.R - feature_data.R assignments.R plotNetwork.R - plotAdductDist.R plot_components.R + feature_data.R assignments.R plotAdductDist.R plot_components.R plotSpectrum.R reexports.R zzz.R Suggests: testthat, covr, diff --git a/R/plotNetwork.R b/R/plotNetwork.R deleted file mode 100644 index 7695f27..0000000 --- a/R/plotNetwork.R +++ /dev/null @@ -1,116 +0,0 @@ - -networkPlot <- function(network,layout,rThreshold,assignedNodes,explainedEdges){ - check_installed(c('ggraph', - 'ggthemes', - 'ggplot2', - 'graphlayouts')) - - rt <- str_c('Visualised using threshold of r > ',rThreshold) - nn <- str_c('Total nodes = ',sum(assignedNodes)) - an <- str_c('Assigned nodes = ', - assignedNodes[1], - ' (', - {assignedNodes[1]/sum(assignedNodes) * 100} %>% - round(),'%)') - ne <- str_c('Total edges = ',sum(explainedEdges)) - ee <- str_c('Explained edges = ', - explainedEdges[1], - ' (', - {explainedEdges[1]/sum(explainedEdges) * 100} %>% - round(),'%)') - - ggraph::ggraph(network,layout = layout) + - ggraph::geom_edge_link(alpha = 0.2) + - ggraph::geom_node_point(ggplot2::aes(fill = Assigned),shape = 21) + - ggthemes::scale_fill_ptol() + - ggraph::theme_graph() + - ggplot2::theme(legend.title = ggplot2::element_blank()) + - ggplot2::coord_fixed() + - ggraph::facet_edges(~Explained) + - ggplot2::labs(title = str_c('Assignment correlation network'), - caption = str_c(rt,nn,an,ne,ee,sep = '\n')) -} - -#' Plot an assignment network -#' @rdname plotNetwork -#' @description plot assignment network -#' @param assignment of class Assignment -#' @param layout graph layout to use. See \code{\link[ggraph]{ggraph}} for layout options -#' @param rThreshold r threhold to use for filtering edge correlation weights -#' @importFrom tidygraph as_tbl_graph bind_graphs -#' @importFrom igraph set_vertex_attr set_edge_attr -#' @export - -setGeneric('plotNetwork',function(assignment, layout = 'stress', rThreshold = 0.7){ - standardGeneric('plotNetwork') -}) - -#' @rdname plotNetwork - -setMethod('plotNetwork',signature = 'Assignment', - function(assignment, layout = 'stress', rThreshold = 0.7){ - - AI <- assignment@addIsoAssign$filtered_graph - TA <- assignment@transAssign %>% - map(~{.$filtered_graph}) - - if (length(TA) > 0){ - if (length(TA) > 1) { - graph <- bind_graphs(graph, - {a <- TA[[1]] - for (i in 2:length(TA)) { - a <- bind_graphs(a,TA[[i]]) - } - a - } - ) - } else { - graph <- bind_graphs(AI,TA[[1]]) - } - } - - e <- edges(graph) %>% - mutate(Explained = 'Explained') - n <- nodes(graph) %>% - select(name:`MF Plausibility (%)`) %>% - distinct() %>% - mutate(Assigned = 'Assigned') - - network <- assignment %>% - .@correlations %>% - filter(coefficient > rThreshold) %>% - as_tbl_graph(directed = F) %>% - activate(nodes) %>% - rename(Feature = name) %>% - mutate(Mode = str_sub(Feature,1,1)) %>% - left_join(n, by = "Feature") %>% - activate(edges) %>% - left_join(e, by = c("Mode1", "Mode2", "m/z1", "m/z2", "RetentionTime1", "RetentionTime2", "log2IntensityRatio", "coefficient", "ID")) - - assigned <- nodes(network)$Assigned - assigned[is.na(assigned)] <- 'Unassigned' - - network <- set_vertex_attr(network,'Assigned',value = assigned) - - explained <- edges(network)$Explained - explained[is.na(explained)] <- 'Unexplained' - - network <- set_edge_attr(network,'Explained',value = explained) - - explainedEdges <- network %>% - edges() %>% - .$Explained %>% - table() - - assignedNodes <- network %>% - nodes() %>% - .$Assigned %>% - table() - - networkPlot(network, - layout, - rThreshold, - assignedNodes, - explainedEdges) - }) - \ No newline at end of file From a2768dd2fd4409d9b2c646709aed8f7154c143dc Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Thu, 19 May 2022 13:24:12 +0100 Subject: [PATCH 187/226] Update documentation --- NAMESPACE | 4 ---- man/plotNetwork.Rd | 21 --------------------- 2 files changed, 25 deletions(-) delete mode 100644 man/plotNetwork.Rd diff --git a/NAMESPACE b/NAMESPACE index 78bfdb8..75e5740 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -36,7 +36,6 @@ export(plan) export(plotAdductDist) export(plotComponent) export(plotFeatureComponents) -export(plotNetwork) export(plotSpectrum) export(ppm) export(relationships) @@ -83,8 +82,6 @@ importFrom(igraph,E) importFrom(igraph,V) importFrom(igraph,degree) importFrom(igraph,edge.attributes) -importFrom(igraph,set_edge_attr) -importFrom(igraph,set_vertex_attr) importFrom(igraph,vertex.attributes) importFrom(lubridate,seconds_to_period) importFrom(magrittr,"%>%") @@ -125,7 +122,6 @@ importFrom(tibble,enframe) importFrom(tibble,tibble) importFrom(tidygraph,activate) importFrom(tidygraph,as_tbl_graph) -importFrom(tidygraph,bind_graphs) importFrom(tidygraph,graph_size) importFrom(tidygraph,group_components) importFrom(tidygraph,morph) diff --git a/man/plotNetwork.Rd b/man/plotNetwork.Rd deleted file mode 100644 index adc5718..0000000 --- a/man/plotNetwork.Rd +++ /dev/null @@ -1,21 +0,0 @@ -% Generated by roxygen2: do not edit by hand -% Please edit documentation in R/plotNetwork.R -\name{plotNetwork} -\alias{plotNetwork} -\alias{plotNetwork,Assignment-method} -\title{Plot an assignment network} -\usage{ -plotNetwork(assignment, layout = "stress", rThreshold = 0.7) - -\S4method{plotNetwork}{Assignment}(assignment, layout = "stress", rThreshold = 0.7) -} -\arguments{ -\item{assignment}{of class Assignment} - -\item{layout}{graph layout to use. See \code{\link[ggraph]{ggraph}} for layout options} - -\item{rThreshold}{r threhold to use for filtering edge correlation weights} -} -\description{ -plot assignment network -} From ae0c7b9970bbbe7ea8dc36281bf7fe6b38d6f8f0 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Thu, 19 May 2022 13:31:28 +0100 Subject: [PATCH 188/226] add missing function import --- NAMESPACE | 1 + R/components.R | 1 + 2 files changed, 2 insertions(+) diff --git a/NAMESPACE b/NAMESPACE index 75e5740..1ca0a65 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -122,6 +122,7 @@ importFrom(tibble,enframe) importFrom(tibble,tibble) importFrom(tidygraph,activate) importFrom(tidygraph,as_tbl_graph) +importFrom(tidygraph,bind_graphs) importFrom(tidygraph,graph_size) importFrom(tidygraph,group_components) importFrom(tidygraph,morph) diff --git a/R/components.R b/R/components.R index 2c535ca..1eb55a6 100644 --- a/R/components.R +++ b/R/components.R @@ -8,6 +8,7 @@ plausibility <- function(size,AIS,weight){ } #' @importFrom purrr compact +#' @importFrom tidygraph bind_graphs clean <- function(graph,adduct_rules_table){ graph %>% From cbe893dc7b59b5cdf6d60909c7703e394237ab87 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Thu, 19 May 2022 13:32:05 +0100 Subject: [PATCH 189/226] use term "selected" instead of "filtered" --- R/assignment.R | 2 +- man/accessors.Rd | 14 +++++++------- man/plotComponent.Rd | 4 ++-- man/plotFeatureComponents.Rd | 4 ++-- tests/testthat/test-assignment.R | 6 ------ 5 files changed, 12 insertions(+), 18 deletions(-) diff --git a/R/assignment.R b/R/assignment.R index 9b366b4..2879f7c 100644 --- a/R/assignment.R +++ b/R/assignment.R @@ -226,7 +226,7 @@ setMethod('graph',signature = 'Assignment', `T` = assignment@transAssign) graph <- switch(type, - filtered = assignment_iteration[[iteration]]$filtered_graph, + selected = assignment_iteration[[iteration]]$filtered_graph, all = assignment_iteration[[iteration]]$graph) return(graph) diff --git a/man/accessors.Rd b/man/accessors.Rd index 5022e22..8ebf9ab 100644 --- a/man/accessors.Rd +++ b/man/accessors.Rd @@ -36,19 +36,19 @@ iterations(assignment) \S4method{iterations}{Assignment}(assignment) -graph(assignment, iteration, type = c("filtered", "all")) +graph(assignment, iteration, type = c("selected", "all")) -\S4method{graph}{Assignment}(assignment, iteration, type = c("filtered", "all")) +\S4method{graph}{Assignment}(assignment, iteration, type = c("selected", "all")) -components(assignment, iteration, type = c("filtered", "all")) +components(assignment, iteration, type = c("selected", "all")) -\S4method{components}{Assignment}(assignment, iteration, type = c("filtered", "all")) +\S4method{components}{Assignment}(assignment, iteration, type = c("selected", "all")) -featureComponents(assignment, feature, type = c("filtered", "all")) +featureComponents(assignment, feature, type = c("selected", "all")) -\S4method{featureComponents}{Assignment}(assignment, feature, type = c("filtered", "all")) +\S4method{featureComponents}{Assignment}(assignment, feature, type = c("selected", "all")) -\S4method{component}{Assignment}(assignment, component, iteration, type = c("filtered", "all")) +\S4method{component}{Assignment}(assignment, component, iteration, type = c("selected", "all")) assignments(assignment) diff --git a/man/plotComponent.Rd b/man/plotComponent.Rd index d8bd70f..247b5ff 100644 --- a/man/plotComponent.Rd +++ b/man/plotComponent.Rd @@ -9,7 +9,7 @@ plotComponent( assignment, component, iteration, - type = c("filtered", "all"), + type = c("selected", "all"), label_size = 3, axis_offset = 0.1, border = NA, @@ -20,7 +20,7 @@ plotComponent( assignment, component, iteration, - type = c("filtered", "all"), + type = c("selected", "all"), label_size = 3, axis_offset = 0.1, border = NA, diff --git a/man/plotFeatureComponents.Rd b/man/plotFeatureComponents.Rd index 945806f..aa19446 100644 --- a/man/plotFeatureComponents.Rd +++ b/man/plotFeatureComponents.Rd @@ -9,7 +9,7 @@ plotFeatureComponents( assignment, feature, iteration, - type = c("all", "filtered"), + type = c("all", "selected"), max_components = 6, label_size = 3, axis_offset = 0.1 @@ -19,7 +19,7 @@ plotFeatureComponents( assignment, feature, iteration, - type = c("all", "filtered"), + type = c("all", "selected"), max_components = 6, label_size = 2, axis_offset = 0.05 diff --git a/tests/testthat/test-assignment.R b/tests/testthat/test-assignment.R index 68d7b2e..f379c07 100644 --- a/tests/testthat/test-assignment.R +++ b/tests/testthat/test-assignment.R @@ -70,12 +70,6 @@ test_that('feature solutions plotting throws an error if an incorrect feature is 'test')) }) -test_that('assignment network can be plotted',{ - pl <- plotNetwork(assignment_FIE) - - expect_s3_class(pl,'ggraph') -}) - test_that('adduct distributions can be plotted',{ pl <- plotAdductDist(assignment_FIE) From 6b8101ad60e839d0a09cd294b38e54bd77d2b9a7 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Thu, 19 May 2022 15:32:41 +0100 Subject: [PATCH 190/226] fix remaining uses of 'filtered' --- R/assignment.R | 20 ++++++++++---------- R/plot_components.R | 10 +++++----- 2 files changed, 15 insertions(+), 15 deletions(-) diff --git a/R/assignment.R b/R/assignment.R index 2879f7c..436a99c 100644 --- a/R/assignment.R +++ b/R/assignment.R @@ -198,7 +198,7 @@ setMethod('iterations',signature = 'Assignment', setGeneric('graph',function(assignment, iteration, - type = c('filtered','all')) + type = c('selected','all')) standardGeneric('graph')) #' @rdname accessors @@ -206,7 +206,7 @@ setGeneric('graph',function(assignment, setMethod('graph',signature = 'Assignment', function(assignment, iteration, - type = c('filtered','all')){ + type = c('selected','all')){ if (!iteration %in% iterations(assignment)) { iters <- assignment %>% @@ -218,7 +218,7 @@ setMethod('graph',signature = 'Assignment', } type <- match.arg(type, - choices = c('filtered','all')) + choices = c('selected','all')) assignment_iteration <- switch( str_remove(iteration,'[1-9]'), @@ -237,7 +237,7 @@ setMethod('graph',signature = 'Assignment', setGeneric('components',function(assignment, iteration, - type = c('filtered','all')) + type = c('selected','all')) standardGeneric('components')) #' @rdname accessors @@ -245,7 +245,7 @@ setGeneric('components',function(assignment, setMethod('components',signature = 'Assignment', function(assignment, iteration, - type = c('filtered','all')){ + type = c('selected','all')){ selected_graph <- graph(assignment,iteration,type) %>% nodes() %>% @@ -260,7 +260,7 @@ setMethod('components',signature = 'Assignment', setGeneric('featureComponents',function(assignment, feature, - type = c('filtered','all')) + type = c('selected','all')) standardGeneric('featureComponents')) #' @rdname accessors @@ -268,7 +268,7 @@ setGeneric('featureComponents',function(assignment, setMethod('featureComponents',signature = 'Assignment', function(assignment, feature, - type = c('filtered','all')){ + type = c('selected','all')){ available_iterations <- iterations(assignment) @@ -282,7 +282,7 @@ setMethod('featureComponents',signature = 'Assignment', setGeneric('component',function(assignment, component, iteration, - type = c('filtered','all')) + type = c('selected','all')) standardGeneric('component')) #' @rdname accessors @@ -291,7 +291,7 @@ setMethod('component',signature = 'Assignment', function(assignment, component, iteration, - type = c('filtered','all')){ + type = c('selected','all')){ iteration_components <- components(assignment, iteration, @@ -403,4 +403,4 @@ setMethod('summariseAssignments',signature = 'Assignment', bind_rows() %>% arrange(desc(Count)) return(assigned) - }) \ No newline at end of file + }) diff --git a/R/plot_components.R b/R/plot_components.R index 21d1fda..f81fab7 100644 --- a/R/plot_components.R +++ b/R/plot_components.R @@ -92,7 +92,7 @@ setGeneric('plotComponent', function(assignment, component, iteration, - type = c('filtered','all'), + type = c('selected','all'), label_size = 3, axis_offset = 0.1, border = NA, @@ -106,7 +106,7 @@ setMethod('plotComponent',signature = 'Assignment', function(assignment, component, iteration, - type = c('filtered','all'), + type = c('selected','all'), label_size = 3, axis_offset = 0.1, border = NA, @@ -169,7 +169,7 @@ setGeneric('plotFeatureComponents', function(assignment, feature, iteration, - type = c('all','filtered'), + type = c('all','selected'), max_components = 6, label_size = 3, axis_offset = 0.1) @@ -183,7 +183,7 @@ setMethod('plotFeatureComponents',signature = 'Assignment', function(assignment, feature, iteration, - type = c('all','filtered'), + type = c('all','selected'), max_components = 6, label_size = 2, axis_offset = 0.05){ @@ -199,7 +199,7 @@ setMethod('plotFeatureComponents',signature = 'Assignment', } type <- match.arg(type, - choices = c('all','filtered')) + choices = c('all','selected')) selected_component <- assignments(assignment) %>% filter(Feature == feature, From a0c6b567c1d32537856a66d4ee989592351fd74e Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Thu, 19 May 2022 16:19:26 +0100 Subject: [PATCH 191/226] increase test coverage --- R/relationships.R | 11 +++---- R/transformationAssign.R | 6 ++-- tests/testthat/test-assignment.R | 52 ++++++++++++++++++++++++++++++-- tests/testthat/test-parameters.R | 11 +++++++ 4 files changed, 69 insertions(+), 11 deletions(-) diff --git a/R/relationships.R b/R/relationships.R index 2a4b5bf..e57242b 100644 --- a/R/relationships.R +++ b/R/relationships.R @@ -11,9 +11,9 @@ setGeneric("calcRelationships", function(assignment,transformations = TRUE) #' @importFrom tibble tibble enframe setMethod('calcRelationships',signature = 'Assignment', - function(assignment,transformations = T){ + function(assignment){ - if (assignment@log$verbose == T) { + if (assignment@log$verbose == TRUE) { startTime <- proc.time() message(blue('Calculating relationships '),cli::symbol$continue,'\r',appendLF = 'FALSE') } @@ -22,11 +22,8 @@ setMethod('calcRelationships',signature = 'Assignment', cors <- assignment@correlations - if (isTRUE(transformations)) { - trans <- c(NA,transformations(assignment)) - } else { - trans <- NA - } + trans <- c(NA,transformations(assignment)) + rel <- cors %>% select(`m/z1`,`m/z2`,Mode1,Mode2) %>% diff --git a/R/transformationAssign.R b/R/transformationAssign.R index aa33d3f..95d2950 100644 --- a/R/transformationAssign.R +++ b/R/transformationAssign.R @@ -130,8 +130,10 @@ setMethod('transformationAssign',signature = 'Assignment', } } - names(assignment@transAssign) <- paste0('T', - seq_along(assignment@transAssign)) + if (length(assignment@transAssign) > 0){ + names(assignment@transAssign) <- paste0('T', + seq_along(assignment@transAssign)) + } if (isTRUE(assignment@log$verbose)) { t_end_time <- proc.time() diff --git a/tests/testthat/test-assignment.R b/tests/testthat/test-assignment.R index f379c07..af32229 100644 --- a/tests/testthat/test-assignment.R +++ b/tests/testthat/test-assignment.R @@ -12,6 +12,15 @@ test_adducts <- list( adducts(assignment_parameters_FIE) <- test_adducts adducts(assignment_parameters_LC) <- test_adducts +transformations(assignment_parameters_LC) <- character() + +FIE_features <- new('Analysis') +metabolyseR::raw(FIE_features) <- metabolyseR::analysisData( + feature_data, + info = tibble::tibble( + ID = feature_data %>% + nrow() %>% + seq_len())) LC_features <- new('Analysis') metabolyseR::preTreated(LC_features) <- metabolyseR::analysisData( @@ -25,8 +34,9 @@ metabolyseR::preTreated(LC_features) <- metabolyseR::analysisData( seq_len())) -assignment_FIE <- assignMFs(feature_data, +assignment_FIE <- assignMFs(FIE_features, assignment_parameters_FIE, + type = 'raw', verbose = TRUE) assignment_LC <- assignMFs(LC_features, @@ -50,6 +60,18 @@ test_that('assignment data can be returned',{ expect_s3_class(featureData(assignment_FIE),'tbl_df') }) +test_that('assignment correlations can be returned',{ + expect_s3_class(correlations(assignment_FIE),'tbl_df') +}) + +test_that('graph method throws an error if incorrect iteration specified',{ + expect_error(graph(assignment_FIE,'incorrect')) +}) + +test_that('component method throws an error if an incorrect component is specified',{ + expect_error(component(assignment_FIE,'incorrect','A&I1')) +}) + test_that('data with assigned feature names can be returned',{ expect_s3_class(assignedData(assignment_FIE),'tbl_df') }) @@ -57,7 +79,8 @@ test_that('data with assigned feature names can be returned',{ test_that('a summary of assignments can be returned',{ expect_s3_class(summariseAssignments(assignment_FIE),'tbl_df') }) -test_that('feature solutions can be plotted',{ + +test_that('feature components can be plotted',{ pl <- plotFeatureComponents(assignment_FIE, 'n191.01962', 'A&I1') @@ -65,6 +88,31 @@ test_that('feature solutions can be plotted',{ expect_s3_class(pl,'patchwork') }) +test_that('plotFeatureComponents throws an error if incorrect feature specified',{ + expect_error(plotFeatureComponents(assignment_FIE, + 'incorrect', + 'A&I1')) +}) + +test_that('plotFeatureComponents throws an error if no components are found',{ + expect_error(plotFeatureComponents(assignment_FIE,"n228.97636",'A&I1')) +}) + +test_that('a component can be plotted',{ + pl <- plotComponent(assignment_FIE, + 1, + 'A&I1') + + expect_s3_class(pl,'ggplot') +}) + +test_that('plotComponent throws an error if incorrect feature specified for highlighting',{ + expect_error(plotComponent(assignment_FIE, + 1, + 'A&I1', + highlight = 'incorrect')) +}) + test_that('feature solutions plotting throws an error if an incorrect feature is provided',{ expect_error(plotFeatureSolutions(assignment_FIE, 'test')) diff --git a/tests/testthat/test-parameters.R b/tests/testthat/test-parameters.R index fc96e87..e7c26c1 100644 --- a/tests/testthat/test-parameters.R +++ b/tests/testthat/test-parameters.R @@ -5,6 +5,17 @@ test_that("technique can be returned", { expect_type(technique(p),'character') }) +test_that("correlation parameters can be returned", { + expect_type(correlationsParameters(p),'list') +}) + +test_that("correlation parameters can be set", { + new_minCoef <- 0.9 + correlationsParameters(p)$minCoef <- new_minCoef + + expect_identical(correlationsParameters(p)$minCoef,new_minCoef) +}) + test_that("limit can be returned", { expect_type(limit(p),'double') }) From 587b3bd16a2af30a59a36fea3ad489505edbb3ad Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Thu, 19 May 2022 16:21:35 +0100 Subject: [PATCH 192/226] added package NEWS --- NEWS.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 NEWS.md diff --git a/NEWS.md b/NEWS.md new file mode 100644 index 0000000..4c83051 --- /dev/null +++ b/NEWS.md @@ -0,0 +1,3 @@ +# assignments 1.0.0 + +* Added a `NEWS.md` file to track changes to the package. From 7db766fe9f5bc844a450b4793a1e1b7d2df9d2f6 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Thu, 19 May 2022 16:24:03 +0100 Subject: [PATCH 193/226] added pkgdown site --- .Rbuildignore | 3 +++ .github/workflows/pkgdown.yaml | 35 ++++++++++++++++++++++++++++++++++ .gitignore | 1 + DESCRIPTION | 1 + _pkgdown.yml | 4 ++++ 5 files changed, 44 insertions(+) create mode 100644 .github/workflows/pkgdown.yaml create mode 100644 _pkgdown.yml diff --git a/.Rbuildignore b/.Rbuildignore index a5e6d7a..16192bc 100644 --- a/.Rbuildignore +++ b/.Rbuildignore @@ -4,3 +4,6 @@ ^\.travis\.yml$ ^codecov\.yml$ ^\.github$ +^_pkgdown\.yml$ +^docs$ +^pkgdown$ diff --git a/.github/workflows/pkgdown.yaml b/.github/workflows/pkgdown.yaml new file mode 100644 index 0000000..63cbb18 --- /dev/null +++ b/.github/workflows/pkgdown.yaml @@ -0,0 +1,35 @@ +# Workflow derived from https://github.com/r-lib/actions/tree/master/examples +# Need help debugging build failures? Start at https://github.com/r-lib/actions#where-to-find-help +on: + push: + branches: [main, master] + release: + types: [published] + workflow_dispatch: + +name: pkgdown + +jobs: + pkgdown: + runs-on: ubuntu-latest + env: + GITHUB_PAT: ${{ secrets.GITHUB_TOKEN }} + steps: + - uses: actions/checkout@v2 + + - uses: r-lib/actions/setup-pandoc@v1 + + - uses: r-lib/actions/setup-r@v1 + with: + use-public-rspm: true + + - uses: r-lib/actions/setup-r-dependencies@v1 + with: + extra-packages: pkgdown + needs: website + + - name: Deploy package + run: | + git config --local user.name "$GITHUB_ACTOR" + git config --local user.email "$GITHUB_ACTOR@users.noreply.github.com" + Rscript -e 'pkgdown::deploy_to_branch(new_process = FALSE)' diff --git a/.gitignore b/.gitignore index 5b6a065..234f028 100644 --- a/.gitignore +++ b/.gitignore @@ -2,3 +2,4 @@ .Rhistory .RData .Ruserdata +docs diff --git a/DESCRIPTION b/DESCRIPTION index 5d8dd17..37196e0 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -43,3 +43,4 @@ Suggests: testthat, patchwork Remotes: jasenfinch/mzAnnotation@devel, jasenfinch/metabolyseR@devel +URL: https://jasenfinch.github.io/assignments/ diff --git a/_pkgdown.yml b/_pkgdown.yml new file mode 100644 index 0000000..4737d62 --- /dev/null +++ b/_pkgdown.yml @@ -0,0 +1,4 @@ +url: https://jasenfinch.github.io/assignments/ +template: + bootstrap: 5 + From c1fd58e05ec59154b9a7acb78f5409cac01a56d7 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Thu, 19 May 2022 16:28:58 +0100 Subject: [PATCH 194/226] Updated github actions workflow --- .github/workflows/R-CMD-check.yaml | 77 ++++++++---------------------- README.md | 2 +- 2 files changed, 21 insertions(+), 58 deletions(-) diff --git a/.github/workflows/R-CMD-check.yaml b/.github/workflows/R-CMD-check.yaml index fc81824..1e73d3e 100644 --- a/.github/workflows/R-CMD-check.yaml +++ b/.github/workflows/R-CMD-check.yaml @@ -1,13 +1,10 @@ -# For help debugging build failures open an issue on the RStudio community with the 'github-actions' tag. -# https://community.rstudio.com/new-topic?category=Package%20development&tags=github-actions +# Workflow derived from https://github.com/r-lib/actions/tree/master/examples +# Need help debugging build failures? Start at https://github.com/r-lib/actions#where-to-find-help on: push: - branches: - - master - - devel + branches: [main, master, devel] pull_request: - branches: - - master + branches: [main, master] name: R-CMD-check @@ -21,67 +18,33 @@ jobs: fail-fast: false matrix: config: + #- {os: macOS-latest, r: 'release'} #- {os: windows-latest, r: 'release'} - #- {os: macOS-latest, r: 'release'} - - {os: ubuntu-20.04, r: 'release', rspm: "https://packagemanager.rstudio.com/cran/__linux__/focal/latest"} - - {os: ubuntu-20.04, r: 'devel', rspm: "https://packagemanager.rstudio.com/cran/__linux__/focal/latest"} + - {os: ubuntu-latest, r: 'devel', http-user-agent: 'release'} + - {os: ubuntu-latest, r: 'release'} + - {os: ubuntu-latest, r: 'oldrel-1'} env: - R_REMOTES_NO_ERRORS_FROM_WARNINGS: true - RSPM: ${{ matrix.config.rspm }} + GITHUB_PAT: ${{ secrets.GITHUB_TOKEN }} + R_KEEP_PKG_SOURCE: yes steps: - uses: actions/checkout@v2 - - uses: r-lib/actions/setup-r@master - with: - r-version: ${{ matrix.config.r }} - - - uses: r-lib/actions/setup-pandoc@master - - - name: Query dependencies - run: | - install.packages('remotes') - saveRDS(remotes::dev_package_deps(dependencies = TRUE), ".github/depends.Rds", version = 2) - writeLines(sprintf("R-%i.%i", getRversion()$major, getRversion()$minor), ".github/R-version") - shell: Rscript {0} + - uses: r-lib/actions/setup-pandoc@v1 - - name: Cache R packages - if: runner.os != 'Windows' - uses: actions/cache@v1 + - uses: r-lib/actions/setup-r@v1 with: - path: ${{ env.R_LIBS_USER }} - key: ${{ runner.os }}-${{ hashFiles('.github/R-version') }}-1-${{ hashFiles('.github/depends.Rds') }} - restore-keys: ${{ runner.os }}-${{ hashFiles('.github/R-version') }}-1- - + r-version: ${{ matrix.config.r }} + http-user-agent: ${{ matrix.config.http-user-agent }} + use-public-rspm: true + - name: Install system dependencies - if: runner.os == 'Linux' run: | - while read -r cmd - do - eval sudo $cmd - done < <(Rscript -e 'writeLines(remotes::system_requirements("ubuntu", "20.04"))') sudo apt install libopenbabel-dev - - - name: Install dependencies - run: | - remotes::install_deps(dependencies = TRUE) - remotes::install_cran("rcmdcheck") - shell: Rscript {0} - - name: Check - env: - _R_CHECK_CRAN_INCOMING_REMOTE_: false - run: rcmdcheck::rcmdcheck(args = c("--no-manual", "--as-cran"), error_on = "warning", check_dir = "check") - shell: Rscript {0} - - - name: Test coverage - run: covr::codecov() - shell: Rscript {0} - - - name: Upload check results - if: failure() - uses: actions/upload-artifact@main + - uses: r-lib/actions/setup-r-dependencies@v1 with: - name: ${{ runner.os }}-r${{ matrix.config.r }}-results - path: check + extra-packages: rcmdcheck + + - uses: r-lib/actions/check-r-package@v1 diff --git a/README.md b/README.md index d70cefe..ca805b9 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ [![Lifecycle: experimental](https://img.shields.io/badge/lifecycle-experimental-orange.svg)](https://www.tidyverse.org/lifecycle/#experimental) - [![R build status](https://github.com/jasenfinch/assignments/workflows/R-CMD-check/badge.svg)](https://github.com/jasenfinch/assignments/actions) +[![R-CMD-check](https://github.com/jasenfinch/MFassign/workflows/R-CMD-check/badge.svg)](https://github.com/jasenfinch/MFassign/actions) [![Coverage Status](https://img.shields.io/codecov/c/github/jasenfinch/assignments/master.svg)](https://codecov.io/github/jasenfinch/assignments?branch=master) [![license](https://img.shields.io/badge/license-GNU%20GPL%20v3.0-blue.svg)](https://github.com/jasenfinch/assignments/blob/master/DESCRIPTION) From 95195d70b2557c19b4eb937bd3f0d4b390dbea53 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Thu, 19 May 2022 16:31:22 +0100 Subject: [PATCH 195/226] added test coverage actions workflow --- .github/workflows/test-coverage.yaml | 34 ++++++++++++++++++++++++++++ README.md | 4 ++-- 2 files changed, 36 insertions(+), 2 deletions(-) create mode 100644 .github/workflows/test-coverage.yaml diff --git a/.github/workflows/test-coverage.yaml b/.github/workflows/test-coverage.yaml new file mode 100644 index 0000000..f016e6d --- /dev/null +++ b/.github/workflows/test-coverage.yaml @@ -0,0 +1,34 @@ +# Workflow derived from https://github.com/r-lib/actions/tree/master/examples +# Need help debugging build failures? Start at https://github.com/r-lib/actions#where-to-find-help +on: + push: + branches: [main, master] + pull_request: + branches: [main, master] + +name: test-coverage + +jobs: + test-coverage: + runs-on: ubuntu-latest + env: + GITHUB_PAT: ${{ secrets.GITHUB_TOKEN }} + + steps: + - uses: actions/checkout@v2 + + - uses: r-lib/actions/setup-r@v1 + with: + use-public-rspm: true + + - name: Install system dependencies + run: | + sudo apt install libopenbabel-dev + + - uses: r-lib/actions/setup-r-dependencies@v1 + with: + extra-packages: covr + + - name: Test coverage + run: covr::codecov() + shell: Rscript {0} diff --git a/README.md b/README.md index ca805b9..1e14fc7 100644 --- a/README.md +++ b/README.md @@ -3,8 +3,8 @@ [![Lifecycle: experimental](https://img.shields.io/badge/lifecycle-experimental-orange.svg)](https://www.tidyverse.org/lifecycle/#experimental) [![R-CMD-check](https://github.com/jasenfinch/MFassign/workflows/R-CMD-check/badge.svg)](https://github.com/jasenfinch/MFassign/actions) -[![Coverage Status](https://img.shields.io/codecov/c/github/jasenfinch/assignments/master.svg)](https://codecov.io/github/jasenfinch/assignments?branch=master) -[![license](https://img.shields.io/badge/license-GNU%20GPL%20v3.0-blue.svg)](https://github.com/jasenfinch/assignments/blob/master/DESCRIPTION) +[![Coverage Status](https://img.shields.io/codecov/c/github/jasenfinch/MFassign/master.svg)](https://codecov.io/github/jasenfinch/MFassign?branch=master) +[![license](https://img.shields.io/badge/license-GNU%20GPL%20v3.0-blue.svg)](https://github.com/jasenfinch/MFassign/blob/master/DESCRIPTION) An R package for molecular formula assignment in high resolution metabolomics From 9cdddf888162ce2c28be91c50ac213b2839aeb1d Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Thu, 19 May 2022 16:31:56 +0100 Subject: [PATCH 196/226] changed lifecycle badge to stable --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 1e14fc7..1497e94 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ # assignments -[![Lifecycle: experimental](https://img.shields.io/badge/lifecycle-experimental-orange.svg)](https://www.tidyverse.org/lifecycle/#experimental) +[![Lifecycle: stable](https://img.shields.io/badge/lifecycle-stable-brightgreen.svg)](https://lifecycle.r-lib.org/articles/stages.html#stable) [![R-CMD-check](https://github.com/jasenfinch/MFassign/workflows/R-CMD-check/badge.svg)](https://github.com/jasenfinch/MFassign/actions) [![Coverage Status](https://img.shields.io/codecov/c/github/jasenfinch/MFassign/master.svg)](https://codecov.io/github/jasenfinch/MFassign?branch=master) [![license](https://img.shields.io/badge/license-GNU%20GPL%20v3.0-blue.svg)](https://github.com/jasenfinch/MFassign/blob/master/DESCRIPTION) From dac99a2a4c85a6ae35ab51b4232f18d801902b27 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Fri, 20 May 2022 00:10:33 +0100 Subject: [PATCH 197/226] export component method --- NAMESPACE | 1 + R/assignment.R | 3 +++ man/accessors.Rd | 3 +++ 3 files changed, 7 insertions(+) diff --git a/NAMESPACE b/NAMESPACE index 1ca0a65..ab3e460 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -19,6 +19,7 @@ export(assignedData) export(assignmentParameters) export(assignments) export(availableTechniques) +export(component) export(components) export(correlations) export(correlationsParameters) diff --git a/R/assignment.R b/R/assignment.R index 436a99c..436fb7b 100644 --- a/R/assignment.R +++ b/R/assignment.R @@ -279,6 +279,9 @@ setMethod('featureComponents',signature = 'Assignment', filter(Feature == feature) }) +#' @rdname accessors +#' @export + setGeneric('component',function(assignment, component, iteration, diff --git a/man/accessors.Rd b/man/accessors.Rd index 8ebf9ab..41db137 100644 --- a/man/accessors.Rd +++ b/man/accessors.Rd @@ -15,6 +15,7 @@ \alias{components,Assignment-method} \alias{featureComponents} \alias{featureComponents,Assignment-method} +\alias{component} \alias{component,Assignment-method} \alias{assignments} \alias{assignments,Assignment-method} @@ -48,6 +49,8 @@ featureComponents(assignment, feature, type = c("selected", "all")) \S4method{featureComponents}{Assignment}(assignment, feature, type = c("selected", "all")) +component(assignment, component, iteration, type = c("selected", "all")) + \S4method{component}{Assignment}(assignment, component, iteration, type = c("selected", "all")) assignments(assignment) From 24f484eba7dad86647a55afc4361e76ea5977ece Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Fri, 20 May 2022 02:13:01 +0100 Subject: [PATCH 198/226] import anti_join --- NAMESPACE | 1 + R/addIsoAssign.R | 10 +++++----- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/NAMESPACE b/NAMESPACE index ab3e460..cdc4095 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -49,6 +49,7 @@ importFrom(crayon,blue) importFrom(crayon,green) importFrom(crayon,red) importFrom(crayon,yellow) +importFrom(dplyr,anti_join) importFrom(dplyr,arrange) importFrom(dplyr,bind_cols) importFrom(dplyr,bind_rows) diff --git a/R/addIsoAssign.R b/R/addIsoAssign.R index 68eacf1..2c42e8c 100644 --- a/R/addIsoAssign.R +++ b/R/addIsoAssign.R @@ -3,7 +3,7 @@ setGeneric("addIsoAssign", function(assignment) standardGeneric("addIsoAssign") ) -#' @importFrom dplyr arrange rowwise slice_sample left_join ungroup +#' @importFrom dplyr arrange rowwise slice_sample left_join ungroup anti_join #' @importFrom stringr str_detect #' @importFrom mzAnnotation calcM ipMF #' @importFrom igraph vertex.attributes V @@ -99,10 +99,10 @@ setMethod('addIsoAssign',signature = 'Assignment', if (counter > 1){ graph <- assignment@addIsoAssign[[counter - 1]]$graph %>% activate(nodes) %>% - dplyr::anti_join(assignment %>% - assignments() %>% - select(dplyr::any_of(c('Feature','Isotope','Adduct','MF'))), - by = 'Feature') + anti_join(assignment %>% + assignments() %>% + select(dplyr::any_of(c('Feature','Isotope','Adduct','MF'))), + by = 'Feature') if (length(graph) == 0) break() From 8dcd717347242a2134fdca7a1d274b702ef60371 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Fri, 20 May 2022 02:42:34 +0100 Subject: [PATCH 199/226] fixed errors caused by graphs with no edges --- R/addIsoAssign.R | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/R/addIsoAssign.R b/R/addIsoAssign.R index 2c42e8c..61b9b45 100644 --- a/R/addIsoAssign.R +++ b/R/addIsoAssign.R @@ -104,7 +104,7 @@ setMethod('addIsoAssign',signature = 'Assignment', select(dplyr::any_of(c('Feature','Isotope','Adduct','MF'))), by = 'Feature') - if (length(graph) == 0) break() + if (nrow(edges(graph)) == 0) break() graph <- graph %>% clean(adductRules(assignment)) %>% From 9ecb2b78fc927d422964fda6a8bc90150911f3e6 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Fri, 20 May 2022 20:49:40 +0100 Subject: [PATCH 200/226] ensure that assignment iteration is correctly named in transformation assignment table --- R/transformationAssign.R | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/R/transformationAssign.R b/R/transformationAssign.R index 95d2950..052bce3 100644 --- a/R/transformationAssign.R +++ b/R/transformationAssign.R @@ -101,7 +101,7 @@ setMethod('transformationAssign',signature = 'Assignment', select(Name:`MF Plausibility (%)`, Mode, Component) %>% - mutate(Iteration = str_c('T',count + 1)) %>% + mutate(Iteration = str_c('T',count)) %>% group_split(MF) %>% map_dfr(~{ if (NA %in% .x$Isotope) return(.x) From e1ec86a2974bf17c26af82c5635c2567a877ed9d Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Sat, 21 May 2022 02:46:10 +0100 Subject: [PATCH 201/226] make contributions of component degree, AIS and weight equal to component plausibility --- R/components.R | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/R/components.R b/R/components.R index 1eb55a6..6416775 100644 --- a/R/components.R +++ b/R/components.R @@ -3,8 +3,8 @@ avg_degree <- function(n_nodes,n_edges){ 2 * (n_edges / n_nodes) } -plausibility <- function(size,AIS,weight){ - size * AIS + weight +plausibility <- function(degree,AIS,weight){ + degree * AIS * weight } #' @importFrom purrr compact @@ -55,16 +55,14 @@ componentMetrics <- function(component,max_add_iso_total){ Density = (2 * Size) / (Nodes * (Nodes - 1)), Weight = sum(Weight) / Nodes, AIS = sum(AIS) / max_add_iso_total, - `Component Plausibility` = plausibility(AIS,Degree,Weight)) + `Component Plausibility` = plausibility(Degree,AIS,Weight)) } componentFilters <- function(){ tibble(Measure = c('Component Plausibility', - 'Degree', - 'AIS', 'MF Plausibility (%)', 'PPM error'), - Direction = c(rep('max',4),'min')) + Direction = c(rep('max',2),'min')) } #' @importFrom tidygraph as_tbl_graph activate morph unmorph graph_size group_components tbl_graph From 7a7a6932414ed3b20cbcc01a381f77b43d87e5d3 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Tue, 24 May 2022 00:54:44 +0100 Subject: [PATCH 202/226] added vignette --- .gitignore | 1 + DESCRIPTION | 8 +- R/parameters.R | 4 +- vignettes/.gitignore | 2 + vignettes/assignments.Rmd | 211 ++++++++++++++++++++++++++++++++++++++ 5 files changed, 222 insertions(+), 4 deletions(-) create mode 100644 vignettes/.gitignore create mode 100644 vignettes/assignments.Rmd diff --git a/.gitignore b/.gitignore index 234f028..0d7f03b 100644 --- a/.gitignore +++ b/.gitignore @@ -3,3 +3,4 @@ .RData .Ruserdata docs +inst/doc diff --git a/DESCRIPTION b/DESCRIPTION index 37196e0..99dcd7d 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -31,7 +31,8 @@ Collate: parameters.R assignment.R correlations.R graph.R assign.R internals.R components.R feature_data.R assignments.R plotAdductDist.R plot_components.R plotSpectrum.R reexports.R zzz.R -Suggests: testthat, +Suggests: + testthat, covr, ggplot2, ggraph, @@ -40,7 +41,10 @@ Suggests: testthat, ggthemes, glue, graphlayouts, - patchwork + patchwork, + knitr, + rmarkdown Remotes: jasenfinch/mzAnnotation@devel, jasenfinch/metabolyseR@devel URL: https://jasenfinch.github.io/assignments/ +VignetteBuilder: knitr diff --git a/R/parameters.R b/R/parameters.R index 9c33c96..5ac7303 100644 --- a/R/parameters.R +++ b/R/parameters.R @@ -8,8 +8,8 @@ #' @slot ppm ppm threshold #' @slot limit amu deviation limit for relationship prediction #' @slot RT_diff_limit limit for retention time differences for correlated features in adduct and isotopic assignment -#' @slot adducts list of character vectors containing the adducts to use. List element names should denote ionisation mode. -#' @slot isotopes character vector of isotopes to use +#' @slot adducts list of character vectors containing the adducts to use. List element names should denote ionisation mode. The order that these adducts are provided denotes their expected relative importance to assignments with the first expected to be the most common and the last the least common within each ionisation mode. +#' @slot isotopes character vector of isotopes to use. Similarly to the adducts, their order denotes the expected commonality in the data. #' @slot transformations character vector of transformations to use #' @slot adduct_rules tibble containing adduct formation rules as returned by `mzAnnotation::adducts()` #' @slot isotope_rules tibble containing isotope rules as returned by `mzAnnotation::isotopes()` diff --git a/vignettes/.gitignore b/vignettes/.gitignore new file mode 100644 index 0000000..097b241 --- /dev/null +++ b/vignettes/.gitignore @@ -0,0 +1,2 @@ +*.html +*.R diff --git a/vignettes/assignments.Rmd b/vignettes/assignments.Rmd new file mode 100644 index 0000000..7c038e3 --- /dev/null +++ b/vignettes/assignments.Rmd @@ -0,0 +1,211 @@ +--- +title: "assignments" +output: rmarkdown::html_vignette +vignette: > + %\VignetteIndexEntry{assignments} + %\VignetteEngine{knitr::rmarkdown} + %\VignetteEncoding{UTF-8} +--- + +```{r, include = FALSE} +knitr::opts_chunk$set( + collapse = TRUE, + comment = "#>", + fig.align = 'center' +) +``` + +## Introduction + +The *assignments* package provides an automated molecular formula assignment approach for high resolution electrospray ionisation mass spectrometry (ESI-MS) data from metabolomics experiments. +This includes data from both direct and flow injection/infusion fingerprinting as well as liquid chromatograph mass spectrometry (LC-MS) profiling analytical techniques. + +This vignette will provide a brief overview of the input data required, parameter selection, performing the assignments and assessing the results. + +Before we begin, first load the package. + +```{r setup} +library(assignments) +``` + +## Computational requirements and parallel processing + +This approach is computationally intensive so the use of high-performance computing resources is recommended. +A suggested minimum would be the use of 16 CPU workers and at least 8GB of RAM per worker (128GB total) to ensure that processing is completed in a reasonable duration. + +The parallel back-end is provided by the [*future*](https://future.futureverse.org/) package. +Information about the available parallel strategies can be found [here](https://future.futureverse.org/#controlling-how-futures-are-resolved). +This example will use a relatively tiny data set so the following example parallel options will be used: + +```{r parallel} +plan('multisession',workers = 2) +``` + +## Input data + +The requirements for data input are designed to be as simple as possible. +Input data should consist of an *m/z* by sample intensity matrix with positive an negative mode data combined where available. +The *m/z* features provided as column names should be in the form of `@`. +Ionisation mode should be given as a prefix `n` or `p` for negative or positive ionisation modes respectively. +Feature *m/z* should be provided to an accuracy of least 5 decimal places. +The retention time portion (`@`) is only required for LC-MS data and should be provided in minutes. + +It is recommended that the data undergo pre-treatment routines such as relative standard deviation filtering, imputation and/or normalisation prior to assignment. +However, this is not essential requirement and raw intensity values could also be used. + +The input data for this example is a subset from an FIE-HRMS metabolomics experiment and is shown below. +The feature intensities are total ion count (TIC) normalised. + +```{r example-data} +feature_data +``` + +## Parameters + +Default parameters for a number of techniques are provided. +The available techniques can be viewed as shown below. + +```{r techniques} +availableTechniques() +``` + +The `FIE-HRMS` fingerprinting technique parameters would also be suitable for direct injection data. +The default parameters are designed to be as widely applicable as possible and should suit many situations. +For this example we will specify the use of the `FIE-HRMS` parameters. + +```{r parameters} +parameters <- assignmentParameters('FIE-HRMS') +``` + +The parameters can then be viewed by printing the returned object. + +```{r print-parameters} +parameters +``` + +It is possible to access and set all of these parameters. +For example, the `adducts` method can be used to access the specified adducts: + +```{r extract-adducts} +adducts(parameters) +``` + +More accessor methods for assignment parameters can be viewed by running `?parameters`. + +Additional adducts, isotopes and transformations rules can also be appended to the relevant rules tables within the assignment parameters object. +See the assignment parameters documentation for more information. + +## Assignment + +To perform the molecular formula assignment we can execute the following. + +```{r assignment} +assignment <- assignMFs(feature_data, + parameters) +``` + +For an overview of the assignment results, we can print the object. + +```{r print-assignment} +assignment +``` + +## Results + +The following can be used to access the assigned *m/z* feature information. + +```{r assignment-results} +assignments(assignment) +``` + +These feature assignments can also be summarised for each molecular formula. + +```{r summarise-assignments} +summariseAssignments(assignment) +``` + +We can extract all the calculated correlations between the *m/z* features. + +```{r correlations} +correlations(assignment) +``` + +As well as all the computed mathematical adduct, isotope and transformation relationships. + +```{r relationships} +relationships(assignment) +``` + +To view all the iterations conducted during the assignment, the following can be used. + +```{r iterations} +iterations(assignment) +``` + +Information for the component subgraphs identified in an iteration can also be extracted. +These can either be the `selected` components or `all` the possible components. + +```{r components} +components(assignment, + iteration = 'A&I1', + type = 'selected') +``` + +We can extract the [*tidygraph*](https://tidygraph.data-imaginist.com/) `tbl_graph` object for a given iterations. + +```{r graph} +graph(assignment, + iteration = 'A&I1', + type = 'selected') +``` + +Along with the graph of individual component. + +```{r component} +component(assignment, + component = 1, + iteration = 'A&I1', + type = 'selected') +``` + +And all the components of a given feature. + +```{r feature-components} +featureComponents(assignment, + feature = 'n191.01962', + type = 'all') +``` + +The graph of an individual component can be visualised. +This first requires the *ggraph* package to be loaded. + +```{r plot-component,fig.height=4,fig.width=4} +library(ggraph) + +plotComponent(assignment, + component = 1, + iteration = 'A&I1', + type = 'selected') +``` + +We can also visualise the components containing a specific feature for a given iteration. + +```{r feature-solutions,fig.width=9,fig.height=7} +plotFeatureComponents( + assignment, + feature = 'n191.01962', + iteration = 'A&I1', + type = 'all', + max_components = 6, + axis_offset = 0.2 +) +``` + +Because a molecular ranking threshold is applied during assignment, it may also be useful to generate all the alternative molecular formulas and their rankings for a specific *m/z*, adduct and isotope using the `ipMF` function from the *mzAnnotation* package. + +```{r alternative-mfs} +mzAnnotation::ipMF(191.01962, + adduct = '[M-H]1-', + isotope = NA, + ppm = 6) +``` From 647b555572375126a5f2b55a07049df04c59ea55 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Wed, 1 Jun 2022 17:40:25 +0100 Subject: [PATCH 203/226] fix correlations accessor method --- R/assignment.R | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/R/assignment.R b/R/assignment.R index 436fb7b..4a87b6f 100644 --- a/R/assignment.R +++ b/R/assignment.R @@ -154,7 +154,7 @@ setGeneric('correlations',function(assignment) setMethod('correlations',signature = 'Assignment', function(assignment){ - assignment@relationships + assignment@correlations }) #' @rdname accessors From fea6ac2a39cfd5e26096d5d7643d0c0b412e6889 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Wed, 20 Jul 2022 18:43:00 +0100 Subject: [PATCH 204/226] fixed error when empty graph encountered during cleaning --- R/addIsoAssign.R | 4 +--- R/components.R | 17 ++++++++++++++--- 2 files changed, 15 insertions(+), 6 deletions(-) diff --git a/R/addIsoAssign.R b/R/addIsoAssign.R index 61b9b45..108b082 100644 --- a/R/addIsoAssign.R +++ b/R/addIsoAssign.R @@ -122,9 +122,7 @@ setMethod('addIsoAssign',signature = 'Assignment', rename(Name = name) %>% mutate(Mode = str_sub(Feature,1,1)) - if (nrow(assigned_features) == 0){ - break() - } + if (nrow(assigned_features) == 0) break() assignment@addIsoAssign[[counter]] <- list( graph = graph, diff --git a/R/components.R b/R/components.R index 6416775..3259dc6 100644 --- a/R/components.R +++ b/R/components.R @@ -11,7 +11,7 @@ plausibility <- function(degree,AIS,weight){ #' @importFrom tidygraph bind_graphs clean <- function(graph,adduct_rules_table){ - graph %>% + cleaned_graph <- graph %>% morph(to_components) %>% furrr::future_map(~{ component_adducts <- .x %>% @@ -37,8 +37,19 @@ clean <- function(graph,adduct_rules_table){ nrow(component_nodes) < 2) NULL else return(.x) }) %>% - compact() %>% - bind_graphs() + compact() + + if (length(cleaned_graph) == 0){ + cleaned_graph <- graph %>% + slice(0) + } + + if (length(cleaned_graph) > 0){ + cleaned_graph <- cleaned_graph %>% + bind_graphs() + } + + return(cleaned_graph) } nComponents <- function(graph){ From 62262f2ec9ce0fa8f63bf24cc7d0477003df8df6 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Tue, 11 Oct 2022 19:26:05 +0100 Subject: [PATCH 205/226] removed the use of the pipe in assignMFs --- R/assign.R | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/R/assign.R b/R/assign.R index 9b5b2ec..07febfc 100644 --- a/R/assign.R +++ b/R/assign.R @@ -57,11 +57,10 @@ setMethod('assignMFs',signature = 'tbl_df', data = feature_data) assignment@log$verbose <- verbose - assignment <- assignment %>% - calcCorrelations() %>% - calcRelationships() %>% - addIsoAssign() %>% - transformationAssign() + assignment <- calcCorrelations(assignment) + assignment <- calcRelationships(assignment) + assignment <- addIsoAssign(assignment) + assignment <- transformationAssign(assignment) if (verbose == TRUE) { endTime <- proc.time() From 0c420355dd6362c7b8f82c969a1709041be5b8aa Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Tue, 11 Oct 2022 19:30:30 +0100 Subject: [PATCH 206/226] declare verbose argument when Assignment object is created within assignMFs --- R/assign.R | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/R/assign.R b/R/assign.R index 07febfc..5b3ba9d 100644 --- a/R/assign.R +++ b/R/assign.R @@ -54,8 +54,8 @@ setMethod('assignMFs',signature = 'tbl_df', assignment <- new('Assignment', parameters, - data = feature_data) - assignment@log$verbose <- verbose + data = feature_data, + log = list(verbose = verbose)) assignment <- calcCorrelations(assignment) assignment <- calcRelationships(assignment) From f60287a582959d775afd8826c2b38be5d66dc543 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Mon, 28 Nov 2022 11:07:12 +0000 Subject: [PATCH 207/226] reexport the magrittr %>% --- R/reexports.R | 5 +++++ man/reexports.Rd | 3 +++ 2 files changed, 8 insertions(+) diff --git a/R/reexports.R b/R/reexports.R index 6df8a4b..5d70681 100644 --- a/R/reexports.R +++ b/R/reexports.R @@ -2,3 +2,8 @@ #' @importFrom future plan #' @export future::plan + +#' @rdname reexports +#' @importFrom magrittr %>% +#' @export +magrittr::`%>%` \ No newline at end of file diff --git a/man/reexports.Rd b/man/reexports.Rd index b2a7ed3..850f1fe 100644 --- a/man/reexports.Rd +++ b/man/reexports.Rd @@ -4,6 +4,7 @@ \name{reexports} \alias{reexports} \alias{plan} +\alias{\%>\%} \title{Objects exported from other packages} \keyword{internal} \description{ @@ -12,5 +13,7 @@ below to see their documentation. \describe{ \item{future}{\code{\link[future]{plan}}} + + \item{magrittr}{\code{\link[magrittr:pipe]{\%>\%}}} }} From 59ed00c6209b1b11ba07b30cb0580b6b51d49fb8 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Mon, 28 Nov 2022 16:16:46 +0000 Subject: [PATCH 208/226] added assignment constructor methods for creating objects of S4 class Assignment --- R/assignment.R | 72 ++++++++++++++++++++++++++------ man/assignment.Rd | 31 ++++++++++++++ tests/testthat/test-assignment.R | 25 +++++++++++ 3 files changed, 116 insertions(+), 12 deletions(-) create mode 100644 man/assignment.Rd diff --git a/R/assignment.R b/R/assignment.R index 4a87b6f..fc8fabb 100644 --- a/R/assignment.R +++ b/R/assignment.R @@ -95,43 +95,43 @@ setMethod('show',signature = 'Assignment', #' @param component component number to extract #' @param feature feature information to extract #' @examples -#' assignment <- new('Assignment', +#' mf_assignments <- new('Assignment', #' data = feature_data) #' #' ## Return feature data -#' featureData(assignment) +#' featureData(mf_assignments) #' #' ## Return correlations -#' correlations(assignment) +#' correlations(mf_assignments) #' #' ## Return relationships -#' relationships(assignment) +#' relationships(mf_assignments) #' #' ## Return the available iterations -#' iterations(assignment) +#' iterations(mf_assignments) #' #' ## Return a selected graph #' \dontrun{ -#' graph(assignment,'A&I1') +#' graph(mf_assignments,'A&I1') #' } #' #' ## Return a component information for a selected graph #' \dontrun{ -#' components(assignment,'A&I1') +#' components(mf_assignments,'A&I1') #' } #' #' ## Return a component information for a selected feature #' \dontrun{ -#' featureComponents(assignment,'n191.01962') +#' featureComponents(mf_assignments,'n191.01962') #' } #' #' ## Extract a component graph #' \dontrun{ -#' component(assignment,1,'A&I1') +#' component(mf_assignments,1,'A&I1') #' } #' #' ## Return assignments -#' assignments(assignment) +#' assignments(mf_assignments) #' @export setGeneric('featureData',function(assignment) @@ -378,9 +378,9 @@ setMethod('assignedData', signature = 'Assignment', #' plan(future::sequential) #' p <- assignmentParameters('FIE-HRMS') #' -#' assignment <- assignMFs(feature_data,p) +#' mf_assignments <- assignMFs(feature_data,p) #' -#' summariseAssignments(assignment) +#' summariseAssignments(mf_assignments) #' } #' @importFrom dplyr desc #' @export @@ -407,3 +407,51 @@ setMethod('summariseAssignments',signature = 'Assignment', arrange(desc(Count)) return(assigned) }) + +#' Create an Assignment S4 class object +#' @rdname assignment +#' @description Constructor methods for creating an object of S4 class `Assignment`. +#' @param feature_data a tibble or an object of S4 class `AnalysisData` or `Analysis` containing the feature intensity matrix of m/z for which to assign molecular formulas. See details. +#' @param parameters an S4 object of class `AssignmentParamters` containing the parameters for molecular formula assignment +#' @return An object of S4 class `Assignment`. +#' @examples +#' mf_assignments <- assignment(feature_data,assignmentParameters('FIE-HRMS')) +#' @export + +setGeneric('assignment',function(feature_data,parameters,...) + standardGeneric('assignment')) + +#' @rdname assignment + +setMethod('assignment',signature = c('tbl_df','AssignmentParameters'), + function(feature_data,parameters){ + new('Assignment', + parameters, + data = feature_data) + }) + + +#' @rdname assignment + +setMethod('assignment',signature = c('AnalysisData','AssignmentParameters'), + function(feature_data,parameters){ + new('Assignment', + parameters, + data = feature_data%>% + dat()) + }) + +#' @rdname assignment + +setMethod('assignment',signature = c('Analysis','AssignmentParameters'), + function(feature_data,parameters,type = c('pre-treated','raw')){ + + type <- match.arg(type, + choices = c('pre-treated','raw')) + + if (type == 'raw') feature_data <- raw(feature_data) + if (type == 'pre-treated') feature_data <- preTreated(feature_data) + + assignment(feature_data, + parameters) + }) \ No newline at end of file diff --git a/man/assignment.Rd b/man/assignment.Rd new file mode 100644 index 0000000..eea790d --- /dev/null +++ b/man/assignment.Rd @@ -0,0 +1,31 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/assignment.R +\name{assignment} +\alias{assignment} +\alias{assignment,tbl_df,AssignmentParameters-method} +\alias{assignment,AnalysisData,AssignmentParameters-method} +\alias{assignment,Analysis,AssignmentParameters-method} +\title{Create an Assignment S4 class object} +\usage{ +assignment(feature_data, parameters, ...) + +\S4method{assignment}{tbl_df,AssignmentParameters}(feature_data, parameters) + +\S4method{assignment}{AnalysisData,AssignmentParameters}(feature_data, parameters) + +\S4method{assignment}{Analysis,AssignmentParameters}(feature_data, parameters, type = c("pre-treated", "raw")) +} +\arguments{ +\item{feature_data}{a tibble or an object of S4 class \code{AnalysisData} or \code{Analysis} containing the feature intensity matrix of m/z for which to assign molecular formulas. See details.} + +\item{parameters}{an S4 object of class \code{AssignmentParamters} containing the parameters for molecular formula assignment} +} +\value{ +An object of S4 class \code{Assignment}. +} +\description{ +Constructor methods for creating an object of S4 class \code{Assignment}. +} +\examples{ +mf_assignments <- assignment(feature_data,assignmentParameters('FIE-HRMS')) +} diff --git a/tests/testthat/test-assignment.R b/tests/testthat/test-assignment.R index af32229..8bc7716 100644 --- a/tests/testthat/test-assignment.R +++ b/tests/testthat/test-assignment.R @@ -129,3 +129,28 @@ test_that('assignment spectrum can be plotted',{ expect_s3_class(pl,'ggplot') }) + +test_that('Assignment class object can be created from a tibble',{ + expect_s4_class(assignment(feature_data, + assignment_parameters_FIE), + 'Assignment') +}) + +test_that('Assignment class object can be created from an AnalysisData class object',{ + expect_s4_class(assignment(FIE_features %>% + raw(), + assignment_parameters_FIE), + 'Assignment') +}) + +test_that('Assignment class object can be created from an Analysis class object',{ + expect_s4_class(assignment(FIE_features, + assignment_parameters_FIE, + type = 'raw'), + 'Assignment') + + expect_s4_class(assignment(LC_features, + assignment_parameters_FIE, + type = 'pre-treated'), + 'Assignment') +}) From cb8222cf8fb7984114e61c16da4cee81ca40a71e Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Mon, 28 Nov 2022 16:53:43 +0000 Subject: [PATCH 209/226] export the individual methods for the steps in the molecular formula assignment approach --- R/addIsoAssign.R | 15 ++++++-- R/correlations.R | 31 +++++++++++++++- R/relationships.R | 14 ++++++- R/transformationAssign.R | 13 ++++++- man/assignment-methods.Rd | 63 ++++++++++++++++++++++++++++++++ tests/testthat/test-assignment.R | 9 +++++ 6 files changed, 138 insertions(+), 7 deletions(-) create mode 100644 man/assignment-methods.Rd diff --git a/R/addIsoAssign.R b/R/addIsoAssign.R index 108b082..0ccb53f 100644 --- a/R/addIsoAssign.R +++ b/R/addIsoAssign.R @@ -1,8 +1,12 @@ +#' @rdname assignment-methods +#' @export + setGeneric("addIsoAssign", function(assignment) standardGeneric("addIsoAssign") ) +#' @rdname assignment-methods #' @importFrom dplyr arrange rowwise slice_sample left_join ungroup anti_join #' @importFrom stringr str_detect #' @importFrom mzAnnotation calcM ipMF @@ -13,6 +17,14 @@ setGeneric("addIsoAssign", function(assignment) setMethod('addIsoAssign',signature = 'Assignment', function(assignment){ + rel <- assignment %>% + relationships() + + if (ncol(rel) == 0){ + stop('No relationships found. Has `calcRelationships()` been called on this object?', + call. = FALSE) + } + if (isTRUE(assignment@log$verbose)) { ai_start_time <- proc.time() message(blue('Adduct & isotopic assignment '), @@ -21,9 +33,6 @@ setMethod('addIsoAssign',signature = 'Assignment', assignment_technique <- technique(assignment) - rel <- assignment %>% - relationships() - if (str_detect(assignment_technique,'LC')){ rel <- rel %>% filter(RetentionTimeDiff <= assignment@RT_diff_limit) diff --git a/R/correlations.R b/R/correlations.R index 7d41602..c1674a6 100644 --- a/R/correlations.R +++ b/R/correlations.R @@ -1,11 +1,40 @@ +#' Molecular formula assignment methods +#' @rdname assignment-methods +#' @description These methods provide the access to performing the individual steps of the molecular +#' formula assignment approach. See Details for more information of when it is best to use these +#' instead of `assignMFs()`. +#' @param assignment an object of S4 class `Assignment` +#' @details +#' In circumstances where the molecular formula assignment approach has high memory requirements, +#' such as where there are many correlations (> 2 million) or many high *m/z* (>700), it may be +#' preferable to perform the assignment steps separately as opposed to using `assignMFs()`. This +#' can reduce the memory overheads required to successfully assign molecular formulas to the data +#' and also enable the possibility of objects to be saved and/or unloaded between the assignment +#' steps where needed. +#' @return An object of S4 class `Assignment` containing molecular formula assignments. +#' @examples +#' \dontrun{ +#' plan(future::sequential) +#' p <- assignmentParameters('FIE-HRMS') +#' +#' mf_assignments <- assignment(feature_data,p) +#' +#' mf_assignments <- mf_assignments %>% +#' calcCorrelations() %>% +#' calcRelationships() %>% +#' addIsoAssign() %>% +#' transformationAssign() +#' } +#' @export setGeneric('calcCorrelations', function(assignment) standardGeneric('calcCorrelations')) +#' @rdname assignment-methods #' @importFrom metabolyseR analysisParameters metabolyse analysisResults setMethod('calcCorrelations',signature = 'Assignment',function(assignment){ - if (assignment@log$verbose == T) { + if (assignment@log$verbose == TRUE) { startTime <- proc.time() message(blue('Calculating correlations '),cli::symbol$continue,'\r',appendLF = FALSE) } diff --git a/R/relationships.R b/R/relationships.R index e57242b..1a62243 100644 --- a/R/relationships.R +++ b/R/relationships.R @@ -1,7 +1,11 @@ -setGeneric("calcRelationships", function(assignment,transformations = TRUE) +#' @rdname assignment-methods +#' @export + +setGeneric("calcRelationships", function(assignment) standardGeneric("calcRelationships")) +#' @rdname assignment-methods #' @importFrom furrr future_map #' @importFrom dplyr mutate bind_rows filter vars contains #' @importFrom dplyr inner_join semi_join select mutate_at relocate @@ -13,6 +17,13 @@ setGeneric("calcRelationships", function(assignment,transformations = TRUE) setMethod('calcRelationships',signature = 'Assignment', function(assignment){ + cors <- assignment@correlations + + if (ncol(cors) == 0){ + stop('No correlations found. Has `calcCorrelations()` been called on this object?', + call. = FALSE) + } + if (assignment@log$verbose == TRUE) { startTime <- proc.time() message(blue('Calculating relationships '),cli::symbol$continue,'\r',appendLF = 'FALSE') @@ -20,7 +31,6 @@ setMethod('calcRelationships',signature = 'Assignment', parameters <- as(assignment,'AssignmentParameters') - cors <- assignment@correlations trans <- c(NA,transformations(assignment)) diff --git a/R/transformationAssign.R b/R/transformationAssign.R index 052bce3..e23e4e3 100644 --- a/R/transformationAssign.R +++ b/R/transformationAssign.R @@ -1,14 +1,25 @@ -#' @importFrom stringr str_c + +#' @rdname assignment-methods +#' @export setGeneric("transformationAssign", function(assignment) standardGeneric("transformationAssign")) +#' @rdname assignment-methods +#' @importFrom stringr str_c #' @importFrom dplyr full_join select distinct group_split #' @importFrom mzAnnotation transformMF setMethod('transformationAssign',signature = 'Assignment', function(assignment){ + assigned <- assignments(assignment) + + if (ncol(assigned) == 0){ + stop('No assignments found. Has `addIsoAssign()` been called on this object?', + call. = FALSE) + } + if (assignment@log$verbose == TRUE) { t_start_time <- proc.time() message(blue('Transformation assignment'), diff --git a/man/assignment-methods.Rd b/man/assignment-methods.Rd new file mode 100644 index 0000000..a8aa0b1 --- /dev/null +++ b/man/assignment-methods.Rd @@ -0,0 +1,63 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/correlations.R, R/addIsoAssign.R, +% R/transformationAssign.R, R/relationships.R +\name{calcCorrelations} +\alias{calcCorrelations} +\alias{calcCorrelations,Assignment-method} +\alias{addIsoAssign} +\alias{addIsoAssign,Assignment-method} +\alias{transformationAssign} +\alias{transformationAssign,Assignment-method} +\alias{calcRelationships} +\alias{calcRelationships,Assignment-method} +\title{Molecular formula assignment methods} +\usage{ +calcCorrelations(assignment) + +\S4method{calcCorrelations}{Assignment}(assignment) + +addIsoAssign(assignment) + +\S4method{addIsoAssign}{Assignment}(assignment) + +transformationAssign(assignment) + +\S4method{transformationAssign}{Assignment}(assignment) + +calcRelationships(assignment) + +\S4method{calcRelationships}{Assignment}(assignment) +} +\arguments{ +\item{assignment}{an object of S4 class \code{Assignment}} +} +\value{ +An object of S4 class \code{Assignment} containing molecular formula assignments. +} +\description{ +These methods provide the access to performing the individual steps of the molecular +formula assignment approach. See Details for more information of when it is best to use these +instead of \code{assignMFs()}. +} +\details{ +In circumstances where the molecular formula assignment approach has high memory requirements, +such as where there are many correlations (> 2 million) or many high \emph{m/z} (>700), it may be +preferable to perform the assignment steps separately as opposed to using \code{assignMFs()}. This +can reduce the memory overheads required to successfully assign molecular formulas to the data +and also enable the possibility of objects to be saved and/or unloaded between the assignment +steps where needed. +} +\examples{ +\dontrun{ +plan(future::sequential) +p <- assignmentParameters('FIE-HRMS') + +mf_assignments <- assignment(feature_data,p) + +mf_assignments <- mf_assignments \%>\% + calcCorrelations() \%>\% + calcRelationships() \%>\% + addIsoAssign() \%>\% + transformationAssign() +} +} diff --git a/tests/testthat/test-assignment.R b/tests/testthat/test-assignment.R index 8bc7716..e44bd8b 100644 --- a/tests/testthat/test-assignment.R +++ b/tests/testthat/test-assignment.R @@ -154,3 +154,12 @@ test_that('Assignment class object can be created from an Analysis class object' type = 'pre-treated'), 'Assignment') }) + +test_that('assignment methods error correctly when slots are empty',{ + mf_assignments <- assignment(feature_data, + assignment_parameters_FIE) + + expect_error(calcRelationships(mf_assignments)) + expect_error(addIsoAssign(mf_assignments)) + expect_error(transformationAssign(mf_assignments)) +}) From ebb0171bc886a780c04abb1279c6f9f64c16d962 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Mon, 28 Nov 2022 16:58:11 +0000 Subject: [PATCH 210/226] update the NAMESPACE --- DESCRIPTION | 2 +- NAMESPACE | 6 ++++++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/DESCRIPTION b/DESCRIPTION index 99dcd7d..8e8924f 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -25,7 +25,7 @@ License: GPL (>= 3) Encoding: UTF-8 LazyData: true Roxygen: list(markdown = TRUE) -RoxygenNote: 7.2.0 +RoxygenNote: 7.2.1 Collate: parameters.R assignment.R correlations.R addIsoAssign.R transformationAssign.R relationships.R graph.R assign.R internals.R components.R diff --git a/NAMESPACE b/NAMESPACE index cdc4095..62383da 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -1,5 +1,6 @@ # Generated by roxygen2: do not edit by hand +export("%>%") export("MFrankThreshold<-") export("adductRules<-") export("adducts<-") @@ -12,13 +13,17 @@ export("ppm<-") export("transformationRules<-") export("transformations<-") export(MFrankThreshold) +export(addIsoAssign) export(adductRules) export(adducts) export(assignMFs) export(assignedData) +export(assignment) export(assignmentParameters) export(assignments) export(availableTechniques) +export(calcCorrelations) +export(calcRelationships) export(component) export(components) export(correlations) @@ -42,6 +47,7 @@ export(ppm) export(relationships) export(summariseAssignments) export(technique) +export(transformationAssign) export(transformationRules) export(transformations) importFrom(cli,console_width) From c285a09561dfdf6006b9ceb1bbaccf6026ae42c4 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Mon, 28 Nov 2022 16:59:09 +0000 Subject: [PATCH 211/226] update documentation and fix examples --- R/assign.R | 2 +- R/assignment.R | 4 ++-- R/plotSpectrum.R | 2 +- R/plot_components.R | 4 ++-- man/AssignmentParameters-class.Rd | 4 ++-- man/accessors.Rd | 20 ++++++++++---------- man/assign.Rd | 2 +- man/assignedData.Rd | 4 ++-- man/plotComponent.Rd | 4 ++-- man/summariseAssignments.Rd | 4 ++-- 10 files changed, 25 insertions(+), 25 deletions(-) diff --git a/R/assign.R b/R/assign.R index 5b3ba9d..9cd0157 100644 --- a/R/assign.R +++ b/R/assign.R @@ -17,7 +17,7 @@ #' plan(future::sequential) #' p <- assignmentParameters('FIE-HRMS') #' -#' assignment <- assignMFs(feature_data,p) +#' mf_assignments <- assignMFs(feature_data,p) #' #' @export diff --git a/R/assignment.R b/R/assignment.R index fc8fabb..68e22d1 100644 --- a/R/assignment.R +++ b/R/assignment.R @@ -332,9 +332,9 @@ setMethod('assignments',signature = 'Assignment', #' plan(future::sequential) #' p <- assignmentParameters('FIE-HRMS') #' -#' assignment <- assignMFs(feature_data,p) +#' mf_assignments <- assignMFs(feature_data,p) #' -#' assignedData(assignment) +#' assignedData(mf_assignment) #' } #' @export diff --git a/R/plotSpectrum.R b/R/plotSpectrum.R index c8c9523..7243b0b 100644 --- a/R/plotSpectrum.R +++ b/R/plotSpectrum.R @@ -54,7 +54,7 @@ setMethod('plotSpectrum',signature = 'Assignment',function(assignment,MF){ filter(MF == mf) dat <- assignment@data %>% - select(feat$Feature) %>% + select(all_of(feat$Feature)) %>% gather('Feature','Intensity') %>% group_by(Feature) %>% summarise(Intensity = mean(Intensity)) %>% diff --git a/R/plot_components.R b/R/plot_components.R index f81fab7..dd7c107 100644 --- a/R/plot_components.R +++ b/R/plot_components.R @@ -82,9 +82,9 @@ plotGraph <- function(graph, #' plan(future::sequential) #' p <- assignmentParameters('FIE-HRMS') #' -#' assignment <- assignMFs(feature_data,p) +#' mf_assignments <- assignMFs(feature_data,p) #' -#' plotComponent(assignment,1,'A&I1') +#' plotComponent(mf_assignments,1,'A&I1') #' } #' @export diff --git a/man/AssignmentParameters-class.Rd b/man/AssignmentParameters-class.Rd index dd34540..b8d3528 100644 --- a/man/AssignmentParameters-class.Rd +++ b/man/AssignmentParameters-class.Rd @@ -24,9 +24,9 @@ An S4 class to store assignment parameters. \item{\code{RT_diff_limit}}{limit for retention time differences for correlated features in adduct and isotopic assignment} -\item{\code{adducts}}{list of character vectors containing the adducts to use. List element names should denote ionisation mode.} +\item{\code{adducts}}{list of character vectors containing the adducts to use. List element names should denote ionisation mode. The order that these adducts are provided denotes their expected relative importance to assignments with the first expected to be the most common and the last the least common within each ionisation mode.} -\item{\code{isotopes}}{character vector of isotopes to use} +\item{\code{isotopes}}{character vector of isotopes to use. Similarly to the adducts, their order denotes the expected commonality in the data.} \item{\code{transformations}}{character vector of transformations to use} diff --git a/man/accessors.Rd b/man/accessors.Rd index 41db137..83e6c5d 100644 --- a/man/accessors.Rd +++ b/man/accessors.Rd @@ -72,41 +72,41 @@ assignments(assignment) Access methods for Assignment S4 class } \examples{ -assignment <- new('Assignment', +mf_assignments <- new('Assignment', data = feature_data) ## Return feature data -featureData(assignment) +featureData(mf_assignments) ## Return correlations -correlations(assignment) +correlations(mf_assignments) ## Return relationships -relationships(assignment) +relationships(mf_assignments) ## Return the available iterations -iterations(assignment) +iterations(mf_assignments) ## Return a selected graph \dontrun{ -graph(assignment,'A&I1') +graph(mf_assignments,'A&I1') } ## Return a component information for a selected graph \dontrun{ -components(assignment,'A&I1') +components(mf_assignments,'A&I1') } ## Return a component information for a selected feature \dontrun{ -featureComponents(assignment,'n191.01962') +featureComponents(mf_assignments,'n191.01962') } ## Extract a component graph \dontrun{ -component(assignment,1,'A&I1') +component(mf_assignments,1,'A&I1') } ## Return assignments -assignments(assignment) +assignments(mf_assignments) } diff --git a/man/assign.Rd b/man/assign.Rd index 5c24a53..8c4403f 100644 --- a/man/assign.Rd +++ b/man/assign.Rd @@ -54,6 +54,6 @@ If argument \code{feature_data} is specified as a tibble, this should be a featu plan(future::sequential) p <- assignmentParameters('FIE-HRMS') -assignment <- assignMFs(feature_data,p) +mf_assignments <- assignMFs(feature_data,p) } diff --git a/man/assignedData.Rd b/man/assignedData.Rd index faa4015..27539ab 100644 --- a/man/assignedData.Rd +++ b/man/assignedData.Rd @@ -23,8 +23,8 @@ Return data table used for assignments with feature assignments added to column plan(future::sequential) p <- assignmentParameters('FIE-HRMS') -assignment <- assignMFs(feature_data,p) +mf_assignments <- assignMFs(feature_data,p) -assignedData(assignment) +assignedData(mf_assignment) } } diff --git a/man/plotComponent.Rd b/man/plotComponent.Rd index 247b5ff..6151948 100644 --- a/man/plotComponent.Rd +++ b/man/plotComponent.Rd @@ -52,8 +52,8 @@ Plot a molecular formula component graph. plan(future::sequential) p <- assignmentParameters('FIE-HRMS') -assignment <- assignMFs(feature_data,p) +mf_assignments <- assignMFs(feature_data,p) -plotComponent(assignment,1,'A&I1') +plotComponent(mf_assignments,1,'A&I1') } } diff --git a/man/summariseAssignments.Rd b/man/summariseAssignments.Rd index ecd0cd7..1586573 100644 --- a/man/summariseAssignments.Rd +++ b/man/summariseAssignments.Rd @@ -23,8 +23,8 @@ Summarise features assigned to molecular formulas. plan(future::sequential) p <- assignmentParameters('FIE-HRMS') -assignment <- assignMFs(feature_data,p) +mf_assignments <- assignMFs(feature_data,p) -summariseAssignments(assignment) +summariseAssignments(mf_assignments) } } From f13c80555cd2b417dc39f1229dfa831f5c92fde5 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Mon, 28 Nov 2022 16:59:23 +0000 Subject: [PATCH 212/226] fix tidyselect warning --- R/internals.R | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/R/internals.R b/R/internals.R index 11de69c..a4d42b2 100644 --- a/R/internals.R +++ b/R/internals.R @@ -16,7 +16,7 @@ eliminate <- function(MFs,by,direction){ bind_cols(MFs %>% select(by = by)) %>% group_by(Feature) %>% filter(by == direct(by)) %>% - select(-by) %>% + select(-all_of(by)) %>% ungroup() } From 26f476359e631236255e763c8c9ae2ad11f6e819 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Mon, 28 Nov 2022 17:46:38 +0000 Subject: [PATCH 213/226] documentation fixes --- .Rbuildignore | 2 ++ .gitignore | 2 ++ NAMESPACE | 1 + R/assign.R | 4 ++-- R/assignment.R | 4 +++- R/internals.R | 2 +- R/plot_components.R | 4 ++-- man/assign.Rd | 4 ++-- man/assignedData.Rd | 4 ++-- man/assignment.Rd | 4 ++++ man/plotComponent.Rd | 2 +- man/plotFeatureComponents.Rd | 2 +- 12 files changed, 23 insertions(+), 12 deletions(-) diff --git a/.Rbuildignore b/.Rbuildignore index 16192bc..9a69a7b 100644 --- a/.Rbuildignore +++ b/.Rbuildignore @@ -7,3 +7,5 @@ ^_pkgdown\.yml$ ^docs$ ^pkgdown$ +^doc$ +^Meta$ diff --git a/.gitignore b/.gitignore index 0d7f03b..130a84f 100644 --- a/.gitignore +++ b/.gitignore @@ -4,3 +4,5 @@ .Ruserdata docs inst/doc +/doc/ +/Meta/ diff --git a/NAMESPACE b/NAMESPACE index 62383da..b647917 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -55,6 +55,7 @@ importFrom(crayon,blue) importFrom(crayon,green) importFrom(crayon,red) importFrom(crayon,yellow) +importFrom(dplyr,all_of) importFrom(dplyr,anti_join) importFrom(dplyr,arrange) importFrom(dplyr,bind_cols) diff --git a/R/assign.R b/R/assign.R index 9cd0157..8ee405e 100644 --- a/R/assign.R +++ b/R/assign.R @@ -4,7 +4,7 @@ #' @param feature_data a tibble or an object of S4 class `AnalysisData` or `Analysis` containing the feature intensity matrix of m/z for which to assign molecular formulas. See details. #' @param parameters an S4 object of class `AssignmentParamters` containing the parameters for molecular formula assignment #' @param verbose should progress output be printed to the console -#' @param type `raw` or `pre-treated` data on which to perform assignment when argument `feature_data` is of class `Analysis` +#' @param type `pre-treated` or `raw` data on which to perform assignment when argument `feature_data` is of class `Analysis` #' @param ... arguments to pass to the relevant method #' @details #' If argument `feature_data` is specified as a tibble, this should be a feature intensity matrix where the columns are the `m/z` features to assign and the rows are the individual observations, with the cells as abundance values. @@ -17,7 +17,7 @@ #' plan(future::sequential) #' p <- assignmentParameters('FIE-HRMS') #' -#' mf_assignments <- assignMFs(feature_data,p) +#' assignments <- assignMFs(feature_data,p) #' #' @export diff --git a/R/assignment.R b/R/assignment.R index 68e22d1..7277f39 100644 --- a/R/assignment.R +++ b/R/assignment.R @@ -334,7 +334,7 @@ setMethod('assignments',signature = 'Assignment', #' #' mf_assignments <- assignMFs(feature_data,p) #' -#' assignedData(mf_assignment) +#' assignedData(mf_assignments) #' } #' @export @@ -413,6 +413,8 @@ setMethod('summariseAssignments',signature = 'Assignment', #' @description Constructor methods for creating an object of S4 class `Assignment`. #' @param feature_data a tibble or an object of S4 class `AnalysisData` or `Analysis` containing the feature intensity matrix of m/z for which to assign molecular formulas. See details. #' @param parameters an S4 object of class `AssignmentParamters` containing the parameters for molecular formula assignment +#' @param type type `pre-treated` or `raw` data on which to perform assignment when argument `feature_data` is of class `Analysis` +#' @param ... arguments to pass to the relevant method #' @return An object of S4 class `Assignment`. #' @examples #' mf_assignments <- assignment(feature_data,assignmentParameters('FIE-HRMS')) diff --git a/R/internals.R b/R/internals.R index a4d42b2..9a86dc7 100644 --- a/R/internals.R +++ b/R/internals.R @@ -7,7 +7,7 @@ elapsedTime <- function(start_time,end_time){ str_c('[',.,']') } -#' @importFrom dplyr bind_cols +#' @importFrom dplyr bind_cols all_of eliminate <- function(MFs,by,direction){ direct <- get(direction) diff --git a/R/plot_components.R b/R/plot_components.R index dd7c107..fa19299 100644 --- a/R/plot_components.R +++ b/R/plot_components.R @@ -72,7 +72,7 @@ plotGraph <- function(graph, #' @param assignment S4 object of class Assignment #' @param component component number to extract #' @param iteration the assignment iteration -#' @param type the graph type to return. `filtered` returns the assignment graph after component selection. `all` returns all assignment components. +#' @param type the graph type to return. `selected` returns the assignment graph after component selection. `all` returns all assignment components. #' @param label_size node label size #' @param axis_offset axis proportion by which to increase axis limits. Prevents cut off of node labels. #' @param border specify a plot border colour @@ -159,7 +159,7 @@ setMethod('plotComponent',signature = 'Assignment', #' @param assignment S4 object of class Assignent #' @param feature name of feature to plot #' @param iteration components from which iteration to plot -#' @param type the graph type to return. `all` returns all assignment components. `filtered` returns the assignment graph after component selection. +#' @param type the graph type to return. `all` returns all assignment components. `selected` returns the assignment graph after component selection. #' @param max_components maximum number of components to plot #' @param label_size node label size #' @param axis_offset axis proportion by which to increase axis limits. Prevents cut off of node labels. diff --git a/man/assign.Rd b/man/assign.Rd index 8c4403f..0c081b5 100644 --- a/man/assign.Rd +++ b/man/assign.Rd @@ -42,7 +42,7 @@ assignMFs( \item{...}{arguments to pass to the relevant method} -\item{type}{\code{raw} or \code{pre-treated} data on which to perform assignment when argument \code{feature_data} is of class \code{Analysis}} +\item{type}{\code{pre-treated} or \code{raw} data on which to perform assignment when argument \code{feature_data} is of class \code{Analysis}} } \description{ assign molecular formulas to a set of given m/z. @@ -54,6 +54,6 @@ If argument \code{feature_data} is specified as a tibble, this should be a featu plan(future::sequential) p <- assignmentParameters('FIE-HRMS') -mf_assignments <- assignMFs(feature_data,p) +assignments <- assignMFs(feature_data,p) } diff --git a/man/assignedData.Rd b/man/assignedData.Rd index 27539ab..faa4015 100644 --- a/man/assignedData.Rd +++ b/man/assignedData.Rd @@ -23,8 +23,8 @@ Return data table used for assignments with feature assignments added to column plan(future::sequential) p <- assignmentParameters('FIE-HRMS') -mf_assignments <- assignMFs(feature_data,p) +assignment <- assignMFs(feature_data,p) -assignedData(mf_assignment) +assignedData(assignment) } } diff --git a/man/assignment.Rd b/man/assignment.Rd index eea790d..2d8d9a9 100644 --- a/man/assignment.Rd +++ b/man/assignment.Rd @@ -19,6 +19,10 @@ assignment(feature_data, parameters, ...) \item{feature_data}{a tibble or an object of S4 class \code{AnalysisData} or \code{Analysis} containing the feature intensity matrix of m/z for which to assign molecular formulas. See details.} \item{parameters}{an S4 object of class \code{AssignmentParamters} containing the parameters for molecular formula assignment} + +\item{...}{arguments to pass to the relevant method} + +\item{type}{type \code{pre-treated} or \code{raw} data on which to perform assignment when argument \code{feature_data} is of class \code{Analysis}} } \value{ An object of S4 class \code{Assignment}. diff --git a/man/plotComponent.Rd b/man/plotComponent.Rd index 6151948..4edc09f 100644 --- a/man/plotComponent.Rd +++ b/man/plotComponent.Rd @@ -34,7 +34,7 @@ plotComponent( \item{iteration}{the assignment iteration} -\item{type}{the graph type to return. \code{filtered} returns the assignment graph after component selection. \code{all} returns all assignment components.} +\item{type}{the graph type to return. \code{selected} returns the assignment graph after component selection. \code{all} returns all assignment components.} \item{label_size}{node label size} diff --git a/man/plotFeatureComponents.Rd b/man/plotFeatureComponents.Rd index aa19446..20377f8 100644 --- a/man/plotFeatureComponents.Rd +++ b/man/plotFeatureComponents.Rd @@ -32,7 +32,7 @@ plotFeatureComponents( \item{iteration}{components from which iteration to plot} -\item{type}{the graph type to return. \code{all} returns all assignment components. \code{filtered} returns the assignment graph after component selection.} +\item{type}{the graph type to return. \code{all} returns all assignment components. \code{selected} returns the assignment graph after component selection.} \item{max_components}{maximum number of components to plot} From b742dc427af7f270a1c13b182a29d256cc2e94a7 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Mon, 28 Nov 2022 17:56:45 +0000 Subject: [PATCH 214/226] Add to README --- README.md | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 1497e94..ed530ac 100644 --- a/README.md +++ b/README.md @@ -7,10 +7,26 @@ [![license](https://img.shields.io/badge/license-GNU%20GPL%20v3.0-blue.svg)](https://github.com/jasenfinch/MFassign/blob/master/DESCRIPTION) -An R package for molecular formula assignment in high resolution metabolomics +> An R package for molecular formula assignment of high resolution ESI-MS based metabolomics data + +### Overview ### Installation +The `assignments` package can be installed from GitHub using the +following: + ``` r -devtools::install_github('jasenfinch/assignments') +remotes::install_github('jasenfinch/assignments') ``` + +### Learn more + +The package documentation can be browsed online at +. + +If this is your first time using `assignments` see the +[vignette](https://jasenfinch.github.io/metabolyseR/articles/assignments.html) for information on how to get started. + +If you believe you’ve found a bug in `assignments`, please file a bug (and, if possible, a [reproducible example](https://reprex.tidyverse.org)) at +. From 1d919d60471f7032e87e445fd340c6a3585b0088 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Mon, 28 Nov 2022 17:57:01 +0000 Subject: [PATCH 215/226] Update DESCRIPTION --- DESCRIPTION | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/DESCRIPTION b/DESCRIPTION index 8e8924f..8af8e2d 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -1,8 +1,8 @@ Package: assignments -Title: Molecular formula assignment for high resolution metabolomics +Title: Molecular Formula Assignment For High Resolution ESI-MS Based Metabolomics Data Version: 1.0.0 Authors@R: person("Jasen", "Finch", email = "jsf9@aber.ac.uk", role = c("aut", "cre")) -Description: Molecular formula assignment for high resolution metabolomics. +Description: A molecular formula assignment approach for high resolution electrospray ionisation mass spectrometry based metabolomics data. Depends: R (>= 3.5.0), Imports: cli, crayon, From 3ff98e5553a2d5f37466ab9e4488cb2c87eba0b0 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Thu, 22 Dec 2022 20:02:22 +0000 Subject: [PATCH 216/226] update GH actions workflow --- .github/workflows/R-CMD-check.yaml | 25 ++++++++++--------- .github/workflows/test-coverage.yaml | 36 ++++++++++++++++++++-------- README.md | 2 +- 3 files changed, 39 insertions(+), 24 deletions(-) diff --git a/.github/workflows/R-CMD-check.yaml b/.github/workflows/R-CMD-check.yaml index 1e73d3e..c21abc8 100644 --- a/.github/workflows/R-CMD-check.yaml +++ b/.github/workflows/R-CMD-check.yaml @@ -1,4 +1,4 @@ -# Workflow derived from https://github.com/r-lib/actions/tree/master/examples +# Workflow derived from https://github.com/r-lib/actions/tree/v2/examples # Need help debugging build failures? Start at https://github.com/r-lib/actions#where-to-find-help on: push: @@ -18,8 +18,8 @@ jobs: fail-fast: false matrix: config: - #- {os: macOS-latest, r: 'release'} - #- {os: windows-latest, r: 'release'} + - {os: macos-latest, r: 'release'} + - {os: windows-latest, r: 'release'} - {os: ubuntu-latest, r: 'devel', http-user-agent: 'release'} - {os: ubuntu-latest, r: 'release'} - {os: ubuntu-latest, r: 'oldrel-1'} @@ -29,22 +29,21 @@ jobs: R_KEEP_PKG_SOURCE: yes steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v3 - - uses: r-lib/actions/setup-pandoc@v1 + - uses: r-lib/actions/setup-pandoc@v2 - - uses: r-lib/actions/setup-r@v1 + - uses: r-lib/actions/setup-r@v2 with: r-version: ${{ matrix.config.r }} http-user-agent: ${{ matrix.config.http-user-agent }} use-public-rspm: true - - - name: Install system dependencies - run: | - sudo apt install libopenbabel-dev - - uses: r-lib/actions/setup-r-dependencies@v1 + - uses: r-lib/actions/setup-r-dependencies@v2 with: - extra-packages: rcmdcheck + extra-packages: any::rcmdcheck + needs: check - - uses: r-lib/actions/check-r-package@v1 + - uses: r-lib/actions/check-r-package@v2 + with: + upload-snapshots: true diff --git a/.github/workflows/test-coverage.yaml b/.github/workflows/test-coverage.yaml index f016e6d..2c5bb50 100644 --- a/.github/workflows/test-coverage.yaml +++ b/.github/workflows/test-coverage.yaml @@ -1,4 +1,4 @@ -# Workflow derived from https://github.com/r-lib/actions/tree/master/examples +# Workflow derived from https://github.com/r-lib/actions/tree/v2/examples # Need help debugging build failures? Start at https://github.com/r-lib/actions#where-to-find-help on: push: @@ -15,20 +15,36 @@ jobs: GITHUB_PAT: ${{ secrets.GITHUB_TOKEN }} steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v3 - - uses: r-lib/actions/setup-r@v1 + - uses: r-lib/actions/setup-r@v2 with: use-public-rspm: true - - - name: Install system dependencies - run: | - sudo apt install libopenbabel-dev - - uses: r-lib/actions/setup-r-dependencies@v1 + - uses: r-lib/actions/setup-r-dependencies@v2 with: - extra-packages: covr + extra-packages: any::covr + needs: coverage - name: Test coverage - run: covr::codecov() + run: | + covr::codecov( + quiet = FALSE, + clean = FALSE, + install_path = file.path(Sys.getenv("RUNNER_TEMP"), "package") + ) shell: Rscript {0} + + - name: Show testthat output + if: always() + run: | + ## -------------------------------------------------------------------- + find ${{ runner.temp }}/package -name 'testthat.Rout*' -exec cat '{}' \; || true + shell: bash + + - name: Upload test results + if: failure() + uses: actions/upload-artifact@v3 + with: + name: coverage-test-failures + path: ${{ runner.temp }}/package diff --git a/README.md b/README.md index 1497e94..2c6ac47 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ [![Lifecycle: stable](https://img.shields.io/badge/lifecycle-stable-brightgreen.svg)](https://lifecycle.r-lib.org/articles/stages.html#stable) -[![R-CMD-check](https://github.com/jasenfinch/MFassign/workflows/R-CMD-check/badge.svg)](https://github.com/jasenfinch/MFassign/actions) +[![R-CMD-check](https://github.com/jasenfinch/MFassign/actions/workflows/R-CMD-check.yaml/badge.svg)](https://github.com/jasenfinch/MFassign/actions/workflows/R-CMD-check.yaml) [![Coverage Status](https://img.shields.io/codecov/c/github/jasenfinch/MFassign/master.svg)](https://codecov.io/github/jasenfinch/MFassign?branch=master) [![license](https://img.shields.io/badge/license-GNU%20GPL%20v3.0-blue.svg)](https://github.com/jasenfinch/MFassign/blob/master/DESCRIPTION) From b4ed9024a6d5e9001f88f6889ef75f0eca982d82 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Wed, 8 Feb 2023 12:24:44 +0000 Subject: [PATCH 217/226] fix missing expression error --- R/components.R | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/R/components.R b/R/components.R index 3259dc6..6290209 100644 --- a/R/components.R +++ b/R/components.R @@ -62,11 +62,12 @@ componentMetrics <- function(component,max_add_iso_total){ component %>% mutate(Size = graph_size(), Nodes = n(), - Degree = avg_degree(Nodes,Size),, + Degree = avg_degree(Nodes,Size), Density = (2 * Size) / (Nodes * (Nodes - 1)), Weight = sum(Weight) / Nodes, AIS = sum(AIS) / max_add_iso_total, - `Component Plausibility` = plausibility(Degree,AIS,Weight)) + `Component Plausibility` = plausibility(Degree,AIS,Weight) + ) } componentFilters <- function(){ From 922cb3ac55449fb2cb712bfa3e663945ea63552f Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Wed, 8 Feb 2023 12:31:47 +0000 Subject: [PATCH 218/226] fix dplyr warning --- R/internals.R | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/R/internals.R b/R/internals.R index 9a86dc7..98fe3c2 100644 --- a/R/internals.R +++ b/R/internals.R @@ -13,7 +13,7 @@ eliminate <- function(MFs,by,direction){ direct <- get(direction) MFs %>% - bind_cols(MFs %>% select(by = by)) %>% + bind_cols(MFs %>% select(by = all_of(by))) %>% group_by(Feature) %>% filter(by == direct(by)) %>% select(-all_of(by)) %>% From ae34e5730c77e929f67b667b6ccf35d15600c06a Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Tue, 14 Feb 2023 10:01:21 +0000 Subject: [PATCH 219/226] ensure the garbage is collected --- R/addIsoAssign.R | 2 ++ R/correlations.R | 2 ++ R/relationships.R | 2 ++ R/transformationAssign.R | 2 ++ 4 files changed, 8 insertions(+) diff --git a/R/addIsoAssign.R b/R/addIsoAssign.R index 0ccb53f..1656e11 100644 --- a/R/addIsoAssign.R +++ b/R/addIsoAssign.R @@ -17,6 +17,8 @@ setGeneric("addIsoAssign", function(assignment) setMethod('addIsoAssign',signature = 'Assignment', function(assignment){ + invisible(gc()) + rel <- assignment %>% relationships() diff --git a/R/correlations.R b/R/correlations.R index c1674a6..c31a9c4 100644 --- a/R/correlations.R +++ b/R/correlations.R @@ -39,6 +39,8 @@ setMethod('calcCorrelations',signature = 'Assignment',function(assignment){ message(blue('Calculating correlations '),cli::symbol$continue,'\r',appendLF = FALSE) } + invisible(gc()) + p <- analysisParameters('correlations') parameters <- as(assignment,'AssignmentParameters') diff --git a/R/relationships.R b/R/relationships.R index 1a62243..3610589 100644 --- a/R/relationships.R +++ b/R/relationships.R @@ -17,6 +17,8 @@ setGeneric("calcRelationships", function(assignment) setMethod('calcRelationships',signature = 'Assignment', function(assignment){ + invisible(gc()) + cors <- assignment@correlations if (ncol(cors) == 0){ diff --git a/R/transformationAssign.R b/R/transformationAssign.R index e23e4e3..917a57d 100644 --- a/R/transformationAssign.R +++ b/R/transformationAssign.R @@ -13,6 +13,8 @@ setGeneric("transformationAssign", function(assignment) setMethod('transformationAssign',signature = 'Assignment', function(assignment){ + invisible(gc()) + assigned <- assignments(assignment) if (ncol(assigned) == 0){ From e545017a4e4fd9c8c1ac4c895693fd305f94180a Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Tue, 21 Feb 2023 12:23:10 +0000 Subject: [PATCH 220/226] update repo location --- .github/workflows/pkgdown.yaml | 33 ++++++++++++++++++++++----------- DESCRIPTION | 8 ++++---- _pkgdown.yml | 2 +- 3 files changed, 27 insertions(+), 16 deletions(-) diff --git a/.github/workflows/pkgdown.yaml b/.github/workflows/pkgdown.yaml index 63cbb18..087f0b0 100644 --- a/.github/workflows/pkgdown.yaml +++ b/.github/workflows/pkgdown.yaml @@ -1,8 +1,10 @@ -# Workflow derived from https://github.com/r-lib/actions/tree/master/examples +# Workflow derived from https://github.com/r-lib/actions/tree/v2/examples # Need help debugging build failures? Start at https://github.com/r-lib/actions#where-to-find-help on: push: branches: [main, master] + pull_request: + branches: [main, master] release: types: [published] workflow_dispatch: @@ -12,24 +14,33 @@ name: pkgdown jobs: pkgdown: runs-on: ubuntu-latest + # Only restrict concurrency for non-PR jobs + concurrency: + group: pkgdown-${{ github.event_name != 'pull_request' || github.run_id }} env: GITHUB_PAT: ${{ secrets.GITHUB_TOKEN }} steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v3 - - uses: r-lib/actions/setup-pandoc@v1 + - uses: r-lib/actions/setup-pandoc@v2 - - uses: r-lib/actions/setup-r@v1 + - uses: r-lib/actions/setup-r@v2 with: use-public-rspm: true - - uses: r-lib/actions/setup-r-dependencies@v1 + - uses: r-lib/actions/setup-r-dependencies@v2 with: - extra-packages: pkgdown + extra-packages: any::pkgdown, local::. needs: website - - name: Deploy package - run: | - git config --local user.name "$GITHUB_ACTOR" - git config --local user.email "$GITHUB_ACTOR@users.noreply.github.com" - Rscript -e 'pkgdown::deploy_to_branch(new_process = FALSE)' + - name: Build site + run: pkgdown::build_site_github_pages(new_process = FALSE, install = FALSE) + shell: Rscript {0} + + - name: Deploy to GitHub pages 🚀 + if: github.event_name != 'pull_request' + uses: JamesIves/github-pages-deploy-action@v4.4.1 + with: + clean: false + branch: gh-pages + folder: docs diff --git a/DESCRIPTION b/DESCRIPTION index 8af8e2d..6704fa2 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -2,7 +2,7 @@ Package: assignments Title: Molecular Formula Assignment For High Resolution ESI-MS Based Metabolomics Data Version: 1.0.0 Authors@R: person("Jasen", "Finch", email = "jsf9@aber.ac.uk", role = c("aut", "cre")) -Description: A molecular formula assignment approach for high resolution electrospray ionisation mass spectrometry based metabolomics data. +Description: A molecular formula assignment approach for electrospray ionisation high resolution mass spectrometry based metabolomics data. Depends: R (>= 3.5.0), Imports: cli, crayon, @@ -44,7 +44,7 @@ Suggests: patchwork, knitr, rmarkdown -Remotes: jasenfinch/mzAnnotation@devel, - jasenfinch/metabolyseR@devel -URL: https://jasenfinch.github.io/assignments/ +Remotes: aberHRML/mzAnnotation, + jasenfinch/metabolyseR +URL: https://aberhrml.github.io/assignments/ VignetteBuilder: knitr diff --git a/_pkgdown.yml b/_pkgdown.yml index 4737d62..3ada4f4 100644 --- a/_pkgdown.yml +++ b/_pkgdown.yml @@ -1,4 +1,4 @@ -url: https://jasenfinch.github.io/assignments/ +url: https://aberhrml.github.io/assignments/ template: bootstrap: 5 From 708f8cbfe77cddaa4c8dedc56aef46dc9f7c5fef Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Tue, 21 Feb 2023 12:23:30 +0000 Subject: [PATCH 221/226] Update repo location and add package overview --- README.md | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index dddd9a9..6008486 100644 --- a/README.md +++ b/README.md @@ -2,31 +2,34 @@ [![Lifecycle: stable](https://img.shields.io/badge/lifecycle-stable-brightgreen.svg)](https://lifecycle.r-lib.org/articles/stages.html#stable) -[![R-CMD-check](https://github.com/jasenfinch/MFassign/actions/workflows/R-CMD-check.yaml/badge.svg)](https://github.com/jasenfinch/MFassign/actions/workflows/R-CMD-check.yaml) -[![Coverage Status](https://img.shields.io/codecov/c/github/jasenfinch/MFassign/master.svg)](https://codecov.io/github/jasenfinch/MFassign?branch=master) -[![license](https://img.shields.io/badge/license-GNU%20GPL%20v3.0-blue.svg)](https://github.com/jasenfinch/MFassign/blob/master/DESCRIPTION) +[![R-CMD-check](https://github.com/aberHRML/assignments/actions/workflows/R-CMD-check.yaml/badge.svg)](https://github.com/aberHRML/assignments/actions/workflows/R-CMD-check.yaml) +[![Coverage Status](https://img.shields.io/codecov/c/github/aberHRML/assignments/master.svg)](https://codecov.io/github/aberHRML/assignments?branch=master) +[![license](https://img.shields.io/badge/license-GNU%20GPL%20v3.0-blue.svg)](https://github.com/aberHRML/assignments/blob/master/DESCRIPTION) +[![GitHub release](https://img.shields.io/github/release/aberHRML/assignments.svg)](https://GitHub.com/aberHRML/assignments/releases/) -> An R package for molecular formula assignment of high resolution ESI-MS based metabolomics data +> An R package for automated molecular formula assignment of ultra-high resolution ESI-MS based metabolomics data ### Overview +This R package provides an automated molecular formula assignment approach for electrospray ionisation ultra-high resolution mass spectrometry (ESI-HRMS) metabolomics data. This includes data from direct and flow injection/infustion (FIE-HRMS) fingerprinting as well as liquid chromatography mass spectrometry (LC-HRMS) profiling. The approach includes correlation analysis, relationship calculation, molecular formula generation and selection and graphical component selection based on adducts, isotopes and transformations. + ### Installation The `assignments` package can be installed from GitHub using the following: ``` r -remotes::install_github('jasenfinch/assignments') +remotes::install_github('aberHRML/assignments') ``` ### Learn more The package documentation can be browsed online at -. +. If this is your first time using `assignments` see the -[vignette](https://jasenfinch.github.io/metabolyseR/articles/assignments.html) for information on how to get started. +[vignette](https://aberhrml.github.io/assignments/articles/assignments.html) for information on how to get started. If you believe you’ve found a bug in `assignments`, please file a bug (and, if possible, a [reproducible example](https://reprex.tidyverse.org)) at -. +. From 84916716cc39d85b4e45e18aab17af1a5984f519 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Tue, 21 Feb 2023 12:28:17 +0000 Subject: [PATCH 222/226] update documentation --- DESCRIPTION | 2 +- man/assignedData.Rd | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/DESCRIPTION b/DESCRIPTION index 6704fa2..4a5c4f3 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -25,7 +25,7 @@ License: GPL (>= 3) Encoding: UTF-8 LazyData: true Roxygen: list(markdown = TRUE) -RoxygenNote: 7.2.1 +RoxygenNote: 7.2.3 Collate: parameters.R assignment.R correlations.R addIsoAssign.R transformationAssign.R relationships.R graph.R assign.R internals.R components.R diff --git a/man/assignedData.Rd b/man/assignedData.Rd index faa4015..72305c1 100644 --- a/man/assignedData.Rd +++ b/man/assignedData.Rd @@ -23,8 +23,8 @@ Return data table used for assignments with feature assignments added to column plan(future::sequential) p <- assignmentParameters('FIE-HRMS') -assignment <- assignMFs(feature_data,p) +mf_assignments <- assignMFs(feature_data,p) -assignedData(assignment) +assignedData(mf_assignments) } } From db000182c74a71bf5d89a02a185fc8f55f86ee95 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Tue, 21 Feb 2023 12:43:07 +0000 Subject: [PATCH 223/226] vignette corrections --- vignettes/assignments.Rmd | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/vignettes/assignments.Rmd b/vignettes/assignments.Rmd index 7c038e3..0deb96d 100644 --- a/vignettes/assignments.Rmd +++ b/vignettes/assignments.Rmd @@ -1,6 +1,8 @@ --- title: "assignments" -output: rmarkdown::html_vignette +output: + rmarkdown::html_vignette: + toc: true vignette: > %\VignetteIndexEntry{assignments} %\VignetteEngine{knitr::rmarkdown} @@ -17,7 +19,7 @@ knitr::opts_chunk$set( ## Introduction -The *assignments* package provides an automated molecular formula assignment approach for high resolution electrospray ionisation mass spectrometry (ESI-MS) data from metabolomics experiments. +The *assignments* package provides an automated molecular formula assignment approach for ultra-high resolution electrospray ionisation mass spectrometry (ESI-MS) data from metabolomics experiments. This includes data from both direct and flow injection/infusion fingerprinting as well as liquid chromatograph mass spectrometry (LC-MS) profiling analytical techniques. This vignette will provide a brief overview of the input data required, parameter selection, performing the assignments and assessing the results. @@ -201,7 +203,7 @@ plotFeatureComponents( ) ``` -Because a molecular ranking threshold is applied during assignment, it may also be useful to generate all the alternative molecular formulas and their rankings for a specific *m/z*, adduct and isotope using the `ipMF` function from the *mzAnnotation* package. +Because a molecular formula ranking threshold is applied during assignment, it may also be useful to generate all the alternative molecular formulas and their rankings for a specific *m/z*, adduct and isotope using the `ipMF` function from the [*mzAnnotation*](https://aberhrml.github.io/mzAnnotation/) package. ```{r alternative-mfs} mzAnnotation::ipMF(191.01962, From a94ed26a0fbe0d8f1922c7baf33bc60f92d54799 Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Tue, 21 Feb 2023 14:31:08 +0000 Subject: [PATCH 224/226] documentation improvements --- R/assign.R | 14 +++- R/assignment.R | 88 ++++++++++------------ R/correlations.R | 6 +- R/feature_data.R | 4 +- R/graph.R | 25 +++++-- R/parameters.R | 49 ++++++++----- R/plotAdductDist.R | 7 +- R/plotSpectrum.R | 9 +-- R/plot_components.R | 48 +++++++----- _pkgdown.yml | 38 ++++++++++ man/Assignment-class.Rd | 18 ++--- man/AssignmentParameters-class.Rd | 24 +++--- man/accessors.Rd | 53 +++++++++++--- man/assign.Rd | 14 +++- man/assignedData.Rd | 30 -------- man/assignment-methods.Rd | 6 +- man/assignment.Rd | 1 + man/assignmentParameters.Rd | 8 +- man/availableTechniques.Rd | 4 +- man/edges.Rd | 14 ---- man/feature_data.Rd | 4 +- man/graph.Rd | 34 +++++++++ man/nodes.Rd | 14 ---- man/parameters.Rd | 20 ++++- man/plotAdductDist.Rd | 17 ----- man/plotComponent.Rd | 59 --------------- man/plotFeatureComponents.Rd | 45 ------------ man/plotSpectrum.Rd | 19 ----- man/plotting.Rd | 117 ++++++++++++++++++++++++++++++ man/summariseAssignments.Rd | 30 -------- 30 files changed, 432 insertions(+), 387 deletions(-) delete mode 100644 man/assignedData.Rd delete mode 100644 man/edges.Rd create mode 100644 man/graph.Rd delete mode 100644 man/nodes.Rd delete mode 100644 man/plotAdductDist.Rd delete mode 100644 man/plotComponent.Rd delete mode 100644 man/plotFeatureComponents.Rd delete mode 100644 man/plotSpectrum.Rd create mode 100644 man/plotting.Rd delete mode 100644 man/summariseAssignments.Rd diff --git a/R/assign.R b/R/assign.R index 8ee405e..9f88ea6 100644 --- a/R/assign.R +++ b/R/assign.R @@ -1,13 +1,19 @@ -#' Assign molecular formulas +#' Perform molecular formula assignment #' @rdname assign -#' @description assign molecular formulas to a set of given m/z. +#' @description Perform automated molecular formula assignment. #' @param feature_data a tibble or an object of S4 class `AnalysisData` or `Analysis` containing the feature intensity matrix of m/z for which to assign molecular formulas. See details. #' @param parameters an S4 object of class `AssignmentParamters` containing the parameters for molecular formula assignment #' @param verbose should progress output be printed to the console -#' @param type `pre-treated` or `raw` data on which to perform assignment when argument `feature_data` is of class `Analysis` +#' @param type `pre-treated` or `raw` data on which to perform assignment when argument `feature_data` is of S4 class `Analysis` #' @param ... arguments to pass to the relevant method #' @details -#' If argument `feature_data` is specified as a tibble, this should be a feature intensity matrix where the columns are the `m/z` features to assign and the rows are the individual observations, with the cells as abundance values. +#' If argument `feature_data` is specified as a tibble, this should be a feature intensity matrix where +#' the columns are the `m/z` features to assign and the rows are the individual observations, with the +#' cells as abundance values. he m/z features provided as column names should be in the form of +#' @. Ionisation mode should be given as a prefix n or p for negative +#' or positive ionisation modes respectively. Feature m/z should be provided to an accuracy of least 5 decimal +#' places. The retention time portion (@) is only required for LC-MS data and should be provided +#' in minutes. #' @importFrom tibble tibble #' @importFrom stringr str_split_fixed #' @importFrom cli console_width diff --git a/R/assignment.R b/R/assignment.R index 7277f39..b986106 100644 --- a/R/assignment.R +++ b/R/assignment.R @@ -1,14 +1,13 @@ #' Assignment #' @rdname Assignment-class -#' @description An S4 class to store assignment results -#' @slot log list containing assignment logs -#' @slot flags character vector containing completed assignment elements -#' @slot data A tibble containing the peak intensity matrix -#' @slot correlations A tibble containing the correlations -#' @slot relationships A tibble containing the predicted relationships -#' @slot addIsoAssign A list containing the results of the adduct and isotope assignment -#' @slot transAssign A list containing the results of the transformation assignment -#' @slot assignments A tibble containing the assigned molecular formulas +#' @description An S4 class to store molecular formula assignment results. +#' @slot log a list containing assignment logs +#' @slot data a tibble containing the *m/z* peak intensity matrix +#' @slot correlations a tibble containing the correlations analysis results +#' @slot relationships a tibble containing the calculated mathematical relationships +#' @slot addIsoAssign a list containing the results of the adduct and isotope assignment iterations +#' @slot transAssign a list containing the results of the transformation assignment iterationst +#' @slot assignments a tibble containing the assigned molecular formulas setClass('Assignment', contains = 'AssignmentParameters', @@ -88,15 +87,30 @@ setMethod('show',signature = 'Assignment', #' Assignment accessors #' @rdname accessors -#' @description Access methods for Assignment S4 class +#' @description Access methods for `Assignment` S4 class #' @param assignment S4 object of class Assignment #' @param iteration the assignment iteration #' @param type the graph type to return. `filtered` returns the assignment graph after component selection. `all` returns all assignment components. #' @param component component number to extract #' @param feature feature information to extract +#' @details +#' * `featureData` - Return the initially specifed *m/z* feature data. +#' * `correlations` - Return the correlation analysis results. +#' * `relationships` - Return the calculated relationships. +#' * `iterations` - Return the assignment iteration performed. +#' * `graph` - Return a selected graph. +#' * `components` - Return the component information for an assignment iteration. +#' * `featureComponents` - Return the component information for a selected feature. +#' * `component` - Extract a component graph. +#' * `assignments` - Return the molecular formulas assigned to the *m/z* features. +#' * `assignedData` - Return the *m/z* peak intensity matrix with the molecular formula assignments included in the column names. +#' * `summariseAssignments` - Return a tibble of the assignments summarised by molecular formula. +#' @return A tibble or `tbl_graph` containing assignment results depending on the method used. #' @examples -#' mf_assignments <- new('Assignment', -#' data = feature_data) +#' plan(future::sequential) +#' p <- assignmentParameters('FIE-HRMS') +#' +#' mf_assignments <- assignMFs(feature_data,p) #' #' ## Return feature data #' featureData(mf_assignments) @@ -111,27 +125,26 @@ setMethod('show',signature = 'Assignment', #' iterations(mf_assignments) #' #' ## Return a selected graph -#' \dontrun{ #' graph(mf_assignments,'A&I1') -#' } #' #' ## Return a component information for a selected graph -#' \dontrun{ #' components(mf_assignments,'A&I1') -#' } #' #' ## Return a component information for a selected feature -#' \dontrun{ #' featureComponents(mf_assignments,'n191.01962') -#' } #' #' ## Extract a component graph -#' \dontrun{ #' component(mf_assignments,1,'A&I1') -#' } #' #' ## Return assignments #' assignments(mf_assignments) +#' +#' ## Return an m/z intensity matrix with the assignments included +#' ## in the column names +#' assignedData(mf_assignments) +#' +#' ## Return the assignments summarised by molecular formula +#' summariseAssignments(mf_assignments) #' @export setGeneric('featureData',function(assignment) @@ -322,26 +335,13 @@ setMethod('assignments',signature = 'Assignment', assignment@assignments }) -#' assignedData -#' @rdname assignedData -#' @description Return data table used for assignments with feature assignments added to column names. -#' @param assignment S4 object of class Assignment -#' @return A tibble containing the original feature data with molecular formula assignments added to teh column names. -#' @examples -#' \dontrun{ -#' plan(future::sequential) -#' p <- assignmentParameters('FIE-HRMS') -#' -#' mf_assignments <- assignMFs(feature_data,p) -#' -#' assignedData(mf_assignments) -#' } +#' @rdname accessors #' @export setGeneric('assignedData',function(assignment) standardGeneric('assignedData')) -#' @rdname assignedData +#' @rdname accessors setMethod('assignedData', signature = 'Assignment', function(assignment){ @@ -368,27 +368,14 @@ setMethod('assignedData', signature = 'Assignment', return(d) }) -#' Summarise assignments -#' @rdname summariseAssignments -#' @description Summarise features assigned to molecular formulas. -#' @param assignment S4 object of class Assignment -#' @return A tibble containing the feature assignments summarised by molecular formula. -#' @examples -#' \dontrun{ -#' plan(future::sequential) -#' p <- assignmentParameters('FIE-HRMS') -#' -#' mf_assignments <- assignMFs(feature_data,p) -#' -#' summariseAssignments(mf_assignments) -#' } +#' @rdname accessors #' @importFrom dplyr desc #' @export setGeneric('summariseAssignments',function(assignment) standardGeneric('summariseAssignments')) -#' @rdname summariseAssignments +#' @rdname accessors setMethod('summariseAssignments',signature = 'Assignment', function(assignment){ @@ -418,6 +405,7 @@ setMethod('summariseAssignments',signature = 'Assignment', #' @return An object of S4 class `Assignment`. #' @examples #' mf_assignments <- assignment(feature_data,assignmentParameters('FIE-HRMS')) +#' mf_assignments #' @export setGeneric('assignment',function(feature_data,parameters,...) diff --git a/R/correlations.R b/R/correlations.R index c31a9c4..f5ec97e 100644 --- a/R/correlations.R +++ b/R/correlations.R @@ -1,6 +1,6 @@ #' Molecular formula assignment methods #' @rdname assignment-methods -#' @description These methods provide the access to performing the individual steps of the molecular +#' @description These methods provide access to performing the individual steps of the molecular #' formula assignment approach. See Details for more information of when it is best to use these #' instead of `assignMFs()`. #' @param assignment an object of S4 class `Assignment` @@ -13,7 +13,6 @@ #' steps where needed. #' @return An object of S4 class `Assignment` containing molecular formula assignments. #' @examples -#' \dontrun{ #' plan(future::sequential) #' p <- assignmentParameters('FIE-HRMS') #' @@ -24,7 +23,8 @@ #' calcRelationships() %>% #' addIsoAssign() %>% #' transformationAssign() -#' } +#' +#' mf_assignments #' @export setGeneric('calcCorrelations', function(assignment) diff --git a/R/feature_data.R b/R/feature_data.R index 15ac94f..f17d3b9 100644 --- a/R/feature_data.R +++ b/R/feature_data.R @@ -1,5 +1,5 @@ #' Example feature data -#' @description Example mass spectral feature intensity table. -#' @format A tibble containing 60 rows and 1003 variables. +#' @description An example `m/z` peak intensity matrix containing total ion count normalised positive and negative mode flow infusion electrospray ionisation mass spectrometry *m/z* features. +#' @format A tibble containing 60 rows and 10 variables. 'feature_data' \ No newline at end of file diff --git a/R/graph.R b/R/graph.R index 40829fb..7a24709 100644 --- a/R/graph.R +++ b/R/graph.R @@ -1,6 +1,23 @@ -#' nodes -#' @description extract node table from tbl_graph object. +#' Extract graph attributes +#' @rdname graph +#' @description Extract node or edge attributes from a *tidygraph* `tbl_graph` object. #' @param graph object of class tbl_graph +#' @examples +#' a_graph <- tidygraph::tbl_graph( +#' nodes = data.frame( +#' name = c('a','b','c') +#' ), +#' edges = data.frame( +#' from = c(1,2), +#' to = c(2,3), +#' type = c(1,2) +#' )) +#' +#' ## Extract graph nodes +#' nodes(a_graph) +#' +#' ## Extract graph edges +#' edges(a_graph) #' @importFrom tibble as_tibble #' @export @@ -10,9 +27,7 @@ nodes <- function(graph){ as_tibble() } -#' edges -#' @description extract edge table from tbl_graph object. -#' @param graph object of class tbl_graph +#' @rdname graph #' @importFrom igraph edge.attributes #' @export diff --git a/R/parameters.R b/R/parameters.R index 5ac7303..fb86832 100644 --- a/R/parameters.R +++ b/R/parameters.R @@ -1,19 +1,19 @@ #' S4 class for assignment parameters #' @rdname AssignmentParameters-class #' @description An S4 class to store assignment parameters. -#' @slot technique assignment technique to use -#' @slot correlations_parameters list of correlation parameters to be passed to `metabolyseR::correlation()` -#' @slot max_M maximum M for which to assign molecular formulas +#' @slot technique the analytical technique +#' @slot correlations_parameters a list of correlation parameters to be passed to `metabolyseR::correlations()` +#' @slot max_M the maximum molecular mass for which to assign molecular formulas #' @slot MF_rank_threshold rank threshold for molecular formula selection -#' @slot ppm ppm threshold -#' @slot limit amu deviation limit for relationship prediction -#' @slot RT_diff_limit limit for retention time differences for correlated features in adduct and isotopic assignment -#' @slot adducts list of character vectors containing the adducts to use. List element names should denote ionisation mode. The order that these adducts are provided denotes their expected relative importance to assignments with the first expected to be the most common and the last the least common within each ionisation mode. -#' @slot isotopes character vector of isotopes to use. Similarly to the adducts, their order denotes the expected commonality in the data. -#' @slot transformations character vector of transformations to use -#' @slot adduct_rules tibble containing adduct formation rules as returned by `mzAnnotation::adducts()` -#' @slot isotope_rules tibble containing isotope rules as returned by `mzAnnotation::isotopes()` -#' @slot transformation_rules tibble containing transformation rules as returned by `mzAnnotation::transformations()` +#' @slot ppm the parts per million error threshold +#' @slot limit the atomic mass unit deviation limit for relationship calculation +#' @slot RT_diff_limit the limit for retention time differences for correlated features in adduct and isotopic assignment +#' @slot adducts a list of character vectors containing the adducts names. List element names should denote ionisation mode. The order that these adducts are provided denotes their expected relative importance to assignments with the first expected to be the most common and the last the least common within each ionisation mode. +#' @slot isotopes a character vector of isotopes to use. Similarly to the adducts, their order denotes the expected commonality in the data. +#' @slot transformations a character vector of transformations molecular formula changes +#' @slot adduct_rules a tibble containing the adduct formation rules as returned by `mzAnnotation::adduct_rules()` +#' @slot isotope_rules a tibble containing the isotope rules as returned by `mzAnnotation::isotope_rules()` +#' @slot transformation_rules tibble containing the transformation rules as returned by `mzAnnotation::transformation_rules()` #' @importFrom mzAnnotation adduct_rules isotope_rules transformation_rules setClass('AssignmentParameters', @@ -125,11 +125,24 @@ setMethod('show',signature = 'AssignmentParameters', #' @rdname parameters #' @description Get and set methods for the `AssignmentParameters` S4 class. #' @param x S4 object of class `AssignmentParameters` -#' @param value value to set +#' @param value the value to set +#' @details +#' * `technique` - Get the analytical technique. +#' * `correlationsParameters` - Get or set the correlation analysis parameters to be passed to `metabolyseR::correlations()`. +#' * `limit` - Get or set the atomic mass unit limit for relationship calculation. +#' * `maxM` - Get or set the maximum molecular mass limit for which to assign molecular formulas. +#' * `MFrankThreshold` - Get or set the molecular formula rank threshold for molecular formula selection. +#' * `ppm` - Get or set the parts per million error threshold. +#' * `isotopes` - Get or set the isotope names. The order in which these are specified denotes the expected relative commonality within the data set. +#' * `adducts` - Get or set the adduct names for the ionisation modes. The order in which these are specified denotes the expected relative commonality within the data set for each ionisation mode. +#' * `transformations` - Get or set the transformation molecular formula changes. +#' * `isotopeRules` - Get or set the isotope rules table. The format of this tibble should match that of `mzAnnotation::isotope_rules()`. +#' * `adductRules` - Get or set the adduct rules table. The format of this tibble should match that of `mzAnnotation::adduct_rules()`. +#' * `techniqueRules` - Get or set the transformation rules table. The format of this tibble should match that of `mzAnnotation::transformation_rules()`. #' @examples #' assignment_parameters <- assignmentParameters('FIE') #' -#' ## Return technique +#' ## Return the analytical technique #' technique(assignment_parameters) #' #' ## Return correlations parameters @@ -507,8 +520,8 @@ setMethod('transformationRules<-',signature = 'AssignmentParameters', return(x) }) -#' Available techniques -#' @description Available techniques for molecular formula assignment. +#' Available analytical techniques +#' @description The available analytical techniques for molecular formula assignment parameters. #' @return A `character` vector of technique names. #' @examples #' availableTechniques() @@ -519,8 +532,10 @@ availableTechniques <- function(){ } #' Assignment parameters -#' @description Return default assignment parameters for a given technique. +#' @description Return the default molecular formula assignment parameters for a given analytical technique. #' @param technique technique to use for assignment +#' @return An object of S4 class `AssignmentParameters` +#' @examples assignmentParameters('FIE-HRMS') #' @importFrom methods new #' @export diff --git a/R/plotAdductDist.R b/R/plotAdductDist.R index 6d4e889..9ef01fa 100644 --- a/R/plotAdductDist.R +++ b/R/plotAdductDist.R @@ -24,10 +24,7 @@ plotDist <- function(x){ strip.text = ggplot2::element_text(face = 'bold')) } -#' Plot adduct frequency distributions -#' @rdname plotAdductDist -#' @description Plot adduct frequency distributions. -#' @param assignment S4 object of class Assignment +#' @rdname plotting #' @importFrom tidyr replace_na #' @export @@ -35,7 +32,7 @@ setGeneric('plotAdductDist',function(assignment){ standardGeneric('plotAdductDist') }) -#' @rdname plotAdductDist +#' @rdname plotting #' @importFrom rlang check_installed setMethod('plotAdductDist',signature = 'Assignment', diff --git a/R/plotSpectrum.R b/R/plotSpectrum.R index 7243b0b..e993fc4 100644 --- a/R/plotSpectrum.R +++ b/R/plotSpectrum.R @@ -19,6 +19,7 @@ spectrumPlot <- function(dat,MF){ y = `Relative Abundance`, label = Label)) + ggplot2::theme_bw() + + ggplot2::scale_y_continuous(expand = c(0,0)) + ggplot2::theme(panel.border = ggplot2::element_blank(), panel.grid = ggplot2::element_blank(), axis.line = ggplot2::element_line(), @@ -32,11 +33,7 @@ spectrumPlot <- function(dat,MF){ ggplot2::facet_wrap(~Mode,scales = 'free') } -#' plotSpectrum -#' @rdname plotSpectrum -#' @description Plot a spectrum for a given molecular formula -#' @param assignment S4 object of class Assignment -#' @param MF molecular formula +#' @rdname plotting #' @importFrom tidyr gather #' @importFrom dplyr group_by summarise #' @export @@ -44,7 +41,7 @@ spectrumPlot <- function(dat,MF){ setGeneric('plotSpectrum',function(assignment,MF) standardGeneric('plotSpectrum')) -#' @rdname plotSpectrum +#' @rdname plotting setMethod('plotSpectrum',signature = 'Assignment',function(assignment,MF){ mf <- MF diff --git a/R/plot_components.R b/R/plot_components.R index fa19299..47e069a 100644 --- a/R/plot_components.R +++ b/R/plot_components.R @@ -66,26 +66,43 @@ plotGraph <- function(graph, ) } -#' Plot a component -#' @rdname plotComponent -#' @description Plot a molecular formula component graph. -#' @param assignment S4 object of class Assignment -#' @param component component number to extract -#' @param iteration the assignment iteration +#' Plot assignment results +#' @rdname plotting +#' @description Plot molecular formula assignment results. +#' @param assignment an object of S4 class Assignment +#' @param feature the *m/z* feature to plot +#' @param MF the assigned molecular formula to plot +#' @param component component number to plot +#' @param iteration the assignment iteration of the component or components #' @param type the graph type to return. `selected` returns the assignment graph after component selection. `all` returns all assignment components. +#' @param max_components themaximum number of components to plot #' @param label_size node label size #' @param axis_offset axis proportion by which to increase axis limits. Prevents cut off of node labels. #' @param border specify a plot border colour #' @param highlight specify a feature node to highlight +#' @details +#' * `plotComponent` - Plot a molecular formula component graph. +#' * `plotFeatureComponents` - Plot the possible component graphs for a given feature. +#' * `plotAdductDist` - Plot frequency distributions of the assigned adducts. +#' * `plotSpectrum` - Plot the spectrum of an assigned molecular formula. #' @examples -#' \dontrun{ +#' library(ggraph) #' plan(future::sequential) #' p <- assignmentParameters('FIE-HRMS') #' #' mf_assignments <- assignMFs(feature_data,p) #' +#' ## Plot a component #' plotComponent(mf_assignments,1,'A&I1') -#' } +#' +#' ## Plot the components for a feature +#' plotFeatureComponents(mf_assignments,'n191.01962','A&I1') +#' +#' ## Plot the adduct distributions +#' plotAdductDist(mf_assignments) +#' +#' ## Plot the spectrum of an assigned molecular formula +#' plotSpectrum(mf_assignments,'C6H8O7') #' @export setGeneric('plotComponent', @@ -100,7 +117,7 @@ setGeneric('plotComponent', standardGeneric('plotComponent')) #' @importFrom dplyr mutate_if -#' @rdname plotComponent +#' @rdname plotting setMethod('plotComponent',signature = 'Assignment', function(assignment, @@ -153,16 +170,7 @@ setMethod('plotComponent',signature = 'Assignment', )) }) -#' Plot the solutions for a feature -#' @rdname plotFeatureComponents -#' @description Plot possible MF solutions for a given feature. -#' @param assignment S4 object of class Assignent -#' @param feature name of feature to plot -#' @param iteration components from which iteration to plot -#' @param type the graph type to return. `all` returns all assignment components. `selected` returns the assignment graph after component selection. -#' @param max_components maximum number of components to plot -#' @param label_size node label size -#' @param axis_offset axis proportion by which to increase axis limits. Prevents cut off of node labels. +#' @rdname plotting #' @export setGeneric('plotFeatureComponents', @@ -176,7 +184,7 @@ setGeneric('plotFeatureComponents', standardGeneric('plotFeatureComponents') ) -#' @rdname plotFeatureComponents +#' @rdname plotting #' @importFrom dplyr slice setMethod('plotFeatureComponents',signature = 'Assignment', diff --git a/_pkgdown.yml b/_pkgdown.yml index 3ada4f4..0433b43 100644 --- a/_pkgdown.yml +++ b/_pkgdown.yml @@ -2,3 +2,41 @@ url: https://aberhrml.github.io/assignments/ template: bootstrap: 5 +reference: + - title: S4 classes + contents: + - Assignment-class + - AssignmentParameters-class + - assignment + + - title: Example data + contents: + - feature_data + + - title: Parameters + contents: + - availableTechniques + - assignmentParameters + - technique + + - title: Assignment + contents: + - assignMFs + - calcCorrelations + + - title: Results + contents: + - featureData + - assignedData + - summariseAssignments + + - title: Plotting + contents: + - plotAdductDist + - plotComponent + - plotFeatureComponents + - plotSpectrum + + - title: Other + contents: + - nodes diff --git a/man/Assignment-class.Rd b/man/Assignment-class.Rd index bb2c107..c7b748b 100644 --- a/man/Assignment-class.Rd +++ b/man/Assignment-class.Rd @@ -5,25 +5,23 @@ \alias{Assignment-class} \title{Assignment} \description{ -An S4 class to store assignment results +An S4 class to store molecular formula assignment results. } \section{Slots}{ \describe{ -\item{\code{log}}{list containing assignment logs} +\item{\code{log}}{a list containing assignment logs} -\item{\code{flags}}{character vector containing completed assignment elements} +\item{\code{data}}{a tibble containing the \emph{m/z} peak intensity matrix} -\item{\code{data}}{A tibble containing the peak intensity matrix} +\item{\code{correlations}}{a tibble containing the correlations analysis results} -\item{\code{correlations}}{A tibble containing the correlations} +\item{\code{relationships}}{a tibble containing the calculated mathematical relationships} -\item{\code{relationships}}{A tibble containing the predicted relationships} +\item{\code{addIsoAssign}}{a list containing the results of the adduct and isotope assignment iterations} -\item{\code{addIsoAssign}}{A list containing the results of the adduct and isotope assignment} +\item{\code{transAssign}}{a list containing the results of the transformation assignment iterationst} -\item{\code{transAssign}}{A list containing the results of the transformation assignment} - -\item{\code{assignments}}{A tibble containing the assigned molecular formulas} +\item{\code{assignments}}{a tibble containing the assigned molecular formulas} }} diff --git a/man/AssignmentParameters-class.Rd b/man/AssignmentParameters-class.Rd index b8d3528..c26b043 100644 --- a/man/AssignmentParameters-class.Rd +++ b/man/AssignmentParameters-class.Rd @@ -10,30 +10,30 @@ An S4 class to store assignment parameters. \section{Slots}{ \describe{ -\item{\code{technique}}{assignment technique to use} +\item{\code{technique}}{the analytical technique} -\item{\code{correlations_parameters}}{list of correlation parameters to be passed to \code{metabolyseR::correlation()}} +\item{\code{correlations_parameters}}{a list of correlation parameters to be passed to \code{metabolyseR::correlations()}} -\item{\code{max_M}}{maximum M for which to assign molecular formulas} +\item{\code{max_M}}{the maximum molecular mass for which to assign molecular formulas} \item{\code{MF_rank_threshold}}{rank threshold for molecular formula selection} -\item{\code{ppm}}{ppm threshold} +\item{\code{ppm}}{the parts per million error threshold} -\item{\code{limit}}{amu deviation limit for relationship prediction} +\item{\code{limit}}{the atomic mass unit deviation limit for relationship calculation} -\item{\code{RT_diff_limit}}{limit for retention time differences for correlated features in adduct and isotopic assignment} +\item{\code{RT_diff_limit}}{the limit for retention time differences for correlated features in adduct and isotopic assignment} -\item{\code{adducts}}{list of character vectors containing the adducts to use. List element names should denote ionisation mode. The order that these adducts are provided denotes their expected relative importance to assignments with the first expected to be the most common and the last the least common within each ionisation mode.} +\item{\code{adducts}}{a list of character vectors containing the adducts names. List element names should denote ionisation mode. The order that these adducts are provided denotes their expected relative importance to assignments with the first expected to be the most common and the last the least common within each ionisation mode.} -\item{\code{isotopes}}{character vector of isotopes to use. Similarly to the adducts, their order denotes the expected commonality in the data.} +\item{\code{isotopes}}{a character vector of isotopes to use. Similarly to the adducts, their order denotes the expected commonality in the data.} -\item{\code{transformations}}{character vector of transformations to use} +\item{\code{transformations}}{a character vector of transformations molecular formula changes} -\item{\code{adduct_rules}}{tibble containing adduct formation rules as returned by \code{mzAnnotation::adducts()}} +\item{\code{adduct_rules}}{a tibble containing the adduct formation rules as returned by \code{mzAnnotation::adduct_rules()}} -\item{\code{isotope_rules}}{tibble containing isotope rules as returned by \code{mzAnnotation::isotopes()}} +\item{\code{isotope_rules}}{a tibble containing the isotope rules as returned by \code{mzAnnotation::isotope_rules()}} -\item{\code{transformation_rules}}{tibble containing transformation rules as returned by \code{mzAnnotation::transformations()}} +\item{\code{transformation_rules}}{tibble containing the transformation rules as returned by \code{mzAnnotation::transformation_rules()}} }} diff --git a/man/accessors.Rd b/man/accessors.Rd index 83e6c5d..8fc5975 100644 --- a/man/accessors.Rd +++ b/man/accessors.Rd @@ -19,6 +19,10 @@ \alias{component,Assignment-method} \alias{assignments} \alias{assignments,Assignment-method} +\alias{assignedData} +\alias{assignedData,Assignment-method} +\alias{summariseAssignments} +\alias{summariseAssignments,Assignment-method} \title{Assignment accessors} \usage{ featureData(assignment) @@ -56,6 +60,14 @@ component(assignment, component, iteration, type = c("selected", "all")) assignments(assignment) \S4method{assignments}{Assignment}(assignment) + +assignedData(assignment) + +\S4method{assignedData}{Assignment}(assignment) + +summariseAssignments(assignment) + +\S4method{summariseAssignments}{Assignment}(assignment) } \arguments{ \item{assignment}{S4 object of class Assignment} @@ -68,12 +80,32 @@ assignments(assignment) \item{component}{component number to extract} } +\value{ +A tibble or \code{tbl_graph} containing assignment results depending on the method used. +} \description{ -Access methods for Assignment S4 class +Access methods for \code{Assignment} S4 class +} +\details{ +\itemize{ +\item \code{featureData} - Return the initially specifed \emph{m/z} feature data. +\item \code{correlations} - Return the correlation analysis results. +\item \code{relationships} - Return the calculated relationships. +\item \code{iterations} - Return the assignment iteration performed. +\item \code{graph} - Return a selected graph. +\item \code{components} - Return the component information for an assignment iteration. +\item \code{featureComponents} - Return the component information for a selected feature. +\item \code{component} - Extract a component graph. +\item \code{assignments} - Return the molecular formulas assigned to the \emph{m/z} features. +\item \code{assignedData} - Return the \emph{m/z} peak intensity matrix with the molecular formula assignments included in the column names. +\item \code{summariseAssignments} - Return a tibble of the assignments summarised by molecular formula. +} } \examples{ -mf_assignments <- new('Assignment', - data = feature_data) +plan(future::sequential) +p <- assignmentParameters('FIE-HRMS') + +mf_assignments <- assignMFs(feature_data,p) ## Return feature data featureData(mf_assignments) @@ -88,25 +120,24 @@ relationships(mf_assignments) iterations(mf_assignments) ## Return a selected graph -\dontrun{ graph(mf_assignments,'A&I1') -} ## Return a component information for a selected graph -\dontrun{ components(mf_assignments,'A&I1') -} ## Return a component information for a selected feature -\dontrun{ featureComponents(mf_assignments,'n191.01962') -} ## Extract a component graph -\dontrun{ component(mf_assignments,1,'A&I1') -} ## Return assignments assignments(mf_assignments) + +## Return an m/z intensity matrix with the assignments included +## in the column names +assignedData(mf_assignments) + +## Return the assignments summarised by molecular formula +summariseAssignments(mf_assignments) } diff --git a/man/assign.Rd b/man/assign.Rd index 0c081b5..332699a 100644 --- a/man/assign.Rd +++ b/man/assign.Rd @@ -5,7 +5,7 @@ \alias{assignMFs,tbl_df-method} \alias{assignMFs,AnalysisData-method} \alias{assignMFs,Analysis-method} -\title{Assign molecular formulas} +\title{Perform molecular formula assignment} \usage{ assignMFs( feature_data, @@ -42,13 +42,19 @@ assignMFs( \item{...}{arguments to pass to the relevant method} -\item{type}{\code{pre-treated} or \code{raw} data on which to perform assignment when argument \code{feature_data} is of class \code{Analysis}} +\item{type}{\code{pre-treated} or \code{raw} data on which to perform assignment when argument \code{feature_data} is of S4 class \code{Analysis}} } \description{ -assign molecular formulas to a set of given m/z. +Perform automated molecular formula assignment. } \details{ -If argument \code{feature_data} is specified as a tibble, this should be a feature intensity matrix where the columns are the \code{m/z} features to assign and the rows are the individual observations, with the cells as abundance values. +If argument \code{feature_data} is specified as a tibble, this should be a feature intensity matrix where +the columns are the \code{m/z} features to assign and the rows are the individual observations, with the +cells as abundance values. he m/z features provided as column names should be in the form of +@. Ionisation mode should be given as a prefix n or p for negative +or positive ionisation modes respectively. Feature m/z should be provided to an accuracy of least 5 decimal +places. The retention time portion (@) is only required for LC-MS data and should be provided +in minutes. } \examples{ plan(future::sequential) diff --git a/man/assignedData.Rd b/man/assignedData.Rd deleted file mode 100644 index 72305c1..0000000 --- a/man/assignedData.Rd +++ /dev/null @@ -1,30 +0,0 @@ -% Generated by roxygen2: do not edit by hand -% Please edit documentation in R/assignment.R -\name{assignedData} -\alias{assignedData} -\alias{assignedData,Assignment-method} -\title{assignedData} -\usage{ -assignedData(assignment) - -\S4method{assignedData}{Assignment}(assignment) -} -\arguments{ -\item{assignment}{S4 object of class Assignment} -} -\value{ -A tibble containing the original feature data with molecular formula assignments added to teh column names. -} -\description{ -Return data table used for assignments with feature assignments added to column names. -} -\examples{ -\dontrun{ -plan(future::sequential) -p <- assignmentParameters('FIE-HRMS') - -mf_assignments <- assignMFs(feature_data,p) - -assignedData(mf_assignments) -} -} diff --git a/man/assignment-methods.Rd b/man/assignment-methods.Rd index a8aa0b1..d1af259 100644 --- a/man/assignment-methods.Rd +++ b/man/assignment-methods.Rd @@ -35,7 +35,7 @@ calcRelationships(assignment) An object of S4 class \code{Assignment} containing molecular formula assignments. } \description{ -These methods provide the access to performing the individual steps of the molecular +These methods provide access to performing the individual steps of the molecular formula assignment approach. See Details for more information of when it is best to use these instead of \code{assignMFs()}. } @@ -48,7 +48,6 @@ and also enable the possibility of objects to be saved and/or unloaded between t steps where needed. } \examples{ -\dontrun{ plan(future::sequential) p <- assignmentParameters('FIE-HRMS') @@ -59,5 +58,6 @@ mf_assignments <- mf_assignments \%>\% calcRelationships() \%>\% addIsoAssign() \%>\% transformationAssign() -} + +mf_assignments } diff --git a/man/assignment.Rd b/man/assignment.Rd index 2d8d9a9..020dbe5 100644 --- a/man/assignment.Rd +++ b/man/assignment.Rd @@ -32,4 +32,5 @@ Constructor methods for creating an object of S4 class \code{Assignment}. } \examples{ mf_assignments <- assignment(feature_data,assignmentParameters('FIE-HRMS')) +mf_assignments } diff --git a/man/assignmentParameters.Rd b/man/assignmentParameters.Rd index ec1cd3a..203bb03 100644 --- a/man/assignmentParameters.Rd +++ b/man/assignmentParameters.Rd @@ -9,6 +9,12 @@ assignmentParameters(technique = availableTechniques()) \arguments{ \item{technique}{technique to use for assignment} } +\value{ +An object of S4 class \code{AssignmentParameters} +} \description{ -Return default assignment parameters for a given technique. +Return the default molecular formula assignment parameters for a given analytical technique. +} +\examples{ +assignmentParameters('FIE-HRMS') } diff --git a/man/availableTechniques.Rd b/man/availableTechniques.Rd index 8774430..abde02b 100644 --- a/man/availableTechniques.Rd +++ b/man/availableTechniques.Rd @@ -2,7 +2,7 @@ % Please edit documentation in R/parameters.R \name{availableTechniques} \alias{availableTechniques} -\title{Available techniques} +\title{Available analytical techniques} \usage{ availableTechniques() } @@ -10,7 +10,7 @@ availableTechniques() A \code{character} vector of technique names. } \description{ -Available techniques for molecular formula assignment. +The available analytical techniques for molecular formula assignment parameters. } \examples{ availableTechniques() diff --git a/man/edges.Rd b/man/edges.Rd deleted file mode 100644 index c64b073..0000000 --- a/man/edges.Rd +++ /dev/null @@ -1,14 +0,0 @@ -% Generated by roxygen2: do not edit by hand -% Please edit documentation in R/graph.R -\name{edges} -\alias{edges} -\title{edges} -\usage{ -edges(graph) -} -\arguments{ -\item{graph}{object of class tbl_graph} -} -\description{ -extract edge table from tbl_graph object. -} diff --git a/man/feature_data.Rd b/man/feature_data.Rd index d0d8326..6d099d7 100644 --- a/man/feature_data.Rd +++ b/man/feature_data.Rd @@ -5,12 +5,12 @@ \alias{feature_data} \title{Example feature data} \format{ -A tibble containing 60 rows and 1003 variables. +A tibble containing 60 rows and 10 variables. } \usage{ feature_data } \description{ -Example mass spectral feature intensity table. +An example \code{m/z} peak intensity matrix containing total ion count normalised positive and negative mode flow infusion electrospray ionisation mass spectrometry \emph{m/z} features. } \keyword{datasets} diff --git a/man/graph.Rd b/man/graph.Rd new file mode 100644 index 0000000..59b6f0f --- /dev/null +++ b/man/graph.Rd @@ -0,0 +1,34 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/graph.R +\name{nodes} +\alias{nodes} +\alias{edges} +\title{Extract graph attributes} +\usage{ +nodes(graph) + +edges(graph) +} +\arguments{ +\item{graph}{object of class tbl_graph} +} +\description{ +Extract node or edge attributes from a \emph{tidygraph} \code{tbl_graph} object. +} +\examples{ +a_graph <- tidygraph::tbl_graph( + nodes = data.frame( + name = c('a','b','c') + ), + edges = data.frame( + from = c(1,2), + to = c(2,3), + type = c(1,2) + )) + +## Extract graph nodes +nodes(a_graph) + +## Extract graph edges +edges(a_graph) +} diff --git a/man/nodes.Rd b/man/nodes.Rd deleted file mode 100644 index 94cdb6f..0000000 --- a/man/nodes.Rd +++ /dev/null @@ -1,14 +0,0 @@ -% Generated by roxygen2: do not edit by hand -% Please edit documentation in R/graph.R -\name{nodes} -\alias{nodes} -\title{nodes} -\usage{ -nodes(graph) -} -\arguments{ -\item{graph}{object of class tbl_graph} -} -\description{ -extract node table from tbl_graph object. -} diff --git a/man/parameters.Rd b/man/parameters.Rd index 0e98529..ce0cf55 100644 --- a/man/parameters.Rd +++ b/man/parameters.Rd @@ -144,15 +144,31 @@ transformationRules(x) <- value \arguments{ \item{x}{S4 object of class \code{AssignmentParameters}} -\item{value}{value to set} +\item{value}{the value to set} } \description{ Get and set methods for the \code{AssignmentParameters} S4 class. } +\details{ +\itemize{ +\item \code{technique} - Get the analytical technique. +\item \code{correlationsParameters} - Get or set the correlation analysis parameters to be passed to \code{metabolyseR::correlations()}. +\item \code{limit} - Get or set the atomic mass unit limit for relationship calculation. +\item \code{maxM} - Get or set the maximum molecular mass limit for which to assign molecular formulas. +\item \code{MFrankThreshold} - Get or set the molecular formula rank threshold for molecular formula selection. +\item \code{ppm} - Get or set the parts per million error threshold. +\item \code{isotopes} - Get or set the isotope names. The order in which these are specified denotes the expected relative commonality within the data set. +\item \code{adducts} - Get or set the adduct names for the ionisation modes. The order in which these are specified denotes the expected relative commonality within the data set for each ionisation mode. +\item \code{transformations} - Get or set the transformation molecular formula changes. +\item \code{isotopeRules} - Get or set the isotope rules table. The format of this tibble should match that of \code{mzAnnotation::isotope_rules()}. +\item \code{adductRules} - Get or set the adduct rules table. The format of this tibble should match that of \code{mzAnnotation::adduct_rules()}. +\item \code{techniqueRules} - Get or set the transformation rules table. The format of this tibble should match that of \code{mzAnnotation::transformation_rules()}. +} +} \examples{ assignment_parameters <- assignmentParameters('FIE') -## Return technique +## Return the analytical technique technique(assignment_parameters) ## Return correlations parameters diff --git a/man/plotAdductDist.Rd b/man/plotAdductDist.Rd deleted file mode 100644 index 193757d..0000000 --- a/man/plotAdductDist.Rd +++ /dev/null @@ -1,17 +0,0 @@ -% Generated by roxygen2: do not edit by hand -% Please edit documentation in R/plotAdductDist.R -\name{plotAdductDist} -\alias{plotAdductDist} -\alias{plotAdductDist,Assignment-method} -\title{Plot adduct frequency distributions} -\usage{ -plotAdductDist(assignment) - -\S4method{plotAdductDist}{Assignment}(assignment) -} -\arguments{ -\item{assignment}{S4 object of class Assignment} -} -\description{ -Plot adduct frequency distributions. -} diff --git a/man/plotComponent.Rd b/man/plotComponent.Rd deleted file mode 100644 index 4edc09f..0000000 --- a/man/plotComponent.Rd +++ /dev/null @@ -1,59 +0,0 @@ -% Generated by roxygen2: do not edit by hand -% Please edit documentation in R/plot_components.R -\name{plotComponent} -\alias{plotComponent} -\alias{plotComponent,Assignment-method} -\title{Plot a component} -\usage{ -plotComponent( - assignment, - component, - iteration, - type = c("selected", "all"), - label_size = 3, - axis_offset = 0.1, - border = NA, - highlight = NA -) - -\S4method{plotComponent}{Assignment}( - assignment, - component, - iteration, - type = c("selected", "all"), - label_size = 3, - axis_offset = 0.1, - border = NA, - highlight = NA -) -} -\arguments{ -\item{assignment}{S4 object of class Assignment} - -\item{component}{component number to extract} - -\item{iteration}{the assignment iteration} - -\item{type}{the graph type to return. \code{selected} returns the assignment graph after component selection. \code{all} returns all assignment components.} - -\item{label_size}{node label size} - -\item{axis_offset}{axis proportion by which to increase axis limits. Prevents cut off of node labels.} - -\item{border}{specify a plot border colour} - -\item{highlight}{specify a feature node to highlight} -} -\description{ -Plot a molecular formula component graph. -} -\examples{ -\dontrun{ -plan(future::sequential) -p <- assignmentParameters('FIE-HRMS') - -mf_assignments <- assignMFs(feature_data,p) - -plotComponent(mf_assignments,1,'A&I1') -} -} diff --git a/man/plotFeatureComponents.Rd b/man/plotFeatureComponents.Rd deleted file mode 100644 index 20377f8..0000000 --- a/man/plotFeatureComponents.Rd +++ /dev/null @@ -1,45 +0,0 @@ -% Generated by roxygen2: do not edit by hand -% Please edit documentation in R/plot_components.R -\name{plotFeatureComponents} -\alias{plotFeatureComponents} -\alias{plotFeatureComponents,Assignment-method} -\title{Plot the solutions for a feature} -\usage{ -plotFeatureComponents( - assignment, - feature, - iteration, - type = c("all", "selected"), - max_components = 6, - label_size = 3, - axis_offset = 0.1 -) - -\S4method{plotFeatureComponents}{Assignment}( - assignment, - feature, - iteration, - type = c("all", "selected"), - max_components = 6, - label_size = 2, - axis_offset = 0.05 -) -} -\arguments{ -\item{assignment}{S4 object of class Assignent} - -\item{feature}{name of feature to plot} - -\item{iteration}{components from which iteration to plot} - -\item{type}{the graph type to return. \code{all} returns all assignment components. \code{selected} returns the assignment graph after component selection.} - -\item{max_components}{maximum number of components to plot} - -\item{label_size}{node label size} - -\item{axis_offset}{axis proportion by which to increase axis limits. Prevents cut off of node labels.} -} -\description{ -Plot possible MF solutions for a given feature. -} diff --git a/man/plotSpectrum.Rd b/man/plotSpectrum.Rd deleted file mode 100644 index ada1c33..0000000 --- a/man/plotSpectrum.Rd +++ /dev/null @@ -1,19 +0,0 @@ -% Generated by roxygen2: do not edit by hand -% Please edit documentation in R/plotSpectrum.R -\name{plotSpectrum} -\alias{plotSpectrum} -\alias{plotSpectrum,Assignment-method} -\title{plotSpectrum} -\usage{ -plotSpectrum(assignment, MF) - -\S4method{plotSpectrum}{Assignment}(assignment, MF) -} -\arguments{ -\item{assignment}{S4 object of class Assignment} - -\item{MF}{molecular formula} -} -\description{ -Plot a spectrum for a given molecular formula -} diff --git a/man/plotting.Rd b/man/plotting.Rd new file mode 100644 index 0000000..0fb0c95 --- /dev/null +++ b/man/plotting.Rd @@ -0,0 +1,117 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/plotAdductDist.R, R/plot_components.R, +% R/plotSpectrum.R +\name{plotAdductDist} +\alias{plotAdductDist} +\alias{plotAdductDist,Assignment-method} +\alias{plotComponent} +\alias{plotComponent,Assignment-method} +\alias{plotFeatureComponents} +\alias{plotFeatureComponents,Assignment-method} +\alias{plotSpectrum} +\alias{plotSpectrum,Assignment-method} +\title{Plot assignment results} +\usage{ +plotAdductDist(assignment) + +\S4method{plotAdductDist}{Assignment}(assignment) + +plotComponent( + assignment, + component, + iteration, + type = c("selected", "all"), + label_size = 3, + axis_offset = 0.1, + border = NA, + highlight = NA +) + +\S4method{plotComponent}{Assignment}( + assignment, + component, + iteration, + type = c("selected", "all"), + label_size = 3, + axis_offset = 0.1, + border = NA, + highlight = NA +) + +plotFeatureComponents( + assignment, + feature, + iteration, + type = c("all", "selected"), + max_components = 6, + label_size = 3, + axis_offset = 0.1 +) + +\S4method{plotFeatureComponents}{Assignment}( + assignment, + feature, + iteration, + type = c("all", "selected"), + max_components = 6, + label_size = 2, + axis_offset = 0.05 +) + +plotSpectrum(assignment, MF) + +\S4method{plotSpectrum}{Assignment}(assignment, MF) +} +\arguments{ +\item{assignment}{an object of S4 class Assignment} + +\item{component}{component number to plot} + +\item{iteration}{the assignment iteration of the component or components} + +\item{type}{the graph type to return. \code{selected} returns the assignment graph after component selection. \code{all} returns all assignment components.} + +\item{label_size}{node label size} + +\item{axis_offset}{axis proportion by which to increase axis limits. Prevents cut off of node labels.} + +\item{border}{specify a plot border colour} + +\item{highlight}{specify a feature node to highlight} + +\item{feature}{the \emph{m/z} feature to plot} + +\item{max_components}{themaximum number of components to plot} + +\item{MF}{the assigned molecular formula to plot} +} +\description{ +Plot molecular formula assignment results. +} +\details{ +\itemize{ +\item \code{plotComponent} - Plot a molecular formula component graph. +\item \code{plotFeatureComponents} - Plot the possible component graphs for a given feature. +\item \code{plotAdductDist} - Plot frequency distributions of the assigned adducts. +\item \code{plotSpectrum} - Plot the spectrum of an assigned molecular formula. +} +} +\examples{ +library(ggraph) +plan(future::sequential) +p <- assignmentParameters('FIE-HRMS') + +mf_assignments <- assignMFs(feature_data,p) + +## Plot a component +plotComponent(mf_assignments,1,'A&I1') + +## Plot the components for a feature +plotFeatureComponents(mf_assignments,'n191.01962','A&I1') + +## Plot the adduct distributions +plotAdductDist(mf_assignments) + +## Plot the spectrum of an assigned molecular formula +plotSpectrum(mf_assignments,'C6H8O7') +} diff --git a/man/summariseAssignments.Rd b/man/summariseAssignments.Rd deleted file mode 100644 index 1586573..0000000 --- a/man/summariseAssignments.Rd +++ /dev/null @@ -1,30 +0,0 @@ -% Generated by roxygen2: do not edit by hand -% Please edit documentation in R/assignment.R -\name{summariseAssignments} -\alias{summariseAssignments} -\alias{summariseAssignments,Assignment-method} -\title{Summarise assignments} -\usage{ -summariseAssignments(assignment) - -\S4method{summariseAssignments}{Assignment}(assignment) -} -\arguments{ -\item{assignment}{S4 object of class Assignment} -} -\value{ -A tibble containing the feature assignments summarised by molecular formula. -} -\description{ -Summarise features assigned to molecular formulas. -} -\examples{ -\dontrun{ -plan(future::sequential) -p <- assignmentParameters('FIE-HRMS') - -mf_assignments <- assignMFs(feature_data,p) - -summariseAssignments(mf_assignments) -} -} From 961a8ea8aeb3bea539e3a28976dc6d0af78938ac Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Tue, 21 Feb 2023 14:46:26 +0000 Subject: [PATCH 225/226] Update the package NEWS --- NEWS.md | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/NEWS.md b/NEWS.md index 4c83051..a51675f 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,3 +1,23 @@ # assignments 1.0.0 * Added a `NEWS.md` file to track changes to the package. + +* The `Assignment` S4 class now inherits from the `AssignmentParameters` S4 class. + +* The molecular formula generation is now handled by [`mzAnnotation::ipMF()`](https://aberhrml.github.io/mzAnnotation/reference/ipMF.html). + +* Improved molecular formula selection routine based on the Seven Golden Rules from [Kind et al. 2007](https://bmcbioinformatics.biomedcentral.com/articles/10.1186/1471-2105-8-105). + +* The adduct and isotope assignment routine now conducted over multiple iterations. + +* Graphical components are now selected using an improved plausibility score. + +* Graphical components are now only retained if they contain at least one non-isotopic assignment. + +* The individual assignment step methods (`calcCorrelations()`, `calcRelationships()`, `addIsoAssign()`, `transformAssign()`) are now exported. + +* Added the `availableTechniques()` function to return the supported analytical techniques. + +* Numerous documentation improvements. + +* Added a usage introduction vignette. From 16f980df3fb1335b00848c67de813336957f83db Mon Sep 17 00:00:00 2001 From: jasenfinch Date: Tue, 21 Feb 2023 15:04:37 +0000 Subject: [PATCH 226/226] Add link to pkgdown site to package NEWS --- NEWS.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/NEWS.md b/NEWS.md index a51675f..109e5bb 100644 --- a/NEWS.md +++ b/NEWS.md @@ -21,3 +21,5 @@ * Numerous documentation improvements. * Added a usage introduction vignette. + +* The package documentation is now available at