Package 'tsf'

Title: Fitting algebraic systems describing thermodynamic binding isotherms
Description: Optimizing of unknown paramaters in algebraic systems which describe thermodynamic bindings of dyes and guest to a host. A script interface as well as a shiny app are included in the package.
Authors: Krämer Konrad [aut, cre],
Maintainer: Krämer Konrad <[email protected]>
License: GPL-3
Version: 0.3
Built: 2026-11-24 09:45:59 UTC
Source: https://github.com/ComPlat/Thermosimfit

Help Index


Converts an algebraic system to a polynome by eliminating variables

Description

Converts an algebraic system to a polynome by eliminating variables

Usage

createPolynom(f, elimVars)

Arguments

f

is a function defining the algebraic system

elimVars

is a character vector defining the variables which have to be eliminated

Value

the resulting polynome of the elimination

Examples

f <- function() {
  h + hd + -h0 = 0
  d + hd -d0 = 0   
  hd / (h*d) -kd = 0
}
elimVars <- c("h", "d")
createPolynom(f, elimVars)

Optimize algebraic systems which describe thermodynamic binding systems

Description

Optimize algebraic systems which describe thermodynamic binding systems

Usage

opti(
  case,
  lowerBounds,
  upperBounds,
  path,
  additionalParameters,
  seed = NULL,
  npop = 40,
  ngen = 200,
  Topology = "random",
  errorThreshold = -Inf,
  error_calc_fct = "Rel. Error",
  add_info = "",
  engine = c("ast2ast", "r")
)

Arguments

case

is a character describing which system should be investigated. Either: "dba_host_const", "dba_dye_const", "ida" or "gda".

lowerBounds

is a numeric vector defining the lower boundaries of the parameter. In case of dba_dye_const or *dba_host_const the first parameter is: khd. In case of ida and ga the first parameter is: kg. Afterwards the parameters I0, IHD and ID have to be repeated for each signal respectivly.

upperBounds

is a numeric vector defining the upper boundaries of the parameter. The order is the same as for the lower boundaries.

path

is a filepath which contains tabular x-y data. The concentraion of dye or guest respectivly is assumed to be in the first column. Furthermore, should the corresponding signals be stored in the other columns. As an alternative an already loaded data.frame can be passed to the function.

additionalParameters

are required parameters which are specific for each case. In case of dba_host_const a numeric vector of length 1 is expected which contains the concentration of the host. In case of dba_dye_const a numeric vector of length 1 is expected which contains the concentration of the dye. In case of ida a numeric vector of length 3 is expected which contains the concentration of the host, dye and the khd parameter. In case of gda a numeric vector of length 3 is expected which contains the concentration of the host, guest and the khd parameter.

seed

is an optional integer argument defining the seed which is set directly for the optimization. In case the argument is not set the current time is used as seed.

npop

is an optional integer argument defining the number of particles during optimization. The default value is set to 40.

ngen

is an optional integer argument defining the number of generations of the particle swarm optimization. The default value is set to 200.

Topology

is an optional character argument defining which topology should be used by the particle swarm algorithm. The options are "star" and "random". The default topology is the "random" topology.

errorThreshold

is an optional numeric argument defining a sufficient small error which acts as a stop signal for the particle swarm algorithm. The default value is set to -Inf.

error_calc_fct

is an optional character argument defining how the error between the in silico signal and the measured signal is calculated. One of Rel. Error, RMSE, SSE, or Huber. The default is Rel. Error.

add_info

is an optional character argument which is printed during optimization

engine

is an optional character argument selecting the fitness-evaluation backend for the particle swarm optimization: "ast2ast" (the default) is an ast2ast-compiled per-particle loss, "r" is the plain-R loss function – see pso's engine parameter for details. Results match to floating-point precision either way.

Value

either an instance of ErrorClass if something went wrong. Otherwise the optimized parameter and the insilico signal values are returned.

Examples

path <- paste0(system.file("examples", package = "tsf"), "/IDA.txt")
opti("ida", c(1, 0, 0, 0), c(10^9, 10^6, 10^6, 10^6), path, c(4.3, 6.0, 7079458))

Parametric bootstrap for a PSO fit

