Package {BIDistances}


Type: Package
Title: Bioinformatic Distances
Version: 0.1.5
Date: 2026-08-03
Maintainer: Michael Thrun <m.thrun@gmx.net>
Description: A collection of high-performance methods for computing distance measures for bioinformatics data. The weighted Euclidean distance can be computed using 'OpenCL' on a GPU or a parallelized implementation on a CPU. Other important distance measures for bioinformatics data are provided by the R package 'parallelDist'. A specialized distance measure for the Gene Ontology is also available.
Depends: R (≥ 3.5.0)
Imports: Rcpp (≥ 1.0.8), RcppParallel, parallelDist, parallel, DataVisualizations, diptest, e1071, vegan, methods, pracma, ggplot2
Suggests: knitr, rmarkdown, remotes, sphet, OpenCL, transport, ineq, memshare, philentropy (≥ 0.10.0), manydist (≥ 0.5.0)
LinkingTo: Rcpp, RcppParallel, RcppArmadillo
NeedsCompilation: yes
SystemRequirements: GNU make, OpenCL library (optional, for GPU acceleration), pandoc (>=1.12.3, needed for vignettes)
License: GPL-3
LazyLoad: yes
LazyData: TRUE
Encoding: UTF-8
VignetteBuilder: knitr
BugReports: https://github.com/Mthrun/BIDistances/issues
Packaged: 2026-08-03 15:14:20 UTC; mct_l
Author: Quirin Stier ORCID iD [aut, rev, ctb], Michael Thrun ORCID iD [aut, cre], Luca Brinkmann [ctb]
Repository: CRAN
Date/Publication: 2026-08-04 08:40:20 UTC

Cosine Distance

Description

Calculates the cosine distance

Usage

CosinusDistance(Data)

Arguments

Data

[1:n,1:d] matrix with n cases, d variables

Details

https://en.wikipedia.org/wiki/Cosine_similarity

Value

Distance

[1:n,1:n] symmetric matrix, containing the distanes of the cases (rows) for the given data

Note

The cosine distance is calculated by calculating the cosine similarity d(i,j)=\max{s}-s(i,j), where s is the cosine similarity and the d the cosine distance.

Author(s)

Michael Thrun

References

http://stats.stackexchange.com/questions/31565/is-there-an-r-function-that-will-compute-the-cosine-dissimilarity-matrix

Examples

data(Hepta)
distMatrix = CosinusDistance(Hepta$Data)

Distances from One Point to All Rows of a Matrix

Description

Calculates the distance from a numeric vector to every row of a numeric matrix and returns the indices of the nearest rows.

Usage

Dist2All(
  X,
  Data,
  SelectFeatures,
  method = "euclidean",
  p = 2,
  knn = 1,
  GPU = FALSE
)

Arguments

X

A numeric vector with one value per column of Data.

Data

A non-empty numeric matrix whose rows are candidate points.

SelectFeatures

Optional logical vector of length ncol(Data). Numeric vectors containing only zero and one are also accepted. At least one column must be selected.

method

Distance method forwarded to parallelDist::parDist(). The default is "euclidean".

p

One finite positive number used for method = "minkowski".

knn

One positive integer. At most nrow(Data) nearest-neighbour indices are returned.

GPU

Logical scalar. When true and method = "euclidean", use EuclideanDistances_GPU(); its automatic CPU fallback remains active. For other methods a warning is issued and the CPU is used.

Value

A list with:

distToAll

Numeric vector containing one distance for every row of Data, in row order.

KNN

Integer vector containing the row indices of the nearest points.

Author(s)

Michael Thrun

Examples

data(Hepta)
result <- Dist2All(Hepta$Data[1, ], Hepta$Data)
stopifnot(length(result$distToAll) == nrow(Hepta$Data))

Distance Distribution

Description

Calculates the distribution of the distances between the data points

Usage

DistanceDistributions(Data, DistanceMethods=c('bhjattacharyya', 'bray',
                                                       'canberra', 'chord',
                                                       'divergence', 'euclidean',
                                                       'minkowski', 'geodesic',
                                                       'hellinger', 'kullback',
                                                       'manhattan', 'maximum',
                                                       'soergel', 'wave',
                                                       'whittaker'),
                               CosineNonParallel = TRUE, CorrelationDist = TRUE,
                               Mahalanobis = FALSE, Podani = FALSE,
                               PlotIt = FALSE, PlotSampleSize = 5e3)

Arguments

Data

[1:n, 1:m] A matrix, containing data as rows.

DistanceMethods

Character vector stating all distance methods such as 'euclidean'.

CosineNonParallel

Boolean stating if cosine should be computed in parallel.

CorrelationDist

Boolean stating if CorrelationDist should be computed.

Mahalanobis

Boolean stating if Mahalanobis should be computed.

Podani

Boolean stating if Podani should be computed.

PlotIt

Boolean: TRUE => create plot. FALSE => no plot.

