Title: | Pre-Process, Visualize and Analyse Spectral Data |
---|---|
Description: | Infrared, near-infrared and Raman spectroscopic data measured during chemical reactions, provide structural fingerprints by which molecules can be identified and quantified. The application of these spectroscopic techniques as inline process analytical tools (PAT), provides the pharmaceutical and chemical industry with novel tools, allowing to monitor their chemical processes, resulting in a better process understanding through insight in reaction rates, mechanistics, stability, etc. Data can be read into R via the generic spc-format, which is generally supported by spectrometer vendor software. Versatile pre-processing functions are available to perform baseline correction by linking to the 'baseline' package; noise reduction via the 'signal' package; as well as time alignment, normalization, differentiation, integration and interpolation. Implementation based on the S4 object system allows storing a pre-processing pipeline as part of a spectral data object, and easily transferring it to other datasets. Interactive plotting tools are provided based on the 'plotly' package. Non-negative matrix factorization (NMF) has been implemented to perform multivariate analyses on individual spectral datasets or on multiple datasets at once. NMF provides a parts-based representation of the spectral data in terms of spectral signatures of the chemical compounds and their relative proportions. See 'hNMF'-package for references on available methods. The functionality to read in spc-files was adapted from the 'hyperSpec' package. |
Authors: | Robin Van Oirbeek [aut], Adriaan Blommaert [aut, cre], Nicolas Sauwen [aut], Tor Maes [ctb], Jan Dijkmans [ctb], Jef Cuypers [ctb], Tatsiana Khamiakova [ctb], Michel Thiel [ctb], Claudia Beleites [ctb] |
Maintainer: | Adriaan Blommaert <[email protected]> |
License: | GPL-3 |
Version: | 4.3.3 |
Built: | 2024-10-27 03:05:34 UTC |
Source: | https://github.com/cran/spectralAnalysis |
generic function to perfom baseline correction
baselineCorrect(object, ...) ## S4 method for signature 'SpectraInTime' baselineCorrect(object, method = "modpolyfit", degree = 4, ...) ## S4 method for signature 'SpectraInTimeComp' baselineCorrect(object, ...)
baselineCorrect(object, ...) ## S4 method for signature 'SpectraInTime' baselineCorrect(object, method = "modpolyfit", degree = 4, ...) ## S4 method for signature 'SpectraInTimeComp' baselineCorrect(object, ...)
object |
a S4 class object |
... |
other parameters passed to |
method |
method of baseline correction, default value is to |
degree |
numeric value, degree of the polynomial used only if |
baseline correction in the wavelength domain by linking to the baseline
spectralEx <- getSpectraInTimeExample() timeRange <- range( getTimePoints( spectralEx ) ) timesToSelect <- e( seq( timeRange[1] , timeRange[2] , length.out = 5 ) ) baselineDefault <- baselineCorrect( spectralEx ) baselineHighPolynomial <- baselineCorrect( spectralEx, method = 'modpolyfit', degree = 4 ) # filtering with fast fourier transform, not so good on example baselineLowpass <- baselineCorrect( spectralEx , method = "lowpass" ) # visual inspection plot( spectralEx ) plot( baselineDefault[ timesToSelect , ] , type = "time" ) plot( baselineHighPolynomial[ timesToSelect , ] , type = "time" ) plot( baselineLowpass[ timesToSelect , ] , type = "time" )
spectralEx <- getSpectraInTimeExample() timeRange <- range( getTimePoints( spectralEx ) ) timesToSelect <- e( seq( timeRange[1] , timeRange[2] , length.out = 5 ) ) baselineDefault <- baselineCorrect( spectralEx ) baselineHighPolynomial <- baselineCorrect( spectralEx, method = 'modpolyfit', degree = 4 ) # filtering with fast fourier transform, not so good on example baselineLowpass <- baselineCorrect( spectralEx , method = "lowpass" ) # visual inspection plot( spectralEx ) plot( baselineDefault[ timesToSelect , ] , type = "time" ) plot( baselineHighPolynomial[ timesToSelect , ] , type = "time" ) plot( baselineLowpass[ timesToSelect , ] , type = "time" )
Check wheter 2 objects are compatible before using them together e.g. in time aligment using a time file with matching experiment name.
checkCompatible(x, y, ...) ## S4 method for signature 'SpectraInTime,ProcessTimes' checkCompatible(x, y) ## S4 method for signature 'ProcessTimes,SpectraInTime' checkCompatible(x, y)
checkCompatible(x, y, ...) ## S4 method for signature 'SpectraInTime,ProcessTimes' checkCompatible(x, y) ## S4 method for signature 'ProcessTimes,SpectraInTime' checkCompatible(x, y)
x |
first object |
y |
second object |
... |
additional parameters |
no output, produces an error when object are not compatible with each other
TRUE
when the aer competible, otherwise it stops and prints a list of error messages
Check if any of the source vectors in the initialized NMF model are redundant and should be omitted from the actual NMF analysis
checkForRedundantSources(seed)
checkForRedundantSources(seed)
seed |
nmfModel object containing initialization of the factor matrices |
boolean vector, indicating which source vector(s) are redundant
Nicolas Sauwen
check wether all elements of of the same class
checkIdenticalClass(listOfObjects, class)
checkIdenticalClass(listOfObjects, class)
listOfObjects |
a list of S4 objects to check |
class |
a class to compare with |
logical value TRUE
if all objects are of the correct class
Adriaan Blommaert
SpectraInTime-class
objects containing 1 spectrum eachFunction to combine SpectraInTime-class
objects containing 1 spectrum each
combineSpectralObjects(objectList, timeRange, checkNames = TRUE)
combineSpectralObjects(objectList, timeRange, checkNames = TRUE)
objectList |
List of |
timeRange |
Numeric value, equal to the maximum time of the measured spectra. |
checkNames |
Boolean - if |
Nicolas Sauwen
Compute relative residual per observation of an NMF fit to a spectral data set
computeNMFResidu(object, NMFResult)
computeNMFResidu(object, NMFResult)
object |
|
NMFResult |
Fitted NMF model |
Dataframe, containing time (observation) vector and residual vector
nsauwen
ElementsToSelect-class
from a numeric vector or multiple numeric values or vectorsCreate an ElementsToSelect-class
from a numeric vector or multiple numeric values or vectors
e(x, ...)
e(x, ...)
x |
numeric vector |
... |
additional numeric vectors |
ElementsToSelect-class
with unique elements
e( 1 , 5, 4.5 ) e( 1:10 , c(4 , 5 , 6 ) , 7 )
e( 1 , 5, 4.5 ) e( 1:10 , c(4 , 5 , 6 ) , 7 )
Elements S4 class useful for closest elements subsetting
elements
numeric vector of elements
Adriaan Blommaert
Get the first spectrum
firstSpectrum(object, ...) ## S4 method for signature 'SpectraInTime' firstSpectrum(object) ## S4 method for signature 'numeric' firstSpectrum(object)
firstSpectrum(object, ...) ## S4 method for signature 'SpectraInTime' firstSpectrum(object) ## S4 method for signature 'numeric' firstSpectrum(object)
object |
S4 object |
... |
additional parameters |
numeric vector containing observations first spectrum
function to get default summary functions
getDefaultSumFunc()
getDefaultSumFunc()
character vector of functions
function to get default time format in the package
getDefaultTimeFormat()
getDefaultTimeFormat()
character vector specifiying a time format
character string iwth default time format
dimensionReduction
-slotgeneric function to extract dimensionReduction
-slot
getDimensionReduction(object, ...)
getDimensionReduction(object, ...)
object |
a S4 class object |
... |
additional parameters |
dimension reduction slot of an object
elements
-slotgeneric function to extract elements
-slot
getElements(object, ...) ## S4 method for signature 'ElementsToSelect' getElements(object)
getElements(object, ...) ## S4 method for signature 'ElementsToSelect' getElements(object)
object |
a S4 class object |
... |
additional parameters |
experimentName
-slotgeneric function to extract experimentName
-slot
getExperimentName(object, ...) ## S4 method for signature 'SpectraInTime' getExperimentName(object)
getExperimentName(object, ...) ## S4 method for signature 'SpectraInTime' getExperimentName(object)
object |
a S4 class object |
... |
additional parameters |
string containing experiment name
extraInfo
-slotgeneric function to extract extraInfo
-slot
getExtraInfo(object, ...) ## S4 method for signature 'SpectraInTime' getExtraInfo(object)
getExtraInfo(object, ...) ## S4 method for signature 'SpectraInTime' getExtraInfo(object)
object |
a S4 class object |
... |
additional parameters |
list of extraInfo
get example list of spectra
getListOfSpectraExample()
getListOfSpectraExample()
list of SpectraInTime-class
Extract spectral input matrix from SpectraInTime-class
and condition properly for NMF modeling
getNMFInputMatrix(object, method = "")
getNMFInputMatrix(object, method = "")
object |
object of the 'spectralData' class, such as a raw SPC file |
method |
name of the NMF method to be used. |
spectral matrix, with wavelengths as its rows and time points as its columns
Nicolas Sauwen
example path process times
getPathProcessTimesExample()
getPathProcessTimesExample()
preprocessing
-slotgeneric function to extract preprocessing
-slot
getPreprocessing(object, ...) ## S4 method for signature 'SpectraInTime' getPreprocessing(object)
getPreprocessing(object, ...) ## S4 method for signature 'SpectraInTime' getPreprocessing(object)
object |
a S4 class object |
... |
additional parameters |
list with preprocessing steps
ProcessTimes-class
example based on
getSpectraInTimeExample
get a minimal ProcessTimes-class
example based on
getSpectraInTimeExample
getProcessTimesExample()
getProcessTimesExample()
Adriaan Blommaert
getProcessTimesExample()
getProcessTimesExample()
ProcessTimesFrame-class
get mimimal example ProcessTimesFrame-class
getProcessTimesFrameExample()
getProcessTimesFrameExample()
Adriaan Blommaert
range
-slotgeneric function to extract range
-slot
getRange(object, ...) ## S4 method for signature 'RangeToSubset' getRange(object)
getRange(object, ...) ## S4 method for signature 'RangeToSubset' getRange(object)
object |
a S4 class object |
... |
additional parameters |
spectra
-slotgeneric function to extract spectra
-slot
getSpectra(object, ...) ## S4 method for signature 'SpectraInTime' getSpectra(object) ## S4 method for signature 'SpectraInTime' getSpectra(object)
getSpectra(object, ...) ## S4 method for signature 'SpectraInTime' getSpectra(object) ## S4 method for signature 'SpectraInTime' getSpectra(object)
object |
a S4 class object |
... |
additional parameters |
matrix of spectra
SpectraInTimeComp-class
Example SpectraInTime-class
with nmf result
using random initialization with rank 2
getSpectraInTimeCompExample()
getSpectraInTimeCompExample()
Adriaan Blommaert
test <- getSpectraInTimeCompExample()
test <- getSpectraInTimeCompExample()
SpectraInTime-class
exponential conversion from 2 concentrations with gaussion curves for spectra at different wavelength per compounds
getSpectraInTimeExample(showPlots = FALSE)
getSpectraInTimeExample(showPlots = FALSE)
showPlots |
logical indicator to show plots |
Adriaan Blommaert
ex1 <- getSpectraInTimeExample()
ex1 <- getSpectraInTimeExample()
spectralAxis
-slotgeneric function to extract spectralAxis
-slot
getSpectralAxis(object, ...) ## S4 method for signature 'SpectraInTime' getSpectralAxis(object)
getSpectralAxis(object, ...) ## S4 method for signature 'SpectraInTime' getSpectralAxis(object)
object |
a S4 class object |
... |
additional parameters |
numeric vector containing wavelengths
startTime
-slotgeneric function to extract startTime
-slot
getStartTime(object, ...) ## S4 method for signature 'SpectraInTime' getStartTime(object)
getStartTime(object, ...) ## S4 method for signature 'SpectraInTime' getStartTime(object)
object |
a S4 class object |
... |
additional parameters |
character vector with start time
timePoints
-slotgeneric function to extract timePoints
-slot
getTimePoints(object, ...) ## S4 method for signature 'SpectraInTime' getTimePoints(object, timePointsAlt = FALSE, timeUnit = "seconds")
getTimePoints(object, ...) ## S4 method for signature 'SpectraInTime' getTimePoints(object, timePointsAlt = FALSE, timeUnit = "seconds")
object |
a S4 class object |
... |
additional parameters |
timePointsAlt |
logical indicator to get alternative (shifted) instead of recorded time points, defaults to |
timeUnit |
unit to use , choose between: |
numberic vector containing timepoints
spectra <- getSpectraInTimeExample() getTimePoints( spectra ) getTimePoints( spectra , timePointsAlt = TRUE ) getTimePoints( spectra , timeUnit = "hours" )
spectra <- getSpectraInTimeExample() getTimePoints( spectra ) getTimePoints( spectra , timePointsAlt = TRUE ) getTimePoints( spectra , timeUnit = "hours" )
units
-slotgeneric function to extract units
-slot
getUnits(object, ...) ## S4 method for signature 'SpectraInTime' getUnits(object)
getUnits(object, ...) ## S4 method for signature 'SpectraInTime' getUnits(object)
object |
a S4 class object |
... |
additional parameters |
list of units
Re-introduce redundant source vectors and corresponding zero abundances into final NMF result
includeRedundantSources(NMFResult, seed_orig, redundantSources)
includeRedundantSources(NMFResult, seed_orig, redundantSources)
NMFResult |
Fitted NMF model |
seed_orig |
Initial NMF model |
redundantSources |
boolean vector, obtained from |
Final NMF model with redundant sources re-introduced
Nicolas Sauwen
Initialize NMF model with initial spectral data
initializeNMFModel(initSpectralData, spectra, spectralAxis = NULL)
initializeNMFModel(initSpectralData, spectra, spectralAxis = NULL)
initSpectralData |
this can be a list of spectralData objects, containing the pure component spectra. It can also be either of the NMF factor matrices with initial values |
spectra |
spectral matrix, with wavelengths as its rows and time points as its columns |
spectralAxis |
vector of wavelength/spectralAxis values |
an object that inherents from the class NMF
Get the last spectrum
lastSpectrum(object, ...) ## S4 method for signature 'numeric' lastSpectrum(object) ## S4 method for signature 'SpectraInTime' lastSpectrum(object)
lastSpectrum(object, ...) ## S4 method for signature 'numeric' lastSpectrum(object) ## S4 method for signature 'SpectraInTime' lastSpectrum(object)
object |
S4 object |
... |
additional parameters |
numeric vector containing values last spectrum
This function automatically recognizes all the files bearing an '.spc' extension and returns a list in which each element corresponds to a different xml file.
loadAllSPCFiles(directoryFiles, selectedFiles = NULL)
loadAllSPCFiles(directoryFiles, selectedFiles = NULL)
directoryFiles |
Character vector indicating the directory from which the files needs to be downloaded. Note that files with an other extension than '.spc' can be stored in this directory. |
selectedFiles |
Character vector listing which files of the chosen directory (as expressed by the 'directoryFiles' argument) should be processed. This argument is used when one wants to process a subset of the spc files of the selected directory only. Note that one should add the complete file name to this list, including the file extension! This is an optional argument with as default value NULL, meaning that by default all files of the selected directory are considered. |
A list is returned of which each element contains a processed SPC file
Substract a baseline either through 1 or 2 points
localBaselineCorrect(object, baseWavelengths = NULL)
localBaselineCorrect(object, baseWavelengths = NULL)
object |
|
baseWavelengths |
numeric vector of 1 or 2 wavelength use to draw a baseline trough,
defaults to |
SpectraInTime-class
with baseline subset
Adriaan Blommaert
spectra <- getSpectraInTimeExample() spectraConstCorrect <- localBaselineCorrect( spectra , baseWavelengths = 240 ) spectraLinCorrect <- localBaselineCorrect( spectra , c( 250 , 330 ) ) plot( spectra ) plot( spectraConstCorrect ) plot( spectraLinCorrect )
spectra <- getSpectraInTimeExample() spectraConstCorrect <- localBaselineCorrect( spectra , baseWavelengths = 240 ) spectraLinCorrect <- localBaselineCorrect( spectra , c( 250 , 330 ) ) plot( spectra ) plot( spectraConstCorrect ) plot( spectraLinCorrect )
condition datamatrix to input in and condition properly for NMF
nonNegativePreprocessing(spectra, method = "")
nonNegativePreprocessing(spectra, method = "")
spectra |
matrix of spectra |
method |
name of the NMF method to be used. |
put negative values to zero, transpose, an add small value zero row (wavelength with only zeros)
matrix, with wavelengths as its rows and time points as its columns
generic normalization function
normalize(object, ...) ## S4 method for signature 'SpectraInTime' normalize( object, method = "normalize", spectralRange = r(-Inf, Inf), spectralAxisVal = NULL, scaleFunction = "sd", meanFunction = NULL ) ## S4 method for signature 'SpectraInTimeComp' normalize(object, ...)
normalize(object, ...) ## S4 method for signature 'SpectraInTime' normalize( object, method = "normalize", spectralRange = r(-Inf, Inf), spectralAxisVal = NULL, scaleFunction = "sd", meanFunction = NULL ) ## S4 method for signature 'SpectraInTimeComp' normalize(object, ...)
object |
a S4 class object |
... |
additional parameters |
method |
a method for normalization or peak correction , choose from: * normalize substract |
spectralRange |
range for integration if method = |
spectralAxisVal |
reference spectral axis value (wavelength or other) for |
scaleFunction |
scale function used when method = |
meanFunction |
mean function used when method = |
spectralEx <- getSpectraInTimeExample() timeRange <- range( getTimePoints( spectralEx )) timesToSelect <- e( seq( timeRange[1] , timeRange[2] , length.out = 5 ) ) plot( spectralEx ) plot( spectralEx[ timesToSelect , ] , type = "time" ) normalizePeak <- normalize( spectralEx , method = "peak" , spectralAxisVal = 400 ) getPreprocessing( normalizePeak ) plot( normalizePeak[ timesToSelect , ] , type = "time" ) plot( normalizePeak ) normalizeIntegration <- normalize( spectralEx , method = "integration" ) plot( normalizeIntegration[ timesToSelect , ] , type = "time" ) normalizedUser <- normalize( spectralEx , method = "normalize" , mean = "median" , scale = "sd" ) plot( normalizedUser[ timesToSelect , ] , type = "time" )
spectralEx <- getSpectraInTimeExample() timeRange <- range( getTimePoints( spectralEx )) timesToSelect <- e( seq( timeRange[1] , timeRange[2] , length.out = 5 ) ) plot( spectralEx ) plot( spectralEx[ timesToSelect , ] , type = "time" ) normalizePeak <- normalize( spectralEx , method = "peak" , spectralAxisVal = 400 ) getPreprocessing( normalizePeak ) plot( normalizePeak[ timesToSelect , ] , type = "time" ) plot( normalizePeak ) normalizeIntegration <- normalize( spectralEx , method = "integration" ) plot( normalizeIntegration[ timesToSelect , ] , type = "time" ) normalizedUser <- normalize( spectralEx , method = "normalize" , mean = "median" , scale = "sd" ) plot( normalizedUser[ timesToSelect , ] , type = "time" )
NMFResult
, estimate coefficients for a new
spectralData object object
using non-negative least squares fitting. The result is
returned as as an NMF model.Based on previously obtained NMF result NMFResult
, estimate coefficients for a new
spectralData object object
using non-negative least squares fitting. The result is
returned as as an NMF model.
predictNNLS(object, NMFResult)
predictNNLS(object, NMFResult)
object |
|
NMFResult |
Fitted NMF model |
Fitted non-negative least squares result in the form of an NMF model
nsauwen
generic function to preprocess an S4 object
preprocess(object, with) ## S4 method for signature 'SpectraInTime,list' preprocess(object, with) ## S4 method for signature 'SpectraInTime,SpectraInTime' preprocess(object, with) ## S4 method for signature 'SpectraInTimeComp,ANY' preprocess(object, with)
preprocess(object, with) ## S4 method for signature 'SpectraInTime,list' preprocess(object, with) ## S4 method for signature 'SpectraInTime,SpectraInTime' preprocess(object, with) ## S4 method for signature 'SpectraInTimeComp,ANY' preprocess(object, with)
object |
a S4 class object |
with |
an other object containing preprocessing information: other S4 object, list or expression |
S4 Class key process times
experimentName
character vector with name of the experiment
timeHeatingAboveMin
time when experiment above minimum temperature
timeStartReaction
time start reaction (end of heating ramp)
timeEndProcess
time timeEndProcess time end of the process, when cooling down starts
Tset
the maximum temperature to indicate timeStartReaction
comments
character vector of comments when NA
values are produced
Adriaan Blommaert
S4 Class key process times in a data frame, every line is convertable to a ProcessTimes-class
processTimes
data.frame with every line process times of an experiment
Adriaan Blommaert
RangeToSubset-class
object from 2 elements or from a vectorcreate a RangeToSubset-class
object from 2 elements or from a vector
r(x, y) ## S4 method for signature 'numeric,numeric' r(x, y) ## S4 method for signature 'RangeToSubset,missing' r(x, y)
r(x, y) ## S4 method for signature 'numeric,numeric' r(x, y) ## S4 method for signature 'RangeToSubset,missing' r(x, y)
x |
numeric value or vector of numeric values |
y |
numeric value missing when x is a vector of values |
Allows for subsetting a range of actual values instead of a range of indicators
range
numeric vector with min and max value
Adriaan Blommaert
read .csv file as process times
readProcessTimes(path, timeFormat = "%Y-%m-%d %H:%M:%OS")
readProcessTimes(path, timeFormat = "%Y-%m-%d %H:%M:%OS")
path |
to the file containing process times information |
timeFormat |
character specifying time format |
readProcessTimes( getPathProcessTimesExample() , timeFormat = "%Y-%m-%d %H:%M:%S" )
readProcessTimes( getPathProcessTimesExample() , timeFormat = "%Y-%m-%d %H:%M:%S" )
This function is an adaptation of the 'read.spc' function of the 'hyperSpec' package : Claudia Beleites and Valter Sergo: 'hyperSpec: a package to handle hyperspectral data sets in R, R package version 0.98-20161118. http://hyperspec.r-forge.r-project.org.
readSPC(filename, keys.log2data = TRUE, keys.hdr2data = FALSE)
readSPC(filename, keys.log2data = TRUE, keys.hdr2data = FALSE)
filename |
Character vector expressing the name of the SPC file (just the name, not the directory). |
keys.log2data |
Logical vector indicating whether the full information (consisting of additional information on the experimental conditions) needs to be parsed from the SPC file or not (TRUE indicates that the full information should be parsed from the SPC file). The default value is FALSE. |
keys.hdr2data |
a character vector of header object to add to backgroundInformation |
Remove redundant sources from the initial NMF model
removeRedundantSources(seed, redundantSources)
removeRedundantSources(seed, redundantSources)
seed |
nmfModel object containing initialization of the factor matrices |
redundantSources |
boolean vector, obtained from |
nmfModel object with redundant sources removed from initial factor matrices
Nicolas Sauwen
Actual NMF analysis
runNMF( spectra, rank, method = "PGNMF", seed = NULL, nruns = 10, checkDivergence = TRUE, timePointsList = NULL, subsamplingFactor = 3, maxIter = 1000 )
runNMF( spectra, rank, method = "PGNMF", seed = NULL, nruns = 10, checkDivergence = TRUE, timePointsList = NULL, subsamplingFactor = 3, maxIter = 1000 )
spectra |
spectral input matrix, with wavelengths as its rows and time points as its columns |
rank |
number of NMF components to be found |
method |
name of the NMF method to be used, consult the help of the 'nmf' function from the NMF package for the methods available by default |
seed |
nmfModel object containing initialization of the factor matrices |
nruns |
number of NMF runs. It is recommended to run the NMF analyses multiple times when random seeding is used, to avoid a suboptimal solution |
checkDivergence |
Boolean indicating whether divergence checking should be performed, defaults to |
timePointsList |
list of time point vectors of the individual experiments |
subsamplingFactor |
subsampling factor used during NMF analysis |
maxIter |
maximum number of iterations per NMF run |
Resulting NMF model (in accordance with the NMF package definition)
Nicolas Sauwen
SpectraInTime-class
from or to a .txt
fileread or save a SpectraInTime-class
from or to a .txt
file
saveSpectra(object, directory, precision = 32) readSpectra(file)
saveSpectra(object, directory, precision = 32) readSpectra(file)
object |
object to save |
directory |
directory to save object |
precision |
number of significant digits controlling precission |
file |
to be read |
the path to which the file is saved
experiment name is used to save the experiment
default time formats are assumed to convert to SpectraInTime-class
some data precession is lost because of internal conversion to JSON format
Adriaan Blommaert
spectra <- getSpectraInTimeExample() saveSpectra( spectra , directory ) experimentName <- getExperimentName( spectra ) file <- file.path( directory , paste0( experimentName , ".txt") ) spectraRead <- readSpectra( file )
spectra <- getSpectraInTimeExample() saveSpectra( spectra , directory ) experimentName <- getExperimentName( spectra ) file <- file.path( directory , paste0( experimentName , ".txt") ) spectraRead <- readSpectra( file )
Apply fixed scaling to NMF model matrices by normalizing the basis vectors
scaleNMFResult(NMFResult)
scaleNMFResult(NMFResult)
NMFResult |
Fitted NMF model |
NMFResult Rescaled NMF model
Nicolas Sauwen
set the experiment name
setExperimentName(object) <- value ## S4 replacement method for signature 'SpectraInTime' setExperimentName(object) <- value ## S4 replacement method for signature 'SpectraInTime' setTimePointsAlt(object) <- value
setExperimentName(object) <- value ## S4 replacement method for signature 'SpectraInTime' setExperimentName(object) <- value ## S4 replacement method for signature 'SpectraInTime' setTimePointsAlt(object) <- value
object |
a S4 class object |
value |
a vector of time points |
SpectraInTime-class
with modified experiment name
set time alternative time axis
setTimePointsAlt(object) <- value
setTimePointsAlt(object) <- value
object |
a S4 class object |
value |
a vector of time points |
SpectraInTime-class
with modified timePointsAlt axis
smoothing is applied along the spectral axis, not the time axis
smooth(object, ...) ## S4 method for signature 'SpectraInTime' smooth( object, method = "sg", order = 3, window = order + 7 - order%%2, derivative = 0, dim = "spectralAxis" ) ## S4 method for signature 'SpectraInTimeComp' smooth(object, ...)
smooth(object, ...) ## S4 method for signature 'SpectraInTime' smooth( object, method = "sg", order = 3, window = order + 7 - order%%2, derivative = 0, dim = "spectralAxis" ) ## S4 method for signature 'SpectraInTimeComp' smooth(object, ...)
object |
a S4 class object |
... |
additional parameters |
method |
character vector smoothing method, options are 'sg' (= default, Savitsky-Golay filter) or 'mean'. |
order |
numeric value, order of the polynomial used to interpolate (only used when |
window |
width of the smoothing default value slightly higher than in the signal package, the user might consider a large value, otherwise smoothing has little effect |
derivative |
derivative to be taken (only used when |
dim |
character string, specifying along which dimension smoothing should be applied. Options are "spectralAxis" (= default) or "time" |
equal distances between wavelenght intervals are assumed
spectralEx <- getSpectraInTimeExample() smoothDefault <- smooth( spectralEx ) timeRange <- range( getTimePoints( spectralEx )) timesToSelect <- e( seq( timeRange[1] , timeRange[2] , length.out = 5 ) ) smoothALot <- smooth( spectralEx , order = 2 , window = 301 ) derivative1 <- smooth( spectralEx , derivative = 1 ) derivative2 <- smooth( spectralEx , derivative = 2 )
spectralEx <- getSpectraInTimeExample() smoothDefault <- smooth( spectralEx ) timeRange <- range( getTimePoints( spectralEx )) timesToSelect <- e( seq( timeRange[1] , timeRange[2] , length.out = 5 ) ) smoothALot <- smooth( spectralEx , order = 2 , window = 301 ) derivative1 <- smooth( spectralEx , derivative = 1 ) derivative2 <- smooth( spectralEx , derivative = 2 )
Spectral-time data for 1 experiment with dimension reduction techique NMF and/or PCA decomposition included
## S4 method for signature 'SpectraInTimeComp' getDimensionReduction(object, type = NULL)
## S4 method for signature 'SpectraInTimeComp' getDimensionReduction(object, type = NULL)
object |
of class SpectraInTimeComp-class |
type |
type of regression method specified, if NULL the entire slot is returned as a list |
dimensionReduction
list containing dimension reduction techique, either PCA or NMF, but only one per kind.
Adriaan Blommaert
# generate example exampleSpectra <- getSpectraInTimeCompExample() # methods PCAResult <- getDimensionReduction( exampleSpectra, type = "PCA" ) NMFResult <- getDimensionReduction( exampleSpectra, type = "NMF" ) dimensionReductions <- getDimensionReduction( exampleSpectra ) str(dimensionReductions ) # subsetting works by reducing to \code{\link{SpectraInTime-class}} subsetting <- exampleSpectra[1:3 , r(400, 450)] # preprocessing methods also reduce the object to \code{\link{SpectraInTime-class}}
# generate example exampleSpectra <- getSpectraInTimeCompExample() # methods PCAResult <- getDimensionReduction( exampleSpectra, type = "PCA" ) NMFResult <- getDimensionReduction( exampleSpectra, type = "NMF" ) dimensionReductions <- getDimensionReduction( exampleSpectra ) str(dimensionReductions ) # subsetting works by reducing to \code{\link{SpectraInTime-class}} subsetting <- exampleSpectra[1:3 , r(400, 450)] # preprocessing methods also reduce the object to \code{\link{SpectraInTime-class}}
The integrated value over a user-specified spectral range is calculated (trapezium rule) per time point, afterwards smoothing over time can be applied
spectralIntegration( object, spectralRange, smoothingValue = 0, timeUnit = "seconds" )
spectralIntegration( object, spectralRange, smoothingValue = 0, timeUnit = "seconds" )
object |
|
spectralRange |
numeric vector of 2 elements i.e. integration limits |
smoothingValue |
numeric value between 0 and 1, amount of |
timeUnit |
character value, choose between: |
data.frame
with variables time
and integratedValue
spectra <- getSpectraInTimeExample() defaults <- spectralIntegration( spectra , c(200 , 300) , timeUnit = "hours" ) unsmoothedTrend <- spectralIntegration( spectra , c(200 , 300) , timeUnit = "hours" ) smoothedTrend <- spectralIntegration( spectra , c(200 , 300) , smoothingValue = 0.5 , timeUnit = "hours" )
spectra <- getSpectraInTimeExample() defaults <- spectralIntegration( spectra , c(200 , 300) , timeUnit = "hours" ) unsmoothedTrend <- spectralIntegration( spectra , c(200 , 300) , timeUnit = "hours" ) smoothedTrend <- spectralIntegration( spectra , c(200 , 300) , smoothingValue = 0.5 , timeUnit = "hours" )
Perform Non-Negative Matrix factorization on spectral data
spectralNMF( object, rank, method = "PGNMF", initSpectralData = NULL, nruns = 10, subsamplingFactor = 1, checkDivergence = TRUE, maxIter = 1000, includeRefs = FALSE )
spectralNMF( object, rank, method = "PGNMF", initSpectralData = NULL, nruns = 10, subsamplingFactor = 1, checkDivergence = TRUE, maxIter = 1000, includeRefs = FALSE )
object |
|
rank |
number of NMF components to be found |
method |
name of the NMF method to be used. "PGNMF" (default), "HALSacc" and "semiNMF" are methods derived from the hNMF package. All methods from the NMF package are also available. |
initSpectralData |
this can be a list of spectralData objects, containing the pure component spectra. It can also be either of the NMF factor matrices with initial values |
nruns |
number of NMF runs. It is recommended to run the NMF analyses multiple times when random seeding is used, to avoid a suboptimal solution |
subsamplingFactor |
subsampling factor used during NMF analysis |
checkDivergence |
Boolean indicating whether divergence checking should be performed |
maxIter |
maximum number of iterations per NMF run |
includeRefs |
boolean, indicating whether references should be included in the input matrix for the NMF analysis |
SpectraInTimeComp-class
which includeds a scaled NMF model (in accordance with the NMF package definition)
Nicolas Sauwen
spectralExample <- getSpectraInTimeExample() nmfResult <- spectralNMF( spectralExample , rank = 2 , subsamplingFactor = 5 ) nmfObject <- getDimensionReduction( nmfResult , type = "NMF")$NMF nmfTrends <- t( NMF::coef( nmfObject ) ) matplot( nmfTrends , type = "l" , x = getTimePoints( spectralExample , timeUnit = "hours" ), xlab = "time in hours" )
spectralExample <- getSpectraInTimeExample() nmfResult <- spectralNMF( spectralExample , rank = 2 , subsamplingFactor = 5 ) nmfObject <- getDimensionReduction( nmfResult , type = "NMF")$NMF nmfTrends <- t( NMF::coef( nmfObject ) ) matplot( nmfTrends , type = "l" , x = getTimePoints( spectralExample , timeUnit = "hours" ), xlab = "time in hours" )
Perform Non-Negative Matrix factorization on list of SPC files
spectralNMFList( objectList, rank, method = "PGNMF", initSpectralData = NULL, nruns = 10, subsamplingFactor = 3, checkDivergence = TRUE, maxIter = 1000 )
spectralNMFList( objectList, rank, method = "PGNMF", initSpectralData = NULL, nruns = 10, subsamplingFactor = 3, checkDivergence = TRUE, maxIter = 1000 )
objectList |
list of SPC files |
rank |
number of NMF components to be found |
method |
name of the NMF method to be used, consult the help of the 'nmf' function from the NMF package for the methods available by default |
initSpectralData |
list of SPC files containing pure component spectra |
nruns |
number of NMF runs. |
subsamplingFactor |
subsampling factor used during NMF analysis |
checkDivergence |
Boolean indicating whether divergence checking should be performed |
maxIter |
maximum number of iterations per NMF run |
list of SpectraInTimeComp-class
Nicolas Sauwen
spectralData <- getListOfSpectraExample() spectraWithNmf <- spectralNMFList( spectralData , rank = 2 )
spectralData <- getListOfSpectraExample() spectraWithNmf <- spectralNMFList( spectralData , rank = 2 )
Compute PLS model
spectralPLSCalibration(objectList, UPLC_DF, ncomp = 10)
spectralPLSCalibration(objectList, UPLC_DF, ncomp = 10)
objectList |
list of SPC files |
UPLC_DF |
dataframe with UPLC data, which should contain the following columns: experiment, time, and 1 column per compound |
ncomp |
number of PLS components, defaults to 10 |
PLS model, as obtained from plsr
Nicolas Sauwen
Perform PLS prediction
spectralPlsPrediction(spectralObject, plsModel, nComp)
spectralPlsPrediction(spectralObject, plsModel, nComp)
spectralObject |
|
plsModel |
PLS model as obtained from |
nComp |
Number of components |
SpectraInTimeComp-class
which includes PLS model + prediction
Nicolas Sauwen
SpectraInTime-class
Subsetting SpectraInTime-class
## S4 method for signature 'SpectraInTime,ANY,ANY' x[i, j, ..., drop = ""] ## S4 method for signature 'SpectraInTime,missing,ANY' x[i, j, ..., drop = ""] ## S4 method for signature 'SpectraInTime,ANY,missing' x[i, j, ..., drop = ""] ## S4 method for signature 'SpectraInTime,missing,missing' x[i, j, ..., drop = ""] ## S4 method for signature 'SpectraInTimeComp,ANY,ANY' x[i, j, ..., drop = ""] ## S4 method for signature 'SpectraInTimeComp,missing,ANY' x[i, j, ..., drop = ""] ## S4 method for signature 'SpectraInTimeComp,ANY,missing' x[i, j, ..., drop = ""]
## S4 method for signature 'SpectraInTime,ANY,ANY' x[i, j, ..., drop = ""] ## S4 method for signature 'SpectraInTime,missing,ANY' x[i, j, ..., drop = ""] ## S4 method for signature 'SpectraInTime,ANY,missing' x[i, j, ..., drop = ""] ## S4 method for signature 'SpectraInTime,missing,missing' x[i, j, ..., drop = ""] ## S4 method for signature 'SpectraInTimeComp,ANY,ANY' x[i, j, ..., drop = ""] ## S4 method for signature 'SpectraInTimeComp,missing,ANY' x[i, j, ..., drop = ""] ## S4 method for signature 'SpectraInTimeComp,ANY,missing' x[i, j, ..., drop = ""]
x |
object to subset |
i |
subsetting rows ( timePoints ) |
j |
subsetting columns ( spectral axis ) |
... |
additional parameters
|
drop |
for consistancy, not used |
### subsetting [ time , spectral axis, options ] spectralEx <- getSpectraInTimeExample() spectraSubset <- spectralEx[ r( 1000 , 30000 ) , r(130 , 135 ) ] spectraSubsetTime <- spectralEx[ r( 1000 , 30000 ) , ] spectraSubsetSpectralVals <- spectralEx[ , r(130 , 135 ) ] spectraSubsetHours <- spectralEx[ r( 1 , 3 ) , r(130 , 135 ) , timeUnit = "hours" ] closestSpectralVals <- spectralEx[ , e( 150, 4, 300, 500 ) ] # remark only unique values spectraSubsetLogical <- spectralEx[ getTimePoints( spectralEx ) > 300 , getSpectralAxis( spectralEx ) <= 500 ]
### subsetting [ time , spectral axis, options ] spectralEx <- getSpectraInTimeExample() spectraSubset <- spectralEx[ r( 1000 , 30000 ) , r(130 , 135 ) ] spectraSubsetTime <- spectralEx[ r( 1000 , 30000 ) , ] spectraSubsetSpectralVals <- spectralEx[ , r(130 , 135 ) ] spectraSubsetHours <- spectralEx[ r( 1 , 3 ) , r(130 , 135 ) , timeUnit = "hours" ] closestSpectralVals <- spectralEx[ , e( 150, 4, 300, 500 ) ] # remark only unique values spectraSubsetLogical <- spectralEx[ getTimePoints( spectralEx ) > 300 , getSpectralAxis( spectralEx ) <= 500 ]
Time align first object, using info in the second object
timeAlign(x, y, ...) ## S4 method for signature 'SpectraInTime,ProcessTimes' timeAlign(x, y, cutCooling = FALSE, cutBeforeMinTemp = FALSE) ## S4 method for signature 'list,ProcessTimesFrame' timeAlign(x, y, cutCooling = FALSE, cutBeforeMinTemp = FALSE) ## S4 method for signature 'list,character' timeAlign( x, y, cutCooling = FALSE, cutBeforeMinTemp = FALSE, timeFormat = "%Y-%m-%d %H:%M:%S" )
timeAlign(x, y, ...) ## S4 method for signature 'SpectraInTime,ProcessTimes' timeAlign(x, y, cutCooling = FALSE, cutBeforeMinTemp = FALSE) ## S4 method for signature 'list,ProcessTimesFrame' timeAlign(x, y, cutCooling = FALSE, cutBeforeMinTemp = FALSE) ## S4 method for signature 'list,character' timeAlign( x, y, cutCooling = FALSE, cutBeforeMinTemp = FALSE, timeFormat = "%Y-%m-%d %H:%M:%S" )
x |
and S4 object to be aligned |
y |
object to use time information from |
... |
additional arguments |
cutCooling |
logical indicator if |
cutBeforeMinTemp |
logical indicator if |
timeFormat |
character vector specifying time format |
SpectraInTime-class
or list of spectra depending on input
spectra <- getSpectraInTimeExample() listOfSpectra <- getListOfSpectraExample() processTimes <- getProcessTimesExample() processTimesFrame <- getProcessTimesFrameExample() pathProcessTimes <- getPathProcessTimesExample() ex1 <- timeAlign( x = spectra , y = processTimes , cutCooling = TRUE , cutBeforeMinTemp = TRUE ) ex2 <- timeAlign( x = listOfSpectra , y = processTimesFrame , cutCooling = TRUE , cutBeforeMinTemp = TRUE ) ex3 <- timeAlign( x = listOfSpectra , y = pathProcessTimes, cutCooling = TRUE , cutBeforeMinTemp = TRUE , timeFormat = "%Y-%m-%d %H:%M:%OS" )
spectra <- getSpectraInTimeExample() listOfSpectra <- getListOfSpectraExample() processTimes <- getProcessTimesExample() processTimesFrame <- getProcessTimesFrameExample() pathProcessTimes <- getPathProcessTimesExample() ex1 <- timeAlign( x = spectra , y = processTimes , cutCooling = TRUE , cutBeforeMinTemp = TRUE ) ex2 <- timeAlign( x = listOfSpectra , y = processTimesFrame , cutCooling = TRUE , cutBeforeMinTemp = TRUE ) ex3 <- timeAlign( x = listOfSpectra , y = pathProcessTimes, cutCooling = TRUE , cutBeforeMinTemp = TRUE , timeFormat = "%Y-%m-%d %H:%M:%OS" )
Upsample NMF result to original temporal resolution
upsampleNMFResult(NMFResult, timePoints, subsamplingFactor, shift = 0)
upsampleNMFResult(NMFResult, timePoints, subsamplingFactor, shift = 0)
NMFResult |
Fitted NMF model |
timePoints |
Original time points |
subsamplingFactor |
Subsampling factor |
shift |
Integer that correctly shifts subsampling index when applying NMF to multiple experiments |
Upsampled NMF model
Nicolas Sauwen
Align SpectraInTime objects with differing wavelength axes to a common wavelength axis using cubic spline interpolation.
wavelengthAlign(ref, toAlign) ## S4 method for signature 'SpectraInTime,SpectraInTime' wavelengthAlign(ref, toAlign) ## S4 method for signature 'SpectraInTime,list' wavelengthAlign(ref, toAlign)
wavelengthAlign(ref, toAlign) ## S4 method for signature 'SpectraInTime,SpectraInTime' wavelengthAlign(ref, toAlign) ## S4 method for signature 'SpectraInTime,list' wavelengthAlign(ref, toAlign)
ref |
|
toAlign |
|
List of aligned SpectraInTime objects, including the reference object.
one or a list of SpectraInTime-class
spectra <- getSpectraInTimeExample() listOfSpectra <- getListOfSpectraExample() # Dummy alignment of spectrum with itself: ex1 <- wavelengthAlign( ref = spectra , toAlign = spectra ) # Alignment of list of spectra with a reference spectrum: ex2 <- wavelengthAlign( ref = spectra , toAlign = listOfSpectra )
spectra <- getSpectraInTimeExample() listOfSpectra <- getListOfSpectraExample() # Dummy alignment of spectrum with itself: ex1 <- wavelengthAlign( ref = spectra , toAlign = spectra ) # Alignment of list of spectra with a reference spectrum: ex2 <- wavelengthAlign( ref = spectra , toAlign = listOfSpectra )