Description

Performs a parametric (residual) bootstrap around a PSO fit obtained with opti: the fitted curve is perturbed with Gaussian noise (per -signal standard deviation estimated from the residuals of the original fit, unless sigma is supplied), and for each replicate every parameter is re-estimated by rerunning the particle swarm. Same design as opti_vapro_bootstrap: the ast2ast-compiled per-particle loss is translated once and reused for the point estimate and every replicate (re-translating per replicate would dominate the runtime for anything but a handful of replicates). The resulting empirical distribution is summarized by mean, standard deviation and percentile confidence intervals.

Usage

opti_bootstrap(
  case,
  lowerBounds,
  upperBounds,
  path,
  additionalParameters,
  nBoot = 500L,
  sigma = NULL,
  npop = 40L,
  ngen = 1000L,
  seed = NULL,
  error_calc_fct = "Rel. Error",
  showProgress = TRUE
)

Arguments

case

is a character describing which system should be investigated. Either "dba_host_const", "dba_dye_const", "ida" or "gda".

lowerBounds

is a numeric vector defining the lower boundaries of the parameter, same as opti.

upperBounds

is a numeric vector defining the upper boundaries of the parameter, same as opti.

path

is a filepath which contains tabular x-y data, or an already loaded data.frame. See opti.

additionalParameters

are required parameters which are specific for each case. See opti.

nBoot

is an optional integer argument defining the number of bootstrap replicates. The default value is set to 500.

sigma

is an optional numeric argument defining the per-signal noise standard deviation used to simulate bootstrap data. If NULL (the default) sigma is estimated from the residuals of the original fit for each signal. A single numeric value is recycled across all signals.

npop

is an optional integer argument defining the number of particles, for the original fit and every bootstrap replicate. The default value is set to 40.

ngen

is an optional integer argument defining the number of generations, for the original fit and every bootstrap replicate. The default value is set to 1000.

seed

is an optional integer argument defining the seed used before simulating the bootstrap data. In case the argument is not set the current time is used as seed.

error_calc_fct

is an optional input defining how the error between the in silico signal and the measured signal is calculated. One of Rel. Error, RMSE, SSE, or Huber. The default is Rel. Error.

showProgress

is an optional logical argument defining whether a text progress bar tracking the bootstrap replicates is printed. The default value is TRUE.

Value

a list containing: draws (a data.frame with one row per successful bootstrap replicate containing the binding parameter and the linear parameters), summary (mean, sd and 2.5/50/97.5 percentiles per parameter), sigma (the noise standard deviation used per signal), n_success (number of successful replicates), n_fail (number of failed replicates), seed and point_estimate (the original PSO fit, as returned by pso).

Examples

path <- paste0(system.file("examples", package = "tsf"), "/IDA.txt")
opti_bootstrap("ida", c(1, 0, 0, 0), c(10^9, 1, 1e5, 1e5), path,
  c(4.3, 6.0, 7079458),
  nBoot = 20, ngen = 50
)

Optimize algebraic systems which describe thermodynamic binding systems using the VAPRO (variable projection) approach

Description

Compared to opti only the nonlinear binding parameter (Ka(HD) or Ka(HG)) is searched, via a linear grid search over the log (i.e. exponentially spaced) parameter space, followed by a local continuous refinement (optimize) restricted to the bracket around the best grid point. The coarse grid keeps the search robust against multiple local optima over the wide parameter range, while the local refinement avoids the discretization artifacts a pure grid search would otherwise introduce (identical estimates across many bootstrap replicates whenever the true parameter uncertainty is smaller than the grid spacing). The linear intercept/slope parameters (I0, IHD, ID) for each signal are not part of the search space. Instead they are profiled out in closed form for every candidate binding parameter using non-negative least squares (nnls).

Usage

opti_vapro(
  case,
  lowerBounds,
  upperBounds,
  path,
  additionalParameters,
  nGrid = 1000L,
  error_calc_fct = "Rel. Error"
)

Arguments

case

is a character describing which system should be investigated. Either: "dba_host_const", "dba_dye_const", "ida" or "gda".

lowerBounds