PlotSampleSize

Integer stating the number of samples for plotting.

Value

List with elements

DistanceMatrix

[1:n, 1:n] numeric matrix containing the distance matrix

DistanceChoice

[1:n, 1:n] numeric matrix containing the distance matrix

OrderedDistances

[1:n, 1:n] numeric matrix containing the distance matrix

ggobject

ggplot object

Author(s)

Michael Thrun


Pairwise Distance, Dissimilarity, or Similarity Matrix

Description

Computes pairwise values between the rows of X. BIDistances-specific methods are retained, parallelDist is tried first for ordinary numeric methods, and philentropy is used only when parallelDist reports that the method name is invalid. Mixed-data calculations use an explicit manydist backend.

Usage

DistanceMatrix(
  X,
  method = "euclidean",
  dim = 2,
  outputisvector = FALSE,
  GPU = FALSE,
  ...
)

Arguments

X

A matrix or data frame whose rows are objects and whose columns are variables. Numeric methods require numeric or logical data. For mixed numeric/factor data, use method = "manydist" and supply X as a data frame so that variable types are preserved. Missing values are not allowed.

method

One non-empty character string. Matching is case-insensitive.

The internal BIDistances methods are "wasserstein", "pearsond", "spearmand", "kendalld", "pearsonm", "spearmanm", "kendallm", and "fractional". They do not use arguments in ....

The wrapper-specific route "sqeuclidean" squares a parallelDist Euclidean matrix, while "fagerdissimilarity" negates the parallelDist "fager" result. On the CPU, these two routes accept applicable parallelDist arguments such as threads.

Every other ordinary method name is first passed to parallelDist::parDist(). Only its “Invalid distance method” error triggers a lookup in philentropy::getDistMethods(). Consequently, a name implemented by both packages always selects the parallelDist definition.

Use "manydist" or "mdist" for mixed-data calculations and select the manydist specification through ..., for example preset = "gower" or preset = "custom", method_cat = "matching".

dim

One finite positive number. It is used as the default Minkowski exponent p, the Wasserstein order, or the fractional-distance exponent. A Minkowski p supplied through ... overrides dim.

outputisvector

Logical scalar. If false, return the full square matrix. If true, return D[upper.tri(D)], preserving the historical BIDistances ordering. If the result is asymmetric, only its upper triangle is returned and a warning is issued.

GPU

Logical scalar. If true, use EuclideanDistances_GPU() for "euclidean" and "sqeuclidean". Other methods use the CPU. The GPU route is optional and retains the automatic CPU fallback of EuclideanDistances_GPU().

...

Uniquely named arguments forwarded to the backend selected by method. They are not automatically filtered. Supply only arguments described in the backend-specific sections below. Arguments in ... are not supported by the internal Wasserstein, correlation, or fractional methods. The GPU backend accepts only Weights, Mem, ctx, backend, and threads.

Details

The aliases "cityblock" and "manhatten" map to "manhattan"; "chebychev" and "chebyshev" map to "maximum"; "braycur" and "braycurtis" map to "bray"; and "squared_euclidean" maps to "sqeuclidean".

Plain overlapping names such as "cosine", "hellinger", and "tanimoto" use parallelDist. Plain "gower" uses the numeric philentropy definition; mixed-data Gower is requested with method = "manydist", preset = "gower".

The philentropy registry includes both distances and similarities. Values are returned unchanged. Some methods are asymmetric, and many are intended for non-negative probability or count vectors.

Value

A numeric square matrix with one row and column per row of X, or a numeric vector containing the upper triangle when outputisvector = TRUE.

Rules for additional arguments

Every argument in ... must have a unique, non-empty name. x and method are controlled by DistanceMatrix() and are rejected when supplied through ....

Backend selection happens before the additional arguments are interpreted. In particular, a method name implemented by both parallelDist and philentropy selects parallelDist. Supplying a philentropy-only argument with such a name does not force the philentropy backend; it normally produces a parallelDist argument error. Use threads for parallelDist and num.threads for philentropy; the two names are not interchangeable.

Additional arguments for the GPU backend

When GPU = TRUE and the method is "euclidean" or "sqeuclidean", the following names may be supplied through ...: Weights, Mem, ctx, backend, and threads. They have the meanings documented in EuclideanDistances_GPU. All other names are rejected before dispatch. The square-Euclidean route squares the matrix returned by that function.

Additional arguments for parallelDist

The following arguments apply when the selected method is implemented by parallelDist::parDist():

threads

Number of CPU threads. With NULL, parallelDist uses the maximum number available on the system.

p

Positive Minkowski exponent, used only with method = "minkowski". When omitted, DistanceMatrix() supplies p = dim.

cov

Covariance matrix used only with method = "mahalanobis". When omitted, parallelDist estimates the covariance matrix from X.

inverted

Logical value used only with Mahalanobis distance. If true, cov is interpreted as an inverse covariance matrix.

window.size

