""" Part of the BlackStar filesystem (bsfs) module. A copy of the license is provided with the project. Author: Matthias Baumgartner, 2022 """ # standard imports import typing # external imports import numpy as np # bsfs imports from bsfs.namespace import ns # constants EPS = 1e-9 # exports __all__: typing.Sequence[str] = ( 'DISTANCE_FU', ) ## code ## def euclid(fst, snd) -> float: """Euclidean distance (l2 norm).""" fst = np.array(fst) snd = np.array(snd) return float(np.linalg.norm(fst - snd)) def cosine(fst, snd) -> float: """Cosine distance.""" fst = np.array(fst) snd = np.array(snd) if (fst == snd).all(): return 0.0 nrm0 = np.linalg.norm(fst) nrm1 = np.linalg.norm(snd) return float(1.0 - np.dot(fst, snd) / (nrm0 * nrm1 + EPS)) def manhatten(fst, snd) -> float: """Manhatten (cityblock) distance (l1 norm).""" fst = np.array(fst) snd = np.array(snd) return float(np.abs(fst - snd).sum()) # Known distance functions. DISTANCE_FU = { ns.bsfs.euclidean: euclid, ns.bsfs.cosine: cosine, ns.bsfs.manhatten: manhatten, } ## EOF ##