is a numeric vector of length 1 defining the lower boundary of the nonlinear binding parameter. In case of dba_dye_const or dba_host_const this is khd. In case of ida and gda this is kg.

upperBounds

is a numeric vector of length 1 defining the upper boundary of the nonlinear binding parameter. The order is the same as for the lower boundary.

path

is a filepath which contains tabular x-y data. The concentraion of dye or guest respectivly is assumed to be in the first column. Furthermore, should the corresponding signals be stored in the other columns. As an alternative an already loaded data.frame can be passed to the function.

additionalParameters

are required parameters which are specific for each case. In case of dba_host_const a numeric vector of length 1 is expected which contains the concentration of the host. In case of dba_dye_const a numeric vector of length 1 is expected which contains the concentration of the dye. In case of ida a numeric vector of length 3 is expected which contains the concentration of the host, dye and the khd parameter. In case of gda a numeric vector of length 3 is expected which contains the concentration of the host, guest and the khd parameter.

nGrid

is an optional integer argument defining the number of exponentially spaced grid points used for the linear search of the nonlinear binding parameter between lowerBounds and upperBounds. The default value is set to 1000.

error_calc_fct

is an optional input defining how the error between the in silico signal and the measured signal is calculated. One can use one of the following predefined functions as character vectors: Rel. Error, RMSE, SSE, or Huber. The default function is Rel. Error. Alternatively a function can be passed to opti_vapro, which has to expect two arguments, first the insilico signal followed by the measured signal.

Value

either an instance of ErrorClass if something went wrong. Otherwise the optimized parameter and the insilico signal values are returned.

Examples

path <- paste0(system.file("examples", package = "tsf"), "/IDA.txt")
opti_vapro("ida", 1, 10^9, path, c(4.3, 6.0, 7079458))

ast2ast-compiled VAPRO fit, alongside the plain-R fit, for every case

Description

Same case dispatch as opti_vapro (dba_dye_const, dba_host_const, ida or gda), but additionally runs the ast2ast-compiled grid search and returns both results side by side – meant for validating the compiled path agrees with the R/nnls-package one, not (yet) as the primary entry point. error_calc_fct is not configurable here: the compiled loss is hardwired to relative error, matching the R side's default.

Usage

opti_vapro_ast2ast(
  case,
  lowerBounds,
  upperBounds,
  path,
  additionalParameters,
  nGrid = 1000L
)

Arguments

case

one of "dba_dye_const", "dba_host_const", "ida" or "gda".

lowerBounds, upperBounds

bounds for the nonlinear binding parameter (Kd or Kga depending on case).

path

file path or already-loaded data.frame, same as opti_vapro.

additionalParameters

same as opti_vapro.

nGrid

number of exponential grid points (default 1000).

Value

a list with r (plain-R fit, as returned by vapro_grid_search) and a2a (ast2ast fit).


Bootstrap uncertainty estimates for a VAPRO fit

Description

Performs a parametric (residual) bootstrap around a VAPRO fit obtained with opti_vapro: the fitted curve is perturbed with Gaussian noise (per-signal standard deviation estimated from the residuals of the original fit, unless sigma is supplied), and for each replicate the binding parameter is re-estimated with the same exponential grid search used by opti_vapro, with the I0/IHD/ID parameters re-profiled via non-negative least squares. The resulting empirical distribution is summarized by mean, standard deviation and percentile confidence intervals.

Usage

opti_vapro_bootstrap(
  case,
  lowerBounds,
  upperBounds,
  path,
  additionalParameters,
  nBoot = 500L,
  sigma = NULL,
  nGrid = 1000L,
  seed = NULL,
  error_calc_fct = "Rel. Error",
  showProgress = TRUE,
  engine = c("r", "ast2ast")
)

Arguments

case

is a character describing which system should be investigated. Either: "dba_host_const", "dba_dye_const", "ida" or "gda".

lowerBounds

is a numeric vector of length 1 defining the lower boundary of the nonlinear binding parameter.

upperBounds

is a numeric vector of length 1 defining the upper boundary of the nonlinear binding parameter.

path

is a filepath which contains tabular x-y data, or an already loaded data.frame. See opti_vapro.

additionalParameters

are required parameters which are specific for each case. See opti_vapro.