Optional integer width of the Sakoe–Chiba window used only with method = "dtw".

norm.method

Optional DTW normalization. Supported values are "path.length", "n", and "n+m".

step.pattern

DTW step pattern. The backend default is "symmetric1". See parDist for the complete set of supported patterns.

func

An external pointer to a compiled C++ distance function, used only with method = "custom". See parDist for the required function signature and a compilation example.

diag, upper

Printing flags attached to the temporary dist object. Because DistanceMatrix() immediately converts that object to a full matrix, these arguments do not change the returned value and should normally be omitted.

The CPU routes method = "sqeuclidean" and method = "fagerdissimilarity" also use this backend. Applicable arguments such as threads are therefore forwarded to the underlying Euclidean or Fager calculation.

All other method-specific semantics, including data-domain restrictions, are those of parallelDist::parDist().

Additional arguments for philentropy

These arguments apply only when parallelDist rejects the method name and the name is present in philentropy::getDistMethods(). For methods that compare probability distributions, rows of X should be non-negative probability vectors, or non-negative count vectors together with est.prob = "empirical".

test.na

Logical value controlling a second missing-value check inside philentropy. If omitted, DistanceMatrix() sets it to FALSE, because X has already been checked.

unit

Logarithm used by log-dependent methods. Valid values are "log" for the natural logarithm, "log2", and "log10". The backend default is "log".

epsilon

Small positive replacement used by applicable methods in otherwise undefined zero-denominator cases. The backend default is 1e-5. Results from zero-heavy distributions can be sensitive to this value, so it should be chosen for the scale and sparsity of the data.

est.prob

Probability estimation from row-wise counts. The default NULL uses rows as supplied. "empirical" divides each row by its row sum before the distance is calculated.

mute.message

Logical value that suppresses messages from philentropy::distance(). If omitted, DistanceMatrix() sets it to TRUE.

num.threads

Number of worker threads used by philentropy. With NULL, the backend uses RCPP_PARALLEL_NUM_THREADS, or two threads when that environment variable is unset.

use.row.names

Controlled by the wrapper and always set to FALSE. The row names of X, when present, are restored on the final matrix.

as.dist.obj

Controlled by the wrapper and always set to FALSE, because DistanceMatrix() requires a full matrix from the backend.

diag, upper

These only control printing when as.dist.obj = TRUE. They therefore do not affect the matrix returned by DistanceMatrix() and should normally be omitted.

The p argument of philentropy::distance() is not normally reachable through this wrapper: "minkowski" is implemented by parallelDist and is therefore dispatched there first.

Additional arguments for manydist

These arguments apply only with method = "manydist" and are forwarded to manydist::mdist(). Character and logical predictor columns are converted to factors before dispatch.

preset

Predefined distance specification. The default is "custom". Current choices include "gower", "unbiased_dependent", "u_dep", "u_indep", "u_mix", "hl", "gudmm", "dkss", "mod_gower", and "euclidean". With a non-custom preset, the preset controls method_cat, method_num, commensurable, and interaction; values supplied for those arguments are ignored by manydist.

response

Optional response column for response-aware categorical dissimilarities. In this wrapper it must be supplied as a character column name, for example response = "class", because the contents of ... are evaluated before manydist::mdist() is called. manydist removes the response column from the predictor set.

method_cat

Categorical-variable dissimilarity used with preset = "custom". Common choices are "matching" and "tvd". Depending on the selected specification, this can be one method for all categorical variables or a method vector aligned with the categorical columns. Use manydist::all_dist_method_specs() to inspect the methods in the installed package.

method_num

Numerical preprocessing used with preset = "custom". Choices are "none" for no preprocessing, "std" for standard-deviation scaling, "range" for range scaling, "robust" for interquartile-range scaling, and "pc_scores" for principal-component score scaling. The default is "std".

commensurable

Logical value. When true and supported by the selected specification, variable-wise dissimilarities are scaled so that their average contributions to the overall dissimilarity are equal to one. The default is TRUE for the custom specification.

ncomp

Positive integer or NULL; number of principal components retained when method_num = "pc_scores". With NULL, all available components are used unless threshold is supplied and supported.

threshold

Numeric value between zero and one, or NULL; optional cumulative-variance threshold used with method_num = "pc_scores".

interaction

Logical value. If true, add an interaction-aware continuous–categorical component based on local predictive separability. The default is FALSE.

prop_nn

Proportion between zero and one giving the nearest-neighbour fraction used only when interaction = TRUE. The default is 0.1.

score

Interaction score used only when interaction = TRUE. Available values include "ba" for balanced accuracy and "logloss". The default is "ba".

decision

Decision rule used when interaction = TRUE and score = "ba". The default is "prior_corrected"; consult mdist for supported rules.

gower_average

Used only with preset = "gower". The default TRUE averages over active variables and matches the usual Gower scale. FALSE returns the sum of the variable-wise Gower contributions.

new_data

