diff options
author | Matthias Baumgartner <dev@igsor.net> | 2023-01-16 21:43:38 +0100 |
---|---|---|
committer | Matthias Baumgartner <dev@igsor.net> | 2023-01-16 21:43:38 +0100 |
commit | e12cd52ad267563c8046a593ad551b1dd089a702 (patch) | |
tree | d94cdf7ac540eb82630f78cbf564682b66007f51 /bsfs/triple_store/sparql/distance.py | |
parent | 7f5a2920ef311b2077300714d7700313077a0bf6 (diff) | |
parent | 3504609e1ba1f7f653fa79910474bebd3ec24d8a (diff) | |
download | bsfs-e12cd52ad267563c8046a593ad551b1dd089a702.tar.gz bsfs-e12cd52ad267563c8046a593ad551b1dd089a702.tar.bz2 bsfs-e12cd52ad267563c8046a593ad551b1dd089a702.zip |
Merge branch 'mb/features' into develop
Diffstat (limited to 'bsfs/triple_store/sparql/distance.py')
-rw-r--r-- | bsfs/triple_store/sparql/distance.py | 56 |
1 files changed, 56 insertions, 0 deletions
diff --git a/bsfs/triple_store/sparql/distance.py b/bsfs/triple_store/sparql/distance.py new file mode 100644 index 0000000..2f5387a --- /dev/null +++ b/bsfs/triple_store/sparql/distance.py @@ -0,0 +1,56 @@ +""" + +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 ## |