nBoot

is an optional integer argument defining the number of bootstrap replicates. The default value is set to 500.

sigma

is an optional numeric argument defining the per-signal noise standard deviation used to simulate bootstrap data. If NULL (the default) sigma is estimated from the residuals of the original fit for each signal. A single numeric value is recycled across all signals.

nGrid

is an optional integer argument defining the number of exponentially spaced grid points used for the linear search of the nonlinear binding parameter, both for the original fit and every bootstrap replicate. The default value is set to 1000.

seed

is an optional integer argument defining the seed used before simulating the bootstrap data. In case the argument is not set the current time is used as seed.

error_calc_fct

is an optional input defining how the error between the in silico signal and the measured signal is calculated. See opti_vapro.

showProgress

is an optional logical argument defining whether a text progress bar tracking the bootstrap replicates is printed. The default value is TRUE.

engine

is an optional character argument selecting the fitting backend: "r" (the default) uses the plain R/nnls-package grid search, identical to previous versions of this function. "ast2ast" uses the ast2ast-compiled grid search (see vapro_ast2ast_bootstrap) instead, which is substantially faster for large nBoot/nGrid since every replicate fit runs compiled instead of interpreted – at the cost of only supporting error_calc_fct = "Rel. Error" (the compiled loss is hardwired to relative error) and not (yet) returning the insilico signal columns that the "r" engine's per-replicate evaluation produces.

Value

a list containing: draws (a data.frame with one row per successful bootstrap replicate containing the binding parameter, the linear parameters and the loss), summary (mean, sd and 2.5/50/97.5 percentiles per parameter), sigma (the noise standard deviation used per signal), n_success (number of successful replicates), n_fail (number of failed replicates) and seed.

Examples

path <- paste0(system.file("examples", package = "tsf"), "/IDA.txt")
opti_vapro_bootstrap("ida", 1e3, 1e9, path, c(4.3, 6.0, 7079458), nBoot = 50)

Particle swarm optimization

Description

Interface to the particle swarm optimization (pso) algorithm.

Usage

pso(
  env,
  lb,
  ub,
  loss,
  ngen,
  npop,
  error_threshold,
  global = FALSE,
  save_swarm = FALSE,
  run_as_shiny = FALSE,
  add_message = "",
  engine = c("r", "ast2ast"),
  loss_particle_a2a = NULL,
  add_params = NULL,
  error_code = 1L
)

Arguments

env

is something that is passed to the loss function in addition to the parameters which get optimized

lb

is a numeric vector defining the lower boundaries of the parameter

ub

is a numeric vector defining the upper boundaries of the parameter

loss

is the loss function for which the optimal parameter set should be found

ngen

is the number of generations the pso should run

npop

is the number of particles which should be used during optimization

error_threshold

is a number defining a sufficient small error at which the optimization is stopped

global

is a logical parameter. If set to TRUE a global star topology is used. Thus, each particle compares itself with the global best particle of the entire swarm. In contrast, if global is set to FALSE a random arbitrary neighborhood is used instead. Thus, each particle has a neighberhood which contains K neighbours where K is between 0 and 3. From the swarm K neighbours are drawn randomly. From the neighberhood the best particle is used for comparison. The neighberhood is calculated for each generation.

save_swarm

is a logical value defining whether the entire optimization should be saved.

run_as_shiny

is an internal parameter which is used when running the shiny app interface.

add_message

is an optional character argument which is printed during optimization

engine

is an optional character argument selecting the fitness-evaluation backend: "r" (the default here – opti, which always supplies loss_particle_a2a/ add_params, defaults to "ast2ast" instead) calls loss directly. "ast2ast" calls the ast2ast-compiled loss_particle_a2a instead for every non-eval fitness evaluation, leaving the rest of this function (RNG draw order, asynchronous per-particle updates, neighbor lookups) untouched – so results differ from engine = "r" only by floating-point-level differences (a different uniroot implementation), not by a different PSO trajectory. Requires loss_particle_a2a and add_params to be supplied; a generic caller of pso() (like the examples below) has no compiled loss to pass, so must use engine = "r".

loss_particle_a2a