Not supported by DistanceMatrix(). Although manydist::mdist() can calculate rectangular new-data-to-training dissimilarities, this wrapper always returns a square within-X matrix.

The installed manydist documentation is authoritative for preset and method registries, which may grow in later releases.

Author(s)

Michael Thrun

References

Sneath, P. H. A. (1957) Some thoughts on bacterial classification. Journal of General Microbiology 17, pages 184-200.

Leydesdorff, L. (2005) Similarity Measures, Author Cocitation Analysis,and Information Theory. In: JASIST 56(7), pp.769-772.

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

Mardia, K. V., Kent, J. T. and Bibby, J. M. (1979) Multivariate Analysis. Academic Press.

Borg, I. and Groenen, P. (1997) Modern Multidimensional Scaling. Theory and Applications. Springer.

Mahalanobis, P. C. (1936) On the generalized distance in statistics. Proceedings of The National Institute of Sciences of India, 12:49-55.

van de Velden, M., Iodice D’Enza, A., Markos, A., & Cavicchia, C. (2026). Unbiased Mixed-Variable Distance. Journal of Computational and Graphical Statistics, 1–12. DOI, 10.1080/10618600.2026.2680181

See Also

parDist, getDistMethods, distance, and mdist.

Examples

X <- rbind(a = c(1, 2, 3), b = c(2, 2, 4), c = c(4, 1, 2))
DistanceMatrix(X, method = "euclidean")
DistanceMatrix(X, method = "minkowski", p = 3)

# Method-specific parallelDist arguments
DistanceMatrix(X, method = "mahalanobis", cov = diag(ncol(X)))
DistanceMatrix(X, method = "dtw", window.size = 1,
               norm.method = "path.length")

if (requireNamespace("philentropy", quietly = TRUE)) {
  counts <- rbind(a = c(1, 4, 5), b = c(2, 3, 5), c = c(6, 2, 2))
  DistanceMatrix(
    counts,
    method = "jensen-shannon",
    est.prob = "empirical",
    unit = "log2",
    epsilon = 1e-8
  )
}

if (requireNamespace("manydist", quietly = TRUE)) {
  mixed <- data.frame(
    value = c(1, 3, 2),
    group = factor(c("a", "b", "a"))
  )
  DistanceMatrix(
    mixed,
    method = "manydist",
    preset = "gower",
    gower_average = TRUE
  )
  DistanceMatrix(
    mixed,
    method = "manydist",
    preset = "custom",
    method_cat = "matching",
    method_num = "robust",
    commensurable = TRUE
  )

  # In this wrapper, response must be a character column name:
  # DistanceMatrix(mixed_with_class, method = "manydist",
  #                preset = "custom", method_cat = "tvd",
  #                response = "class")
}

Weighted Euclidean Distances with an Optional OpenCL Backend

Description

Computes all pairwise weighted Euclidean distances between rows of a numeric matrix. An optional OpenCL backend can use an available accelerator; a CPU implementation is always available.

Usage

EuclideanDistances_GPU(
  Data,
  Weights,
  Mem = 2,
  OutputType = "mat",
  ctx = NULL,
  backend = c("auto", "opencl", "cpu"),
  threads = 2L
)

Arguments

Data

A numeric matrix. Rows are observations and columns are features.

Weights

Optional non-negative numeric vector with one value per column of Data. The default is a vector of ones.

Mem

One finite positive number giving the device-memory budget in GiB. The OpenCL planner uses a conservative estimate of eight bytes per value.

OutputType

One of "mat", "dist", or "vec". "mat" returns the full square matrix, "dist" returns a dist object, and "vec" returns the full matrix as a column-major vector of length nrow(Data)^2.

ctx

An optional OpenCL context created by OpenCL::oclContext(). It is ignored by the CPU backend. When it is NULL, the OpenCL backend creates a context with precision = "best".

backend

Backend selection. "auto" tries OpenCL and falls back to the CPU with a warning when the package, platform, device, context, kernel, or allocation is unavailable. "opencl" requires OpenCL and reports an error instead of falling back. "cpu" never probes OpenCL.

threads

Number of CPU threads used by the CPU backend or an automatic fallback. Must be either 1 or 2; the default is 2 to respect CRAN's shared-resource policy. It is ignored after a successful OpenCL calculation.

Details

For rows x_i and x_j, the returned value is

\left(\sum_k w_k (x_{ik} - x_{jk})^2\right)^{1/2}.

The OpenCL package is suggested rather than imported, so BIDistances can be installed and checked on systems without OpenCL headers, drivers, or hardware. Depending on the memory budget, the OpenCL path uses a full-matrix, output-batched, or input-blocked implementation.

With precision = "best", OpenCL may use single precision on devices without double-precision support. Small numerical differences from the CPU result are therefore possible.

Value

A square numeric matrix, a dist object, or a full column-major numeric vector, according to OutputType.

Author(s)

