| Title: | Spatial Metabolomics and Multi-Omics Analysis |
|---|---|
| Description: | Provides analysis, annotation, visualisation, and multi-omic integration methods for spatial metabolomics data. SpaMTP interoperates with Cardinal and SpatialExperiment containers, with optional Seurat conversion; supports indexed accurate-mass annotation using versioned RaMP resources; and implements spatial feature analysis, pathway enrichment, pathway-network visualisation, and alignment with spatial transcriptomics data. |
| Authors: | Andrew Causer [aut] (ORCID: <https://orcid.org/0009-0001-7341-8366>), Tianyao Lu [aut, cre], Christopher C.J. Fitzgerald [aut] (ORCID: <https://orcid.org/0000-0003-3935-4300>), GML Lab [lbr], Brain Cancer Research Lab [lbr], UQ Institute [fnd], QIMR Institute [fnd], WEHI Institute [fnd] |
| Maintainer: | Tianyao Lu <[email protected]> |
| License: | MIT + file LICENSE |
| Version: | 0.99.11 |
| Built: | 2026-10-14 02:16:19 UTC |
| Source: | https://github.com/BiocStaging/SpaMTP |
Adds in backslashes required to take into account special using grepl such as brackets and +
add_backslashes_to_specialfeatures(input_string)add_backslashes_to_specialfeatures(input_string)
input_string |
Character string requiring additional backslashes |
Character string containing double backslashes around special features
Adds custom metabolite annotations to respective m/z values (ideal for specific matrices such as FMP10).
addCustomMZAnnotations( data, annotations, assay = "main", return.only.annotated = FALSE, mass.threshold = 0.05, annotation.column = "all_IsomerNames" )addCustomMZAnnotations( data, annotations, assay = "main", return.only.annotated = FALSE, mass.threshold = 0.05, annotation.column = "all_IsomerNames" )
data |
Bioconductor experiment containing m/z intensity values. |
annotations |
data.frame containing two columns named 'annotation' and 'mass'. These columns should contain the custom metabolite annotation and the relative m/z mass respectively. |
assay |
Primary or alternative experiment whose |
return.only.annotated |
Boolean defining whether to return a Bioconductor experiment containing only successfully annotated m/z values (default = FALSE). |
mass.threshold |
Numeric value defining the acceptable threshold (plus-minus) between the custom annotations and the actual m/z values contained within the SpaMTP object (default = 0.05). |
annotation.column |
Name of the |
Bioconductor experiment containing the custom annotations stored in the feature metadata dataframe.
utils::str(formals(addCustomMZAnnotations)) # annotated_data <- addCustomMZAnnotations(SpaMTP.obj, annotation.df)utils::str(formals(addCustomMZAnnotations)) # annotated_data <- addCustomMZAnnotations(SpaMTP.obj, annotation.df)
Adds metabolite annotations to respective m/z values generated using an FMP10 matrix. This is done based on a curated FMP10 matrix database.
addFMP10Annotations( obj, only.fmp.adduct = FALSE, add.custom.annotation = NULL, assay = "main", return.only.annotated = FALSE, mass.threshold = 0.05, annotation.column = "all_IsomerNames", database = NULL, database_version = "latest", database_source = c("auto", "spamtpdb"), database_local_dir = NULL )addFMP10Annotations( obj, only.fmp.adduct = FALSE, add.custom.annotation = NULL, assay = "main", return.only.annotated = FALSE, mass.threshold = 0.05, annotation.column = "all_IsomerNames", database = NULL, database_version = "latest", database_source = c("auto", "spamtpdb"), database_local_dir = NULL )
obj |
Bioconductor experiment containing m/z intensity values for annotation. Data should be generated with a FMP10 matrix. |
only.fmp.adduct |
Boolean indicating if only metabolites with FMP10+ adducts ( |
add.custom.annotation |
data.frame containing addition FMP10 metabolite annotations that are not in the current FMP10 database. Note: this data.frame must contain these column c("mass", "annotation", "Adduct", "Formula", "Isomers", "Isomers_IDs"). If set to NULL, only reference FMP10 database will be used (default = NULL). |
assay |
Primary or alternative experiment whose |
return.only.annotated |
Boolean defining whether to return a Bioconductor experiment containing only successfully annotated m/z values (default = FALSE). |
mass.threshold |
Numeric value defining the acceptable threshold (plus-minus) between the custom annotations and the actual m/z values contained within the SpaMTP object (default = 0.05). |
annotation.column |
Name of the |
database |
Optional named list of database resources, normally created
by |
database_version |
SpaMTPdb/RaMP version used for annotation lookup. |
database_source |
Database source; see |
database_local_dir |
Optional staged SpaMTPdb resource directory. |
Bioconductor experiment containing the relative metabolite annotations stored in the feature metadata dataframe.
utils::str(formals(addFMP10Annotations)) # addFMP10Annotations(spamtp, only.fmp.adduct = FALSE)utils::str(formals(addFMP10Annotations)) # addFMP10Annotations(spamtp, only.fmp.adduct = FALSE)
Attach and optionally align an optical image to MSI
addSMImage( image_path, SpaMTP, imageId = "optical", sampleId = NULL, scaleFactor = 1, transformation = NULL, interactive = TRUE, ... )addSMImage( image_path, SpaMTP, imageId = "optical", sampleId = NULL, scaleFactor = 1, transformation = NULL, interactive = TRUE, ... )
image_path |
Local image path. |
SpaMTP |
A SpatialExperiment. |
imageId |
Identifier for the attached image. |
sampleId |
Sample identifier; required for multi-sample objects. |
scaleFactor |
Image pixels per spatial coordinate unit. |
transformation |
Optional 3 by 3 matrix mapping MSI to image coordinates in full spatial units. |
interactive |
Open the manual alignment app when no matrix is supplied. |
... |
Additional arguments to shiny::runApp when interactive is TRUE. |
A SpatialExperiment with an imgData entry and optionally transformed spatialCoords. Coordinate alignment requires one tissue sample.
This is a small SpaMTP generic around SpatialExperiment::addImg(). Images
are stored in imgData() and may remain path-backed by setting
load = FALSE.
addSpatialImage( x, imageSource, scaleFactor = 1, sampleId = unique(x$sample_id)[[1L]], imageId = tools::file_path_sans_ext(basename(imageSource)), load = FALSE, ... ) ## S4 method for signature 'SpatialExperiment' addSpatialImage( x, imageSource, scaleFactor = 1, sampleId = unique(x$sample_id)[[1L]], imageId = tools::file_path_sans_ext(basename(imageSource)), load = FALSE, ... )addSpatialImage( x, imageSource, scaleFactor = 1, sampleId = unique(x$sample_id)[[1L]], imageId = tools::file_path_sans_ext(basename(imageSource)), load = FALSE, ... ) ## S4 method for signature 'SpatialExperiment' addSpatialImage( x, imageSource, scaleFactor = 1, sampleId = unique(x$sample_id)[[1L]], imageId = tools::file_path_sans_ext(basename(imageSource)), load = FALSE, ... )
x |
A |
imageSource |
Local PNG/JPEG path or supported URL. |
scaleFactor |
Image scale factor. |
sampleId |
Sample identifier represented by the image. |
imageId |
Image identifier. |
load |
Whether to load the raster immediately. |
... |
Reserved for class-specific methods. |
The updated object.
methods::showMethods("addSpatialImage")methods::showMethods("addSpatialImage")
Adds spatial shrunken centroid (SSC) labels to
Cardinal::pixelData(data)[["ssc"]] through its public replacement accessor.
This function accepts Cardinal containers only; it does not modify S4 slots
directly or require Seurat.
addSSCAnnotation(data, data_ssc, resolution)addSSCAnnotation(data, data_ssc, resolution)
data |
A Cardinal Object containing the raw/binned m/z count data. |
data_ssc |
A Cardinal Object containing the ssc segmentation results. Note: Cardinal's spatialShrunkenCentroids() must be run to generate this object. |
resolution |
An integer (< v3.6.0) or string (>= v3.6.0) defining the ssc segmentation resolution to add to the raw Cardinal object. |
A Cardinal Object containing the raw m/z counts and the relative ssc segmentation annotations per pixel.
utils::str(formals(addSSCAnnotation)) # ssc_data <- Cardinal::spatialShrunkenCentroids(CardinalObj, ...) # new_CardinalObj <- addSSCAnnotation(CardinalObj, ssc_data, resolution ="r=2,k=8,s=32")utils::str(formals(addSSCAnnotation)) # ssc_data <- Cardinal::spatialShrunkenCentroids(CardinalObj, ...) # new_CardinalObj <- addSSCAnnotation(CardinalObj, ssc_data, resolution ="r=2,k=8,s=32")
The transcriptome must contain the same spatial pixels as the metabolomics
object. It is stored with SingleCellExperiment::altExp() rather than as a
second Seurat assay.
addTranscriptome( x, transcriptome, name = "transcriptome", assayName = "counts", ... ) ## S4 method for signature 'SpatialExperiment' addTranscriptome( x, transcriptome, name = "transcriptome", assayName = "counts", ... )addTranscriptome( x, transcriptome, name = "transcriptome", assayName = "counts", ... ) ## S4 method for signature 'SpatialExperiment' addTranscriptome( x, transcriptome, name = "transcriptome", assayName = "counts", ... )
x |
A |
transcriptome |
A matrix or |
name |
Name used in |
assayName |
Assay name used when |
... |
Reserved for class-specific methods. |
The updated SpatialExperiment.
methods::showMethods("addTranscriptome")methods::showMethods("addTranscriptome")
A small table of legacy adduct definitions retained for compatibility with
earlier SpaMTP workflows. New annotation code should use adductRules(),
which includes charge, stoichiometry, ion-mode, and chemical-validity fields.
data(adduct_file)data(adduct_file)
A data frame with 47 rows and 6 variables:
Adduct notation.
Legacy ion-mass expression.
Ion charge.
Analyte stoichiometric multiplier.
Exact mass shift.
Ion polarity.
A data frame of legacy adduct definitions.
adductRules(), maldiMatrixRules()
The rules use neutral monoisotopic mass and explicit ion masses. Each row stores the molecular multiplier, total numerator mass shift, charge, number of protons removed from the analyte, and the charge contributed by added species. This allows rules to be checked before candidate generation.
adductRules( polarity = c("both", "positive", "negative", "neutral"), include_complex = TRUE )adductRules( polarity = c("both", "positive", "negative", "neutral"), include_complex = TRUE )
polarity |
One of |
include_complex |
Include multimers, solvent clusters, metal-exchange, and multiply charged ions. |
A data frame containing validated adduct rules.
utils::str(formals(adductRules))utils::str(formals(adductRules))
A supplied homogeneous matrix is applied reproducibly without a GUI. With transformation = NULL, an interactive preview allows translation, rotation, scaling and reflection. Coordinates are always stored in their full spatial units; an imgData scaleFactor affects only display of the reference image.
alignSpatialOmics( sm.data, st.data, transformation = NULL, image.slice = NULL, msi.pixel.multiplier = 1, shiny.host = "127.0.0.1", shiny.port = NULL, verbose = FALSE )alignSpatialOmics( sm.data, st.data, transformation = NULL, image.slice = NULL, msi.pixel.multiplier = 1, shiny.host = "127.0.0.1", shiny.port = NULL, verbose = FALSE )
sm.data, st.data
|
Source and reference SpatialExperiment objects, each containing one tissue sample. |
transformation |
A 3 by 3 homogeneous matrix mapping source coordinates to reference coordinates, or NULL for interactive alignment. |
image.slice |
Optional reference image ID in imgData(st.data). |
msi.pixel.multiplier |
Explicit initial scaling of source coordinates. Defaults to one. Applied before transformation, including GUI transforms. |
shiny.host, shiny.port
|
Host and optional port for the interactive app. |
verbose |
Show alignment messages. |
The source SpatialExperiment with updated spatialCoords and alignment provenance recorded by applySpatialAlignment.
Adds descriptive region-versus-rest effects, detection fractions, region means and eligibility audits. Existing biological-replicate contrasts remain unchanged. Optional native spatial modules call findSpatiallyVariableMetabolites and runSpatialGraphPCA on an explicitly bounded, recorded feature/point screen. Works with any modality names, species and observation metadata, including results saved by earlier workflow versions.
analyzeSpaMTPRegions( result, regions = NULL, min_region_size = 3, native = list(), markers = TRUE, spatial_blocks = 6 )analyzeSpaMTPRegions( result, regions = NULL, min_region_size = 3, native = list(), markers = TRUE, spatial_blocks = 6 )
result |
A spamtp_workflow result. |
regions |
A colData column for regions; NULL uses the workflow group, or workflow_cluster if clustering was requested. No labels are invented. |
min_region_size |
Minimum observations in both a region and its reference. |
native |
Named settings: moran, graph_pca, max_points (600), max_features (50), neighbors (4), lambda (0.5). These additional bounded screens default FALSE; the workflow structure module runs full-observation Graph PCA separately and uses it in the comparative analysis. |
markers |
Compute native scran marker scores through findAllDEMs. |
spatial_blocks |
Number of coordinate-only blocks per sample for marker sensitivity; zero disables block omission. These are not biological replicates. |
Region effects use all labelled retained observations. Blank/NA labels are excluded and counted in the audit. No P values are inferred from pixels or random pools. Moran's I statistics are exploratory and use BH within the selected feature family per modality and sample; this screening is not a genome-wide or biological-replicate test. Marker reference means equally weight other eligible regions, following scran pairwise summaries.
The result with region_analysis, native_analysis and updated provenance.
utils::str(formals(analyzeSpaMTPRegions))utils::str(formals(analyzeSpaMTPRegions))
This function assigns each valid m/z peak with one/multiple metabolite names based on the mass difference between the observed value and the theoretical value documented in the reference database. This function is to be used when dealing with large datasets as a preprocessing step. Users can annotate m/z values first and then subset their data accordinly before loading it into a Bioconductor experiment.
annotateBigData( mzs, db = NULL, ppm_error = NULL, adducts = NULL, polarity = NULL, tof_resolution = 30000, verbose = TRUE, maldi_matrix = NULL, database_version = "latest", database_source = c("auto", "spamtpdb"), database_local_dir = NULL, ... )annotateBigData( mzs, db = NULL, ppm_error = NULL, adducts = NULL, polarity = NULL, tof_resolution = 30000, verbose = TRUE, maldi_matrix = NULL, database_version = "latest", database_source = c("auto", "spamtpdb"), database_local_dir = NULL, ... )
mzs |
Vector containing m/z values for annotation. |
db |
Reference metabolite dataset in the form of a data.frame. SpaMTP
provides four pre-cleaned databases ( |
ppm_error |
Mass tolerance in ppm. If |
adducts |
Optional adduct names/notations; see |
polarity |
Character string defining the ion mode. When |
tof_resolution |
Instrument resolving power retained for compatibility; it can only tighten, not widen, the default 5 ppm mass-accuracy threshold. |
verbose |
Boolean indicating whether to show the message. If TRUE the message will be show, else the message will be suppressed (default = TRUE). |
maldi_matrix |
Optional MALDI matrix/reagent profile used for automatic
rule selection. The |
database_version |
SpaMTPdb/RaMP version used when |
database_source |
Database source used when |
database_local_dir |
Optional staged SpaMTPdb resource directory. |
... |
Additional indexed annotation/scoring arguments passed to
|
A data.frame containing all successfully annotated m/z values, with their corresponding annotation.
utils::str(formals(annotateBigData)) #cardinal <- readImzML("./Test_Data/Spotted/test_data1") #mzs <- data.frame(Cardinal::featureData(cardinal))$mz #results <- annotateBigData(mzs, db = HMDB_db, ppm_error = 3, adducts = c("M-H", "M+Cl"), polarity = "negative") #cardinal_subset <- Cardinal::subset(cardinal, mz %in% results$observed_mz)utils::str(formals(annotateBigData)) #cardinal <- readImzML("./Test_Data/Spotted/test_data1") #mzs <- data.frame(Cardinal::featureData(cardinal))$mz #results <- annotateBigData(mzs, db = HMDB_db, ppm_error = 3, adducts = c("M-H", "M+Cl"), polarity = "negative") #cardinal_subset <- Cardinal::subset(cardinal, mz %in% results$observed_mz)
Adds aligned mapping columns to the selected experiment's rowData() and
provenance to its metadata(). Expression values, feature names, row order,
spatial coordinates and paired experiments are preserved. Multiple assay
rows that map to one gene are annotated, not silently summed; pathway
enrichment performs gene-level deduplication separately.
annotateGeneIdentifiers( object, assay = "main", id_column = NULL, id_type = c("auto", "symbol", "entrez", "ensembl", "uniprot", "hgnc"), ... )annotateGeneIdentifiers( object, assay = "main", id_column = NULL, id_type = c("auto", "symbol", "entrez", "ensembl", "uniprot", "hgnc"), ... )
object |
A SummarizedExperiment, SingleCellExperiment or SpatialExperiment, including native objects provided by SpaMTPData. |
assay |
The primary experiment ( |
id_column |
Gene identifier column in the selected |
id_type |
Identifier type. |
... |
Passed to |
The input object with spamtp_gene_* mapping columns and
metadata(experiment)$gene_mapping provenance and input audit.
utils::str(formals(annotateGeneIdentifiers))utils::str(formals(annotateGeneIdentifiers))
Convenience wrapper that builds an index when one is not supplied. Reuse a pre-built index for repeated or large searches.
annotateMZ( observed_mz, db = NULL, index = NULL, polarity = NULL, adducts = NULL, rules = NULL, maldi_matrix = NULL, ppm = 5, ms1_spectrum = NULL, database_version = "latest", database_source = c("auto", "spamtpdb"), database_local_dir = NULL, infer_structure = c("auto", "never", "always"), structure_backend = c("auto", "native"), structure_workers = getOption("SpaMTP.smiles_workers", 1L), min_structure_score = 0.05, ... )annotateMZ( observed_mz, db = NULL, index = NULL, polarity = NULL, adducts = NULL, rules = NULL, maldi_matrix = NULL, ppm = 5, ms1_spectrum = NULL, database_version = "latest", database_source = c("auto", "spamtpdb"), database_local_dir = NULL, infer_structure = c("auto", "never", "always"), structure_backend = c("auto", "native"), structure_workers = getOption("SpaMTP.smiles_workers", 1L), min_structure_score = 0.05, ... )
observed_mz |
Numeric vector of observed m/z values. |
db |
Metabolite database used when |
index |
Optional pre-built |
polarity |
Ion mode. When |
adducts |
Optional adduct subset. When |
rules |
Optional custom rule table. |
maldi_matrix |
Optional MALDI matrix/reagent profile used to select
rules automatically when |
ppm |
Mass tolerance in ppm. |
ms1_spectrum |
Optional contextual spectrum. |
database_version |
SpaMTPdb/RaMP version used when |
database_source |
Database source used when |
database_local_dir |
Optional staged SpaMTPdb resource directory. |
infer_structure, structure_backend, structure_workers, min_structure_score
|
Structure-aware
rule-selection arguments passed to |
... |
Additional arguments passed to |
A ranked candidate data frame.
utils::str(formals(annotateMZ))utils::str(formals(annotateMZ))
This function assigns each valid m/z peak with one/multiple metabolite names based on the mass difference between the observed value and the theoretical value documented in the reference database. Versioned RaMP, HMDB, LIPID MAPS, ChEBI, and GNPS resources are provided by SpaMTPdb and can be combined with user-supplied reference tables.
annotateSM( data, db = NULL, assay = "main", raw.mz.column = "raw_mz", ppm_error = NULL, adducts = NULL, polarity = NULL, tof_resolution = 30000, filepath = NULL, return.only.annotated = TRUE, save.intermediate = TRUE, min_score = 0, verbose = TRUE, maldi_matrix = NULL, database_version = "latest", database_source = c("auto", "spamtpdb"), database_local_dir = NULL, ... )annotateSM( data, db = NULL, assay = "main", raw.mz.column = "raw_mz", ppm_error = NULL, adducts = NULL, polarity = NULL, tof_resolution = 30000, filepath = NULL, return.only.annotated = TRUE, save.intermediate = TRUE, min_score = 0, verbose = TRUE, maldi_matrix = NULL, database_version = "latest", database_source = c("auto", "spamtpdb"), database_local_dir = NULL, ... )
data |
Bioconductor experiment containing m/z values for annotation. |
db |
Reference metabolite dataset in the form of a data.frame. When
|
assay |
Character string defining the primary or alternative experiment which contains the mz counts being annotated (default = "Spatial"). |
raw.mz.column |
Character string naming the feature-metadata column containing raw m/z values without the |
ppm_error |
Mass tolerance in ppm. If |
adducts |
Optional adduct names/notations; see |
polarity |
Character string defining the ion mode. When |
tof_resolution |
Instrument resolving power retained for compatibility; it can only tighten, not widen, the default 5 ppm mass-accuracy threshold. |
filepath |
Character string of the directory to store the _annotated_mz_peaks.csv. If set to NULL no dataframe will be saved (default = NULL). |
return.only.annotated |
Boolean value indicating if the annotated Bioconductor experiment should only include m/z values that were successfully annotated (default = TRUE). |
save.intermediate |
Boolean indicating whether to store the scored
annotation result and its pipeline/RaMP provenance in
|
min_score |
Minimum annotation score retained in the stored candidate
table. The default |
verbose |
Boolean indicating whether to show the message. If TRUE the message will be show, else the message will be suppressed (default = TRUE). |
maldi_matrix |
Optional MALDI matrix or derivatization reagent name.
When supplied, SpaMTP selects validated matrix-specific rules
automatically. |
database_version |
SpaMTPdb/RaMP version used when |
database_source |
Database source used when |
database_local_dir |
Optional staged SpaMTPdb resource directory. |
... |
Additional indexed annotation/scoring arguments passed to
|
A Bioconductor experiment with m/z values annotated. These annotations are stored in the selected experiment's rowData().
utils::str(formals(annotateSM)) # HMDB_db <- load("data/HMDB_1_names.rds")utils::str(formals(annotateSM)) # HMDB_db <- load("data/HMDB_1_names.rds")
Add SMILES-derived structural features to a metabolite database
annotateSMILESStructure( db, smiles_column = NULL, backend = c("auto", "native"), overwrite = FALSE, strict = FALSE, workers = getOption("SpaMTP.smiles_workers", 1L) )annotateSMILESStructure( db, smiles_column = NULL, backend = c("auto", "native"), overwrite = FALSE, strict = FALSE, workers = getOption("SpaMTP.smiles_workers", 1L) )
db |
A metabolite data frame. |
smiles_column |
Column containing SMILES. When |
backend |
Parser backend passed to |
overwrite |
Replace existing feature values. By default only absent or missing values are filled. |
strict |
Passed to |
workers |
Parallel workers passed to |
db with structure-derived columns appended or completed.
utils::str(formals(annotateSMILESStructure))utils::str(formals(annotateSMILESStructure))
Helper function for annotateSM() and fishersPathwayAnalysis().
annotateTable( mz_df, db = NULL, ppm_error = NULL, adducts = NULL, polarity = NULL, tof_resolution = 30000, verbose = TRUE, index = NULL, rules = NULL, ms1_spectrum = NULL, use_mass_defect = TRUE, check_isotopes = TRUE, check_adduct_network = TRUE, min_score = 0, maldi_matrix = NULL, database_version = "latest", database_source = c("auto", "spamtpdb"), database_local_dir = NULL, infer_structure = c("auto", "never", "always"), structure_backend = c("auto", "native"), structure_workers = getOption("SpaMTP.smiles_workers", 1L), min_structure_score = 0.05 )annotateTable( mz_df, db = NULL, ppm_error = NULL, adducts = NULL, polarity = NULL, tof_resolution = 30000, verbose = TRUE, index = NULL, rules = NULL, ms1_spectrum = NULL, use_mass_defect = TRUE, check_isotopes = TRUE, check_adduct_network = TRUE, min_score = 0, maldi_matrix = NULL, database_version = "latest", database_source = c("auto", "spamtpdb"), database_local_dir = NULL, infer_structure = c("auto", "never", "always"), structure_backend = c("auto", "native"), structure_workers = getOption("SpaMTP.smiles_workers", 1L), min_structure_score = 0.05 )
mz_df |
dataframe containing m/z values for annotation. |
db |
Reference metabolite dataset in the form of a data.frame. May be
|
ppm_error |
Mass tolerance in ppm. If |
adducts |
Optional adduct names/notations; see |
polarity |
Character string defining the ion mode. When |
tof_resolution |
Instrument resolving power retained for compatibility; it can only tighten, not widen, the default 5 ppm mass-accuracy threshold. |
verbose |
Boolean indicating whether to show the message. If TRUE the message will be show, else the message will be suppressed (default = TRUE). |
index |
Optional reusable index created by |
rules |
Optional custom adduct rule table; see |
ms1_spectrum |
Optional contextual MS1 spectrum with |
use_mass_defect |
Apply the CHO negative mass-defect penalty. |
check_isotopes |
Score carbon-13 and halogen isotope evidence when a contextual spectrum is supplied. |
check_adduct_network |
Downweight complex ions whose base monomer family is absent from the contextual spectrum. |
min_score |
Minimum final annotation score to retain. |
maldi_matrix |
Optional MALDI matrix/reagent profile used for automatic
rule selection. |
database_version |
SpaMTPdb/RaMP version used when |
database_source |
Database source used when |
database_local_dir |
Optional staged SpaMTPdb resource directory. |
infer_structure |
|
structure_backend |
SMILES parser passed to |
structure_workers |
Number of workers used for runtime SMILES parsing. |
min_structure_score |
Minimum rule-specific structural prior retained during candidate-index construction. |
Generates an intermediate annotated m/z dataframe
### HelperFunction### HelperFunction
Reports whether downstream pathway functions will use the current indexed, scored RaMP annotation pipeline or a legacy mass-match result.
annotationInfo(SpaMTP)annotationInfo(SpaMTP)
SpaMTP |
A SingleCellExperiment, including SpatialExperiment. |
A named list containing annotation schema, engine, RaMP version, provenance, and candidate count where available.
utils::str(formals(annotationInfo))utils::str(formals(annotationInfo))
Aligns a moving Spatial Metabolomics (SM) SpatialExperiment
to a fixed SpatialExperiment. The function can apply coordinates exported by
the SMINT workflow, apply a homogeneous transformation matrix, estimate an
affine transform from paired landmarks, or run the STalign LDDMM backend used
by SMINT through reticulate.
applySpatialAlignment( SM.data, ST.data = NULL, alignment = NULL, method = c("lddmm", "affine"), SM.fov = NULL, ST.image = NULL, SM.boundary = "centroids", SM.landmarks = NULL, ST.landmarks = NULL, landmark.order = c("xy", "yx"), SM.landmark.space = c("original", "preprocessed"), coordinate.columns = NULL, cell.column = NULL, ST.scale.factor = NULL, source.scale = 1, source.rotate = 0, source.flip = c(FALSE, FALSE), source.translate = c(0, 0), source.origin = NULL, dx = 30, niter = 1000, epV = 200, device = c("auto", "cpu", "cuda"), seed = 1, lddmm.args = list(), python = NULL, alignment.name = "SMINT", store = TRUE, return = c("object", "result"), diagnostics.max.points = 10000, verbose = TRUE )applySpatialAlignment( SM.data, ST.data = NULL, alignment = NULL, method = c("lddmm", "affine"), SM.fov = NULL, ST.image = NULL, SM.boundary = "centroids", SM.landmarks = NULL, ST.landmarks = NULL, landmark.order = c("xy", "yx"), SM.landmark.space = c("original", "preprocessed"), coordinate.columns = NULL, cell.column = NULL, ST.scale.factor = NULL, source.scale = 1, source.rotate = 0, source.flip = c(FALSE, FALSE), source.translate = c(0, 0), source.origin = NULL, dx = 30, niter = 1000, epV = 200, device = c("auto", "cpu", "cuda"), seed = 1, lddmm.args = list(), python = NULL, alignment.name = "SMINT", store = TRUE, return = c("object", "result"), diagnostics.max.points = 10000, verbose = TRUE )
SM.data |
A |
ST.data |
An optional matching spatial container with fixed coordinates.
It is required when computing an affine or LDDMM alignment, but is optional
when applying final coordinates supplied through |
alignment |
Optional precomputed alignment. Accepted inputs are a data
frame or matrix of final coordinates; a 2-by-3 or 3-by-3 homogeneous
transformation matrix; a list containing |
method |
Alignment method used when |
SM.fov |
Optional imgData image ID for the moving experiment. By default,
the first image in |
ST.image |
Optional imgData image ID for the fixed experiment. By
default, the first image in |
SM.boundary |
Compatibility label; coordinates are always read from spatialCoords(). |
SM.landmarks, ST.landmarks
|
Matched landmark coordinates as two-column
matrices or data frames in x-y order. At least three non-collinear pairs are
required for |
landmark.order |
Coordinate-column order in both landmark inputs.
|
SM.landmark.space |
Whether SM landmarks use the |
coordinate.columns |
Optional names or integer positions of the x and y columns in a precomputed coordinate table. |
cell.column |
Optional name or integer position of the cell/spot ID column in a precomputed coordinate table. When no IDs are available, rows must already be in the same order as the moving SM centroids. |
ST.scale.factor |
Optional fixed-coordinate scale factor. Supply a
numeric value or a scale-factor name such as |
source.scale |
Numeric scalar or x-y vector applied to moving coordinates before fitting. This reproduces the initial SM scaling step in the SMINT notebooks. |
source.rotate |
Counter-clockwise rotation in degrees, around the origin, applied after scaling. |
source.flip |
Logical x-y vector indicating reflection around the origin. |
source.translate |
Numeric x-y translation applied after scaling, reflection, and rotation. |
source.origin |
Optional numeric x-y lower bound. Coordinates are shifted
only where necessary so that their minima are at least this value. Use
|
dx |
Raster spacing passed to |
niter |
Number of LDDMM optimisation iterations. |
epV |
Velocity-field gradient step passed to |
device |
One of |
seed |
Random seed set for NumPy and Torch before LDDMM. |
lddmm.args |
Named list of additional arguments passed to
|
python |
Optional path to a Python executable containing |
alignment.name |
Name used to store alignment provenance in
|
store |
Logical; store lightweight provenance and diagnostics in the returned object. |
return |
Either |
diagnostics.max.points |
Maximum number of moving and fixed points used for nearest-neighbour diagnostics. |
verbose |
Logical; print progress messages. |
Python is only required when method = "lddmm" and alignment = NULL.
Precomputed SMINT coordinates and affine landmark alignment are handled
entirely in R. The backend summary records STalign's affine component as
affine_yx; it is not the complete nonlinear LDDMM transformation.
The updated spatial container when return = "object"; otherwise an object of class
spamtp_spatial_alignment containing the aligned object and alignment
details.
utils::str(formals(applySpatialAlignment)) # Apply coordinates already exported by the SMINT/STalign notebook. aligned_sm <- applySpatialAlignment( SM.data = sm, ST.data = st, alignment = "Ven5_z2_transformed_metabolites_coordinates.csv", coordinate.columns = c("x_transformed", "y_transformed") ) # Run the notebook's landmark-guided LDDMM workflow from R. fit <- applySpatialAlignment( SM.data = sm, ST.data = st, method = "lddmm", SM.landmarks = sm_landmarks, ST.landmarks = st_landmarks, landmark.order = "yx", # point-annotator row/column order SM.landmark.space = "preprocessed", # landmarks selected after rasterization source.scale = 10, source.rotate = 90, source.origin = c(0, 0), python = "/path/to/STalign_env/bin/python", return = "result" ) fit$diagnosticsutils::str(formals(applySpatialAlignment)) # Apply coordinates already exported by the SMINT/STalign notebook. aligned_sm <- applySpatialAlignment( SM.data = sm, ST.data = st, alignment = "Ven5_z2_transformed_metabolites_coordinates.csv", coordinate.columns = c("x_transformed", "y_transformed") ) # Run the notebook's landmark-guided LDDMM workflow from R. fit <- applySpatialAlignment( SM.data = sm, ST.data = st, method = "lddmm", SM.landmarks = sm_landmarks, ST.landmarks = st_landmarks, landmark.order = "yx", # point-annotator row/column order SM.landmark.space = "preprocessed", # landmarks selected after rasterization source.scale = 10, source.rotate = 90, source.origin = c(0, 0), python = "/path/to/STalign_env/bin/python", return = "result" ) fit$diagnostics
Convert a SpatialExperiment to a Cardinal experiment
asCardinal(x, ...) ## S4 method for signature 'SpatialExperiment' asCardinal(x, ...) ## S4 method for signature 'MSImagingExperiment' asCardinal(x, ...) ## S4 method for signature 'MSImagingArrays' asCardinal(x, ...)asCardinal(x, ...) ## S4 method for signature 'SpatialExperiment' asCardinal(x, ...) ## S4 method for signature 'MSImagingExperiment' asCardinal(x, ...) ## S4 method for signature 'MSImagingArrays' asCardinal(x, ...)
x |
An object to convert. |
... |
Arguments passed to the class-specific method. |
A Cardinal MSImagingExperiment, or unchanged MSImagingArrays input.
methods::showMethods("asCardinal")methods::showMethods("asCardinal")
asSpatialExperiment() is the Bioconductor-native conversion entry point
used by SpaMTP. Continuous or unaligned raw spectra should remain in a
Cardinal MSImagingArrays or MSImagingExperiment; conversion is intended for data with a
common feature-by-pixel matrix, typically after peak alignment or binning.
asSpatialExperiment(x, ...) ## S4 method for signature 'MSImagingExperiment' asSpatialExperiment(x, ...) ## S4 method for signature 'MSImagingArrays' asSpatialExperiment(x, ...) ## S4 method for signature 'SpatialExperiment' asSpatialExperiment(x, ...) ## S4 method for signature 'SummarizedExperiment' asSpatialExperiment(x, coordinates = c("x", "y"), ...)asSpatialExperiment(x, ...) ## S4 method for signature 'MSImagingExperiment' asSpatialExperiment(x, ...) ## S4 method for signature 'MSImagingArrays' asSpatialExperiment(x, ...) ## S4 method for signature 'SpatialExperiment' asSpatialExperiment(x, ...) ## S4 method for signature 'SummarizedExperiment' asSpatialExperiment(x, coordinates = c("x", "y"), ...)
x |
An object to convert. |
... |
Arguments passed to the class-specific method. |
coordinates |
Column names in |
A SpatialExperiment.
methods::showMethods("asSpatialExperiment")methods::showMethods("asSpatialExperiment")
The sum is stored in colData without modifying the expression assays.
binMetabolites( data, mzs, assay = "main", slot = "counts", bin_name = "Binned_Metabolites" )binMetabolites( data, mzs, assay = "main", slot = "counts", bin_name = "Binned_Metabolites" )
data |
A SpatialExperiment or aligned Cardinal experiment. |
mzs |
Character feature IDs to sum. Duplicates count once. |
assay |
Primary or alternative experiment. |
slot |
Expression assay. See experimentAccess for the experiment/matrix distinction. |
bin_name |
Output colData column name. Existing columns are protected. |
The updated SpatialExperiment.
utils::str(formals(binMetabolites))utils::str(formals(binMetabolites))
Convert a binned Cardinal matrix to an optional Seurat object
binnedCardinalToSeurat( data, mtx, multi.run = FALSE, assay = "Spatial", verbose = TRUE )binnedCardinalToSeurat( data, mtx, multi.run = FALSE, assay = "Spatial", verbose = TRUE )
data |
Cardinal object supplying coordinates and metadata. |
mtx |
Binned feature-by-pixel matrix. |
multi.run |
Retained for compatibility. |
assay |
Name of the Seurat assay. |
verbose |
Show conversion messages. |
A Seurat object.
utils::str(formals(binnedCardinalToSeurat))utils::str(formals(binnedCardinalToSeurat))
MSImagingArrays or MSImagingExperiment input delegates binning to Cardinal and is converted
to SpatialExperiment only after a common feature axis exists.
SpatialExperiment input returns a new binned SpatialExperiment.
For aligned matrices, bins start at the minimum observed m/z and use
linear (mz) or log-mass (ppm) spacing. Each feature is assigned once
to its nearest bin on that axis (midpoints go up); empty bins are omitted.
Thus sum binning conserves each pixel's total intensity. Cardinal input
uses Cardinal's reference-window binning convention instead.
binSpaMTP( data, resolution, units = "ppm", assay = "main", slot = "counts", method = c("sum", "mean", "max", "min"), return.only.mtx = FALSE ) ## S4 method for signature 'SpatialExperiment' binSpaMTP( data, resolution, units = "ppm", assay = "main", slot = "counts", method = c("sum", "mean", "max", "min"), return.only.mtx = FALSE ) ## S4 method for signature 'MSImagingExperiment' binSpaMTP( data, resolution, units = "ppm", assay = "main", slot = "counts", method = c("sum", "mean", "max", "min"), return.only.mtx = FALSE ) ## S4 method for signature 'MSImagingArrays' binSpaMTP( data, resolution, units = "ppm", assay = "main", slot = "counts", method = c("sum", "mean", "max", "min"), return.only.mtx = FALSE ) ## S4 method for signature 'ANY' binSpaMTP( data, resolution, units = "ppm", assay = "main", slot = "counts", method = c("sum", "mean", "max", "min"), return.only.mtx = FALSE )binSpaMTP( data, resolution, units = "ppm", assay = "main", slot = "counts", method = c("sum", "mean", "max", "min"), return.only.mtx = FALSE ) ## S4 method for signature 'SpatialExperiment' binSpaMTP( data, resolution, units = "ppm", assay = "main", slot = "counts", method = c("sum", "mean", "max", "min"), return.only.mtx = FALSE ) ## S4 method for signature 'MSImagingExperiment' binSpaMTP( data, resolution, units = "ppm", assay = "main", slot = "counts", method = c("sum", "mean", "max", "min"), return.only.mtx = FALSE ) ## S4 method for signature 'MSImagingArrays' binSpaMTP( data, resolution, units = "ppm", assay = "main", slot = "counts", method = c("sum", "mean", "max", "min"), return.only.mtx = FALSE ) ## S4 method for signature 'ANY' binSpaMTP( data, resolution, units = "ppm", assay = "main", slot = "counts", method = c("sum", "mean", "max", "min"), return.only.mtx = FALSE )
data |
A |
resolution |
Positive bin resolution. |
units |
Resolution units, either |
assay |
Primary MSI experiment name; alternative modalities cannot be binned. |
slot |
Matrix layer or SpatialExperiment assay to bin. See experimentAccess for the experiment/matrix distinction. |
method |
Aggregation method. |
return.only.mtx |
Return only the binned matrix. |
A binned SpatialExperiment or matrix.
methods::showMethods("binSpaMTP")methods::showMethods("binSpaMTP")
Connects RaMP gene records to HGNC using explicit stable identifiers, then approved and previous symbols. Shared aliases are never used to merge RaMP records. Conflicting stable identifiers quarantine the affected RaMP record. Multiple non-conflicting RaMP records for one HGNC gene share one canonical RaMP ID (lexicographically first); their pathway memberships can then be united and counted once. No transitive merging across different HGNC genes or orthology conversion is performed. A fingerprint of normalized RaMP identifiers and common names guards index reuse. Reordering rows, duplicating evidence or changing unrelated columns does not invalidate it. Rebuild saved indices from older schema versions with this function before using them in a new workflow.
buildGeneMappingIndex( source_df, gene_reference = NULL, gene_reference_version = "latest", gene_reference_local_dir = NULL, organism = "Homo sapiens", offline = FALSE )buildGeneMappingIndex( source_df, gene_reference = NULL, gene_reference_version = "latest", gene_reference_local_dir = NULL, organism = "Homo sapiens", offline = FALSE )
source_df |
RaMP identifier table from SpaMTPdb, with |
gene_reference |
HGNC reference data frame. |
gene_reference_version |
Version in SpaMTPdb's separate HGNC registry. |
gene_reference_local_dir |
Local HGNC resource directory. |
organism |
Must be |
offline |
Require local or cached HGNC data. |
A spamtp_gene_index list containing reference lookup, gene groups,
per-RaMP identity decisions, precomputed conflict membership, evidence and
resource provenance including source_fingerprint.
utils::str(formals(buildGeneMappingIndex))utils::str(formals(buildGeneMappingIndex))
Expected adduct m/z values are generated once, sorted, and queried by binary interval search. This is the one-dimensional equivalent of an interval tree and avoids scanning every database row for every observed peak.
buildMZAnnotationIndex( db, polarity = NULL, adducts = NULL, rules = NULL, maldi_matrix = NULL, collapse_isomers = TRUE, infer_structure = c("auto", "never", "always"), structure_backend = c("auto", "native"), structure_workers = getOption("SpaMTP.smiles_workers", 1L), min_structure_score = 0.05 )buildMZAnnotationIndex( db, polarity = NULL, adducts = NULL, rules = NULL, maldi_matrix = NULL, collapse_isomers = TRUE, infer_structure = c("auto", "never", "always"), structure_backend = c("auto", "native"), structure_workers = getOption("SpaMTP.smiles_workers", 1L), min_structure_score = 0.05 )
db |
Metabolite database. Both the legacy SpaMTP five-column/wide
database and the RaMP |
polarity |
|
adducts |
Optional character vector of adduct names or bracketed
notations. When |
rules |
Optional custom rule table. See |
maldi_matrix |
Optional MALDI matrix or derivatization reagent profile.
When supplied and |
collapse_isomers |
Collapse records sharing formula, exact mass, and proton bound before indexing. |
infer_structure |
|
structure_backend |
SMILES parser used by |
structure_workers |
Number of workers used for runtime SMILES parsing. |
min_structure_score |
Minimum rule-specific structural prior retained before m/z indexing. Set to zero to rank without structure-based pruning. |
An object of class spamtp_mz_index.
utils::str(formals(buildMZAnnotationIndex))utils::str(formals(buildMZAnnotationIndex))
Unites pathway memberships of non-conflicting RaMP records belonging to one HGNC gene. Retains raw memberships and excluded conflicting records. Reuse this index in enrichment, expression aggregation, scoring and named pathway plots to obtain the same identities and membership sets. Pathways are keyed by pathwayRampId; identical display names never merge distinct pathways.
buildPathwayIndex( database = NULL, gene_mapping = c("auto", "hgnc", "ramp"), gene_reference = NULL, gene_index = NULL, gene_reference_version = "latest", gene_reference_local_dir = NULL, organism = "Homo sapiens", database_version = "latest", database_source = c("auto", "spamtpdb"), database_local_dir = NULL )buildPathwayIndex( database = NULL, gene_mapping = c("auto", "hgnc", "ramp"), gene_reference = NULL, gene_index = NULL, gene_reference_version = "latest", gene_reference_local_dir = NULL, organism = "Homo sapiens", database_version = "latest", database_source = c("auto", "spamtpdb"), database_local_dir = NULL )
database |
A resource bundle with analytehaspathway and pathway, and source_df for gene harmonization. NULL retrieves these from SpaMTPdb. |
gene_mapping |
|
gene_reference |
HGNC reference data frame. |
gene_index |
Optional index built from the same source table by
|
gene_reference_version |
Version in SpaMTPdb's separate HGNC registry. |
gene_reference_local_dir |
Local HGNC resource directory. |
organism |
Must be |
database_version |
SpaMTPdb/RaMP version used for pathway lookup. |
database_source |
Database source; see |
database_local_dir |
Optional staged SpaMTPdb resource directory. |
A spamtp_pathway_index containing canonical and raw member sets, conflicting members, metadata, gene_index and resource fingerprints. Database size means unique analyte identities after reconciliation and conflict exclusion, before intersecting with measured features.
db <- list(analytehaspathway = data.frame(rampId = "RAMP_C_1", pathwayRampId = "P1"), pathway = data.frame(pathwayRampId = "P1")) buildPathwayIndex(db)$membersdb <- list(analytehaspathway = data.frame(rampId = "RAMP_C_1", pathwayRampId = "P1"), pathway = data.frame(pathwayRampId = "P1")) buildPathwayIndex(db)$members
Calculates the mz range of the observed_df
calculate_bounds(input_df)calculate_bounds(input_df)
input_df |
DataFrame of the observed dataframe being annotated |
A list containing the lower and upper mz range for the provided sample
# mz_df$row_id <- seq(1, length(mz_df$mz)) # mass_range <- calculate_bounds(mz_df) # lower_bound <- mass_range$lower_bound # upper_bound <- mass_range$upper_bound# mz_df$row_id <- seq(1, length(mz_df$mz)) # mass_range <- calculate_bounds(mz_df) # lower_bound <- mass_range$lower_bound # upper_bound <- mass_range$upper_bound
When pathway.assay contains RaMP analytes rather than pathway scores, createPathwayObject is reused to calculate scores in a temporary altExp. Set pathway.scores=TRUE to use an existing pathway-level assay directly. Input containers are never modified.
calculateAnnotationStatistics( data, mz.assay = "main", pathway.assay = "pathway", mz.slot = "counts", pathway.slot = "counts", return.top = TRUE, corr_theshold = 0, corr_weight = 1, n_weight = 1, database = NULL, database_version = "latest", database_source = c("auto", "spamtpdb"), database_local_dir = NULL, pathway.scores = FALSE, pathway_index = NULL, gene_mapping = c("auto", "hgnc", "ramp"), gene_reference = NULL, gene_index = NULL, gene_reference_version = "latest", gene_reference_local_dir = NULL, organism = "Homo sapiens", duplicate_genes = c("error", "mean", "sum") )calculateAnnotationStatistics( data, mz.assay = "main", pathway.assay = "pathway", mz.slot = "counts", pathway.slot = "counts", return.top = TRUE, corr_theshold = 0, corr_weight = 1, n_weight = 1, database = NULL, database_version = "latest", database_source = c("auto", "spamtpdb"), database_local_dir = NULL, pathway.scores = FALSE, pathway_index = NULL, gene_mapping = c("auto", "hgnc", "ramp"), gene_reference = NULL, gene_index = NULL, gene_reference_version = "latest", gene_reference_local_dir = NULL, organism = "Homo sapiens", duplicate_genes = c("error", "mean", "sum") )
data |
A SingleCellExperiment or SpatialExperiment with paired altExp. |
mz.assay |
Primary experiment ("main") or alternative MSI experiment. |
pathway.assay |
Alternative experiment of RaMP analytes, or pathway scores when pathway.scores=TRUE. |
mz.slot |
Expression assay in the MSI experiment. See experimentAccess for the experiment/matrix distinction. |
pathway.slot |
Input expression assay in pathway.assay. See experimentAccess for the experiment/matrix distinction. |
return.top |
Return one best evaluable candidate per feature; FALSE returns a named list of all candidate tables. Features without a score remain as NA rows in top results and NULL entries when no table is possible. |
corr_theshold |
Minimum signed pathway correlation (legacy spelling). |
corr_weight, n_weight
|
Non-negative weights, not both zero. |
database |
Optional named list from loadSpaMTPDatabase. |
database_version, database_source, database_local_dir
|
Database selection; see loadSpaMTPDatabase. |
pathway.scores |
Whether pathway.assay already contains pathway scores. |
pathway_index |
A reusable index from buildPathwayIndex(). When supplied, its gene identities and memberships must match any explicit database or gene_index. Fingerprints prevent incompatible reuse. |
gene_mapping |
|
gene_reference |
HGNC reference data frame. |
gene_index |
Optional index built from the same source table by
|
gene_reference_version |
Version in SpaMTPdb's separate HGNC registry. |
gene_reference_local_dir |
Local HGNC resource directory. |
organism |
Must be |
duplicate_genes |
How to aggregate expression rows of one gene. The default errors for differing rows and deduplicates identical rows. Explicit mean or sum requires choosing an appropriate expression scale; sum is generally inappropriate for log-transformed expression. |
Uses the score definition and missing-data rules documented in
calculateSingleAnnotationStatistics(). The reported pval and pval_adj
columns are heuristic ranking measures, not calibrated identification
p-values or biological-replicate inference.
A data.frame preserving feature order and rowData, with ranked annotation columns; or a named list when return.top=FALSE.
utils::str(formals(calculateAnnotationStatistics))utils::str(formals(calculateAnnotationStatistics))
Pearson correlations are calculated directly between a selected m/z assay and pathway expression in altExp, aligned by pixel IDs. This replaces the former temporary Seurat assay and synthetic-mass Cardinal conversion.
calculateSingleAnnotationStatistics( mz, data, mz.assay = "main", pathway.assay = "pathway", mz.slot = "counts", pathway.slot = "pathwayScores", corr_theshold = 0, corr_weight = 1, n_weight = 1, database = NULL, database_version = "latest", database_source = c("auto", "spamtpdb"), database_local_dir = NULL )calculateSingleAnnotationStatistics( mz, data, mz.assay = "main", pathway.assay = "pathway", mz.slot = "counts", pathway.slot = "pathwayScores", corr_theshold = 0, corr_weight = 1, n_weight = 1, database = NULL, database_version = "latest", database_source = c("auto", "spamtpdb"), database_local_dir = NULL )
mz |
One numeric m/z query or exact character feature ID. |
data |
A SingleCellExperiment or SpatialExperiment with paired altExp. |
mz.assay |
Primary experiment ("main") or alternative MSI experiment. |
pathway.assay |
Alternative experiment containing pathway-level scores. |
mz.slot |
Expression assay in the MSI experiment. See experimentAccess for the experiment/matrix distinction. |
pathway.slot |
Expression assay in the pathway experiment. See experimentAccess for the experiment/matrix distinction. |
corr_theshold |
Minimum signed pathway correlation (legacy spelling). |
corr_weight, n_weight
|
Non-negative weights, not both zero. |
database |
Optional named list from loadSpaMTPDatabase. |
database_version, database_source, database_local_dir
|
Database selection; see loadSpaMTPDatabase. |
For each candidate, max_cor is the signed correlation of the pathway with largest absolute correlation; ties use pathway ID order. n_sig_path counts finite correlations strictly greater than corr_theshold (zero therefore counts positive correlations, not every pathway). The score is corr_weight * scale(abs(max_cor)) + n_weight * scale(n_sig_path), across candidates for one feature. A constant component contributes zero. Constant expression and unmeasured pathways have undefined correlations. Scores require two evaluable candidates; otherwise scores and probabilities are NA.
pval is the standard-normal upper tail of this weighted score; pval_adj applies BH within each feature. These are legacy heuristic ranking measures, not calibrated identification p-values: the weighted components are not independent, the combined score need not be standard normal, and pixels are not biological replicates. Correlation is across all supplied pixels; subset samples/conditions beforehand when appropriate.
Current scored RaMP annotations take precedence over rowData RaMP IDs. Older all_Isomers_IDs columns can be mapped via source_df$sourceId. Duplicate candidate IDs are counted once.
A tibble ordered by decreasing score, containing metabolite, ramp_id, n_sig_path, max_cor, z_score, pval and pval_adj.
utils::str(formals(calculateSingleAnnotationStatistics))utils::str(formals(calculateSingleAnnotationStatistics))
Convert a Cardinal object to an optional Seurat object
cardinalToSeurat( data, multi.run = FALSE, seurat.coord = NULL, assay = "Spatial", verbose = TRUE )cardinalToSeurat( data, multi.run = FALSE, seurat.coord = NULL, assay = "Spatial", verbose = TRUE )
data |
A Cardinal |
multi.run |
Retained for compatibility; run identities are preserved during the intermediate conversion. |
seurat.coord |
Optional replacement coordinates with |
assay |
Name of the Seurat assay. |
verbose |
Show conversion messages. |
A Seurat object.
utils::str(formals(cardinalToSeurat))utils::str(formals(cardinalToSeurat))
The intensity matrix is stored as an assay, Cardinal featureData() becomes
rowData(), pixelData() becomes colData(), and coord() becomes
spatialCoords(). This conversion materialises a matter-backed intensity
matrix; raw continuous data should be binned with Cardinal before conversion.
cardinalToSpatialExperiment(x, assayName = "counts", materialize = TRUE)cardinalToSpatialExperiment(x, assayName = "counts", materialize = TRUE)
x |
A Cardinal |
assayName |
Name of the assay in the returned object. |
materialize |
Whether a non-matrix Cardinal assay may be materialised. |
A SpatialExperiment.
utils::str(formals(cardinalToSpatialExperiment))utils::str(formals(cardinalToSpatialExperiment))
Checks if the complete adduct is in the data base, else returns a truncated adduct
check_and_truncate_adduct_vector(adduct, db, verbose = TRUE)check_and_truncate_adduct_vector(adduct, db, verbose = TRUE)
adduct |
Character string defining the adduct to be checked. |
db |
DataFrame of the current reference database. |
verbose |
Boolean indicating whether to show the message. If TRUE the message will be show, else the message will be suppressed (default = TRUE). |
Character string of the complete or truncated adduct
# HMDB_db <- load("data/HMDB_1_names.rds") # check_and_truncate_adduct_vector(c("M+H"), HMDB_db)# HMDB_db <- load("data/HMDB_1_names.rds") # check_and_truncate_adduct_vector(c("M+H"), HMDB_db)
Checks if the Cardinal Package installed is >= version 3.6.0
check_cardinal_version()check_cardinal_version()
Boolean indicating if the version of Cardinal is >= 3.6.0
Inspect the alignment of two spatial experiments
checkAlignment( SM.data, ST.data, names = c("SM", "ST"), cols = NULL, image.slice = NULL, size = 0.5 )checkAlignment( SM.data, ST.data, names = c("SM", "ST"), cols = NULL, image.slice = NULL, size = 0.5 )
SM.data, ST.data
|
SpatialExperiment objects in the same coordinate units. |
names |
Two labels for the source and target measurements. |
cols |
Two point colours. |
image.slice |
Optional image ID in ST.data. With multiple samples, subset to one sample before drawing an image overlay. |
size |
Point size. |
A ggplot; multiple samples are shown in separate panels.
Combines rigid tranformation matrices in the following order: translation of points to origin (0, 0) -> reflection of points -> rotation by alpha degrees and translation of points to new center
combineTransformations( center.cur, center.new, alpha, mirror.x = FALSE, mirror.y = FALSE )combineTransformations( center.cur, center.new, alpha, mirror.x = FALSE, mirror.y = FALSE )
center.cur |
(x, y) image pixel coordinates specifying the current center of the tissue (stored as the |
center.new |
(x, y) image pixel coordinates specifying the new center (image center) |
alpha |
Rotation angle |
mirror.x, mirror.y
|
Logical values indicating reflection across the x or y axis before rotation. |
A 3-by-3 homogeneous affine-transformation matrix.
utils::str(formals(combineTransformations)) transformation <- combineTransformations( center.cur = c(0, 0), center.new = c(10, 20), alpha = 90 ) stopifnot(identical(dim(transformation), c(3L, 3L)))utils::str(formals(combineTransformations)) transformation <- combineTransformations( center.cur = c(0, 0), center.new = c(10, 20), alpha = 90 ) stopifnot(identical(dim(transformation), c(3L, 3L)))
Convert an optional Seurat object to Cardinal
convertSeuratToCardinal( data, assay = "Spatial", slot = "counts", run_col = NULL, feature.metadata = FALSE, verbose = TRUE )convertSeuratToCardinal( data, assay = "Spatial", slot = "counts", run_col = NULL, feature.metadata = FALSE, verbose = TRUE )
data |
A Seurat object. |
assay |
Seurat assay to convert. |
slot |
Exact Seurat expression layer name, read with
|
run_col |
Optional cell-metadata column containing run identifiers. |
feature.metadata |
Retained for compatibility. Feature metadata are always preserved. |
verbose |
Show conversion messages. |
A Cardinal MSImagingExperiment.
utils::str(formals(convertSeuratToCardinal))utils::str(formals(convertSeuratToCardinal))
Combines selected modalities as a scaled alternative experiment. Useful for integrating multiple modalities (e.g. transcriptomics, proteomics, metabolomics) that have already been scaled.
createMergedModalityAssay( SpaMTP, assays.to.merge, new.assay = "merged", return.original = TRUE, verbose = FALSE )createMergedModalityAssay( SpaMTP, assays.to.merge, new.assay = "merged", return.original = TRUE, verbose = FALSE )
SpaMTP |
A SpatialExperiment containing at least two paired modalities. |
assays.to.merge |
At least two distinct modality names: |
new.assay |
Name of the output alternative experiment, not an expression
matrix (default = |
return.original |
TRUE adds an altExp; FALSE returns only the merged feature space. |
verbose |
Reserved compatibility argument; no progress messages are emitted. |
Prefers the native scaled assay, then the legacy scale.data assay;
otherwise centres and scales logcounts, normcounts or counts across
pixels. Constant features become zero.
The merged values are stored as scaled, never relabelled as counts.
If return.original = TRUE, the input SpatialExperiment with
altExp(SpaMTP, new.assay) containing a scaled assay. Otherwise a new
SpatialExperiment with merged rows, the same pixels and a scaled assay.
x <- SpatialExperiment::SpatialExperiment( assays = list(counts = rbind(a = 1:4, b = 4:1)), spatialCoords = cbind(x = 1:4, y = 0), colData = S4Vectors::DataFrame(row.names = paste0("p", 1:4))) rna <- matrix(c(1, 3, 2, 4), nrow = 1, dimnames = list("gene1", colnames(x))) x <- addTranscriptome(x, rna) x <- createMergedModalityAssay(x, c("main", "transcriptome")) merged <- SingleCellExperiment::altExp(x, "merged") SummarizedExperiment::assay(merged, "scaled")x <- SpatialExperiment::SpatialExperiment( assays = list(counts = rbind(a = 1:4, b = 4:1)), spatialCoords = cbind(x = 1:4, y = 0), colData = S4Vectors::DataFrame(row.names = paste0("p", 1:4))) rna <- matrix(c(1, 3, 2, 4), nrow = 1, dimnames = list("gene1", colnames(x))) x <- addTranscriptome(x, rna) x <- createMergedModalityAssay(x, c("main", "transcriptome")) merged <- SingleCellExperiment::altExp(x, "merged") SummarizedExperiment::assay(merged, "scaled")
Maps genes or mass features to RaMP identities in a new altExp().
Rows are gene/compound identities, not pathway scores. Use this identity
expression for enrichment or co-regulation analysis, or call
createPathwayObject() to construct pathway-level scores.
createPathwayAssay( SpaMTP, analyte_type = "metabolites", assay = "Spatial", slot = "counts", new_assay = "pathway", annotation_score_threshold = 0.05, annotation_source = c("current", "auto", "legacy"), verbose = TRUE, database = NULL, database_version = "latest", database_source = c("auto", "spamtpdb"), database_local_dir = NULL, gene_mapping = c("auto", "hgnc", "ramp"), gene_reference = NULL, gene_index = NULL, gene_reference_version = "latest", gene_reference_local_dir = NULL, organism = "Homo sapiens", pathway_index = NULL, duplicate_genes = c("error", "mean", "sum"), id_column = NULL, metabolite_ambiguity = c("expand", "exclude") )createPathwayAssay( SpaMTP, analyte_type = "metabolites", assay = "Spatial", slot = "counts", new_assay = "pathway", annotation_score_threshold = 0.05, annotation_source = c("current", "auto", "legacy"), verbose = TRUE, database = NULL, database_version = "latest", database_source = c("auto", "spamtpdb"), database_local_dir = NULL, gene_mapping = c("auto", "hgnc", "ramp"), gene_reference = NULL, gene_index = NULL, gene_reference_version = "latest", gene_reference_local_dir = NULL, organism = "Homo sapiens", pathway_index = NULL, duplicate_genes = c("error", "mean", "sum"), id_column = NULL, metabolite_ambiguity = c("expand", "exclude") )
SpaMTP |
A SingleCellExperiment, including SpatialExperiment, containing metabolomic or transcriptomic expression. |
analyte_type |
Character string specifying the type of analytes to process.Must be either "genes" or "metabolites" (default = "metabolites"). |
assay |
Primary ( |
slot |
Expression assay name within the selected experiment
(default = |
new_assay |
Name for the identity-level |
annotation_score_threshold |
Minimum indexed annotation score used to map m/z features to RaMP compounds (default = 0.05). |
annotation_source |
Metabolite annotation provenance. |
verbose |
Boolean logical value indicating whether to print verbose messages during execution. (default = TRUE). |
database |
Optional named list of database resources, normally created
by |
database_version |
SpaMTPdb/RaMP version used for pathway lookup. |
database_source |
Database source; see |
database_local_dir |
Optional staged SpaMTPdb resource directory. |
gene_mapping |
|
gene_reference |
HGNC reference data frame. |
gene_index |
Optional index built from the same source table by
|
gene_reference_version |
Version in SpaMTPdb's separate HGNC registry. |
gene_reference_local_dir |
Local HGNC resource directory. |
organism |
Must be |
pathway_index |
A reusable index from buildPathwayIndex(). When supplied, its gene identities and memberships must match any explicit database or gene_index. Fingerprints prevent incompatible reuse. |
duplicate_genes |
How to aggregate expression rows of one gene. The default errors for differing rows and deduplicates identical rows. Explicit mean or sum requires choosing an appropriate expression scale; sum is generally inappropriate for log-transformed expression. |
id_column |
Gene identifier column in the selected |
metabolite_ambiguity |
Expand a mass feature into candidate compounds (historical behavior), or exclude features mapping to more than one compound. The workflow explicitly defaults to exclude. Candidate pairs, excluded features and exact aggregation weights are retained in metadata. |
Gene expression uses the shared HGNC identity index. Non-conflicting RaMP records of one gene count once. Different expression rows for a gene require an explicit aggregation choice. In custom RaMP-only compatibility mode the historical default is mean. The selected expression assay name is preserved for genes, including logcounts. Inputs, member coverage, duplicate handling and index provenance are stored in metadata(altExp(x, new_assay))$pathway_mapping.
The input container with a new
SingleCellExperiment::altExp(SpaMTP, new_assay). Its expression assay
retains the name supplied in slot, and its rowData() describes the
RaMP identities and original measured features.
utils::str(formals(createPathwayAssay)) ## Create a pathway assay from metabolite data #spamtp_obj <- createPathwayAssay(spamtp_obj, analyte_type = "metabolites", assay = "SPM", new_assay = "pathway") ## Create a pathway assay from gene data with verbose output #spamtp_obj <- createPathwayAssay(spamtp_obj, analyte_type = "genes", assay = "SPT", new_assay = "gene_pathway", verbose = TRUE)utils::str(formals(createPathwayAssay)) ## Create a pathway assay from metabolite data #spamtp_obj <- createPathwayAssay(spamtp_obj, analyte_type = "metabolites", assay = "SPM", new_assay = "pathway") ## Create a pathway assay from gene data with verbose output #spamtp_obj <- createPathwayAssay(spamtp_obj, analyte_type = "genes", assay = "SPT", new_assay = "gene_pathway", verbose = TRUE)
This function computes pathway-level scores from analyte-level expression data and stores them in altExp for SingleCellExperiment-derived objects. Each score is the sum of matched expression divided by the square root of the matched feature count, then centred and scaled across pixels. Constant scores are zero; unmatched pathways are removed or stored as NA.
createPathwayObject( object, assay = NULL, slot = "logcounts", new.assay = "pathway", remove.nans = TRUE, database = NULL, database_version = "latest", database_source = c("auto", "spamtpdb"), database_local_dir = NULL, gene_mapping = c("auto", "hgnc", "ramp"), gene_reference = NULL, gene_index = NULL, gene_reference_version = "latest", gene_reference_local_dir = NULL, organism = "Homo sapiens", pathway_index = NULL, duplicate_genes = c("error", "mean", "sum"), min_path_size = 1, max_path_size = Inf )createPathwayObject( object, assay = NULL, slot = "logcounts", new.assay = "pathway", remove.nans = TRUE, database = NULL, database_version = "latest", database_source = c("auto", "spamtpdb"), database_local_dir = NULL, gene_mapping = c("auto", "hgnc", "ramp"), gene_reference = NULL, gene_index = NULL, gene_reference_version = "latest", gene_reference_local_dir = NULL, organism = "Homo sapiens", pathway_index = NULL, duplicate_genes = c("error", "mean", "sum"), min_path_size = 1, max_path_size = Inf )
object |
A SingleCellExperiment (including SpatialExperiment) with expression features indexed by gene identifiers or RaMP IDs. |
assay |
Primary or alternative experiment to score. |
slot |
Expression assay. If omitted for a Bioconductor container, prefers logcounts, normcounts, then counts in the selected experiment. See experimentAccess for the experiment/matrix distinction. |
new.assay |
Name for the pathway-level |
remove.nans |
Remove pathways without matched analytes (default TRUE). |
database |
Optional named list of database resources, normally created
by |
database_version |
SpaMTPdb/RaMP version used for pathway lookup. |
database_source |
Database source; see |
database_local_dir |
Optional staged SpaMTPdb resource directory. |
gene_mapping |
|
gene_reference |
HGNC reference data frame. |
gene_index |
Optional index built from the same source table by
|
gene_reference_version |
Version in SpaMTPdb's separate HGNC registry. |
gene_reference_local_dir |
Local HGNC resource directory. |
organism |
Must be |
pathway_index |
A reusable index from buildPathwayIndex(). When supplied, its gene identities and memberships must match any explicit database or gene_index. Fingerprints prevent incompatible reuse. |
duplicate_genes |
How to aggregate expression rows of one gene. The default errors for differing rows and deduplicates identical rows. Explicit mean or sum requires choosing an appropriate expression scale; sum is generally inappropriate for log-transformed expression. |
min_path_size |
Minimum measured unique members to score (default 1). |
max_path_size |
Maximum measured unique members to score (default Inf). |
Accepts gene identifiers directly or a harmonized RaMP assay. min_path_size and max_path_size are applied to measured unique members. rowData contains database_size (after identity reconciliation), database_raw_size, measured_size, coverage_fraction, used_size, database_members, measured_members, used_members and excluded_conflict_records. The complete coverage table, including excluded and unmeasured pathways, is retained in metadata(altExp(x, new.assay))$pathway_mapping$coverage. Scores summarize observed expression; they are not pathway activity tests.
The input with pathwayScores in a new alternative experiment. Pathway identifiers are preserved.
utils::str(formals(createPathwayObject))utils::str(formals(createPathwayObject))
Filters the provided metabolomic database by polarity and adducts
db_adduct_filter(db, adduct, polarity = "neg", verbose = TRUE)db_adduct_filter(db, adduct, polarity = "neg", verbose = TRUE)
db |
DataFrame of the current reference database. |
adduct |
Character string defining the adduct to be checked. |
polarity |
Character string defining the polarity of the adducts (default = "neg"). |
verbose |
Boolean indicating whether to show the message. If TRUE the message will be show, else the message will be suppressed (default = TRUE). |
A filtered reference metabolomic database DataFrame
# HMDB_db <- load("data/HMDB_1_names.rds") # db_adduct_filter(HMDB_db,c("M+H"), polarity = "pos")# HMDB_db <- load("data/HMDB_1_names.rds") # db_adduct_filter(HMDB_db,c("M+H"), polarity = "pos")
A lightweight, dependency-free SMILES graph parser identifies common metabolite functional groups and derives interpretable positive-ion, negative-ion, alkali-binding, and neutral-mass priors. The parser is intended for candidate prioritisation rather than pKa, proton-affinity, or quantum chemistry calculations. Stereochemistry is accepted but does not change the counts.
deconvolveSMILES( smiles, backend = c("auto", "native"), strict = FALSE, workers = getOption("SpaMTP.smiles_workers", 1L) )deconvolveSMILES( smiles, backend = c("auto", "native"), strict = FALSE, workers = getOption("SpaMTP.smiles_workers", 1L) )
smiles |
Character vector of SMILES strings. |
backend |
Currently |
strict |
Stop when any SMILES cannot be parsed. When |
workers |
Number of forked workers used for unique SMILES on platforms
supporting |
A data frame with functional-group counts, ion-mode scores, and a
human-readable structure_evidence field.
utils::str(formals(deconvolveSMILES))utils::str(formals(deconvolveSMILES))
Generates a heatmap of DEMs generated from edgeR analysis run using findAllDEMs().
This function uses pheatmap to plot data.
demsHeatmap( edgeR_output, n = 5, only.pos = FALSE, FDR.threshold = 0.05, logfc.threshold = 0.5, order.by = "FDR", scale = "row", color = (grDevices::colorRampPalette(c("navy", "white", "red")))(50), cluster_cols = FALSE, cluster_rows = TRUE, fontsize_row = 15, fontsize_col = 15, cutree_cols = 9, silent = TRUE, plot_annotations_column = NULL, save_to_path = NULL, plot.save.width = 20, plot.save.height = 20, nlabels.to.show = NULL, annotation_colors = NULL )demsHeatmap( edgeR_output, n = 5, only.pos = FALSE, FDR.threshold = 0.05, logfc.threshold = 0.5, order.by = "FDR", scale = "row", color = (grDevices::colorRampPalette(c("navy", "white", "red")))(50), cluster_cols = FALSE, cluster_rows = TRUE, fontsize_row = 15, fontsize_col = 15, cutree_cols = 9, silent = TRUE, plot_annotations_column = NULL, save_to_path = NULL, plot.save.width = 20, plot.save.height = 20, nlabels.to.show = NULL, annotation_colors = NULL )
edgeR_output |
A list containing outputs from edgeR analysis (from findAllDEMs()). This includes pseudo-bulked counts and DEMs. |
n |
A numeric integer that defines the number of UP and DOWN regulated peaks to plot (default = 25). |
only.pos |
Boolean indicating if only positive markers should be returned (default = FALSE). |
FDR.threshold |
Numeric value that defines the FDR threshold to use for defining most significant results (default = 0.05). |
logfc.threshold |
Numeric value that defines the logFC threshold to use for filtering significant results (default = 0.5). |
order.by |
Ranking column: |
scale |
A character string indicating if the values should be centered and scaled in either the row direction or the column direction, or none. Corresponding values are "row", "column" and "none" |
color |
A vector of colors used in heatmap (default = grDevices::colorRampPalette(c("navy", "white", "red"))(50)). |
cluster_cols |
Boolean value determining if columns should be clustered or hclust object (default = FALSE). |
cluster_rows |
Boolean value determining if rows should be clustered or hclust object (default = TRUE). |
fontsize_row |
A numeric value defining the fontsize of rownames (default = 15). |
fontsize_col |
A numeric value defining the fontsize of colnames (default = 15). |
cutree_cols |
A numeric value defining the number of clusters the columns are divided into, based on the hierarchical clustering(using cutree), if cols are not clustered, the argument is ignored (default = 9). |
silent |
Boolean value indicating if the plot should not be draw (default = TRUE). |
plot_annotations_column |
Character string indicating the column name that contains the metabolite annotations to plot. Annotations = TRUE must be used in findAllDEMs() for edgeR output to include annotations. If plot_annotations_column = NULL, m/z vaues will be plotted (default = NULL). |
save_to_path |
Character string defining the full filepath and name of the plot to be saved as. |
plot.save.width |
Integer value representing the width of the saved pdf plot (default = 20). |
plot.save.height |
Integer value representing the height of the saved pdf plot (default = 20). |
nlabels.to.show |
Numeric value defining the number of annotations to show per m/z (default = NULL). |
annotation_colors |
List for specifying annotation_row and annotation_col track colors manually. Check pheatmap R-Package documentation for details. If set to 'NA', default coloring will be used (default = NA). |
A heatmap plot of significantly differentially expressed metabolites defined in the edgeR ouput object.
utils::str(formals(demsHeatmap)) # demsHeatmap(DEMs)utils::str(formals(demsHeatmap)) # demsHeatmap(DEMs)
The spatial kernel uses coordinates of nonzero pixels, not intensity weights. The mass-spectrum overlay uses an intensity-weighted density without replicating each mass according to its intensity. This exploratory viewer is not a spatial significance test. Its HTML requires internet access to load the existing Plotly and JavaScript KDE libraries.
densityMap( object, assay = "main", slot = "counts", folder = getwd(), sampleId = NULL, ... )densityMap( object, assay = "main", slot = "counts", folder = getwd(), sampleId = NULL, ... )
object |
A SpatialExperiment or aligned Cardinal experiment. |
assay |
Primary or alternative experiment. |
slot |
Non-negative intensity assay. See experimentAccess for the experiment/matrix distinction. |
folder |
Output directory. |
sampleId |
Sample ID; required for multiple samples. |
... |
Reserved; unused arguments cause an error. |
Invisibly, the path to mzs_density_map.html.
utils::str(formals(densityMap))utils::str(formals(densityMap))
SpaMTP uses public S4 accessors, not internal slots. A SpatialExperiment is a SingleCellExperiment and a SummarizedExperiment. The required container class is stated on each function's help page; spatial operations need coordinates, while paired modalities and reductions need SingleCellExperiment infrastructure. Raw, unaligned MSI spectra remain in Cardinal until binned or aligned to a common feature-by-pixel matrix.
This is a documentation topic, not a callable function. The accessors
described here return the selected data: assay() returns a matrix-like
object, altExp() returns an alternative experiment, rowData() and
colData() return DataFrame objects, and spatialCoords() returns a
coordinate matrix. Replacement accessors update the corresponding data
in the experiment. See each accessor's help page for its full return contract.
In analysis functions, assay selects the primary experiment ("main")
or a named SingleCellExperiment::altExp(). The compatibility arguments
slot, slots, SM.slot, ST.slot, SM_slot, ST_slot, mz.slot and
pathway.slot select expression assay names within those experiments.
They do not name S4 slots. Supply exact, non-empty character names, not
numeric matrix positions. For example, assay = "transcriptome" and
slot = "logcounts" read
SummarizedExperiment::assay(SingleCellExperiment::altExp(x, "transcriptome"), "logcounts").
The expression assays within one experiment share feature and pixel axes;
counts, normcounts, logcounts and scaled represent different value
scales, not different modalities. Each alternative experiment has its own
feature rows and the same paired pixel columns. Inspect assayNames() and
altExpNames() before selecting data. No automatic alias maps data to
logcounts or scale.data to scaled during matrix access.
For older analysis calls, NULL, "primary", "Spatial", "SPM", the
primary experiment's mainExpName(), and its expression assay names can
also select the primary experiment. An exact alternative-experiment name
takes precedence over these aliases. Prefer "main" and explicit
altExpNames() in new code. An expression name supplied as assay does
not replace the separate slot selection. Constructors and explicit
converters have their own documented naming arguments.
Use SummarizedExperiment::rowData() for feature annotations and
SummarizedExperiment::colData() for pixel metadata. A primary experiment
and each altExp() have separate rowData() and S4Vectors::metadata().
Parent pixel metadata are not automatically copied into an extracted
alternative experiment. Use SingleCellExperiment::colLabels() for groups,
reducedDim() for embeddings and colPair() for pixel-pair graphs.
SpatialExperiment coordinates and images are accessed with
spatialCoords(), imgData() and imgRaster().
Accessors have replacement forms. Standard column subsetting keeps paired alternative experiments and spatial coordinates aligned. Row subsetting changes only the selected experiment's feature space. SpaMTP does not require users to define additional S4 slots or inspect internal storage.
Core analysis does not use Seurat. SeuratObject is an optional dependency
for seuratToSingleCellExperiment(), seuratToSpatialExperiment() and
spatialExperimentToSeurat(). Convert once at the boundary, then use the
native Bioconductor workflow. Seurat assay names become experiment names;
selected Seurat layers become expression assays as documented by the converter.
asSpatialExperiment(), addTranscriptome(), normalizeSMData(),
scaleSMData(), runMetabolicPCA()
x <- SpatialExperiment::SpatialExperiment( assays = list(counts = rbind(a = 1:4, b = 4:1)), spatialCoords = cbind(x = 1:4, y = 0), colData = S4Vectors::DataFrame(row.names = paste0("p", 1:4))) rna <- matrix(c(1, 3, 2, 4), nrow = 1, dimnames = list("gene1", colnames(x))) x <- addTranscriptome(x, rna) x <- normalizeSMData(x, "LogNormalize", assay = "transcriptome", slot = "counts", verbose = FALSE) rna <- SingleCellExperiment::altExp(x, "transcriptome") SummarizedExperiment::assayNames(rna) SummarizedExperiment::assay(rna, "logcounts") SummarizedExperiment::rowData(rna)$feature_label <- "example gene" SingleCellExperiment::altExp(x, "transcriptome") <- rna SummarizedExperiment::colData(x)$region <- c("A", "A", "B", "B") selected <- x[, x$region == "A"] stopifnot(identical(colnames(SingleCellExperiment::altExp(selected, "transcriptome")), colnames(selected)))x <- SpatialExperiment::SpatialExperiment( assays = list(counts = rbind(a = 1:4, b = 4:1)), spatialCoords = cbind(x = 1:4, y = 0), colData = S4Vectors::DataFrame(row.names = paste0("p", 1:4))) rna <- matrix(c(1, 3, 2, 4), nrow = 1, dimnames = list("gene1", colnames(x))) x <- addTranscriptome(x, rna) x <- normalizeSMData(x, "LogNormalize", assay = "transcriptome", slot = "counts", verbose = FALSE) rna <- SingleCellExperiment::altExp(x, "transcriptome") SummarizedExperiment::assayNames(rna) SummarizedExperiment::assay(rna, "logcounts") SummarizedExperiment::rowData(rna)$feature_label <- "example gene" SingleCellExperiment::altExp(x, "transcriptome") <- rna SummarizedExperiment::colData(x)$region <- c("A", "A", "B", "B") selected <- x[, x$region == "A"] stopifnot(identical(colnames(SingleCellExperiment::altExp(selected, "transcriptome")), colnames(selected)))
Finds differentially expressed m/z values/metabolites between all comparison groups.
findAllDEMs( data, ident, n = 3, logFC_threshold = 1.2, DE_output_dir = NULL, run_name = "findAllDEMs", annotation.column = NULL, assay = "Spatial", slot = "counts", return.individual = FALSE, verbose = TRUE, seed = 1234, method = c("technical", "markers", "replicate"), replicate = NULL, contrasts = list(), min_region_size = 3, spatial_blocks = 0 )findAllDEMs( data, ident, n = 3, logFC_threshold = 1.2, DE_output_dir = NULL, run_name = "findAllDEMs", annotation.column = NULL, assay = "Spatial", slot = "counts", return.individual = FALSE, verbose = TRUE, seed = 1234, method = c("technical", "markers", "replicate"), replicate = NULL, contrasts = list(), min_region_size = 3, spatial_blocks = 0 )
data |
A SingleCellExperiment, including SpatialExperiment, for
|
ident |
Column name in |
n |
An integer that defines the number of pseudo-replicates (pools) per sample (default = 3). |
logFC_threshold |
Technical-mode fold-change threshold, passed as
|
DE_output_dir |
A character string defining the directory path for all output files to be stored. This path must a new directory. Else, set to NULL as default. |
run_name |
A character string defining the title of this DE analysis that will be used when saving DEMs to .csv file (default = 'findAllDEMs'). |
annotation.column |
Optional column in the selected experiment's
|
assay |
Primary ( |
slot |
Expression assay name within the selected experiment
(default = |
return.individual |
In technical mode, return one result per group instead of a merged result. Unsupported in marker/replicate modes. |
verbose |
Boolean indicating whether to show the message. If TRUE the message will be show, else the message will be suppressed (default = TRUE). |
seed |
Numeric value used to set the seed for reproducible randomisation (default = 1234). |
method |
|
replicate |
Complete colData field identifying biological replicates. |
contrasts |
Named list of numerator, denominator and paired settings, required for replicate inference. At least three replicates per arm or three complete pairs are required. |
min_region_size |
Minimum labelled observations in a marker group. |
spatial_blocks |
Number of spatial blocks per sample for a leave-one-block sensitivity analysis of marker effects, or zero to disable. Blocks use coordinates only. They are not biological replicates or confidence intervals. |
A result list, not a modified experiment. Technical mode returns
pooled values in counts and differential results in DEMs (or a list
per group when return.individual = TRUE). Marker mode returns DEMs,
scores, expression, group eligibility and provenance. Replicate mode
returns group_means and named tests with status and, when eligible,
limma tables and the biological-replicate design. Marker mode may return
status = "skipped" with a reason when too few groups are eligible.
utils::str(formals(findAllDEMs))utils::str(formals(findAllDEMs))
Finds if any metabolite is duplicated across multiple m/z values.
findDuplicateAnnotations(data, assay = "main")findDuplicateAnnotations(data, assay = "main")
data |
Bioconductor experiment containing annotated m/z values. |
assay |
Character string defining the primary or alternative experiment that contains the annotated metadata corresponding to the m/z values (default = "Spatial"). |
Vector of character strings describing metabolites that are assigned to multiple m/z values
utils::str(formals(findDuplicateAnnotations))utils::str(formals(findDuplicateAnnotations))
Finds the nearest m/z peak to a given value in a SpaMTP Object
findNearestMZ(data, target_mz, assay = NULL)findNearestMZ(data, target_mz, assay = NULL)
data |
A SummarizedExperiment, including SingleCellExperiment or
SpatialExperiment, with feature m/z values in |
target_mz |
Numeric value defining the target m/z peak |
assay |
Primary ( |
The exact character feature identifier for the nearest measured m/z, not a numeric mass. Ties select the first feature in the stored order.
utils::str(formals(findNearestMZ)) # findNearestMZ(spe, target_mz = 400.01)utils::str(formals(findNearestMZ)) # findNearestMZ(spe, target_mz = 400.01)
This the function used to compute the gene/metabolites set enrichment for multi-omics spatial data
findRegionalPathways( SpaMTP, ident, DE.list = NULL, analyte_types = c("genes", "metabolites"), SM_assay = "main", ST_assay = "transcriptome", SM_slot = "counts", ST_slot = "counts", min_path_size = 5, max_path_size = 500, pval_cutoff_mets = 0.05, pval_cutoff_genes = 0.05, annotation_score_threshold = 0.05, annotation_source = c("current", "auto", "legacy"), verbose = TRUE, database = NULL, database_version = "latest", database_source = c("auto", "spamtpdb"), database_local_dir = NULL, gene_mapping = c("auto", "hgnc", "ramp"), gene_reference = NULL, gene_index = NULL, gene_reference_version = "latest", gene_reference_local_dir = NULL, organism = "Homo sapiens", pathway_index = NULL, ranks = NULL, rank_scale = c("rms", "none"), nPermSimple = 1000 )findRegionalPathways( SpaMTP, ident, DE.list = NULL, analyte_types = c("genes", "metabolites"), SM_assay = "main", ST_assay = "transcriptome", SM_slot = "counts", ST_slot = "counts", min_path_size = 5, max_path_size = 500, pval_cutoff_mets = 0.05, pval_cutoff_genes = 0.05, annotation_score_threshold = 0.05, annotation_source = c("current", "auto", "legacy"), verbose = TRUE, database = NULL, database_version = "latest", database_source = c("auto", "spamtpdb"), database_local_dir = NULL, gene_mapping = c("auto", "hgnc", "ramp"), gene_reference = NULL, gene_index = NULL, gene_reference_version = "latest", gene_reference_local_dir = NULL, organism = "Homo sapiens", pathway_index = NULL, ranks = NULL, rank_scale = c("rms", "none"), nPermSimple = 1000 )
SpaMTP |
A Bioconductor experiment contains spatial metabolomics(SM)/transcriptomics(ST) data or both, if contains SM data, it should be annotated via SpaMTP::annotateSM function. |
ident |
A character scalar specifying the region column in cell metadata. |
DE.list |
A list consisting of differential expression data.frames for each input modality. Within each data.frame column names MUST include 'cluster', 'gene', ('avg_log2FC' or 'logFC') and ('p_val_adj' or 'FDR'). |
analyte_types |
Vector of character strings defining which analyte types to use. Options can be c("genes"), c("metabolites") or both (default = c("genes", "metabolites")). |
SM_assay |
Primary MSI experiment name (default = "main"). |
ST_assay |
Paired transcriptome altExp name (default = "transcriptome"). |
SM_slot |
Expression assay name within the metabolomics experiment
selected by |
ST_slot |
Expression assay name within the transcriptomics experiment
selected by |
min_path_size |
The min number of metabolites in a specific pathway (default = 5). |
max_path_size |
The max number of metabolites in a specific pathway (default = 500). |
pval_cutoff_mets |
Adjusted p-value cutoff used when constructing
metabolite ranks. Set to |
pval_cutoff_genes |
A numerical value defining the adjusted p value cutoff for significant differentially expressed genes. If |
annotation_score_threshold |
Minimum indexed annotation score used for
pathway mapping. It can be changed without re-running |
annotation_source |
Metabolite annotation provenance. The default,
|
verbose |
Boolean indicating whether to show informative messages. If FALSE these messages will be suppressed (default = TRUE). |
database |
Optional named list of database resources, normally created
by |
database_version |
SpaMTPdb/RaMP version used for pathway lookup. |
database_source |
Database source; see |
database_local_dir |
Optional staged SpaMTPdb resource directory. |
gene_mapping |
|
gene_reference |
HGNC reference data frame. |
gene_index |
Optional index built from the same source table by
|
gene_reference_version |
Version in SpaMTPdb's separate HGNC registry. |
gene_reference_local_dir |
Local HGNC resource directory. |
organism |
Must be |
pathway_index |
A reusable index from buildPathwayIndex(). When supplied, its gene identities and memberships must match any explicit database or gene_index. Fingerprints prevent incompatible reuse. |
ranks |
Alternative to DE.list: named genes/metabolites matrices with features in rows and regions in columns. Uses complete, unfiltered ranks. Metabolite rows must be explicit RaMP compound IDs. Map expression with createPathwayAssay before calculating identity-level effects. |
rank_scale |
RMS-scale each modality's rank vector before concatenating, or none. Pathways can still be dominated by the more densely measured modality. |
nPermSimple |
Preliminary permutations for the ranks interface. |
Gene mapping uses the same identity index as
fishersPathwayAnalysis(). Multiple RaMP records of a gene have their
memberships united. If multiple input features map to that gene with
different differential statistics in one cluster, resolve the duplicate
features before differential analysis; the function does not select an
arbitrary statistic.
A data frame of regional pathway enrichment results, not a modified experiment. The complete-ranks interface also attaches the ranks, pathway coverage, mapping and multiple-testing provenance as attributes.
utils::str(formals(findRegionalPathways))utils::str(formals(findRegionalPathways))
Calls ape::Moran.I with inverse squared Euclidean distance weights and zero diagonal, row-standardized by ape. Samples are analysed separately. Constant features return NA.
findSpatiallyVariableMetabolites( object, assay = "main", slot = "counts", image = NULL, nfeatures = 2000, max_spots = 5000, seed = 1, verbose = TRUE, sampleId = NULL )findSpatiallyVariableMetabolites( object, assay = "main", slot = "counts", image = NULL, nfeatures = 2000, max_spots = 5000, seed = 1, verbose = TRUE, sampleId = NULL )
object |
A SpatialExperiment or aligned MSImagingExperiment. |
assay |
Primary ( |
slot |
Assay containing expression values. See experimentAccess for the experiment/matrix distinction. |
image |
Retained for compatibility; coordinates use spatialCoords. |
nfeatures |
Maximum variable features selected. |
max_spots |
Maximum pixels for the dense distance matrix; NULL uses all. |
seed |
Random seed for sampling; caller RNG state is restored. |
verbose |
Show progress messages. |
sampleId |
A sample_id in colData. Required for multiple samples. |
A SpatialExperiment with statistics, BH-adjusted p-values, flags and ranks in rowData of the selected experiment. Settings and sampled pixel IDs are stored in metadata(object)$moransi.
x <- SpatialExperiment::SpatialExperiment( assays = list(counts = rbind(a = 1:6, b = c(1, 3, 5, 2, 4, 6))), rowData = S4Vectors::DataFrame(mz = c(100, 200)), spatialCoords = cbind(x = 1:6, y = 0), colData = S4Vectors::DataFrame(row.names = paste0("p", 1:6))) x <- findSpatiallyVariableMetabolites(x) getSpatiallyVariableMetabolites(x)x <- SpatialExperiment::SpatialExperiment( assays = list(counts = rbind(a = 1:6, b = c(1, 3, 5, 2, 4, 6))), rowData = S4Vectors::DataFrame(mz = c(100, 200)), spatialCoords = cbind(x = 1:6, y = 0), colData = S4Vectors::DataFrame(row.names = paste0("p", 1:6))) x <- findSpatiallyVariableMetabolites(x) getSpatiallyVariableMetabolites(x)
Fisher Exact Tests for Pathway Enrichment
fishersPathwayAnalysis( Analyte, max_path_size = 500, min_path_size = 5, alternative = "greater", pathway_all_info = FALSE, pval_cutoff = NULL, verbose = TRUE, database = NULL, database_version = "latest", database_source = c("auto", "spamtpdb"), database_local_dir = NULL, universe = NULL, gene_mapping = c("auto", "hgnc", "ramp"), gene_reference = NULL, gene_index = NULL, gene_reference_version = "latest", gene_reference_local_dir = NULL, organism = "Homo sapiens", pathway_index = NULL, ... )fishersPathwayAnalysis( Analyte, max_path_size = 500, min_path_size = 5, alternative = "greater", pathway_all_info = FALSE, pval_cutoff = NULL, verbose = TRUE, database = NULL, database_version = "latest", database_source = c("auto", "spamtpdb"), database_local_dir = NULL, universe = NULL, gene_mapping = c("auto", "hgnc", "ramp"), gene_reference = NULL, gene_index = NULL, gene_reference_version = "latest", gene_reference_local_dir = NULL, organism = "Homo sapiens", pathway_index = NULL, ... )
Analyte |
Foreground analytes as a named list with elements |
max_path_size |
Maximum pathway size within the analysis universe (inclusive; default 500). |
min_path_size |
Minimum pathway size within the analysis universe (inclusive; positive integer, default 5). |
alternative |
Fisher test alternative: |
pathway_all_info |
Include names, input IDs and m/z adduct information for foreground members of each pathway. Does not change the tests. |
pval_cutoff |
Optional BH-adjusted p-value (FDR) cutoff in |
verbose |
Whether to print progress messages. Mapping warnings are
always emitted, including when |
database |
Optional named resource list from |
database_version |
SpaMTPdb/RaMP version used for pathway lookup. |
database_source |
Database source; see |
database_local_dir |
Optional staged SpaMTPdb resource directory. |
universe |
Optional measured background, in the same named-list format
as |
gene_mapping |
|
gene_reference |
HGNC reference data frame. |
gene_index |
Optional index built from the same source table by
|
gene_reference_version |
Version in SpaMTPdb's separate HGNC registry. |
gene_reference_local_dir |
Local HGNC resource directory. |
organism |
Must be |
pathway_index |
A reusable index from buildPathwayIndex(). When supplied, its gene identities and memberships must match any explicit database or gene_index. Fingerprints prevent incompatible reuse. |
... |
Arguments passed to the indexed |
With universe size U, foreground size K, pathway size M and overlap a, the
test table is matrix(c(a, M - a, K - a, U - K - M + a), nrow = 2).
Memberships and identifiers are deduplicated by RaMP ID. Pathway sizes are
computed after intersecting with the universe; size filtering never changes
that universe. All pathways passing the size limits are tested, including
zero-overlap pathways. BH correction uses this complete family, before any
output cutoff. Missing display metadata does not remove a test.
Unmapped input values are excluded with warnings and recorded in the
enrichment attribute. An empty mapped universe is an error. An empty
foreground gives p-values of 1 for all eligible pathways. If no pathways
pass the size limits, a zero-row data frame is returned.
For a targeted panel, provide the measured panel as universe; the default
database background is not a substitute for the detection background.
m/z foreground and background values are annotated together with identical
settings. All mapped candidate RaMP IDs are retained; ambiguous mass matches
are not confirmed compound identifications. In a combined analysis, genes
and compounds are counted as individual RaMP IDs in a single pooled test.
A data frame sorted by p_val, retaining the columns pathway_name,
pathway_id, type, pathwayCategory, p_val, fdr, ratio,
analytes_in_pathways (overlap) and total_in_pathways (size within the
universe). Also includes pathwayRampId, foreground_analytes_number
and background_analytes_number. pathway_all_info = TRUE adds member
information. The enrichment attribute records mapped foreground and
universe IDs, unmapped inputs, excluded foreground IDs, universe source,
alternative, size limits and the number of tests before output filtering.
Its gene_mapping entry contains per-input mapping status, gene groups,
excluded conflicting RaMP records and versioned reference provenance.
utils::str(formals(fishersPathwayAnalysis)) # For a targeted gene panel: # fishersPathwayAnalysis( # Analyte = list(genes = paste0("gene_symbol:", significant_genes)), # universe = list(genes = paste0("gene_symbol:", measured_panel_genes)) # )utils::str(formals(fishersPathwayAnalysis)) # For a targeted gene panel: # fishersPathwayAnalysis( # Analyte = list(genes = paste0("gene_symbol:", significant_genes)), # universe = list(genes = paste0("gene_symbol:", measured_panel_genes)) # )
Filters reference Database to only select natural elements
formula_filter(df, elements = NULL)formula_filter(df, elements = NULL)
df |
DataFrame of the reference database. |
elements |
Vector of character strings of elements to include (default = c("H", "C", "N", "O", "S", "Cl", "Br", "F", "Na", "P", "I", "Si")). |
A refined DataFrame which only includes annotations containing the specified elements
## Get filtered DB by adduct # db_1 <- db_adduct_filter(db, test_add_pos, polarity = "pos") ## Refine to only include natural elements # db_2 <- formula_filter(db_1)## Get filtered DB by adduct # db_1 <- db_adduct_filter(db, test_add_pos, polarity = "pos") ## Refine to only include natural elements # db_2 <- formula_filter(db_1)
Helper function for building a pathway db based on detected
get_analytes_db(input_id, analytehaspathway, chem_props, pathway)get_analytes_db(input_id, analytehaspathway, chem_props, pathway)
input_id |
Vector of characters defining the detected . |
analytehaspathway |
A dataframe containing RAMP_pathway ID's. |
chem_props |
A database containing the chemical properties and metadata of each RAMP_DB analyte. |
pathway |
A dataframe containing RAMP_DB pathways and their relative metadata |
A analyte database containing corresponding pathways associated with each detected metabolite
#HELPER FUNCTION#HELPER FUNCTION
Runs K-means on an embedding read through SingleCellExperiment::reducedDim()
and writes pixel cluster labels to SummarizedExperiment::colData().
getKmeanClusters( data, reduction = "SpatialPCA", cluster.name = "spatial_clusters", clusters = 8, iter.max = 10, nstart = 1, algorithm = c("Hartigan-Wong", "Lloyd", "Forgy", "MacQueen"), trace = FALSE, seed = 888 )getKmeanClusters( data, reduction = "SpatialPCA", cluster.name = "spatial_clusters", clusters = 8, iter.max = 10, nstart = 1, algorithm = c("Hartigan-Wong", "Lloyd", "Forgy", "MacQueen"), trace = FALSE, seed = 888 )
data |
A SingleCellExperiment, including SpatialExperiment, containing
an embedding such as the result of |
reduction |
Name in |
cluster.name |
Column name in |
clusters |
Integer defining the number of clusters to form (default = 8). |
iter.max |
Integer defining the maximum number of iterations allowed (default = 10). |
nstart |
Integer stating the number of random sets to choose (default = 1). |
algorithm |
Character string defining the K-means algorithm to use. One of |
trace |
Logical boolean indicating whether to produce tracing information on the progress of the algorithm (default = FALSE). |
seed |
Integer of the random seed to use for reproducibility (default = 888). |
The input container with cluster assignments in
SummarizedExperiment::colData(data)[[cluster.name]].
utils::str(formals(getKmeanClusters))utils::str(formals(getKmeanClusters))
The main user-facing function to download annotations and ion images for a METASPACE dataset.
getMetaspace( dataset_id, fdr = 0.1, database = c("HMDB", "v4"), include_images = TRUE, api_key = NULL, isotope_idx = 1, relative = TRUE )getMetaspace( dataset_id, fdr = 0.1, database = c("HMDB", "v4"), include_images = TRUE, api_key = NULL, isotope_idx = 1, relative = TRUE )
dataset_id |
Character string of the METASPACE dataset ID. |
fdr |
Numeric, the FDR level threshold (default = 0.1). |
database |
Character vector, specifying the database name and version (default = c("HMDB", "v4")). |
include_images |
Logical, if TRUE, downloads all ion image matrices (default = TRUE). |
api_key |
Optional character string, your METASPACE API key (default = NULL). |
isotope_idx |
Integer, index of the isotope image to download for all annotations (1 for main peak) (default = 1). |
relative |
Logical, if TRUE, normalizes pixel intensities (0-1 range) (default = TRUE). |
A list with two elements: annotations (data.frame) and images (list of 2D matrices).
utils::str(formals(getMetaspace)) # getMetaspace(dataset_id = "2020-12-07_03h16m14s", fdr = 0.1, database= c("HMDB", "v4"), relative = TRUE)utils::str(formals(getMetaspace)) # getMetaspace(dataset_id = "2020-12-07_03h16m14s", fdr = 0.1, database= c("HMDB", "v4"), relative = TRUE)
Gets values from a single metadata column for a respective m/z value.
getMZMetadata( obj, mz, assay = "main", metadata.column = "all_IsomerNames", separate = TRUE )getMZMetadata( obj, mz, assay = "main", metadata.column = "all_IsomerNames", separate = TRUE )
obj |
Bioconductor experiment containing annotated m/z values. |
mz |
Character string specifying the m/z value to return the metadata for. |
assay |
Character string defining the primary or alternative experiment that contains the annotated metadata corresponding to the m/z values (default = "Spatial"). |
metadata.column |
Character string corresponding to the assay feature metadata column to extract (default = "all_IsomerNames"). |
separate |
Boolean indicating whether to separate the metadata string and return a vector. Note, if |
Vector of character strings containing the metadata for a specific mz value.
utils::str(formals(getMZMetadata)) # getMZMetadata(SpaMTP, mz = "mz-100", metadata.column = "all_IsomerNames") ##### Example for getting metabolite annotation IDs for a m/z value # getMZMetadata(SpaMTP, mz = "mz-100", metadata.column = "all_Isomers")utils::str(formals(getMZMetadata)) # getMZMetadata(SpaMTP, mz = "mz-100", metadata.column = "all_IsomerNames") ##### Example for getting metabolite annotation IDs for a m/z value # getMZMetadata(SpaMTP, mz = "mz-100", metadata.column = "all_Isomers")
Used to subset dataset to only include annotations that have n number of entries. For example some peaks can have multiple annotations. Peaks which have above n number of annotations assigned will be removed from Bioconductor experiment.
getRefinedAnnotations(obj, assay = "main", n = 1)getRefinedAnnotations(obj, assay = "main", n = 1)
obj |
A SummarizedExperiment, including SingleCellExperiment or
SpatialExperiment. The selected experiment must have annotations in |
assay |
Primary ( |
n |
Integer defining the number of entries an annotation can have assigned. Any higher counts will be removed (default = 1). |
The input container with the selected experiment restricted to
features having at most n annotations. Pixel columns are unchanged.
utils::str(formals(getRefinedAnnotations)) # HMDB_db <- load("data/HMDB_1_names.rds")utils::str(formals(getRefinedAnnotations)) # HMDB_db <- load("data/HMDB_1_names.rds")
Get the top spatially variable metabolites
getSpatiallyVariableMetabolites(object, assay = "main", n = 10)getSpatiallyVariableMetabolites(object, assay = "main", n = 10)
object |
A SpatialExperiment returned by findSpatiallyVariableMetabolites. |
assay |
Primary or alternative experiment containing results. |
n |
Maximum number of feature names. |
Feature names in Moran's I rank order, excluding untested features.
This function computes the coordinates of a square's four corners based on a given center point and width.
getSquareCoordinates(center_x, center_y, width, name)getSquareCoordinates(center_x, center_y, width, name)
center_x |
Numeric value defining the x-coordinate of the square's center. |
center_y |
Numeric value defining the y-coordinate of the square's center. |
width |
Numeric value indicating the width of the square. |
name |
Character string specifying the label assigned to the square for identification. |
A data frame with columns Selection, X, and Y representing the square's name and corner coordinates.
utils::str(formals(getSquareCoordinates)) getSquareCoordinates(center_x = 5, center_y = 5, width = 4, name = "MySquare")utils::str(formals(getSquareCoordinates)) getSquareCoordinates(center_x = 5, center_y = 5, width = 4, name = "MySquare")
All matching peaks are summed per metabolite. A peak shared by overlapping mass-tolerance windows is counted once. No temporary metadata is written.
imageMZAnnotationPlot( object, metabolites, plusminus = NULL, fov = NULL, cols = c("lightgrey", "firebrick1"), size = 0.5, min.cutoff = NA, max.cutoff = NA, split.by = NULL, alpha = 1, border.color = "white", border.size = 0, dark.background = TRUE, crop = FALSE, cells = NULL, scale = c("feature", "all", "none"), axes = FALSE, combine = TRUE, coord.fixed = TRUE, assay = "main", slot = "counts", column.name = "all_IsomerNames", plot.exact = TRUE, plot.pixel = FALSE, verbose = TRUE, ... )imageMZAnnotationPlot( object, metabolites, plusminus = NULL, fov = NULL, cols = c("lightgrey", "firebrick1"), size = 0.5, min.cutoff = NA, max.cutoff = NA, split.by = NULL, alpha = 1, border.color = "white", border.size = 0, dark.background = TRUE, crop = FALSE, cells = NULL, scale = c("feature", "all", "none"), axes = FALSE, combine = TRUE, coord.fixed = TRUE, assay = "main", slot = "counts", column.name = "all_IsomerNames", plot.exact = TRUE, plot.pixel = FALSE, verbose = TRUE, ... )
object |
A SpatialExperiment or aligned Cardinal MSImagingExperiment. |
metabolites |
Metabolite names to search in feature annotations. |
plusminus |
Optional non-negative absolute m/z tolerance. |
fov |
Optional sample IDs from colData(object)$sample_id. |
cols |
Gradient colours. |
size |
Point size. |
min.cutoff, max.cutoff
|
One cutoff or one per query; numeric or quantile strings such as "q10". NA uses the observed range. |
split.by |
Optional colData column for separate panels within samples. |
alpha |
Point opacity, or a two-value range mapped to expression. |
border.color, border.size
|
Point border colour and width. |
dark.background |
Use a black plot background. |
crop |
Crop to the selected pixels. |
cells |
Optional pixel IDs to display. |
scale |
Colour limits: "feature" across samples, "all" across all queries, or "none" separately for each panel. |
axes |
Show axes. |
combine |
Combine panels; FALSE returns a list of ggplots. |
coord.fixed |
Use a fixed coordinate aspect ratio. |
assay |
Primary experiment ("main") or altExp name. |
slot |
Expression assay name, e.g. "counts" or "logcounts". See experimentAccess for the experiment/matrix distinction. |
column.name |
Annotation column in rowData. |
plot.exact |
Match complete semicolon-delimited names (case-insensitive). |
plot.pixel |
Draw square rather than circular point symbols. |
verbose |
Retained for call compatibility. |
... |
Former Seurat segmentation, molecule and blending arguments are unsupported and cause an error; convert and plot these separately. |
A ggplot or list of panels.
utils::str(formals(imageMZAnnotationPlot))utils::str(formals(imageMZAnnotationPlot))
These functions read the primary experiment or a named altExp without modifying the object. Numeric m/z queries select the nearest measured mass; character feature IDs select exact rows. A mass tolerance sums all peaks within that distance of the selected measured mass. Overlapping annotation windows count each peak once. Multiple samples are plotted separately.
imageMZPlot( object, mzs, plusminus = NULL, fov = NULL, cols = c("lightgrey", "firebrick1"), size = 0.5, min.cutoff = NA, max.cutoff = NA, split.by = NULL, alpha = 1, border.color = "white", border.size = 0, dark.background = TRUE, crop = FALSE, cells = NULL, scale = c("feature", "all", "none"), axes = FALSE, combine = TRUE, coord.fixed = TRUE, assay = "main", slot = "counts", plot.pixel = FALSE, verbose = TRUE, ... )imageMZPlot( object, mzs, plusminus = NULL, fov = NULL, cols = c("lightgrey", "firebrick1"), size = 0.5, min.cutoff = NA, max.cutoff = NA, split.by = NULL, alpha = 1, border.color = "white", border.size = 0, dark.background = TRUE, crop = FALSE, cells = NULL, scale = c("feature", "all", "none"), axes = FALSE, combine = TRUE, coord.fixed = TRUE, assay = "main", slot = "counts", plot.pixel = FALSE, verbose = TRUE, ... )
object |
A SpatialExperiment or aligned Cardinal MSImagingExperiment. |
mzs |
Numeric m/z values or character feature IDs. |
plusminus |
Optional non-negative absolute m/z tolerance. |
fov |
Optional sample IDs from colData(object)$sample_id. |
cols |
Gradient colours. |
size |
Point size. |
min.cutoff, max.cutoff
|
One cutoff or one per query; numeric or quantile strings such as "q10". NA uses the observed range. |
split.by |
Optional colData column for separate panels within samples. |
alpha |
Point opacity, or a two-value range mapped to expression. |
border.color, border.size
|
Point border colour and width. |
dark.background |
Use a black plot background. |
crop |
Crop to the selected pixels. |
cells |
Optional pixel IDs to display. |
scale |
Colour limits: "feature" across samples, "all" across all queries, or "none" separately for each panel. |
axes |
Show axes. |
combine |
Combine panels; FALSE returns a list of ggplots. |
coord.fixed |
Use a fixed coordinate aspect ratio. |
assay |
Primary experiment ("main") or altExp name. |
slot |
Expression assay name, e.g. "counts" or "logcounts". See experimentAccess for the experiment/matrix distinction. |
plot.pixel |
Draw square rather than circular point symbols. |
verbose |
Retained for call compatibility. |
... |
Former Seurat segmentation, molecule and blending arguments are unsupported and cause an error; convert and plot these separately. |
A ggplot, or a list of panels when combine is FALSE.
x <- SpatialExperiment::SpatialExperiment( assays = list(counts = rbind(a = 1:4, b = 4:1)), rowData = S4Vectors::DataFrame(mz = c(100, 200)), colData = S4Vectors::DataFrame(row.names = paste0("p", 1:4)), spatialCoords = cbind(x = 1:4, y = c(0, 1, 0, 1))) imageMZPlot(x, mzs = 100)x <- SpatialExperiment::SpatialExperiment( assays = list(counts = rbind(a = 1:4, b = 4:1)), rowData = S4Vectors::DataFrame(mz = c(100, 200)), colData = S4Vectors::DataFrame(row.names = paste0("p", 1:4)), spatialCoords = cbind(x = 1:4, y = c(0, 1, 0, 1))) imageMZPlot(x, mzs = 100)
The app sums every measured feature within the selected mass window without changing the input assays or annotations. The mass-axis controls use rowData masses, never mean intensities. No browser is launched by this function.
interactiveSpatialPlot( obj, assay = "main", slot = "counts", image = NULL, sampleId = NULL )interactiveSpatialPlot( obj, assay = "main", slot = "counts", image = NULL, sampleId = NULL )
obj |
A SpatialExperiment or aligned Cardinal experiment. |
assay |
Primary or alternative experiment. |
slot |
Expression assay. See experimentAccess for the experiment/matrix distinction. |
image |
Optional image ID from imgData. |
sampleId |
Optional sample ID. NULL displays separate sample panels. |
A Shiny application object; use shiny::runApp to launch.
utils::str(formals(interactiveSpatialPlot))utils::str(formals(interactiveSpatialPlot))
Builds a sparse adjacency matrix representing the k-nearest neighbour relationships between spots or cells, using Euclidean distance between spatial coordinates.
kNeighborsGraph( location, n_neighbors, platform, include_self = FALSE, alg = "kd_tree" )kNeighborsGraph( location, n_neighbors, platform, include_self = FALSE, alg = "kd_tree" )
location |
A data frame or matrix with columns |
n_neighbors |
Integer value defining the number of neighbours to consider. |
platform |
Character string being either |
include_self |
Boolean logical value stating whether to include self-connections (default = FALSE). |
alg |
Character string specifying the algorithm to use for nearest neighbour search. Passed to |
A sparse adjacency matrix (dgCMatrix) representing the k-NN graph.
utils::str(formals(kNeighborsGraph)) ### HELPER FUNCTIONutils::str(formals(kNeighborsGraph)) ### HELPER FUNCTION
Filters the annotation list to only include the first n number of annotations per m/z
labels_to_show(annotation_column, n = 3)labels_to_show(annotation_column, n = 3)
annotation_column |
Vector from the |
n |
Numeric value defining the number of annotations to keep (default = 3). |
Vector containing the first n number of annotations
Downloads METASPACE data, converts it to a feature matrix, and
packages it in a Bioconductor SpatialExperiment. Use explicit conversion for other containers.
Coordinates are stored in spatialCoords() without redundant copies in
colData(); dataset and acquisition metadata remain in colData().
loadMetaspace( dataset_id, fdr = 0.1, database = c("HMDB", "v4"), api_key = NULL, relative = FALSE, transform = FALSE, verbose = TRUE, returnType = "SpatialExperiment" )loadMetaspace( dataset_id, fdr = 0.1, database = c("HMDB", "v4"), api_key = NULL, relative = FALSE, transform = FALSE, verbose = TRUE, returnType = "SpatialExperiment" )
dataset_id |
Character string of the METASPACE dataset ID. |
fdr |
Numeric, the FDR level threshold (default = 0.1). |
database |
Character vector, specifying the database name and version (default = c("HMDB", "v4")). |
api_key |
Optional character string, your METASPACE API key (default = NULL). |
relative |
Logical, if TRUE, normalizes pixel intensities (0-1 range) (default = FALSE). |
transform |
Boolean specifiying whether to transform/flip the image (default = FALSE). |
verbose |
Boolean indicating whether to show the message. If TRUE the message will be show, else the message will be suppressed (default = TRUE). |
returnType |
Output container; only |
A SpatialExperiment.
utils::str(formals(loadMetaspace)) # loadMetaspace(dataset_id = "2020-12-07_03h16m14s", fdr = 0.1, database= c("HMDB", "v4"), relative = TRUE)utils::str(formals(loadMetaspace)) # loadMetaspace(dataset_id = "2020-12-07_03h16m14s", fdr = 0.1, database= c("HMDB", "v4"), relative = TRUE)
Raw spectra remain in Cardinal's file-backed MSImagingArrays, without
asking the reader to infer a shared mass axis.
Once a resolution is supplied and Cardinal has
produced a common binned feature axis, the default return value is a
SpatialExperiment. Seurat conversion is explicit and optional.
loadSM( file, mass.range = NULL, resolution = NA, units = "ppm", verbose = TRUE, assay = "Spatial", multi.run = FALSE, returnType = c("auto", "Cardinal", "SpatialExperiment") )loadSM( file, mass.range = NULL, resolution = NA, units = "ppm", verbose = TRUE, assay = "Spatial", multi.run = FALSE, returnType = c("auto", "Cardinal", "SpatialExperiment") )
file |
Character string defining the directory path of the file and the file name. |
mass.range |
Optional two-element mass range for binning. Requires resolution; raw spectral filtering should be performed in Cardinal. |
resolution |
Numeric value defining the the accuracy to which the m/z values will be binned after reading. This value can be in either "ppm" or "mz" depending on the units type specified (default = 10). |
units |
Character string defining the resolution value unit type, either c("ppm", "mz") (default = "ppm") |
verbose |
Boolean indicating whether to show informative processing messages. If TRUE the message will be show, else the message will be suppressed (default = TRUE) |
assay |
Label stored in mainExpName(); intensities are in the counts assay. |
multi.run |
Retained for compatibility; Cardinal run IDs are preserved. |
returnType |
Output container. |
A Cardinal MSImagingArrays/MSImagingExperiment, or a SpatialExperiment.
utils::str(formals(loadSM)) # data <-loadSM(name = "run1", folder = "/Documents/SpaMTP_test_data/", mass.range = c(160,1500), resolution = 10, assay = "Spatial")utils::str(formals(loadSM)) # data <-loadSM(name = "run1", folder = "/Documents/SpaMTP_test_data/", mass.range = c(160,1500), resolution = 10, assay = "Spatial")
Loads a coherent group of annotation resources from SpaMTPdb. Retrieved resources are cached for the current R session. A named custom bundle can be supplied for offline, testing, or user-curated workflows.
loadSpaMTPDatabase( resources = c("chem_props", "source_df", "analyte", "analytehaspathway", "pathway"), version = "latest", source = c("auto", "spamtpdb"), database = NULL, local_dir = NULL, hub = NULL, offline = FALSE, refresh = FALSE, verify = TRUE )loadSpaMTPDatabase( resources = c("chem_props", "source_df", "analyte", "analytehaspathway", "pathway"), version = "latest", source = c("auto", "spamtpdb"), database = NULL, local_dir = NULL, hub = NULL, offline = FALSE, refresh = FALSE, verify = TRUE )
resources |
Character vector of resource names. Use
|
version |
SpaMTPdb/RaMP resource version, or |
source |
Database source. |
database |
Optional named list containing the requested resources. When supplied, no Hub lookup is performed. |
local_dir |
Optional directory containing staged SpaMTPdb |
hub |
Optional pre-created |
offline |
If |
refresh |
If |
verify |
Verify local resource files against the SpaMTPdb registry.
Defaults to |
Exact affected RaMP 3.0.7 topology resources receive a checksum-guarded
correction for historical interaction-code and direction recycling. Source
labels are retained in source_reaction_type; the resource attribute
spamtp_interaction_repair records the correction separately from the
original download metadata. Published files are unchanged. See
vignette("Pathway_Database_Integration", package = "SpaMTP") for provenance
and reproducible build instructions.
A named list containing the requested resources.
utils::str(formals(loadSpaMTPDatabase)) example_database <- list( ramp_db_metadata = list(ramp_version = "example") ) database <- loadSpaMTPDatabase( "ramp_db_metadata", database = example_database ) names(database)utils::str(formals(loadSpaMTPDatabase)) example_database <- list( ramp_db_metadata = list(ramp_version = "example") ) database <- loadSpaMTPDatabase( "ramp_db_metadata", database = example_database ) names(database)
The registry separates conventional MALDI matrices, reactive matrices, and derivatization reagents. A registered profile does not necessarily imply that a universal mass-shift rule is available: some reactions require a coupling reagent, produce several products, or remain strongly dependent on the analyte structure and acquisition conditions.
maldiMatrixProfiles(matrix = NULL)maldiMatrixProfiles(matrix = NULL)
matrix |
Optional matrix/reagent name or alias. When |
A data frame describing supported matrix profiles and their current automatic-rule status.
utils::str(formals(maldiMatrixProfiles))utils::str(formals(maldiMatrixProfiles))
Conventional matrices select ordinary ion rules and, where validated, matrix-metabolite adducts. Reactive matrices additionally select covalent product rules. Profiles without a verified universal net transformation are retained in the registry but do not generate speculative mass shifts.
maldiMatrixRules( maldi_matrix, polarity = NULL, include_standard = TRUE, include_matrix_products = TRUE )maldiMatrixRules( maldi_matrix, polarity = NULL, include_standard = TRUE, include_matrix_products = TRUE )
maldi_matrix |
Matrix or derivatization reagent name; aliases such as
|
polarity |
|
include_standard |
Include the validated ordinary adduct rules. |
include_matrix_products |
Include validated matrix-adduct or reactive product rules. |
A validated adduct/reaction rule data frame accepted by
buildMZAnnotationIndex().
utils::str(formals(maldiMatrixRules))utils::str(formals(maldiMatrixRules))
Accepts approved, previous and alias symbols (bare or gene_symbol:), HGNC,
Entrez, Ensembl gene IDs (optional version suffix), UniProt and RaMP IDs.
Ambiguous identifiers are excluded, never expanded to multiple genes.
Different RaMP records of the same resolved HGNC gene share one canonical
RaMP ID. Gene references are supplied by SpaMTPdb; this function does not
query live annotation services. Input order and duplicates are preserved.
mapGeneIdentifiers( genes, database = NULL, index = NULL, gene_reference = NULL, gene_reference_version = "latest", gene_reference_local_dir = NULL, organism = "Homo sapiens", ambiguous = c("exclude", "error"), verbose = TRUE, database_version = "latest", database_local_dir = NULL, offline = FALSE )mapGeneIdentifiers( genes, database = NULL, index = NULL, gene_reference = NULL, gene_reference_version = "latest", gene_reference_local_dir = NULL, organism = "Homo sapiens", ambiguous = c("exclude", "error"), verbose = TRUE, database_version = "latest", database_local_dir = NULL, offline = FALSE )
genes |
Vector of gene identifiers. |
database |
Optional named SpaMTPdb resource bundle with |
index |
Optional reusable index from |
gene_reference |
HGNC reference data frame. |
gene_reference_version |
Version in SpaMTPdb's separate HGNC registry. |
gene_reference_local_dir |
Local HGNC resource directory. |
organism |
Must be |
ambiguous |
Exclude ambiguous mappings with audit status, or error. |
verbose |
Warn about unresolved input rows. |
database_version |
RaMP version, independent of the HGNC version. |
database_local_dir |
Local staged RaMP directory. |
offline |
Require local or cached HGNC data. |
One row per input with gene_id (HGNC), approved symbol,
canonical_ramp_id, all equivalent ramp_ids (semicolon separated),
status, mapping method and candidate_gene_ids. The gene_mapping
attribute records provenance. mapped_ramp_only explicitly denotes an
unharmonized RaMP record without a resolved HGNC identity.
candidate_ramp_ids records raw candidates encountered for direct RaMP
IDs or source crossreferences, including unresolved/conflicting records.
A shared crossreference with unresolved competitors remains ambiguous
even if only one candidate has a resolved HGNC identity.
utils::str(formals(mapGeneIdentifiers))utils::str(formals(mapGeneIdentifiers))
Both inputs must already use the same planar coordinate units and matching sample_id values. Mapping never links different samples. ST.hires uses target centroids inside square MSI pixels; ties use the nearest MSI centre then pixel ID. Otherwise each MSI pixel must cover overlap.threshold of the target spot/polygon area. Matching MSI intensities are averaged with equal weights.
mapSpatialOmics( SM.data, ST.data, ST.hires = FALSE, SM.assay = "main", ST.assay = "main", SM.pixel.width = NULL, overlap.threshold = 0.2, annotations = TRUE, add.metadata = TRUE, merge.unique.metadata = TRUE, map.data = FALSE, new_SPT.assay = "transcriptome", new_SPM.assay = "main", verbose = FALSE, ST.radius = NULL, ST.polygons = NULL, dropUnmapped = FALSE )mapSpatialOmics( SM.data, ST.data, ST.hires = FALSE, SM.assay = "main", ST.assay = "main", SM.pixel.width = NULL, overlap.threshold = 0.2, annotations = TRUE, add.metadata = TRUE, merge.unique.metadata = TRUE, map.data = FALSE, new_SPT.assay = "transcriptome", new_SPM.assay = "main", verbose = FALSE, ST.radius = NULL, ST.polygons = NULL, dropUnmapped = FALSE )
SM.data, ST.data
|
SpatialExperiment objects with aligned coordinates. |
ST.hires |
Use point-in-pixel mapping for high-resolution target cells. |
SM.assay, ST.assay
|
Primary ( |
SM.pixel.width |
Square MSI pixel width in coordinate units. NULL estimates the median positive nearest-neighbour distance within samples. |
overlap.threshold |
Minimum fraction of target area covered by a pixel. |
annotations |
Preserve MSI rowData and annotation provenance. |
add.metadata |
Include summaries of source pixel metadata in colData. |
merge.unique.metadata |
Remove duplicate values in source summaries. |
map.data |
Map all source assays; FALSE maps counts only. |
new_SPT.assay |
Name of the transcriptome alternative experiment. |
new_SPM.assay |
Name of the primary metabolomics experiment. |
verbose |
Show progress messages. |
ST.radius |
Target spot radius, scalar or one per target pixel, in spatial coordinate units; alternatively supply ST.polygons. |
ST.polygons |
An sf polygon object with a cell column matching ST.data. |
dropUnmapped |
Remove targets without matching MSI pixels. FALSE keeps zero-filled intensities and marks these pixels with mapped = FALSE. |
A SpatialExperiment with MSI assays on the target coordinates, target transcriptomes in altExp, target images and metadata, and mapping provenance.
Feature masses come from rowData, so arbitrary feature IDs are supported.
massIntensityPlot( data, group.by = NULL, split.by = NULL, cols = NULL, assay = "main", slot = "counts", label.annotations = FALSE, annotation.column = "all_IsomerNames", mz.labels = NULL, metabolite.labels = NULL, xlab = "m/z", ylab = "intensity", mass.range = NULL, y.lim = NULL, labelCex = 5, labelAdj = -1, labelOffset = 0, labelCol = "#eb4034", nlabels.to.show = NULL )massIntensityPlot( data, group.by = NULL, split.by = NULL, cols = NULL, assay = "main", slot = "counts", label.annotations = FALSE, annotation.column = "all_IsomerNames", mz.labels = NULL, metabolite.labels = NULL, xlab = "m/z", ylab = "intensity", mass.range = NULL, y.lim = NULL, labelCex = 5, labelAdj = -1, labelOffset = 0, labelCol = "#eb4034", nlabels.to.show = NULL )
data |
A SpatialExperiment or aligned Cardinal experiment. |
group.by |
Optional colData column defining overlaid groups. |
split.by |
Optional colData column defining separate panels; mutually exclusive with group.by. |
cols |
Optional group colours. |
assay |
Primary or alternative experiment. |
slot |
Expression assay. See experimentAccess for the experiment/matrix distinction. |
label.annotations |
Display annotations instead of m/z labels. |
annotation.column |
Annotation column in rowData. |
mz.labels |
Numeric m/z values to label using nearest measured peaks. |
metabolite.labels |
Metabolite names to label; mutually exclusive with mz.labels. |
xlab, ylab
|
Axis labels. |
mass.range |
Optional two-value displayed mass range. |
y.lim |
Optional y-axis limits. |
labelCex |
Text size. |
labelAdj, labelOffset
|
Vertical and horizontal text justification. |
labelCol |
Text colour. |
nlabels.to.show |
Maximum annotations displayed per feature. |
A ggplot.
utils::str(formals(massIntensityPlot))utils::str(formals(massIntensityPlot))
Creates a client object with methods to interact with the METASPACE GraphQL API.
metaspaceClient(host = "https://metaspace2020.org", api_key = NULL)metaspaceClient(host = "https://metaspace2020.org", api_key = NULL)
host |
Character string specifying the METASPACE host URL (default = "https://metaspace2020.org"). |
api_key |
Optional. Your METASPACE API key for accessing private datasets. If accessing a public dataset this can be left as |
A list containing functions for querying METASPACE data.
utils::str(formals(metaspaceClient)) # ms <- metaspaceClient()utils::str(formals(metaspaceClient)) # ms <- metaspaceClient()
Transforms the list of 2D ion image matrices from getMetaspace into a single matrix suitable for spatial analysis packages.
metaspaceToFeatureMatrix(metaspace_data, transform = FALSE, verbose = TRUE)metaspaceToFeatureMatrix(metaspace_data, transform = FALSE, verbose = TRUE)
metaspace_data |
A list object returned by |
transform |
Logical. If TRUE, transposes each image matrix before flattening (e.g., to align coordinate systems) (default = FALSE). |
verbose |
Boolean indicating whether to show the message. If TRUE the message will be show, else the message will be suppressed (default = TRUE). |
A numeric matrix where rows are molecular features (m/z) and columns are spatial pixels (named 'x_y').
utils::str(formals(metaspaceToFeatureMatrix)) # metaspaceToFeatureMatrix(mtx, transform = TRUE)utils::str(formals(metaspaceToFeatureMatrix)) # metaspaceToFeatureMatrix(mtx, transform = TRUE)
SpatialExperiment input uses paired alternative experiments and combines equal-weight PCA embeddings generated with scater. This is not Seurat WNN; the historical WNN workflow remains in the published-workflow branch.
multiOmicIntegration( multiomic.data, reduction.list = list("spm.pca", "spt.pca"), dims.list = list(1:30, 1:30), return.intermediate = FALSE, verbose = FALSE, modalities = c("main", "transcriptome"), ... ) ## S4 method for signature 'SpatialExperiment' multiOmicIntegration( multiomic.data, reduction.list = list("spm.pca", "spt.pca"), dims.list = list(1:30, 1:30), return.intermediate = FALSE, verbose = FALSE, modalities = c("main", "transcriptome"), ... ) ## S4 method for signature 'ANY' multiOmicIntegration( multiomic.data, reduction.list = list("spm.pca", "spt.pca"), dims.list = list(1:30, 1:30), return.intermediate = FALSE, verbose = FALSE, modalities = c("main", "transcriptome"), ... )multiOmicIntegration( multiomic.data, reduction.list = list("spm.pca", "spt.pca"), dims.list = list(1:30, 1:30), return.intermediate = FALSE, verbose = FALSE, modalities = c("main", "transcriptome"), ... ) ## S4 method for signature 'SpatialExperiment' multiOmicIntegration( multiomic.data, reduction.list = list("spm.pca", "spt.pca"), dims.list = list(1:30, 1:30), return.intermediate = FALSE, verbose = FALSE, modalities = c("main", "transcriptome"), ... ) ## S4 method for signature 'ANY' multiOmicIntegration( multiomic.data, reduction.list = list("spm.pca", "spt.pca"), dims.list = list(1:30, 1:30), return.intermediate = FALSE, verbose = FALSE, modalities = c("main", "transcriptome"), ... )
multiomic.data |
A SpatialExperiment with a primary modality and paired
alternative experiments in |
reduction.list |
Reduction names for the primary MSI and alternative modalities (default = list("spm.pca", "spt.pca")). |
dims.list |
List containing the numeric range of principle component dimension to include for each modality (default = list(1:30,1:30)). |
return.intermediate |
Retain per-modality PCA results in reducedDims(). |
verbose |
Show progress messages (default = FALSE). |
modalities |
Primary experiment ( |
... |
Additional arguments passed to scater::runPCA(). |
The input container with an integrated representation. For
SpatialExperiment this is reducedDim(x, "integrated").
utils::str(formals(multiOmicIntegration)) # SpaMTP.obj <- multiOmicIntegration(SpaMTP.obj, reduction.list = list("spt.pca", "spm.pca"), dims.list = list(1:30, 1:30))utils::str(formals(multiOmicIntegration)) # SpaMTP.obj <- multiOmicIntegration(SpaMTP.obj, reduction.list = list("spt.pca", "spm.pca"), dims.list = list(1:30, 1:30))
Generates a Boxplot of spatial metabolic intensity data
mzBoxPlot( data, group.by = NULL, mzs = NULL, assay = "main", slot = "counts", title = "BoxPlot", x.lab = "var", y.lab = "intensity", show.points = TRUE, bottom.cutoff = NULL, top.cutoff = NULL, log.data = FALSE, cols = NULL, verbose = FALSE )mzBoxPlot( data, group.by = NULL, mzs = NULL, assay = "main", slot = "counts", title = "BoxPlot", x.lab = "var", y.lab = "intensity", show.points = TRUE, bottom.cutoff = NULL, top.cutoff = NULL, log.data = FALSE, cols = NULL, verbose = FALSE )
data |
Bioconductor experiment containing the metabolomic intensity data. |
group.by |
Name of the |
mzs |
Vector of characters defining which features (m/z's) to label on the plot. If |
assay |
Primary ( |
slot |
Expression assay name within the selected experiment. See experimentAccess for the experiment/matrix distinction. |
title |
Character string of the plot title (default = "BoxPlot"). |
x.lab |
Character string of the x-axis label (default = "var"). |
y.lab |
Character string of the y-axis label (default = "intensity"). |
show.points |
Boolean value describing whether to show each individual data point (default = TRUE). |
bottom.cutoff |
Numeric value defining the percent of data to exclude for the lower end of the distribution. A bottom.cutoff = 0.05 will remove the bottom 5% of data point (default = NULL). |
top.cutoff |
Numeric value defining the percent of data to exclude for the upper end of the distribution. A top.cutoff = 0.05 will remove the top 5% of data point (default = NULL). |
log.data |
Boolean value indicating whether to log transform the y-axis values (default = FALSE). |
cols |
Vector of strings defining the colours to use for plotting. This vector should match the length of unique groups (default = NULL). |
verbose |
Boolean indicating whether to show the message. If TRUE the message will be show, else the message will be suppressed (default = FALSE). |
A ggplot box-plot object.
utils::str(formals(mzBoxPlot))utils::str(formals(mzBoxPlot))
Generates a ridge plot of spatial metabolic intensity data
mzRidgePlot( data, group.by = NULL, mzs = NULL, assay = "main", slot = "counts", title = "RidgePlot", x.lab = "intensity", y.lab = "var", bottom.cutoff = NULL, top.cutoff = NULL, bins = 1000, log.data = FALSE, cols = NULL, verbose = FALSE )mzRidgePlot( data, group.by = NULL, mzs = NULL, assay = "main", slot = "counts", title = "RidgePlot", x.lab = "intensity", y.lab = "var", bottom.cutoff = NULL, top.cutoff = NULL, bins = 1000, log.data = FALSE, cols = NULL, verbose = FALSE )
data |
Bioconductor experiment containing the metabolomic intensity data. |
group.by |
Name of the |
mzs |
Vector of characters defining which features (m/z's) to label on the plot. If |
assay |
Primary ( |
slot |
Expression assay name within the selected experiment. See experimentAccess for the experiment/matrix distinction. |
title |
Character string of the plot title (default = "RidgePlot"). |
x.lab |
Character string of the x-axis label (default = "var"). |
y.lab |
Character string of the y-axis label (default = "intensity"). |
bottom.cutoff |
Numeric value defining the percent of data to exclude for the lower end of the distribution. A bottom.cutoff = 0.05 will remove the bottom 5% of data point (default = NULL). |
top.cutoff |
Numeric value defining the percent of data to exclude for the upper end of the distribution. A top.cutoff = 0.05 will remove the top 5% of data point (default = NULL). |
bins |
number of bins to group |
log.data |
Boolean value indicating whether to log transform the y-axis values (default = FALSE). |
cols |
Vector of strings defining the colours to use for plotting. This vector should match the length of unique groups (default = NULL). |
verbose |
Boolean indicating whether to show the message. If TRUE the message will be show, else the message will be suppressed (default = FALSE). |
A ggplot ridge-plot object.
utils::str(formals(mzRidgePlot))utils::str(formals(mzRidgePlot))
Generates a violin plot of spatial metabolic intensity data
mzViolinPlot( data, group.by = NULL, mzs = NULL, assay = "main", slot = "counts", title = "Expression", x.lab = "var", y.lab = "intensity", show.points = TRUE, bottom.cutoff = NULL, top.cutoff = NULL, log.data = FALSE, cols = NULL, verbose = FALSE )mzViolinPlot( data, group.by = NULL, mzs = NULL, assay = "main", slot = "counts", title = "Expression", x.lab = "var", y.lab = "intensity", show.points = TRUE, bottom.cutoff = NULL, top.cutoff = NULL, log.data = FALSE, cols = NULL, verbose = FALSE )
data |
Bioconductor experiment containing the metabolomic intensity data. |
group.by |
Name of the |
mzs |
Vector of characters defining which features (m/z's) to label on the plot. If |
assay |
Primary ( |
slot |
Expression assay name within the selected experiment. See experimentAccess for the experiment/matrix distinction. |
title |
Character string of the plot title (default = "Expression"). |
x.lab |
Character string of the x-axis label (default = "var"). |
y.lab |
Character string of the y-axis label (default = "intensity"). |
show.points |
Boolean value describing whether to show each individual data point (default = TRUE). |
bottom.cutoff |
Numeric value defining the percent of data to exclude for the lower end of the distribution. A bottom.cutoff = 0.05 will remove the bottom 5% of data point (default = NULL). |
top.cutoff |
Numeric value defining the percent of data to exclude for the upper end of the distribution. A top.cutoff = 0.05 will remove the top 5% of data point (default = NULL). |
log.data |
Boolean value indicating whether to log transform the y-axis values (default = FALSE). |
cols |
Vector of strings defining the colours to use for plotting. This vector should match the length of unique groups (default = NULL). |
verbose |
Boolean indicating whether to show the message. If TRUE the message will be show, else the message will be suppressed (default = FALSE). |
A ggplot violin-plot object.
utils::str(formals(mzViolinPlot))utils::str(formals(mzViolinPlot))
SingleCellExperiment methods store the result in the standard normcounts or
logcounts assays. Cardinal input delegates TIC normalization to Cardinal
and remains file-backed. Convert Seurat inputs explicitly before analysis.
Cardinal normalization follows Cardinal's deferred-processing model;
queued steps are executed by Cardinal::process(), binSpaMTP(), or conversion
of an aligned experiment to SpatialExperiment.
normalizeSMData( data, normalisation.type = "TIC", scale.factor = NULL, assay = "main", slot = "counts", verbose = TRUE ) ## S4 method for signature 'SingleCellExperiment' normalizeSMData( data, normalisation.type = "TIC", scale.factor = NULL, assay = "main", slot = "counts", verbose = TRUE ) ## S4 method for signature 'MSImagingExperiment' normalizeSMData( data, normalisation.type = "TIC", scale.factor = NULL, assay = "main", slot = "counts", verbose = TRUE ) ## S4 method for signature 'MSImagingArrays' normalizeSMData( data, normalisation.type = "TIC", scale.factor = NULL, assay = "main", slot = "counts", verbose = TRUE ) ## S4 method for signature 'ANY' normalizeSMData( data, normalisation.type = "TIC", scale.factor = NULL, assay = "main", slot = "counts", verbose = TRUE )normalizeSMData( data, normalisation.type = "TIC", scale.factor = NULL, assay = "main", slot = "counts", verbose = TRUE ) ## S4 method for signature 'SingleCellExperiment' normalizeSMData( data, normalisation.type = "TIC", scale.factor = NULL, assay = "main", slot = "counts", verbose = TRUE ) ## S4 method for signature 'MSImagingExperiment' normalizeSMData( data, normalisation.type = "TIC", scale.factor = NULL, assay = "main", slot = "counts", verbose = TRUE ) ## S4 method for signature 'MSImagingArrays' normalizeSMData( data, normalisation.type = "TIC", scale.factor = NULL, assay = "main", slot = "counts", verbose = TRUE ) ## S4 method for signature 'ANY' normalizeSMData( data, normalisation.type = "TIC", scale.factor = NULL, assay = "main", slot = "counts", verbose = TRUE )
data |
A SingleCellExperiment (including SpatialExperiment), Cardinal MSImagingArrays/MSImagingExperiment. |
normalisation.type |
|
scale.factor |
Positive target total before log transformation. When NULL, native TIC uses the number of features and RC/LogNormalize use 10000. Set to 1e6 explicitly for counts/intensities per million. Zero-total pixels remain zero. Cardinal requires NULL and uses its own TIC scaling. |
assay |
Primary ( |
slot |
Expression assay name within the selected experiment. See experimentAccess for the experiment/matrix distinction. |
verbose |
Boolean indicating whether to show the message. If TRUE the message will be show, else the message will be suppressed (default = TRUE). |
An object of the same container family with normalized values.
utils::str(formals(normalizeSMData))utils::str(formals(normalizeSMData))
Builds a self-contained data payload and an interactive D3 visualization for selected pathways across spatial clusters. Topology lookup, edge preparation, differential-expression matching, and matrix extraction are indexed so they are not repeated for every cluster-pathway pair.
pathwayNetworkPlots( SpaMTP, ident, regpathway, DE.list, selected_pathways = NULL, path = getwd(), SM_slot = "counts", ST_slot = "counts", colour_palette = NULL, SM_assay = "main", ST_assay = "transcriptome", analyte_types = c("genes", "metabolites"), annotation_source = c("current", "auto", "legacy"), annotation_score_threshold = NULL, annotation_score_floor = 0.01, metabolite_detection = c("leading_edge", "annotated"), image = NULL, verbose = TRUE, top_n_pathways = 10L, max_nodes = 500L, label_mode = c("detected", "all", "none"), max_spatial_points = 50000L, layout_mode = c("repulsion", "force", "radial", "bipartite"), database = NULL, database_version = "latest", database_source = c("auto", "spamtpdb"), database_local_dir = NULL, gene_mapping = c("auto", "hgnc", "ramp"), gene_reference = NULL, gene_index = NULL, gene_reference_version = "latest", gene_reference_local_dir = NULL, organism = "Homo sapiens", pathway_index = NULL )pathwayNetworkPlots( SpaMTP, ident, regpathway, DE.list, selected_pathways = NULL, path = getwd(), SM_slot = "counts", ST_slot = "counts", colour_palette = NULL, SM_assay = "main", ST_assay = "transcriptome", analyte_types = c("genes", "metabolites"), annotation_source = c("current", "auto", "legacy"), annotation_score_threshold = NULL, annotation_score_floor = 0.01, metabolite_detection = c("leading_edge", "annotated"), image = NULL, verbose = TRUE, top_n_pathways = 10L, max_nodes = 500L, label_mode = c("detected", "all", "none"), max_spatial_points = 50000L, layout_mode = c("repulsion", "force", "radial", "bipartite"), database = NULL, database_version = "latest", database_source = c("auto", "spamtpdb"), database_local_dir = NULL, gene_mapping = c("auto", "hgnc", "ramp"), gene_reference = NULL, gene_index = NULL, gene_reference_version = "latest", gene_reference_local_dir = NULL, organism = "Homo sapiens", pathway_index = NULL )
SpaMTP |
A SpatialExperiment with paired transcriptomics in altExp.
Subset to one sample before exporting. Metabolomics must be annotated by
|
ident |
Metadata column used to identify spatial clusters or regions. |
regpathway |
Data frame returned by |
DE.list |
One differential-expression data frame per requested analyte
type. Data frames must contain |
selected_pathways |
Optional pathway names or source IDs. Matching is
case-insensitive. When |
path |
Output directory for the generated HTML file. |
SM_slot |
Expression assay name within the |
ST_slot |
Expression assay name within the |
colour_palette |
Colours used for the spatial abundance raster. |
SM_assay |
Primary ( |
ST_assay |
Paired transcriptome alternative experiment name. |
analyte_types |
One or both of |
annotation_source |
Metabolite annotation provenance. The default,
|
annotation_score_threshold |
Minimum indexed annotation score used for
metabolite matching. When |
annotation_score_floor |
Lowest annotation score embedded in the HTML
for interactive filtering. It is automatically lowered when the initial
|
metabolite_detection |
Which metabolite nodes receive detected styling.
|
image |
Optional image ID validated against imgData. Coordinates always come from spatialCoords; the optical raster is not embedded in this viewer. |
verbose |
Display progress messages. |
top_n_pathways |
Number of pathways selected when |
max_nodes |
Maximum number of nodes per cluster-pathway view. Detected
leading-edge analytes are always retained, followed by their neighbours and
high-degree nodes. Use |
label_mode |
Initial node-label mode: detected nodes only, all nodes, or no labels. It can also be changed interactively. |
max_spatial_points |
Maximum number of spatial points embedded in the
HTML. Larger datasets are deterministically downsampled for responsive
browser rendering. Use |
layout_mode |
Initial network layout. |
database |
Optional named list of database resources, normally created
by |
database_version |
SpaMTPdb/RaMP version used for pathway lookup. |
database_source |
Database source; see |
database_local_dir |
Optional staged SpaMTPdb resource directory. |
gene_mapping |
|
gene_reference |
HGNC reference data frame. |
gene_index |
Optional index built from the same source table by
|
gene_reference_version |
Version in SpaMTPdb's separate HGNC registry. |
gene_reference_local_dir |
Local HGNC resource directory. |
organism |
Must be |
pathway_index |
A reusable index from buildPathwayIndex(). When supplied, its gene identities and memberships must match any explicit database or gene_index. Fingerprints prevent incompatible reuse. |
Gene differential values use the shared HGNC mapping index. For display, the same resolved gene value is attached to its equivalent raw RaMP topology nodes; this does not introduce additional enrichment tests.
Invisibly returns the generated HTML file path.
utils::str(formals(pathwayNetworkPlots)) # pathwayNetworkPlots( # SpaMTP, ident = "Custom_ident", regpathway = regpathway, # DE.list = DE.list, selected_pathways = "WP1902" # )utils::str(formals(pathwayNetworkPlots)) # pathwayNetworkPlots( # SpaMTP, ident = "Custom_ident", regpathway = regpathway, # DE.list = DE.list, selected_pathways = "WP1902" # )
For combined feature panels, request combine=FALSE from the original plot function and pass the resulting list. This function changes point symbols, not tissue geometry or the physical pixel footprint.
pixelPlot(plot)pixelPlot(plot)
plot |
A ggplot with point layers, or a list of such plots. |
The ggplot or list, retaining images, coordinates, scales and labels.
utils::str(formals(pixelPlot))utils::str(formals(pixelPlot))
Expression comes from the primary or alternative experiment; numeric colData columns can also be plotted. Coordinates and images use SpatialExperiment accessors. Only one sample is displayed at a time.
plot3DFeature( data, features, assays = c("transcriptome", "main"), slots = "counts", between.layer.height = 100, names = NULL, size = 3, col.palette = "Reds", x.axis.label = "x", y.axis.label = "y", z.axis.label = "z", show.x.ticks = FALSE, show.y.ticks = FALSE, show.z.ticks = FALSE, show.image = NULL, plot.height = 800, plot.width = 1500, image.sf = NULL, downscale.image = NULL, sampleId = NULL )plot3DFeature( data, features, assays = c("transcriptome", "main"), slots = "counts", between.layer.height = 100, names = NULL, size = 3, col.palette = "Reds", x.axis.label = "x", y.axis.label = "y", z.axis.label = "z", show.x.ticks = FALSE, show.y.ticks = FALSE, show.z.ticks = FALSE, show.image = NULL, plot.height = 800, plot.width = 1500, image.sf = NULL, downscale.image = NULL, sampleId = NULL )
data |
A SpatialExperiment or aligned Cardinal experiment. |
features |
One or two feature IDs or numeric colData column names. A single feature is repeated for comparison across two experiments. |
assays |
One or two primary/altExp names. |
slots |
One or two expression assay names. See experimentAccess for the experiment/matrix distinction. |
between.layer.height |
Distance between layers. |
names |
Optional layer labels. |
size |
Marker size. |
col.palette |
One or two Plotly colour palettes. |
x.axis.label, y.axis.label, z.axis.label
|
Axis labels. |
show.x.ticks, show.y.ticks, show.z.ticks
|
Show axis tick labels. |
show.image |
Optional image ID from imgData. |
plot.height, plot.width
|
Widget dimensions. |
image.sf |
Retired Seurat scale-factor selector; must be NULL. The selected imgData row supplies the scaleFactor. |
downscale.image |
Optional positive integer raster sampling stride. |
sampleId |
Sample ID; required when data contains multiple samples. |
A Plotly widget.
utils::str(formals(plot3DFeature))utils::str(formals(plot3DFeature))
Plot named pathways on a dimensionality reduction
plotPathways( pathways, object, title = NULL, assay = "main", slot = "logcounts", reduction = NULL, colors = c("darkblue", "lightgrey", "darkred"), guide = "colourbar", database = NULL, database_version = "latest", database_source = c("auto", "spamtpdb"), database_local_dir = NULL, pathway_index = NULL, gene_mapping = c("auto", "hgnc", "ramp"), gene_reference = NULL, gene_index = NULL, gene_reference_version = "latest", gene_reference_local_dir = NULL, organism = "Homo sapiens", duplicate_genes = c("error", "mean", "sum"), ... )plotPathways( pathways, object, title = NULL, assay = "main", slot = "logcounts", reduction = NULL, colors = c("darkblue", "lightgrey", "darkred"), guide = "colourbar", database = NULL, database_version = "latest", database_source = c("auto", "spamtpdb"), database_local_dir = NULL, pathway_index = NULL, gene_mapping = c("auto", "hgnc", "ramp"), gene_reference = NULL, gene_index = NULL, gene_reference_version = "latest", gene_reference_local_dir = NULL, organism = "Homo sapiens", duplicate_genes = c("error", "mean", "sum"), ... )
pathways |
Character vector of pathwayRampId values or unambiguous database pathway names. |
object |
A SpatialExperiment with reducedDims. |
title |
Optional plot title. |
assay |
Primary ( |
slot |
Expression assay name within the selected experiment
(default = |
reduction |
Name in reducedDimNames(object). NULL prefers UMAP, TSNE, then PCA, otherwise the first available reduction. |
colors |
Gradient colours. |
guide |
Colour guide type. |
database |
Optional named list of database tables. |
database_version |
Database version. |
database_source |
Database source, auto or spamtpdb. |
database_local_dir |
Optional local database directory. |
pathway_index |
A reusable index from buildPathwayIndex(). When supplied, its gene identities and memberships must match any explicit database or gene_index. Fingerprints prevent incompatible reuse. |
gene_mapping |
|
gene_reference |
HGNC reference data frame. |
gene_index |
Optional index built from the same source table by
|
gene_reference_version |
Version in SpaMTPdb's separate HGNC registry. |
gene_reference_local_dir |
Local HGNC resource directory. |
organism |
Must be |
duplicate_genes |
How to aggregate expression rows of one gene. The default errors for differing rows and deduplicates identical rows. Explicit mean or sum requires choosing an appropriate expression scale; sum is generally inappropriate for log-transformed expression. |
... |
Additional arguments to scater::plotReducedDim. |
A named list of ggplots with pathway_coverage and pathway_index attributes; each plot also carries its exact pathway_scores.
Plot named pathways in tissue coordinates
plotPathwaysSpatially( pathways, object, images = NULL, title = NULL, image.alpha = 1, assay = "main", slot = "logcounts", colors = c("darkblue", "lightgrey", "darkred"), guide = "colourbar", database = NULL, database_version = "latest", database_source = c("auto", "spamtpdb"), database_local_dir = NULL, pathway_index = NULL, gene_mapping = c("auto", "hgnc", "ramp"), gene_reference = NULL, gene_index = NULL, gene_reference_version = "latest", gene_reference_local_dir = NULL, organism = "Homo sapiens", duplicate_genes = c("error", "mean", "sum"), ... )plotPathwaysSpatially( pathways, object, images = NULL, title = NULL, image.alpha = 1, assay = "main", slot = "logcounts", colors = c("darkblue", "lightgrey", "darkred"), guide = "colourbar", database = NULL, database_version = "latest", database_source = c("auto", "spamtpdb"), database_local_dir = NULL, pathway_index = NULL, gene_mapping = c("auto", "hgnc", "ramp"), gene_reference = NULL, gene_index = NULL, gene_reference_version = "latest", gene_reference_local_dir = NULL, organism = "Homo sapiens", duplicate_genes = c("error", "mean", "sum"), ... )
pathways |
Character vector of pathwayRampId values or unambiguous database pathway names. |
object |
A SpatialExperiment with reducedDims. |
images |
Image IDs in imgData to overlay; NULL draws coordinates only. |
title |
Optional plot title. |
image.alpha |
Image opacity. |
assay |
Primary ( |
slot |
Expression assay name within the selected experiment
(default = |
colors |
Gradient colours. |
guide |
Colour guide type. |
database |
Optional named list of database tables. |
database_version |
Database version. |
database_source |
Database source, auto or spamtpdb. |
database_local_dir |
Optional local database directory. |
pathway_index |
A reusable index from buildPathwayIndex(). When supplied, its gene identities and memberships must match any explicit database or gene_index. Fingerprints prevent incompatible reuse. |
gene_mapping |
|
gene_reference |
HGNC reference data frame. |
gene_index |
Optional index built from the same source table by
|
gene_reference_version |
Version in SpaMTPdb's separate HGNC registry. |
gene_reference_local_dir |
Local HGNC resource directory. |
organism |
Must be |
duplicate_genes |
How to aggregate expression rows of one gene. The default errors for differing rows and deduplicates identical rows. Explicit mean or sum requires choosing an appropriate expression scale; sum is generally inappropriate for log-transformed expression. |
... |
Additional arguments to plotSinglePathwaySpatially. |
A named list of spatial pathway plots, carrying the same coverage and score attributes as plotPathways().
Visualisation of Set Enrichment Analysis Results from SpaMTP::findRegionalPathways().
plotRegionalPathways( regpathway, ident.column = "Cluster_id", selected_pathways = NULL, sig_cutoff = NULL, num_display = NULL, text_size = NULL, verbose = TRUE, database = NULL, database_version = "latest", database_source = c("auto", "spamtpdb"), database_local_dir = NULL )plotRegionalPathways( regpathway, ident.column = "Cluster_id", selected_pathways = NULL, sig_cutoff = NULL, num_display = NULL, text_size = NULL, verbose = TRUE, database = NULL, database_version = "latest", database_source = c("auto", "spamtpdb"), database_local_dir = NULL )
regpathway |
A dataframe generated by the |
ident.column |
A character string specifying the column name of the |
selected_pathways |
A character vector specifying the names or IDs of pathways to be included in the analysis (e.g., |
sig_cutoff |
Within-family BH-adjusted P-value cutoff for the point outline. NULL uses 0.05. Display selection does not recompute adjustment. |
num_display |
An integer specifying the number of pathways to display in the plot. If set to null will plot the smaller of either 10 pathways or the number of unique pathways provided in 'regpathway' (default = NULL). |
text_size |
A numeric value controlling the size of the text elements in the plot. If NULL the default text size is 12 (default = NULL). |
verbose |
Boolean indicating whether to show the message. If TRUE the message will be show, else the message will be suppressed (default = TRUE). |
database |
Optional named list of database resources, normally created
by |
database_version |
SpaMTPdb/RaMP version used for pathway lookup. |
database_source |
Database source; see |
database_local_dir |
Optional staged SpaMTPdb resource directory. |
A ggplot object representing the set enrichment analysis results.
utils::str(formals(plotRegionalPathways)) # plotRegionalPathways(SpaMTP, ident = "clusters", regpathway = pathway_df)utils::str(formals(plotRegionalPathways)) # plotRegionalPathways(SpaMTP, ident = "clusters", regpathway = pathway_df)
Scores are the sum of matched feature values divided by the square root of the matched feature count, then centred and scaled across pixels. Constant scores are shown as zero. Plotting uses scater::plotReducedDim.
plotSinglePathway( pathway, object, title = NULL, assay = "main", slot = "logcounts", reduction = NULL, colors = c("darkblue", "lightgrey", "darkred"), guide = "colourbar", pathway_index = NULL, duplicate_genes = "error", ... )plotSinglePathway( pathway, object, title = NULL, assay = "main", slot = "logcounts", reduction = NULL, colors = c("darkblue", "lightgrey", "darkred"), guide = "colourbar", pathway_index = NULL, duplicate_genes = "error", ... )
pathway |
Character vector of feature IDs in one pathway. |
object |
A SpatialExperiment with reducedDims. |
title |
Optional plot title. |
assay |
Primary ( |
slot |
Expression assay name within the selected experiment
(default = |
reduction |
Name in reducedDimNames(object). NULL prefers UMAP, TSNE, then PCA, otherwise the first available reduction. |
colors |
Gradient colours. |
guide |
Colour guide type. |
pathway_index |
A reusable index from buildPathwayIndex(). When supplied, its gene identities and memberships must match any explicit database or gene_index. Fingerprints prevent incompatible reuse. |
duplicate_genes |
How to aggregate expression rows of one gene. The default errors for differing rows and deduplicates identical rows. Explicit mean or sum requires choosing an appropriate expression scale; sum is generally inappropriate for log-transformed expression. |
... |
Additional arguments to scater::plotReducedDim. |
A ggplot displaying the pathway score.
x <- SpatialExperiment::SpatialExperiment( assays = list(logcounts = rbind(a = 1:4, b = 4:1)), spatialCoords = cbind(x = 1:4, y = 0), colData = S4Vectors::DataFrame(row.names = paste0("p", 1:4))) SingleCellExperiment::reducedDim(x, "PCA") <- cbind(1:4, c(1, 3, 2, 4)) plotSinglePathway("a", x)x <- SpatialExperiment::SpatialExperiment( assays = list(logcounts = rbind(a = 1:4, b = 4:1)), spatialCoords = cbind(x = 1:4, y = 0), colData = S4Vectors::DataFrame(row.names = paste0("p", 1:4))) SingleCellExperiment::reducedDim(x, "PCA") <- cbind(1:4, c(1, 3, 2, 4)) plotSinglePathway("a", x)
Plot a pathway score in tissue coordinates
plotSinglePathwaySpatially( pathway, object, images = NULL, title = NULL, image.alpha = 1, assay = "main", slot = "logcounts", colors = c("darkblue", "lightgrey", "darkred"), guide = "colourbar", crop = TRUE, min.cutoff = NA, max.cutoff = NA, ncol = NULL, pt.size.factor = 1.6, alpha = 1, shape = 16, stroke = 0, interactive = FALSE, image.labels = NULL, pathway_index = NULL, duplicate_genes = "error" )plotSinglePathwaySpatially( pathway, object, images = NULL, title = NULL, image.alpha = 1, assay = "main", slot = "logcounts", colors = c("darkblue", "lightgrey", "darkred"), guide = "colourbar", crop = TRUE, min.cutoff = NA, max.cutoff = NA, ncol = NULL, pt.size.factor = 1.6, alpha = 1, shape = 16, stroke = 0, interactive = FALSE, image.labels = NULL, pathway_index = NULL, duplicate_genes = "error" )
pathway |
Character vector of feature IDs in one pathway. |
object |
A SpatialExperiment with reducedDims. |
images |
Image IDs in imgData to overlay; NULL draws coordinates only. |
title |
Optional plot title. |
image.alpha |
Image opacity. |
assay |
Primary ( |
slot |
Expression assay name within the selected experiment
(default = |
colors |
Gradient colours. |
guide |
Colour guide type. |
crop |
Whether to restrict plotting to the pixel extent. |
min.cutoff, max.cutoff
|
Numeric or quantile colour cutoffs. |
ncol |
Number of columns in the combined plot. |
pt.size.factor |
Point size. |
alpha |
Point opacity (the first value is used). |
shape |
Point shape. |
stroke |
Point border width. |
interactive |
Convert the result to an interactive plotly plot. |
image.labels |
Optional labels for the selected images. |
pathway_index |
A reusable index from buildPathwayIndex(). When supplied, its gene identities and memberships must match any explicit database or gene_index. Fingerprints prevent incompatible reuse. |
duplicate_genes |
How to aggregate expression rows of one gene. The default errors for differing rows and deduplicates identical rows. Explicit mean or sum requires choosing an appropriate expression scale; sum is generally inappropriate for log-transformed expression. |
A ggplot or combined plot; a plotly object if interactive is TRUE.
x <- SpatialExperiment::SpatialExperiment( assays = list(logcounts = rbind(a = 1:4, b = 4:1)), spatialCoords = cbind(x = 1:4, y = 0), colData = S4Vectors::DataFrame(row.names = paste0("p", 1:4))) plotSinglePathwaySpatially("a", x)x <- SpatialExperiment::SpatialExperiment( assays = list(logcounts = rbind(a = 1:4, b = 4:1)), spatialCoords = cbind(x = 1:4, y = 0), colData = S4Vectors::DataFrame(row.names = paste0("p", 1:4))) plotSinglePathwaySpatially("a", x)
This S4 plotting entry point reads feature values from an assay and pixel
positions from SpatialExperiment::spatialCoords(). It therefore does not
require a Seurat image or field-of-view object.
plotSpatialFeature( x, features, assayName = "counts", labels = NULL, pointSize = 1.6, alpha = 1, minCutoff = NA, maxCutoff = NA, combine = TRUE, ncol = NULL, ... ) ## S4 method for signature 'SpatialExperiment' plotSpatialFeature( x, features, assayName = "counts", labels = NULL, pointSize = 1.6, alpha = 1, minCutoff = NA, maxCutoff = NA, combine = TRUE, ncol = NULL, ... ) ## S4 method for signature 'MSImagingExperiment' plotSpatialFeature( x, features, assayName = "counts", labels = NULL, pointSize = 1.6, alpha = 1, minCutoff = NA, maxCutoff = NA, combine = TRUE, ncol = NULL, ... )plotSpatialFeature( x, features, assayName = "counts", labels = NULL, pointSize = 1.6, alpha = 1, minCutoff = NA, maxCutoff = NA, combine = TRUE, ncol = NULL, ... ) ## S4 method for signature 'SpatialExperiment' plotSpatialFeature( x, features, assayName = "counts", labels = NULL, pointSize = 1.6, alpha = 1, minCutoff = NA, maxCutoff = NA, combine = TRUE, ncol = NULL, ... ) ## S4 method for signature 'MSImagingExperiment' plotSpatialFeature( x, features, assayName = "counts", labels = NULL, pointSize = 1.6, alpha = 1, minCutoff = NA, maxCutoff = NA, combine = TRUE, ncol = NULL, ... )
x |
A spatial experiment. |
features |
Feature names to plot. |
assayName |
Assay containing the feature values. |
labels |
Optional panel labels corresponding to |
pointSize |
Point size. |
alpha |
Point opacity. |
minCutoff, maxCutoff
|
Numeric cutoffs, or strings such as |
combine |
Whether to combine multiple panels. |
ncol |
Number of columns in a combined plot. |
... |
Reserved for class-specific methods. |
A ggplot, a combined plot, or a list of plots.
methods::showMethods("plotSpatialFeature")methods::showMethods("plotSpatialFeature")
Calculates the ppm error as a valve
ppm_error(observed_mz, reference_mz, ppm)ppm_error(observed_mz, reference_mz, ppm)
observed_mz |
Numeric value defining the observed mz value. |
reference_mz |
Numeric value defining the reference mz value. |
ppm |
Numeric value defining the maximum acceptable ppm_error/threshold for searching. |
Numeric value defining the ppm_error between the observed and reference mz value
### Helper Function ###### Helper Function ###
Calculates the absolute ppm difference between observed and reference m/z values and returns whether each comparison satisfies the tolerance.
ppm_range_match(observed_mz, reference_mz, ppm)ppm_range_match(observed_mz, reference_mz, ppm)
observed_mz |
Numeric value defining the observed mz value. |
reference_mz |
Numeric value defining the reference mz value. |
ppm |
Numeric value defining the maximum acceptable ppm_error/threshold for searching. |
Boolean value indicating if a match is found (TRUE) or not (FALSE)
### Helper Function ###### Helper Function ###
This function applies the same functional-group and ion-mode logic used by
buildMZAnnotationIndex() before any observed m/z is supplied. It is useful
for auditing which protonation, deprotonation, alkali-binding, or reactive
matrix hypotheses SpaMTP will retain for a structure.
predictAdductsFromSMILES( smiles, polarity = NULL, maldi_matrix = NULL, rules = NULL, min_structure_score = 0.05, backend = c("auto", "native"), workers = getOption("SpaMTP.smiles_workers", 1L) )predictAdductsFromSMILES( smiles, polarity = NULL, maldi_matrix = NULL, rules = NULL, min_structure_score = 0.05, backend = c("auto", "native"), workers = getOption("SpaMTP.smiles_workers", 1L) )
smiles |
Character vector of SMILES strings. |
polarity |
|
maldi_matrix |
Optional MALDI matrix/reagent profile. |
rules |
Optional custom rule table. It cannot be combined with
|
min_structure_score |
Minimum rule-specific structural prior marked as retained. |
backend, workers
|
Passed to |
A ranked data frame with one row per structure/rule combination.
utils::str(formals(predictAdductsFromSMILES))utils::str(formals(predictAdductsFromSMILES))
Print an indexed metabolite annotation search space
## S3 method for class 'spamtp_mz_index' print(x, ...)## S3 method for class 'spamtp_mz_index' print(x, ...)
x |
A |
... |
Additional arguments reserved for print-method compatibility. |
x, invisibly.
Find all library spectra10 above a cosine threshold for each imaging peak, restricting to a global precursor-mz range.
Pseudo_msms( raw_mz, counts, spectra10_list, ppm_tol = 10, frag_tol_da = 0.01, cos_threshold = 0.7, min_precursor = 0, max_precursor = Inf )Pseudo_msms( raw_mz, counts, spectra10_list, ppm_tol = 10, frag_tol_da = 0.01, cos_threshold = 0.7, min_precursor = 0, max_precursor = Inf )
raw_mz |
Numeric vector of length n_peaks |
counts |
Numeric matrix n_peaks × n_pixels |
spectra10_list |
List of Spectrum2 objects (length N_lib) |
ppm_tol |
Precursor‐matching tolerance in ppm (default 10) |
frag_tol_da |
Fragment‐matching tolerance in Da (default 0.01) |
cos_threshold |
Minimum cosine similarity to report (default 0.7) |
min_precursor |
Minimum allowed precursor m/z (default = 0, i.e. no lower bound) |
max_precursor |
Maximum allowed precursor m/z (default = Inf, i.e. no upper bound) |
A list of length n_peaks. Each element is an integer vector giving the indices in spectra10_list of all library spectra10 with cosine >= cos_threshold (or integer(0) if none).
Candidates are pruned by ppm tolerance and proton/charge validity during index construction, then ranked using mass error, rule prior, mass-defect, isotope, and contextual adduct-family evidence.
queryMZAnnotationIndex( observed_mz, index, ppm = 5, ms1_spectrum = NULL, use_mass_defect = TRUE, check_isotopes = TRUE, check_adduct_network = TRUE, min_score = 0 )queryMZAnnotationIndex( observed_mz, index, ppm = 5, ms1_spectrum = NULL, use_mass_defect = TRUE, check_isotopes = TRUE, check_adduct_network = TRUE, min_score = 0 )
observed_mz |
Numeric vector of observed m/z values. |
index |
A |
ppm |
Mass tolerance in parts per million. |
ms1_spectrum |
Optional contextual spectrum with |
use_mass_defect |
Apply the CHO negative mass-defect penalty. |
check_isotopes |
Score carbon-13 and, when relevant, chlorine/bromine M+2 patterns. |
check_adduct_network |
Downweight complex ions whose base monomer
family is absent from |
min_score |
Minimum final score to retain. |
A ranked candidate data frame.
utils::str(formals(queryMZAnnotationIndex))utils::str(formals(queryMZAnnotationIndex))
A small lookup table mapping SpaMTP interaction style codes to visual properties used by the interactive pathway-network viewer.
data(reaction_type)data(reaction_type)
A data frame with 18 rows and 5 variables:
Stable SpaMTP style code; not a database-specific factor index.
Human-readable reaction type.
Line style.
Arrowhead style.
Edge colour.
A data frame of pathway-network reaction styles.
This function reads SM data stored in a table format, with one row per
pixel and two columns named 'x' and 'y' storing its coordinates.
All other columns should be the relative m/z values containing the intensity values of each pixel.
Coordinates are stored only in spatialCoords(), not duplicated in
pixel metadata where a later alignment could leave them out of date.
readSMMatrix( mtx.file, assay = "Spatial", verbose = TRUE, feature.start.column = 1, mz.prefix = NULL, project.name = "SpaMTP", returnType = "SpatialExperiment" )readSMMatrix( mtx.file, assay = "Spatial", verbose = TRUE, feature.start.column = 1, mz.prefix = NULL, project.name = "SpaMTP", returnType = "SpatialExperiment" )
mtx.file |
Character string defining the path of the spatial metabolomic image matrix .csv file. |
assay |
Label stored in mainExpName(); intensities are in the counts assay. |
verbose |
Boolean indicating whether to show the message. If TRUE, the message will be shown; else, it will be suppressed (default = TRUE). |
feature.start.column |
Numeric value defining the start index containing the x, y, and m/z value columns within the table (default = 1). |
mz.prefix |
Character string matching the prefix string in front of each m/z name (default = NULL). |
project.name |
Character string defining the name of the sample to be assigned as |
returnType |
Output container; only |
NOTE: The input file must be in a format similar to the table below:
A data.frame: 5 × 5 x y mz1 mz2 mz3 1 0 1 0 0 11 2 0 2 0 0 0 3 0 3 0 0 0 4 0 4 20 0 0 5 0 5 0 0 0
The first two columns (x, y) contain the respective spatial coordinates.
The subsequent columns contain the m/z values and their intensities for each spatial pixel.
A SpatialExperiment.
utils::str(formals(readSMMatrix)) # msi_data <- readSMMatrix("~/Documents/msi_mtx.csv")utils::str(formals(readSMMatrix)) # msi_data <- readSMMatrix("~/Documents/msi_mtx.csv")
Based on rgoslin, this function has the ability to simplify lipid annotations into more general terms, groups and classes. This function can input a data frame containing a column storing the annotation and refine only the entries which are annotated as known lipid structures.
refineLipids( data, annotation.column = "annotations", database = "HMDB", lipid_info = "simple" )refineLipids( data, annotation.column = "annotations", database = "HMDB", lipid_info = "simple" )
data |
data.frame containing a column with lipid annotations |
annotation.column |
Character string matching the column name containing the lipid annotations in the provided df (default = "annotations"). |
database |
Character string defining the database matching the lipid annotations. Possible entries include c('Shorthand2020','Goslin','FattyAcids','LipidMaps','SwissLipids','HMDB') (default = "HMDB"). |
lipid_info |
Character string defining what level of information to return for each lipid. Options are either "all" or "simple". "Simple" returns a smaller, simplified list of annotations for each lipid. Please visit https://bioconductor.org/packages/release/bioc/vignettes/rgoslin/inst/doc/introduction.html to see all possible outputs (default = "simple")). |
Data.frame containing additional columns with simplified lipid names
utils::str(formals(refineLipids)) # refineLipids(DEPs_df)utils::str(formals(refineLipids)) # refineLipids(DEPs_df)
The HTML embeds PNG figures and styles and needs no network, Pandoc or R session to view. Full tables, mapping weights, processing settings and the analysed object are also saved for reproducibility. Existing files are never overwritten. A report is published to output_dir only after rendering succeeds.
renderSpaMTPReport( result, output_dir, max_points = 5000, interactive = TRUE, preview_features = 180, preview_points = min(max_points, 2000), table_rows = 1000 )renderSpaMTPReport( result, output_dir, max_points = 5000, interactive = TRUE, preview_features = 180, preview_points = min(max_points, 2000), table_rows = 1000 )
result |
A spamtp_workflow result from runSpaMTPWorkflow. |
output_dir |
New or empty output directory. |
max_points |
Maximum observations displayed per scatter plot. Analyses and exported tables are not subsampled. |
interactive |
Embed an offline region/DE explorer using local JavaScript. |
preview_features |
Maximum feature profiles embedded in the explorer. |
preview_points |
Maximum spatial/distribution observations embedded. |
table_rows |
Maximum preloaded ranked rows per region or contrast. Full tables are exported independently of this preview limit. |
Absolute path to report.html, invisibly.
utils::str(formals(renderSpaMTPReport))utils::str(formals(renderSpaMTPReport))
Worker function for calculating differentially abundant metabolites per pooling group.
Used by the compatibility method = "technical" branch of findAllDEMs().
Fits limma to log2(counts(pooled_data) + 1) and uses limma::treat();
an edgeR DGEList stores the values and results, but no edgeR count-model
test or voom transformation is performed. Technical pools are not independent
biological replicates.
runDE( pooled_data, data, ident, output_dir, run_name, n, logFC_threshold, annotation.column, assay, return.individual = FALSE, verbose = TRUE )runDE( pooled_data, data, ident, output_dir, run_name, n, logFC_threshold, annotation.column, assay, return.individual = FALSE, verbose = TRUE )
pooled_data |
A SingleCellExperiment object which contains the pooled pseudo-replicate data. |
data |
The original SummarizedExperiment, including SingleCellExperiment or SpatialExperiment, supplying pixel groups and feature annotations. |
ident |
Column in |
output_dir |
Existing directory for output CSV tables, or NULL to omit file output. |
run_name |
A character string defining the title of this DE analysis (will be used when saving DEMs to .csv file). |
n |
An integer that defines the number of pseudo-replicates per sample (default = 3). |
logFC_threshold |
Fold-change threshold passed as
|
annotation.column |
Column in the selected experiment's |
assay |
Primary ( |
return.individual |
Boolean value defining whether to return a list of individual edgeR objects for each designated ident. If FALSE, one merged edgeR object will be returned (default = FALSE). |
verbose |
Boolean indicating whether to show the message. If TRUE the message will be show, else the message will be suppressed (default = TRUE). |
A modified edgeR object which contains the relative pseudo-bulking analysis outputs, including a DEMs data.frame with a list of differential expressed m/z metabolites
utils::str(formals(runDE))utils::str(formals(runDE))
Uses scater::runPCA() and stores embeddings in reducedDim(). The user can provide a bin/resolution size to increase the bin size and reduce the dimensionality/noise of the SM dataset prior to calculating PCAs.
runMetabolicPCA( SpaMTP, npcs = 30, variance_explained_threshold = 0.9, assay = "main", slot = "counts", show_variance_plot = FALSE, bin_resolution = NULL, resolution_units = "ppm", bin_method = "sum", reduction.name = "pca", verbose = TRUE, features = NULL, scale = FALSE )runMetabolicPCA( SpaMTP, npcs = 30, variance_explained_threshold = 0.9, assay = "main", slot = "counts", show_variance_plot = FALSE, bin_resolution = NULL, resolution_units = "ppm", bin_method = "sum", reduction.name = "pca", verbose = TRUE, features = NULL, scale = FALSE )
SpaMTP |
A SingleCellExperiment, including SpatialExperiment, containing the selected primary or alternative experiment. |
npcs |
Positive number of PCs, capped by matrix dimensions. NULL uses the variance threshold. |
variance_explained_threshold |
Cumulative variance fraction in (0, 1], used only when npcs is NULL. |
assay |
Primary ( |
slot |
Expression assay name within the selected experiment
(default = |
show_variance_plot |
Boolean indicating weather to display the variance plot output by this analysis (default = FALSE). |
bin_resolution |
Numeric value defining the resolution to use for binning m/z peaks. If set to |
resolution_units |
Character string specifying the units of the |
bin_method |
Character string defining the method to use for binning respective m/z peaks that fall within a bin. Options for this parameter can be one of "sum", "mean", "max" or "min". |
reduction.name |
Name in |
verbose |
Boolean indicating whether to show the message. If TRUE the message will be show, else the message will be suppressed (default = TRUE). |
features |
Optional exact feature identifiers. When supplied, all and only these rows enter PCA; the scater top-500 default is bypassed. |
scale |
Scale features to unit variance before PCA. |
The input with PCA embeddings in reducedDim().
counts <- matrix(seq_len(30), nrow = 5) sce <- SingleCellExperiment::SingleCellExperiment(assays = list(counts = counts)) sce <- runMetabolicPCA(sce, npcs = 2) SingleCellExperiment::reducedDimNames(sce) ## For running PCA on un-adjusted peak bin sizes # spamtp_obj <- runMetabolicPCA(spamtp_obj, npcs = 50) ## For running PCA on increased peak bin sizes # spamtp_obj <- runMetabolicPCA(spamtp_obj, npcs = 50, bin_resolution = 50)counts <- matrix(seq_len(30), nrow = 5) sce <- SingleCellExperiment::SingleCellExperiment(assays = list(counts = counts)) sce <- runMetabolicPCA(sce, npcs = 2) SingleCellExperiment::reducedDimNames(sce) ## For running PCA on un-adjusted peak bin sizes # spamtp_obj <- runMetabolicPCA(spamtp_obj, npcs = 50) ## For running PCA on increased peak bin sizes # spamtp_obj <- runMetabolicPCA(spamtp_obj, npcs = 50, bin_resolution = 50)
Runs pooling of a SpaMTP dataset to generate pseudo-replicates for each unique identity provided.
This function is used by findAllDEMs().
These random pools are technical partitions, not independent biological
replicates; resulting p-values must not be interpreted as biological
replication. For population inference aggregate independent samples instead.
runPooling(data.filt, idents, n, assay, slot, seed = 1234, verbose = TRUE)runPooling(data.filt, idents, n, assay, slot, seed = 1234, verbose = TRUE)
data.filt |
A Bioconductor experiment containing count values for pooling. |
idents |
A character string defining the idents column to pool the data against. |
n |
An integer defining the amount of pseudo-replicates to generate for each sample (default = 3). |
assay |
Primary ( |
slot |
Expression assay name within the selected experiment. Values must be finite and non-negative for technical pooling. See experimentAccess for the experiment/matrix distinction. |
seed |
Numeric value used to set the seed for reproducible randomisation (default = 1234). |
verbose |
Boolean indicating whether to show the message. If TRUE the message will be show, else the message will be suppressed (default = TRUE). |
A SingleCellExperiment object which contains pooled (n)-pseudo-replicate counts data based on the Bioconductor experiment input
utils::str(formals(runPooling))utils::str(formals(runPooling))
This function is adapted from the fgsea::geseca package to identify significantly expressed RAMP_DB pathways based on an expression/feature embedding matrix.
runRAMPGeseca( E, minSize = 1, maxSize = nrow(E) - 1, center = TRUE, scale = FALSE, sampleSize = 101, eps = 1e-50, nproc = 0, BPPARAM = NULL, nPermSimple = 1000, database = NULL, database_version = "latest", database_source = c("auto", "spamtpdb"), database_local_dir = NULL, pathway_index = NULL, gene_mapping = c("auto", "hgnc", "ramp"), gene_reference = NULL, gene_index = NULL, gene_reference_version = "latest", gene_reference_local_dir = NULL, organism = "Homo sapiens", duplicate_genes = c("error", "mean", "sum") )runRAMPGeseca( E, minSize = 1, maxSize = nrow(E) - 1, center = TRUE, scale = FALSE, sampleSize = 101, eps = 1e-50, nproc = 0, BPPARAM = NULL, nPermSimple = 1000, database = NULL, database_version = "latest", database_source = c("auto", "spamtpdb"), database_local_dir = NULL, pathway_index = NULL, gene_mapping = c("auto", "hgnc", "ramp"), gene_reference = NULL, gene_index = NULL, gene_reference_version = "latest", gene_reference_local_dir = NULL, organism = "Homo sapiens", duplicate_genes = c("error", "mean", "sum") )
E |
Expression matrix with gene identifiers or RaMP IDs as rows and observations as columns. |
minSize |
Minimal size of a gene set to test. All pathways below the threshold are excluded (default = 1). |
maxSize |
Maximal size of a gene set to test. All pathways above the threshold are excluded (default = |
center |
a logical value indicating whether the gene expression should be centered to have zero mean before the analysis takes place (default = TRUE). |
scale |
a logical value indicating whether the gene expression should be scaled to have unit variance before the analysis takes place (default = FALSE). |
sampleSize |
sample size for conditional sampling (default = 101). |
eps |
This parameter sets the boundary for calculating P-values (default = 1e-50). |
nproc |
If not equal to zero sets BPPARAM to use nproc workers (default = 0). |
BPPARAM |
Parallelization parameter used in bplapply (default = NULL). |
nPermSimple |
Number of permutations in the simple geseca implementation for preliminary estimation of P-values (default = 1000). |
database |
Optional named list of database resources, normally created
by |
database_version |
SpaMTPdb/RaMP version used for pathway lookup. |
database_source |
Database source; see |
database_local_dir |
Optional staged SpaMTPdb resource directory. |
pathway_index |
A reusable index from buildPathwayIndex(). When supplied, its gene identities and memberships must match any explicit database or gene_index. Fingerprints prevent incompatible reuse. |
gene_mapping |
|
gene_reference |
HGNC reference data frame. |
gene_index |
Optional index built from the same source table by
|
gene_reference_version |
Version in SpaMTPdb's separate HGNC registry. |
gene_reference_local_dir |
Local HGNC resource directory. |
organism |
Must be |
duplicate_genes |
How to aggregate expression rows of one gene. The default errors for differing rows and deduplicates identical rows. Explicit mean or sum requires choosing an appropriate expression scale; sum is generally inappropriate for log-transformed expression. |
A table with GESECA results. Each row corresponds to a tested RAMP_DB pathway.
utils::str(formals(runRAMPGeseca)) # sig_pathways <- runRAMPGeseca(E, minSize=15, maxSize=500)utils::str(formals(runRAMPGeseca)) # sig_pathways <- runRAMPGeseca(E, minSize=15, maxSize=500)
Acquires native inputs, audits QC, aligns and maps independent modalities, normalizes explicitly selected layers, computes per-modality PCA and an equal-weight joint representation, and produces descriptive associations, optional replicate-level contrasts, annotations and shared-index pathways. See the End_to_End_Workflow vignette for the input and configuration schema.
runSpaMTPWorkflow( input, modalities, output_dir = NULL, reference = NULL, alignment = list(), mapping = list(), group = NULL, replicate = NULL, contrasts = list(), observation_unit = "spatial observation", coordinate_units = NULL, npcs = 15, max_features = 2000, clusters = NULL, association_features = 20, seed = 1, title = "SpaMTP multi-omics report", regions = group, native = list(), structure = list() )runSpaMTPWorkflow( input, modalities, output_dir = NULL, reference = NULL, alignment = list(), mapping = list(), group = NULL, replicate = NULL, contrasts = list(), observation_unit = "spatial observation", coordinate_units = NULL, npcs = 15, max_features = 2000, clusters = NULL, association_features = 20, seed = 1, title = "SpaMTP multi-omics report", regions = group, native = list(), structure = list() )
input |
A SpatialExperiment, its RDS path, a pinned SpaMTPData resource specification, or a named list of independent inputs of these forms. |
modalities |
Named list of specifications with type and layer, plus optional normalization, scale_factor, min_detected, species, annotation, and pathways. Paired input names are main followed by selected altExp names. |
output_dir |
Optional new directory for report, tables and result RDS. |
reference |
Name of the reference modality for independent inputs. |
alignment |
Named settings for each moving modality: method='identity' explicitly declares registered coordinates; otherwise arguments for applySpatialAlignment (e.g. method='affine', alignment or landmarks). |
mapping |
Named per-moving-modality specifications: method='nearest' with max_distance, or method='pixel' with width and optional target_radius, target_polygons and overlap_threshold, in aligned coordinate units. |
group |
Optional colData field for descriptive summaries and plot colour. |
replicate |
Optional colData field identifying biological replicates. |
contrasts |
Named list of numerator, denominator and paired settings. Tests require at least three independent biological replicates per group. |
observation_unit |
Description of what a column represents. |
coordinate_units |
Description of reference coordinate units; required when independent inputs are mapped. |
npcs, max_features
|
Maximum PCs and variable features per modality. |
clusters |
Optional explicit k for exploratory k-means in joint space, or in PCA space when exactly one modality is selected. NULL does not choose a biological partition automatically. |
association_features |
Maximum regional-marker/variable-feature anchors for each modality pair. Targets are the other modality's PCA-selected features. Raw and covariate-residual correlations have no pixel P values. |
seed |
Random seed, restored on exit. |
title |
Report title. |
regions |
Region metadata column, defaulting to group. NULL can use requested workflow clusters when group is absent. |
native |
Named native spatial settings; see analyzeSpaMTPRegions. |
structure |
Native representation/evaluation settings: spatial, primary (pca or spatial), neighbors, lambda, platform, external reference metadata, k_grid, stability_blocks and umap. Graph PCA uses all retained observations and the same selected, scaled features as ordinary PCA. Clustering stability conditions on full-data embeddings; it is not independent-specimen validation. |
Only observations passing QC in every selected modality and having mappings in every moving modality enter joint analysis. Excluded positions remain in the audit. Raw input assays are preserved. Automatic normalization uses log2(1 + 10000 * value / column sum) for metabolomics/transcriptomics counts, log2(1 + value) for protein counts, and preserves other layers. This is a configurable baseline, not a batch correction or platform-specific raw-signal preprocessing method. Spatial mapping can reuse source pixels; correlations and clusters are exploratory. Contrasts average workflow values within biological replicate and group, not random pixel pools.
A spamtp_workflow list containing object, QC, alignment/mapping audit, analysis, settings, stage log and session information. output_dir also receives a self-contained report.html, CSV tables and workflow.rds.
utils::str(formals(runSpaMTPWorkflow))utils::str(formals(runSpaMTPWorkflow))
Computes a graph-regularised PCA using spatial coordinates and scaled expression data. A k-nearest neighbour (k-NN) graph is computed using spatial locations and used to regularise the PCA decomposition via a graph Laplacian. The result is stored in reducedDim(), with spatial edges in colPairs().
runSpatialGraphPCA( data, n_components = 50, assay = "main", slot = "scaled", image = NULL, platform = "Visium", lambda = 0.5, n_neighbors = NULL, include_self = FALSE, alg = "kd_tree", fast = TRUE, graph_name = "SpatialKNN", reduction_name = "SpatialPCA", verbose = TRUE )runSpatialGraphPCA( data, n_components = 50, assay = "main", slot = "scaled", image = NULL, platform = "Visium", lambda = 0.5, n_neighbors = NULL, include_self = FALSE, alg = "kd_tree", fast = TRUE, graph_name = "SpatialKNN", reduction_name = "SpatialPCA", verbose = TRUE )
data |
A SpatialExperiment or aligned Cardinal MSImagingExperiment. |
n_components |
Integer specifying the number of principal components to compute (default = 50). |
assay |
Primary ( |
slot |
Expression assay name within the selected experiment
(default = |
image |
Reserved; must be NULL. Subset pixels before running graph PCA. |
platform |
Character string matching either |
lambda |
Numeric value defining the regularisation parameter that controls the influence of the graph Laplacian (default = 0.5). |
n_neighbors |
Integer value specifying the number of spatial neighbours to use. If |
include_self |
Boolean logical value indicating whether to include self-connections in the graph (default = FALSE). |
alg |
Character string specifying the algorithm to use for nearest neighbour search (passed to |
fast |
Use partial eigendecomposition via |
graph_name |
Name for pixel edges in |
reduction_name |
Name for the parent object's
|
verbose |
Boolean indicating whether to show the message. If TRUE the message will be show, else the message will be suppressed (default = TRUE). |
Note: This method has been adapted from the GraphPCA Python package (doi:10.1186/s13059-024-03429-x).
A SpatialExperiment with a new colPair() graph and reducedDim()
embedding. Expression assays are preserved.
utils::str(formals(runSpatialGraphPCA)) # spamtp_obj <- runSpatialGraphPCA(spamtp_obj, platform = "Visium")utils::str(formals(runSpatialGraphPCA)) # spamtp_obj <- runSpatialGraphPCA(spamtp_obj, platform = "Visium")
Saves a demsHeatmap as a PDF
savePheatmapAsPDF(pheatmap, filename, width = 20, height = 20)savePheatmapAsPDF(pheatmap, filename, width = 20, height = 20)
pheatmap |
A pheatmap plot object that is being saved. |
filename |
Character string defining the full filepath and name of the plot to be saved as. |
width |
Integer value representing the width of the saved pdf plot (default = 20). |
height |
Integer value representing the height of the saved pdf plot (default = 20). |
The generated PDF path, invisibly.
utils::str(formals(savePheatmapAsPDF)) # savePheatmapAsPDF(pheatmap, filename = "/Documents/plots/pheatmap1")utils::str(formals(savePheatmapAsPDF)) # savePheatmapAsPDF(pheatmap, filename = "/Documents/plots/pheatmap1")
This function saves a Bioconductor experiment into a standard single-cell/spatial file format.
This includes a filtered_feature_bc_matrix folder containing files storing the features, barcode/pixels and intensity matrix.
Pixel metadata are also stored. Feature annotations and spatial image files
are optional exports; the export does not preserve every alternative
experiment or analysis result. Use saveRDS() for an entire R container.
saveSpaMTPData( data, outdir, assay = "Spatial", slot = "counts", image = NULL, annotations = FALSE, generate.h5 = TRUE, verbose = TRUE )saveSpaMTPData( data, outdir, assay = "Spatial", slot = "counts", image = NULL, annotations = FALSE, generate.h5 = TRUE, verbose = TRUE )
data |
A SummarizedExperiment, including SingleCellExperiment or SpatialExperiment. Image export requires SpatialExperiment. |
outdir |
Character string of the directory to save the mtx.mtx, barcode.tsv, features.tsv, barcode_metadata.csv and feature_metadata.csv in. |
assay |
Character string defining the primary or alternative experiment that contains the m/z count data (default = "Spatial"). |
slot |
Expression assay name within the selected experiment
(default = |
image |
Image ID identifying exactly one imgData row; NULL omits image export. |
annotations |
Boolean values defining if the Bioconductor experiment contains annotations to be saved (default = FALSE). |
generate.h5 |
Boolean value indicating whether to generate a filtered_feature_bc_matrix.h5 file. Often used by data loading functions (e.g. scanpy.load_visium). If |
verbose |
Boolean indicating whether to show informative processing messages. If TRUE the message will be show, else the message will be suppressed (default = TRUE). Details
|
The output-directory path, invisibly.
utils::str(formals(saveSpaMTPData))utils::str(formals(saveSpaMTPData))
Each feature is centred and/or scaled across pixels using base R's
scale(). Zero-variance features become zero after centring and scaling.
The input assay is preserved and the result is stored in scaled by
default. This materialises a dense matrix; use implicit centring in PCA
instead when a full scaled matrix would exceed available memory.
scaleSMData( data, assay = "main", slot = "logcounts", center = TRUE, scale = TRUE, outputAssay = "scaled" )scaleSMData( data, assay = "main", slot = "logcounts", center = TRUE, scale = TRUE, outputAssay = "scaled" )
data |
A SingleCellExperiment, including SpatialExperiment. |
assay |
Primary ( |
slot |
Input expression assay, usually |
center, scale
|
Logical values passed to base |
outputAssay |
Name of a new assay for scaled values. Must differ from the input assay and must not already exist. |
The input container with a scaled assay in the selected experiment.
counts <- matrix(seq_len(20), nrow = 4, dimnames = list(paste0("mz-", 101:104), paste0("p", 1:5))) sce <- SingleCellExperiment::SingleCellExperiment(assays = list(counts = counts)) sce <- normalizeSMData(sce, "LogNormalize", verbose = FALSE) sce <- scaleSMData(sce) SummarizedExperiment::assayNames(sce)counts <- matrix(seq_len(20), nrow = 4, dimnames = list(paste0("mz-", 101:104), paste0("p", 1:5))) sce <- SingleCellExperiment::SingleCellExperiment(assays = list(counts = counts)) sce <- normalizeSMData(sce, "LogNormalize", verbose = FALSE) sce <- scaleSMData(sce) SummarizedExperiment::assayNames(sce)
Searches through annotated m/z values to return all which contain the metabolite search term provided
searchAnnotations( data, metabolite, assay = "main", search.exact = FALSE, column.name = "all_IsomerNames" )searchAnnotations( data, metabolite, assay = "main", search.exact = FALSE, column.name = "all_IsomerNames" )
data |
Bioconductor experiment containing annotated m/z values. |
metabolite |
Character string of metabolite search term. |
assay |
Character string defining the primary or alternative experiment that contains the annotated metadata corresponding to the m/z values (default = "Spatial"). |
search.exact |
Boolean value defining if to only return m/z values which contain the exact match to the metabolite search term (default = FALSE). |
column.name |
Character string defining the feature-metadata column where annotations are stored (default = "all_IsomerNames"). |
A Data.Frame containing the peak metadata corresponding to the metabolite search term provided
utils::str(formals(searchAnnotations))utils::str(formals(searchAnnotations))
This function opens a Shiny app to allow users to manually annotate Regions of Interest (ROIs) on spatial transcriptomics or metabolomics data stored in a SpatialExperiment. Users can interactively select regions using lasso selection, assign custom names to each ROI, and save the results as binary (0/1) columns in colData.
selectROIs(object, sampleId = NULL, launch = TRUE)selectROIs(object, sampleId = NULL, launch = TRUE)
object |
A SpatialExperiment with spatial coordinates and metadata. |
sampleId |
The sample to select regions from; required for multiple samples. |
launch |
Launch the app; FALSE returns a Shiny app for embedding or testing. |
The app includes options to:
Choose a metadata column to display.
Adjust the spot size for display.
Use lasso to select spots and name each ROI.
Save each ROI to colData without overwriting existing columns.
Return the final SpatialExperiment upon clicking "Finish".
Selection uses the exact points returned by plotly's lasso tool.
A SpatialExperiment with ROI columns (1 = selected, 0 = unselected within sample, NA = other samples), or a Shiny app if launch is FALSE.
utils::str(formals(selectROIs))utils::str(formals(selectROIs))
Conversion is the only part of SpaMTP that uses SeuratObject. Coordinates
are not required. The selected layer keeps its original name (for example,
counts or data); select that assay explicitly in downstream functions.
Other Seurat assays with the same pixels become altExp() entries.
Only one exact layer is converted, not all split layers. Join split layers
in Seurat before conversion when the complete dataset is needed.
Cell/feature metadata, active identities and stored analysis metadata are
retained. Reductions, graphs, optical images and Seurat commands are not
converted. Stored metadata should contain portable R/Bioconductor values;
entries containing Seurat objects/classes in lists are skipped with a warning.
seuratToSingleCellExperiment( x, assay = NULL, layer = "counts", includeAltExps = TRUE )seuratToSingleCellExperiment( x, assay = NULL, layer = "counts", includeAltExps = TRUE )
x |
A Seurat object. |
assay |
Primary Seurat assay; defaults to its active assay. |
layer |
Exact layer to convert. No partial matching is performed. |
includeAltExps |
Convert other assays with the same pixels. |
A SingleCellExperiment with the selected expression layer.
if (requireNamespace("SeuratObject", quietly = TRUE)) { counts <- matrix(seq_len(12), nrow = 3, dimnames = list(paste0("gene", 1:3), paste0("cell", 1:4))) seu <- SeuratObject::CreateSeuratObject(counts) sce <- seuratToSingleCellExperiment(seu) SummarizedExperiment::assayNames(sce) }if (requireNamespace("SeuratObject", quietly = TRUE)) { counts <- matrix(seq_len(12), nrow = 3, dimnames = list(paste0("gene", 1:3), paste0("cell", 1:4))) seu <- SeuratObject::CreateSeuratObject(counts) sce <- seuratToSingleCellExperiment(seu) SummarizedExperiment::assayNames(sce) }
Convert once at the workflow boundary, then use Bioconductor containers
throughout SpaMTP. Expression and metadata follow
seuratToSingleCellExperiment(). Coordinates are matched by pixel names,
never by position. Supply coordinates for multi-image data or image
formats without x/y columns; coordinate units and orientation must already
be consistent. Optical rasters, graphs and reductions are not transferred.
Attach optical images separately with addSpatialImage().
When a single image/FOV is present, its public GetTissueCoordinates()
accessor is the default coordinate source, even if historical x/y columns
remain in cell metadata. Metadata coordinates are used automatically only
when there are no images. Multiple images always require an explicit
selection. Centroids are read as pixel centres, not expanded polygon
vertices. The selected source is recorded in
metadata(x)$seurat_interoperability; retained legacy coordinate columns
are archival and must not replace spatialCoords(x) in native analysis.
seuratToSpatialExperiment( x, assay = NULL, layer = "counts", image = NULL, includeAltExps = TRUE, coordinates = NULL )seuratToSpatialExperiment( x, assay = NULL, layer = "counts", image = NULL, includeAltExps = TRUE, coordinates = NULL )
x |
A Seurat object. |
assay |
Primary Seurat assay; defaults to its active assay. |
layer |
Exact layer to convert, usually |
image |
Optional Seurat image/FOV used for coordinates. A single image is selected automatically; its coordinates take precedence over metadata. |
includeAltExps |
Convert other assays with matching pixels. |
coordinates |
Optional matrix/data.frame with x/y columns and pixel
names in row names or a |
A SpatialExperiment.
if (requireNamespace("SeuratObject", quietly = TRUE)) { counts <- matrix(seq_len(12), nrow = 3, dimnames = list(paste0("mz-", 101:103), paste0("pixel", 1:4))) seu <- SeuratObject::CreateSeuratObject(counts) xy <- cbind(x = 1:4, y = c(0, 1, 0, 1)) rownames(xy) <- colnames(seu) spe <- seuratToSpatialExperiment(seu, coordinates = xy) spe <- normalizeSMData(spe, verbose = FALSE) }if (requireNamespace("SeuratObject", quietly = TRUE)) { counts <- matrix(seq_len(12), nrow = 3, dimnames = list(paste0("mz-", 101:103), paste0("pixel", 1:4))) seu <- SeuratObject::CreateSeuratObject(counts) xy <- cbind(x = 1:4, y = c(0, 1, 0, 1)) rownames(xy) <- colnames(seu) spe <- seuratToSpatialExperiment(seu, coordinates = xy) spe <- normalizeSMData(spe, verbose = FALSE) }
Inspect SpaMTP database resources
spaMTPDatabaseInfo(version = NULL)spaMTPDatabaseInfo(version = NULL)
version |
Optional SpaMTPdb resource version. |
A data frame describing resources in SpaMTPdb.
utils::str(formals(spaMTPDatabaseInfo)) spaMTPDatabaseInfo()utils::str(formals(spaMTPDatabaseInfo)) spaMTPDatabaseInfo()
Convert a SpatialExperiment to Cardinal
spatialExperimentToCardinal(x, assayName = "counts")spatialExperimentToCardinal(x, assayName = "counts")
x |
A |
assayName |
Name of the assay to convert. |
A Cardinal MSImagingExperiment.
utils::str(formals(spatialExperimentToCardinal))utils::str(formals(spatialExperimentToCardinal))
This conversion is provided only for users who explicitly need a Seurat workflow. Only SeuratObject is needed for conversion; Seurat analysis is not used. The requested layer is placed in the Seurat counts layer; choose counts when raw intensities are needed. Other layers, reductions and optical images are not converted; spatial coordinates are exported as centroids. Alternative experiments without the requested layer are skipped with a warning, rather than treating a derived score assay as raw counts.
spatialExperimentToSeurat( x, assayName = "Spatial", layer = "counts", imageName = "fov", includeAltExps = TRUE )spatialExperimentToSeurat( x, assayName = "Spatial", layer = "counts", imageName = "fov", includeAltExps = TRUE )
x |
A |
assayName |
Name for the primary Seurat assay. |
layer |
SpatialExperiment assay to convert. |
imageName |
Name for the centroid FOV. |
includeAltExps |
Convert alternative experiments to Seurat assays. |
A Seurat object.
utils::str(formals(spatialExperimentToSeurat))utils::str(formals(spatialExperimentToSeurat))
Matching peaks are summed using the same rules as imageMZAnnotationPlot.
spatialMZAnnotationPlot( object, metabolites, plusminus = NULL, images = NULL, crop = TRUE, assay = "main", slot = "counts", keep.scale = "feature", min.cutoff = NA, max.cutoff = NA, ncol = NULL, combine = TRUE, pt.size.factor = 1.6, alpha = c(1, 1), image.alpha = 1, stroke = 0.25, interactive = FALSE, information = NULL, column.name = "all_IsomerNames", plot.exact = TRUE, verbose = TRUE )spatialMZAnnotationPlot( object, metabolites, plusminus = NULL, images = NULL, crop = TRUE, assay = "main", slot = "counts", keep.scale = "feature", min.cutoff = NA, max.cutoff = NA, ncol = NULL, combine = TRUE, pt.size.factor = 1.6, alpha = c(1, 1), image.alpha = 1, stroke = 0.25, interactive = FALSE, information = NULL, column.name = "all_IsomerNames", plot.exact = TRUE, verbose = TRUE )
object |
A SpatialExperiment or aligned Cardinal MSImagingExperiment. |
metabolites |
Metabolite names to search in feature annotations. |
plusminus |
Optional non-negative absolute m/z tolerance. |
images |
Optional image IDs in imgData. |
crop |
Crop to the selected pixels. |
assay |
Primary experiment ("main") or altExp name. |
slot |
Expression assay name, e.g. "counts" or "logcounts". See experimentAccess for the experiment/matrix distinction. |
keep.scale |
Colour scaling: "feature", "all" or "none"; NULL means "none". |
min.cutoff, max.cutoff
|
One cutoff or one per query; numeric or quantile strings such as "q10". NA uses the observed range. |
ncol |
Number of columns in combined plots. |
combine |
Combine panels; FALSE returns a list of ggplots. |
pt.size.factor |
Point size. |
alpha |
Point opacity, or a two-value range mapped to expression. |
image.alpha |
Optical image opacity. |
stroke |
Point border width. |
interactive |
Return Plotly widgets rather than static plots. |
information |
Deprecated Seurat hover data; non-NULL is unsupported. |
column.name |
Annotation column in rowData. |
plot.exact |
Match complete semicolon-delimited names (case-insensitive). |
verbose |
Retained for call compatibility. |
A ggplot or Plotly widget; a list when combine=FALSE.
utils::str(formals(spatialMZAnnotationPlot))utils::str(formals(spatialMZAnnotationPlot))
Images come from imgData and use its scaleFactor to place the raster in spatialCoords units. Each sample/image is a separate panel. With images=NULL all samples are plotted without an image.
spatialMZPlot( object, mzs, plusminus = NULL, images = NULL, crop = TRUE, assay = "main", slot = "counts", keep.scale = "feature", min.cutoff = NA, max.cutoff = NA, ncol = NULL, combine = TRUE, pt.size.factor = 1.6, alpha = c(1, 1), image.alpha = 1, stroke = 0.25, interactive = FALSE, information = NULL, verbose = TRUE )spatialMZPlot( object, mzs, plusminus = NULL, images = NULL, crop = TRUE, assay = "main", slot = "counts", keep.scale = "feature", min.cutoff = NA, max.cutoff = NA, ncol = NULL, combine = TRUE, pt.size.factor = 1.6, alpha = c(1, 1), image.alpha = 1, stroke = 0.25, interactive = FALSE, information = NULL, verbose = TRUE )
object |
A SpatialExperiment or aligned Cardinal MSImagingExperiment. |
mzs |
Numeric m/z values or character feature IDs. |
plusminus |
Optional non-negative absolute m/z tolerance. |
images |
Optional image IDs in imgData. |
crop |
Crop to the selected pixels. |
assay |
Primary experiment ("main") or altExp name. |
slot |
Expression assay name, e.g. "counts" or "logcounts". See experimentAccess for the experiment/matrix distinction. |
keep.scale |
Colour scaling: "feature", "all" or "none"; NULL means "none". |
min.cutoff, max.cutoff
|
One cutoff or one per query; numeric or quantile strings such as "q10". NA uses the observed range. |
ncol |
Number of columns in combined plots. |
combine |
Combine panels; FALSE returns a list of ggplots. |
pt.size.factor |
Point size. |
alpha |
Point opacity, or a two-value range mapped to expression. |
image.alpha |
Optical image opacity. |
stroke |
Point border width. |
interactive |
Return Plotly widgets rather than static plots. |
information |
Deprecated Seurat hover data; non-NULL is unsupported. |
verbose |
Retained for call compatibility. |
A ggplot or Plotly widget; a list when combine=FALSE.
utils::str(formals(spatialMZPlot))utils::str(formals(spatialMZPlot))
Spectral binning of intensity values stored in a Matrix object, converted from matter.
spectralBinning( matrix, ref, index, method = c("sum", "mean", "max", "min"), tolerance )spectralBinning( matrix, ref, index, method = c("sum", "mean", "max", "min"), tolerance )
matrix |
matter matrix object containing the intensity values to be binned. |
ref |
A vector of reference mass-to-charge (m/z) values for binning. If left unspecified, mass range will be used to generate reference peaks. |
index |
Character string specifying the column name for the m/z values (default = "mz"). |
method |
A character vector specifying the binning method. Options include |
tolerance |
Numeric value specifying the tolerance for m/z matching (default = |
Matrix object containing the binned intensity values matching the provided reference list.
utils::str(formals(spectralBinning)) #Helper function for binning data in Matrix formatutils::str(formals(spectralBinning)) #Helper function for binning data in Matrix format
Helper function for QC plots by generating intensity count data
statPlot( data, group.by = NULL, assay = "main", slot = "counts", bottom.cutoff = NULL, top.cutoff = NULL, log.data = FALSE, verbose = FALSE )statPlot( data, group.by = NULL, assay = "main", slot = "counts", bottom.cutoff = NULL, top.cutoff = NULL, log.data = FALSE, verbose = FALSE )
data |
A SingleCellExperiment, including SpatialExperiment. |
group.by |
Name of the |
assay |
Primary ( |
slot |
Expression assay name within the selected experiment. See experimentAccess for the experiment/matrix distinction. |
bottom.cutoff |
Numeric value defining the percent of data to exclude for the lower end of the distribution. A bottom.cutoff = 0.05 will remove the bottom 5% of data point (default = NULL). |
top.cutoff |
Numeric value defining the percent of data to exclude for the upper end of the distribution. A top.cutoff = 0.05 will remove the top 5% of data point (default = NULL). |
log.data |
Boolean value indicating whether to log transform the y-axis values (default = FALSE). |
verbose |
Boolean indicating whether to show the message. If TRUE the message will be show, else the message will be suppressed (default = FALSE). |
A data.frame containing the relative transformed and sum counts required for various QC plots
utils::str(formals(statPlot))utils::str(formals(statPlot))
Subset a Bioconductor experiment by a list of m/z's
subsetMZFeatures(data, features, assay = "main")subsetMZFeatures(data, features, assay = "main")
data |
A Bioconductor experiment for subsetting. |
features |
A list of character strings defining the features/mz values to subset against. |
assay |
A character string identifying the primary or alternative experiment which contains the count data being subset. |
A subset Bioconductor experiment containing only m/z values that were specified
utils::str(formals(subsetMZFeatures))utils::str(formals(subsetMZFeatures))
Uses the container's standard bracket method so alternative experiments, reduced dimensions and spatial edges remain synchronized with pixels.
subsetSPM( object = NULL, subset = NULL, cells = NULL, idents = NULL, features = NULL, verbose = FALSE, ... )subsetSPM( object = NULL, subset = NULL, cells = NULL, idents = NULL, features = NULL, verbose = FALSE, ... )
object |
A SummarizedExperiment, including SingleCellExperiment or SpatialExperiment. |
subset |
Logical expression indicating features/variables to keep |
cells |
A vector of cells to keep; if |
idents |
A vector of identity classes to keep |
features |
A vector of feature names or indices to keep |
verbose |
Boolean indicating whether to show the message. If TRUE the message will be show, else the message will be suppressed (default = FALSE). |
... |
Reserved; additional arguments are rejected. |
Function params/args:
A subset of the same Bioconductor container class.
utils::str(formals(subsetSPM)) # subsetSPM(spe, subset = region == "edge")utils::str(formals(subsetSPM)) # subsetSPM(spe, subset = region == "edge")
This function is mainly used for normalising a merged Bioconductor experiment containing multiple samples.
tmmNormalize( combined.obj, ident, refIdent, normalisation.type = "CPM", CPM.scale.factor = 1e+06, assay = "main", slot = "counts", verbose = FALSE )tmmNormalize( combined.obj, ident, refIdent, normalisation.type = "CPM", CPM.scale.factor = 1e+06, assay = "main", slot = "counts", verbose = FALSE )
combined.obj |
Bioconductor experiment that contains groups being normalized. |
ident |
Character string defining the column name or ident group to normalize between. |
refIdent |
Character string specifying one class/group type to use as a reference for TMM normalisation. |
normalisation.type |
Character string defining the normalization method to run. Options are either c("CPM", "TIC", "LogNormalize") which represent counts per million (CPM), Total Ion Current (TIC) normalization or Log Normalization, respectively (default = "CPM"). |
CPM.scale.factor |
Numeric value that sets the scale factor for pixel/spot level normalization. Following normalization the total intensity value across each pixel will equal this value (default = 1e6). |
assay |
Primary ( |
slot |
Expression assay name within the selected experiment. See experimentAccess for the experiment/matrix distinction. |
verbose |
Boolean indicating whether to show the message. If TRUE the message will be show, else the message will be suppressed (default = FALSE). |
Bioconductor experiment with count values normalised and corrected for between categories
utils::str(formals(tmmNormalize))utils::str(formals(tmmNormalize))
Two demonstrators derived from the checksum-verified SpaMTPData 1.1.0
native resources are installed in extdata. Read them with
readRDS(system.file("extdata", "dhb_demo.rds", package = "SpaMTP"))
or the corresponding human_demo.rds path.
dhb_demo.rds160 paired DHB/Visium locations from one mouse
brain section: 80 on each archived lesion side, nearest that side's ACB
coordinate centroid. All 2,075 mass features and 32,285 RNA features
are retained. RegionLoupe and lesion retain source labels.
human_demo.rds240 paired locations nearest the coordinate-wise
median of the human brain section. All 574 mass features and 339 RNA
features are retained, with archived cout_labels.
Distance ties are resolved by barcode. No expression, test statistic or
annotation result is used to select observations. Counts, pairing and original
coordinates are unchanged; cached annotations, derived layers and images are
omitted. Both files contain a SpatialExperiment with counts and an
SPT alternative experiment containing the paired RNA counts.
metadata(x)$vignette_subset records the recipe, barcodes, original
dimensions and source provenance. These are subsets of single specimens;
regional and lesion differences are descriptive, not population inference.
Recreate the files by sourcing the installed
workflows/prepare_vignette_data.R and calling
prepareVignetteData(outputDir, nativeDir) with a new output directory
and an optional directory of verified native resources. The source files are
mouse_brain_dhb_striatum_spe.rds (MD5
629a3f78651a512484550b4ba0e5d66c) and
human_brain_integrated_spe.rds (MD5
95a713223b184b4f9f38780ee5c16917).
This documentation topic describes files containing
SpatialExperiment objects; it does not define a function.
SpaMTPData native resources 1.1.0, https://zenodo.org/records/22733262.
Displays the pathway analysis results form running the 'fishersPathwayAnalysis()' function
visualisePathways( SpaMTP, pathway_df, assay = "SPM", slot = "counts", min_n = 3, p_val_threshold = 0.1, method = "ward.D2", verbose = TRUE, database = NULL, database_version = "latest", database_source = c("auto", "spamtpdb"), database_local_dir = NULL, ... )visualisePathways( SpaMTP, pathway_df, assay = "SPM", slot = "counts", min_n = 3, p_val_threshold = 0.1, method = "ward.D2", verbose = TRUE, database = NULL, database_version = "latest", database_source = c("auto", "spamtpdb"), database_local_dir = NULL, ... )
SpaMTP |
A SpatialExperiment used for fishersPathwayAnalysis. |
pathway_df |
Dataframe containing the pathway enrichment results (output from SpaMTP::fishersPathwayAnalysis function). |
assay |
Primary ( |
slot |
Expression assay name within the selected experiment
(default = |
min_n |
Integer value specifying the minimum number of analytes required to be present in a pathway (default = 3). |
p_val_threshold |
The p-val cutoff to keep the pathways generated from fisher exact test (default = "0.1"). |
method |
Character string defining the statistical method used to calculate hclust (default = "ward.D2"). |
verbose |
Boolean indicating whether to show informative messages. If FALSE these messages will be suppressed (default = TRUE). |
database |
Optional named list of database resources, normally created
by |
database_version |
SpaMTPdb/RaMP version used for pathway lookup. |
database_source |
Database source; see |
database_local_dir |
Optional staged SpaMTPdb resource directory. |
... |
The arguments pass to stats::hclust |
A combined gg, ggplot object with pathway and dendrogram
utils::str(formals(visualisePathways))utils::str(formals(visualisePathways))