is the ast2ast-compiled per-particle loss function, required when engine = "ast2ast".

add_params

is the struct passed to loss_particle_a2a, required when engine = "ast2ast".

error_code

selects the error function used by loss_particle_a2a when engine = "ast2ast" (see pso_error_code()).

Examples

rosenbrock <- function(parameter, env, Ignore) {
  value <- 0
  for (i in 1:(length(parameter) - 1)) {
    value <- value +
      100 * (parameter[i + 1] - parameter[i]^2)^2 +
      (1 - parameter[i])^2
  }
  return(value)
}

set.seed(1234)
res <- tsf::pso(
  new.env(), rep(-10, 3), rep(10, 3), rosenbrock, 1000, 40,
  0.00001, TRUE, FALSE
)

Joint kernel-density bootstrap for repeated PSO fits

Description

Repeated PSO runs trace out an empirical distribution for each fitted parameter. This estimates, for every parameter, the kernel-density mode of that joint distribution and a bootstrap confidence interval on that mode: the joint kernel density is fit once on the parameter estimates, then re-fit on n_boot resamples (with replacement) of those same estimates to build the mode's bootstrap distribution.

Usage

pso_uncertainty(df, n_boot = 1000L, gridsize = 15L, seed = NULL)

Arguments

df

is a data.frame with one row per PSO repetition and one column per core parameter (the binding constant plus I0/IHD/ID per signal), with any bookkeeping columns (repetition/dataset) already dropped. See pso_uncertainty_batch for computing this directly off a Batch-PSO result.

n_boot

is the number of bootstrap resamples used to build the confidence interval for each parameter's kernel-density mode. The default value is set to 1000.

gridsize

is the number of grid points per dimension used to evaluate the kernel density (passed to ks::kde); the mode is read off this grid, so it also bounds the mode's resolution. Cost scales with gridsize^ncol(df). The default value is set to 15.

seed

is an optional integer argument defining the seed used before bootstrapping. In case the argument is not set the current time is used as seed.

Value

a list containing: mode (named numeric vector, one entry per parameter), lower_ci and upper_ci (the same, 95% bootstrap interval), density (a named list of data.frames, one per parameter, with columns x/y for plotting the marginal of the joint kernel density) and n_used (the number of repetitions the joint density was fit on).

Examples

df <- data.frame(
  kG = rnorm(30, 1e7, 1e6),
  I0 = rnorm(30, 0, 0.01),
  IHD = rnorm(30, 1e5, 1e4),
  ID = rnorm(30, 100, 10)
)
pso_uncertainty(df, n_boot = 50)

PSO uncertainty from a Batch-PSO result

Description

Turns a Batch-PSO result (repeated PSO fits, possibly across several uploaded files/datasets) into the joint-kernel-density bootstrap of pso_uncertainty. Each dataset's repetitions are first ranked by mean squared error and the best best_pct% are kept (so a dataset with worse PSO convergence doesn't get outvoted purely on raw MSE terms) - this ranking/filtering happens separately per dataset, before anything is combined; the survivors from every dataset are then pooled into one joint distribution. Pooling across datasets is what captures actual measurement noise (each file is an independent noisy replicate) rather than only PSO's own run-to-run convergence variability - so this is only meaningful when the batch has multiple files uploaded as replicate measurements of the same system; with a single dataset it still runs, but only reflects optimizer variability.

Usage

pso_uncertainty_batch(
  values,
  best_pct = 50,
  n_boot = 1000L,
  gridsize = 15L,
  seed = NULL
)

Arguments

values

is the batch result list as produced by batch or the Batch-PSO tab (i.e. an object with $params and $metrices, each a list with one entry per PSO repetition).

best_pct

is the percentage (0-100) of best-by-error repetitions to keep per dataset before pooling. The default value is set to 50.

n_boot

is passed through to pso_uncertainty. The default value is set to 1000.

gridsize

is passed through to pso_uncertainty.

seed

is passed through to pso_uncertainty.

Value

see pso_uncertainty.


Offers a GUI for the optimization of algebraic systems describing thermodynamic binding systems

Description

Offers a GUI for the optimization of algebraic systems describing thermodynamic binding systems

Usage

runApp(port)

Arguments