Quirin Stier, Michael Thrun, Luca Brinkmann

See Also

calculateMemoryDemandGPU, DistanceMatrix, as.dist

Examples

Data <- as.matrix(iris[1:8, 1:4])
Weights <- c(1, 2, 0.5, 1)

D <- EuclideanDistances_GPU(
  Data,
  Weights,
  backend = "cpu",
  OutputType = "mat"
)
reference <- as.matrix(stats::dist(sweep(Data, 2, sqrt(Weights), "*")))
dimnames(reference) <- dimnames(D)
stopifnot(isTRUE(all.equal(D, reference)))

## Not run: 
## This block requires an installed OpenCL implementation and usable device.
Dgpu <- EuclideanDistances_GPU(
  Data,
  Weights,
  backend = "opencl",
  OutputType = "mat"
)
stopifnot(isTRUE(all.equal(Dgpu, reference, tolerance = 1e-5)))

## End(Not run)

Calculates fractional distances

Description

Calculates distance matrix, through \left( \sum_{i=1}^{n} |x_i - y_i|^p \right)^{1/p}

Usage

FractionalDistance(Data, p)

Arguments

Data

[1:n,1:d] Matrix, with n cases, d variables

p

Scalar, value for p

Details

Values of p < 1 can be used, which can be useful for high-dimensional data, see references.

Value

DistanceMatrix

[1:n,1:n] symmetric Matrix, containing the distances between the cases (rows) of the input matrix

Author(s)

Michael Thrun

References

Aggrawal, C. C., Hinneburg, A., Keim, D. (2001), On the Suprising Behavior of Distance Metrics in High Dimensional Space.

Examples

data(Hepta)
distMatrix = FractionalDistance(Hepta$Data, p = 1/2)

Gini Distance Between Features

Description

Computes a distance matrix between the columns of a data matrix based on differences in their Gini coefficients.

Usage

GiniDist(Data)

Arguments

Data

A numeric matrix of size n \times d, where rows correspond to observations and columns to features.

Details

For each feature (column) in Data, the Gini coefficient is computed using the ineq package. The distance between two features i and j is defined as the absolute difference of their Gini coefficients:

d(i,j) = | Gini(x_i) - Gini(x_j) |

The result is returned as a symmetric distance matrix.

Value

A symmetric d \times d distance matrix of class dist.

Author(s)

Michael Thrun (December 2023)

See Also

ineq from the ineq package for computing Gini coefficients.

Examples

# Example with simulated data
set.seed(123)
X <- matrix(runif(50), nrow = 10, ncol = 5)
GiniDist(X)

Hearingloss data

Description

Hearingloss data, with Gene2GoTerm matrix.

Usage

data('Hearingloss_N109')

Details

FeatureMarix_Gene2Term contains the dataset, NCBI are the row names for the genes and GoTerm_Header contains the column names for the GoTerms. Size of data matrix is 109 with dimension 829.

Source

NCBI OtoGenome Test for Hearing Loss, accessed 24 June 2022.

References

GeneTestingRegistry (2018). OtoGenome Test for Hearing Loss Retrieved 2017

Examples

data(Hearingloss_N109)
str(Hearingloss_N109)

Hellinger4ConditionalPDF

Description

Hellinger4ConditionalPDF

Usage

Hellinger4ConditionalPDF(Data, Cls)

Arguments

Data

[1:n,1:d] numeric matrix with data.

Cls

Optional numeric matrix with data.

Value

Matrix with index integer vector and a numeric vector containing hellinger distance between conditional probability density estimation for both classes of the binary classification vector.

Author(s)

Quirin Stier

Examples

Data = iris[1:100, 1:4]
Cls  = as.numeric(iris[1:100, 5])
Hellinger4ConditionalPDF(Data, Cls)

Hepta introduced in [Ultsch, 2003]

Description

Clearly defined clusters, different variances. Detailed description of dataset and its clustering challenge is provided in [Thrun/Ultsch, 2020].

Usage

data('Hepta')

Details

Size 212, Dimensions 3, stored in Hepta$Data

Classes 7, stored in Hepta$Cls

References

[Ultsch, 2003] Ultsch, A.: Maps for the visualization of high-dimensional data spaces, Proc. Workshop on Self organizing Maps (WSOM), pp. 225-230, Kyushu, Japan, 2003.

[Thrun/Ultsch, 2020] Thrun, M. C., & Ultsch, A.: Clustering Benchmark Datasets Exploiting the Fundamental Clustering Problems, Data in Brief, Vol. 30(C), pp. 105501, doi:10.1016/j.dib.2020.105501, 2020.

Examples

data(Hepta)
str(Hepta)

Kullback-Leibler divergence

Description

Kullback-Leibler divergence KLD of discrete distributions or their pdfs

Usage

Kullback_Leibler_div(P, Q, sym = 1, PDF = FALSE, Eps = 1/10000)

Arguments

P

Distribution (data sample) P having the same dirccrete range unique(c(P,Q), or estimated pdf of P depending on PDF input parameter

Q

Distribution (data sample) Q having the same dirccrete range unique(c(P,Q), or estimated pdf of Q depending on PDF input parameter

sym

default ==1: if sym ==1 then the symmetical KLD is returned

PDF

boolean, FALSE: assume sample(distibutions), TRUE assumes estimated probability density functions

Eps

threshold for dealin with very small probabilites

Details

If P and Q are pdfs they have to have the same length and we assume that they have the same kernels.

NaN in the distributions are ignored. not defined for zero probabilities, replace with very small values.

Value

KLD

Kullback-Leibler divergence

p

frequency counts of distributions or initial pdf depending on PDF input parameter

q

frequency counts of distributionsor initial pdf depending on PDF input parameter

x

the unique discrete x values of P and Q: x = unique([P;Q]), NULL if PDF=TRUE

Author(s)

Michael Thrun


Pairwise Squared Generalized Mahalanobis Distances

Description

Function to calculate the squared generalized Mahalanobis distance between all pairs of rows in a data frame with respect to a covariance matrix. The element of the i-th row and j-th column of the distance matrix is defined as

D_{ij}^2 = (\bold{x}_i - \bold{x}_j)' \bold{\Sigma}^{-1} (\bold{x}_i - \bold{x}_j)

Usage

Mahalanobis(X, cov, inverted = FALSE)

Arguments

X

a matrix of data (n x d) n cases, d variables

cov

a variance-covariance matrix (p x p).

inverted

logical. If FALSE (default), cov is supposed to be a variance-covariance matrix.

Value

Distances[1:n,1:n]

Note

copy of function in biotools package, because this packages doesnt work under mac os

Author(s)

Anderson Rodrigo da Silva <anderson.agro@hotmail.com>

References

Mahalanobis, P. C. (1936) On the generalized distance in statistics. Proceedings of The National Institute of Sciences of India, 12:49-55.

See Also

dist

Examples

# Manly (2004, p.65-66)
x1 <- c(131.37, 132.37, 134.47, 135.50, 136.17)
x2 <- c(133.60, 132.70, 133.80, 132.30, 130.33)
x3 <- c(99.17, 99.07, 96.03, 94.53, 93.50)
x4 <- c(50.53, 50.23, 50.57, 51.97, 51.37)
x <- cbind(x1, x2, x3, x4)
Cov <- matrix(c(21.112,0.038,0.078,2.01, 0.038,23.486,5.2,2.844,
	0.078,5.2,24.18,1.134, 2.01,2.844,1.134,10.154), 4, 4)
Mahalanobis(x, Cov)

# End (not run)

Shared Neighbor Distance

Description

Calculates the Shared Neighbor Distance

Usage

SharedNeighborDistance(Data, k = 5, NThreads = NULL, ComputationInR = FALSE)

Arguments

Data

[1:n,1:d] matrix with n cases, d variables

k

Integer defining the number of nearest neighbors

NThreads

Number of threads in parallel computation.

ComputationInR

Boolean (Default ComputationInR = FALSE). If FALSE, do computation in Rcpp, else in R (very slow).

Value

Distance

[1:n,1:n] symmetric matrix, containing the distanes of the cases (rows) for the given data

Author(s)

Quirin Stier

References

https://github.com/albert-espin/snn-clustering/blob/master/SNN/snn.py

Examples

data(Hepta)
distMatrix = SharedNeighborDistance(Hepta$Data, NThreads = 1, ComputationInR=TRUE)

Term frequency-inverse document frequency distance

Description

Computes the term frequency inverse document frequency (tfidf) distance for a FeatureMatrix_Gene2GoTerm. In case of genes with annotated GOterms from gene ontology genes can be interpreted as documents and GOterms as terms.

Usage

Tfidf_dist(FeatureMatrix_Gene2GoTerm, tf_fun = mean)

Arguments

FeatureMatrix_Gene2GoTerm

[1:n,1:d] Matrix, with n genes and d GO-Terms.

tf_fun

Function, defining the numerator value in the normalized Term-frequency. The default is the mean of the not 0 values.

Details

For the FeatureMatrix_Gene2GoTerm it is:
FeatureMatrix_Gene2GoTerm[i,j] > 0 iff GOterm j is relevant for gene i. The FeatureMatrix_Gene2GoTerm[i,j] > 1 if the specific gene is annotated by in a specific GO-Term with more than one evidence code FeatureMatrix_Gene2GoTerm[i,j] is the frequency of term js occurance in document i.

Value

List with

dist

Numeric vector containing the tdfidf distances between the documents = absolute difference of TfidfWeights

TfidfWeights

[1:n] Numeric vector containing the term frequence inverse document frequency weights used for the distance, given as the Term frequency*Inverse document frequency

Author(s)

Michael Thrun

References

Stier, Q. and Thrun, M., C.: Deriving homogeneous subsets from gene sets by exploiting the Gene Ontology, Informatica, in review, 2023

Examples

data(Hearingloss_N109)
V = Tfidf_dist(Hearingloss_N109$FeatureMatrix_Gene2Term)
dist = V$dist
TfidfWeights = V$TfidfWeights

Calculate Toroidal Euclidean Distances

Description

Computes the Euclidean distances between one two-dimensional position and a collection of positions on a rectangular toroidal grid. A toroidal grid uses periodic boundary conditions, so positions near opposite grid edges may be close to one another.

Usage

ToroidDist2All(positionxy, AllPositions, Lines, Columns)

Arguments

positionxy

A numeric vector of length two containing the coordinates of the reference position in the form c(x, y).

AllPositions

A numeric matrix or data frame with two columns. Each row represents one position in the form c(x, y).

Lines

A positive numeric scalar specifying the extent of the grid in the first coordinate direction.

Columns

A positive numeric scalar specifying the extent of the grid in the second coordinate direction.

Details

For each row of AllPositions, the function first calculates the absolute coordinate differences

d_x = |x_i - x|

and

d_y = |y_i - y|.

Periodic boundary conditions are then applied separately to both coordinates. The distances used by the implementation are

d_x^* = \min(d_x, \mathrm{Lines} - d_x + 1)

and

d_y^* = \min(d_y, \mathrm{Columns} - d_y + 1).

The resulting toroidal Euclidean distance is

D_i = \sqrt{(d_x^*)^2 + (d_y^*)^2}.

The computation is vectorized over the rows of AllPositions.

Coordinates should use the same coordinate system and indexing convention as the grid dimensions supplied through Lines and Columns. The function does not check whether coordinates lie within the stated grid dimensions.

Value

A numeric vector with one element for each row of AllPositions. The i-th element is the toroidal Euclidean distance between positionxy and row i of AllPositions.

Author(s)

Michael Thrun

See Also

dist for ordinary distance calculations.

Examples

## Distances to positions away from the grid boundaries
positionxy <- c(1, 1)
AllPositions <- rbind(
  c(2, 3),
  c(5, 2)
)

ToroidDist2All(
  positionxy = positionxy,
  AllPositions = AllPositions,
  Lines = 40,
  Columns = 80
)

## Positions on opposite sides of the grid can be close because
## distances may wrap around the grid boundaries
edgePositions <- rbind(
  c(40, 1),
  c(1, 80),
  c(40, 80)
)

ToroidDist2All(
  positionxy = c(1, 1),
  AllPositions = edgePositions,
  Lines = 40,
  Columns = 80
)

TransformSimilarity2MetricDistance

Description

TransformSimilarity2MetricDistance

Usage

TransformSimilarity2MetricDistance(Similarity)

Arguments

Similarity

Similarity

Value

Similarity

Author(s)

Michael Thrun


VariablePrecision

Description

Computes the variable precision

Usage

VariablePrecision(Variable)

Arguments

Variable

Numeric vector [1:n] or matrix [1:n, 1:d]

Value

matrix of distances, symmetric

Author(s)

Michael Thrun

Examples

data(Hepta)
distMat = VariablePrecision(as.matrix(iris[, 1]))

distMat = VariablePrecision(as.matrix(iris[, 1:4]))

Wasserstein Distance

Description

Computes the Wasserstein distance for a data matrix

Usage

WassersteinDist(Data, p = 1, InverseWeighting = FALSE)

Arguments

Data

data matrix of n cases and d feautures

p

scalar higher than one, the power to which the Euclidean distance between points is taken in order to compute transportation costs.

InverseWeighting

weighting per row can be either 1 (FALSE) or 1/n (TRUE)

Details

Wasserstein distance, also known as Earth Mover’s Distance (EMD) is the distance between two probability distributions over a region D. The Wasserstein distance of order p is defined as the p-th root of the total cost incurred when transporting measure a to measure b in an optimal way, where the cost of transporting a unit of mass from x to y is given as the p-th power of the Euclidean distance.

It is claimed to be useful for distributions that do not align well with traditional measures like Euclidean distance.

Value

matrix of distances, symmetric

Author(s)

Michae Thrun

References

...

See Also

wasserstein1d

Examples

data(Hepta)
distMat=WassersteinDist(Hepta$Data)

Plan Device-Memory Batches for Weighted Euclidean Distances

Description

Selects one of three OpenCL execution layouts and calculates the corresponding batch sizes from the number of rows, number of columns, and a device-memory budget.

Usage

calculateMemoryDemandGPU(n, d, mem = 2)

Arguments

n

One positive integer: the number of observations (rows).

d

One positive integer: the number of features (columns).

mem

One finite positive number giving the memory budget in GiB.

Details

The estimate conservatively uses eight bytes per input, weight, and output value.

Version 0

The complete input and output matrix fit in the budget.

Version 1

The complete input fits, while output columns are processed in batches.

Version 2

Two input blocks and their output block are processed at a time.

The calculation is a planning estimate. Device-specific limits, driver memory, and other allocations can still prevent an OpenCL allocation. With backend = "auto", EuclideanDistances_GPU() catches such failures and uses its CPU backend.

Value

A list with components:

maxBatchSize

Maximum planned rows or output columns per batch.

minNrBatches

Number of planned batches.

batchSizes

Integer vector containing each batch size.

Version

Integer execution-layout identifier: 0, 1, or 2.

Author(s)

Luca Brinkmann, with portability revisions by Michael Thrun

See Also

EuclideanDistances_GPU

Examples

info <- calculateMemoryDemandGPU(70000, 784, 6)

fastPdist

Description

calculates pairwise euclidean distances

Usage

fastPdist(X)

Arguments

X

[1:n,1:m] data to calculate distances to

Value

dist[1:n,1:n] distances

Author(s)

Michael Thrun


fastPdist

Description

calculates pairwise euclidean distances

Usage

fastPdistC(Ar,Br)

Arguments

Ar

[1:n,1:m] data to calculate distances to

Br

[1:n,1:m] data to calculate distances to

Value

dist[1:n,1:n] distances

Author(s)

Felix Riede


Computes dissimilarity indices Jaccard

Description

The function computes dissimilarity indices Jaccard, which index is computed as 2B/(1+B), where B is Bray-Curtis dissimilarity

Usage

jaccard(X)

Arguments

X

Distance Matrix

Value

Kosinusdistanz der beiden Vektoren x,y

Author(s)

MT


Find Nearest Neighbors from a Distance Matrix

Description

For every point, finds the k nearest other points represented by a square distance matrix. The point itself is excluded explicitly rather than by assuming that the diagonal is the unique smallest value.

Usage

knneighborDistances(k, Distances)

Arguments

k

A single integer giving the number of nearest neighbors to return. It must satisfy 1 <= k < n, where n is the number of points.

Distances

A square numeric distance matrix, a dist object, or a numeric condensed-distance vector accepted by pracma::squareform(). Row i represents point i.

Details

Missing values are not accepted. Infinite distances are allowed. Equal finite or infinite distances are ordered by the point index, with the smaller index first.

Value

A list with two components:

NNind

An integer matrix with n rows and k columns. Row i contains the indices of the nearest neighbors of point i.

NNdists

A numeric matrix with n rows and k columns. Row i contains the corresponding distances.

Author(s)

Michael Thrun

Examples

Distances <- matrix(
  c(
    0, 1, 4, 1,
    1, 0, 2, 3,
    4, 2, 0, 5,
    1, 3, 5, 0
  ),
  nrow = 4,
  byrow = TRUE
)

knneighborDistances(2, Distances)

msmd

Description

msmd

Usage

msmd(Values1, Values2, ParameterC)

Arguments

Values1

[1:N1] Numeric vector with values of the first time series.

Values2

[1:N1] Numeric vector with values of the second time series.

ParameterC

Numeric vector with time stamps of the first time series.

Value

List with elements

Value

Distance measure

Author(s)

Quirin Stier


Nearest

Description

returns the index of the nearest neighbour of a given data point.

Usage

nearest(Data, i, defined)

Arguments

Data

A matrix holding n data points as row vectors.

i

the index of the data point, who's nearest neighbour is sought.

defined

A row vector with 1 for all columns of data that are used for the computation. If missing, all columns are used.

Value

nNInd

The index of the nearest neighbour of data[i, ]

Author(s)

Michael Thrun, Raphael Paebst


Calculate toroid Euclidean Distances

Description

Calculate toroid Euclidean Distances

Usage

pdistToroid(X,Y,Lines,Columns,Points)

Arguments

X

vector of grid koordinated on a planar grid of size Lines

Y

vector of grid koordinated on a planar grid of size Columns

Lines

lines of the planar grid

Columns

columns of the planar grid

Points

Substitute for X and Y if available. 2D matrix as concatenation of two vectors

Value

distance(s) between row(s) of x and y in MATHLBs pdist form

Author(s)

MT


twed

Description

twed

Usage

twed(Values1, Values2, Time1, Time2, Nu = 1, Lambda = 1, Degree = 2)

Arguments

Values1

[1:N1] Numeric vector with values of the first time series.

Values2

[1:N1] Numeric vector with values of the second time series.

Time1

[1:N1] Numeric vector with time stamps of the first time series.

Time2

[1:N1] Numeric vector with time stamps of the second time series.

Nu

Optional, Numeric: Elasticity parameter - nu >=0 needed for distance measure.

Lambda

Optional, Numeric: Penalty for deletion operation.

Degree

Optional, Integer: Degree of the p norm for local cost.

Value

List with elements

TWED

TWED distance between time series Values1 (Time1) and Values2 (Time2)

DPMatrix

[1:n, 1:m] Numeric matrix

Author(s)

Quirin Stier