port

is a number defining the port to use.

Examples

tsf::runApp()

Optimize algebraic systems which describe thermodynamic binding systems

Description

Optimize algebraic systems which describe thermodynamic binding systems

Usage

sensitivity(
  case,
  parameters,
  path,
  additionalParameters,
  percentage = NULL,
  OffsetBoundaries = NULL,
  runAsShiny = FALSE,
  error_calc_fct = "rel. Error"
)

Arguments

case

is a character describing which system should be investigated. Either: "dba_host_const", "dba_dye_const", "ida" or "gda".

parameters

is a numeric vector containing already optimized parameter. In case of dba_dye_const or *dba_host_const the first parameter is: khd. In case of ida and ga the first parameter is: kg. Afterwards the parameters I0, IHD and ID have to be repeated for each signal respectivly. It is mandatory that the entries are named as described above.

path

is a filepath which contains tabular x-y data. The concentraion of dye or guest respectivly is assumed to be in the first column. Furthermore, should the corresponding signal be stored in the second column. As an alternative an already loaded data.frame can be passed to the function.

additionalParameters

are required parameters which are specific for each case. In case of hg a numeric vector of length 1 is expected which contains the concentration of the host. In case of ida a numeric vector of length 3 is expected which contains the concentration of the host, dye and the khd parameter. In case of gda a numeric vector of length 3 is expected which contains the concentration of the host, guest and the khd parameter.

percentage

is the percentage +/- from parameters in which the sensitivity should be analysed.

OffsetBoundaries

in case percentage is not suitable a numeric vector (equivalent to parameters) can be used which is added/substracted from parameters. It is only possible to set either percentage or OffsetBoundaries.

runAsShiny

is internally used when running the algorithm from shiny.

error_calc_fct

is an optional input defining how the error between the in silico signal and the measured signal is calculated. One can use one of the following predefined functions as character vectors: Rel. Error, RMSE, SSE, or Huber. The default function is Rel. Error. Alternatively a function can be passed to opti, which has to expect two arguments, first the insilico signal followed by the measured signal.

Value

a plot showing the sensitivity

Examples

path <- paste0(system.file("examples", package = "tsf"), "/IDA.txt")
res <- opti("ida", c(1, 0, 0, 0), c(10^9, 10^6, 10^6, 10^6), path, c(4.3, 6.0, 7079458))
sensitivity("ida", res[[2]], path, c(4.3, 6.0, 7079458), 20)

Parametric bootstrap for a VAPRO fit, using the ast2ast-compiled grid search for every fit (point estimate + all nBoot replicates), for any of the four cases.

Description

Same design as opti_vapro_bootstrap(): fit once, estimate per-signal noise sigma from the residuals of that fit (unless sigma is supplied), then for each replicate simulate new Gaussian noise around the fitted curve and refit. Noise generation stays in R – ast2ast has no RNG, and reproducibility (set.seed()) depends on R's own RNG algorithm anyway, so there'd be nothing to gain compiling that part. Every fit (the coarse grid search over the nonlinear binding parameter, root-find + NNLS per grid point) runs compiled.

Usage

vapro_ast2ast_bootstrap(
  case,
  lowerBounds,
  upperBounds,
  path,
  additionalParameters,
  nBoot = 500L,
  sigma = NULL,
  nGrid = 1000L,
  seed = NULL,
  showProgress = TRUE
)

Arguments

case

one of "dba_dye_const", "dba_host_const", "ida" or "gda".

lowerBounds, upperBounds

bounds for the nonlinear binding parameter.

path

file path or already-loaded data.frame, same as opti_vapro.

additionalParameters

same as opti_vapro.

nBoot

number of bootstrap replicates (default 500).

sigma

per-signal noise sd; NULL (default) estimates it from the residuals of the original fit. A single value is recycled.

nGrid

number of exponential grid points, for the original fit and every replicate (default 1000).

seed

RNG seed; if NULL the current time is used.

showProgress

print a text progress bar (default TRUE).

Value

a list: draws (one row per successful replicate), summary (mean/sd/2.5%/50%/97.5% per parameter), sigma, n_success, n_fail, seed, point_estimate (the original GridResult).