Skip to content

Commit

Permalink
feat(distance): add/update argmin fns/params
Browse files Browse the repository at this point in the history
- add argminN() for numeric inputs
- updata argmin fn to accept metric functions OR IDistance impls
- add thi.ng/checks as direct dependency (already was transitive)
  • Loading branch information
postspectacular committed Sep 24, 2021
1 parent 6af7e1e commit 9c0f003
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 6 deletions.
1 change: 1 addition & 0 deletions packages/distance/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
},
"dependencies": {
"@thi.ng/api": "^7.2.0",
"@thi.ng/checks": "^2.9.11",
"@thi.ng/errors": "^1.3.4",
"@thi.ng/heaps": "^1.3.1",
"@thi.ng/math": "^4.0.6",
Expand Down
32 changes: 26 additions & 6 deletions packages/distance/src/argmin.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import type { Fn } from "@thi.ng/api";
import type { Fn, NumericArray } from "@thi.ng/api";
import { isFunction } from "@thi.ng/checks/is-function";
import type { ReadonlyVec } from "@thi.ng/vectors";
import type { IDistance } from "./api";
import type { IDistance, Metric } from "./api";
import { knearest } from "./knearest";
import { DIST_SQ } from "./squared";
import { DIST_SQ, DIST_SQ1 } from "./squared";

/**
* Takes a vector `p`, array of `samples` and a `dist`ance function. Computes
Expand All @@ -21,12 +22,31 @@ import { DIST_SQ } from "./squared";
export const argmin = (
p: ReadonlyVec,
samples: ReadonlyVec[],
{ metric: dist }: IDistance<ReadonlyVec> = DIST_SQ
dist: Metric<ReadonlyVec> | IDistance<ReadonlyVec> = DIST_SQ
) => {
const distFn = isFunction(dist) ? dist : dist.metric;
let minD = Infinity;
let minArg = -1;
for (let i = 0, n = samples.length; i < n; i++) {
const d = dist(p, samples[i]);
const d = distFn(p, samples[i]);
if (d < minD) {
minD = d;
minArg = i;
}
}
return minArg;
};

export const argminN = (
p: number,
samples: NumericArray,
dist: Metric<number> | IDistance<number> = DIST_SQ1
) => {
const distFn = isFunction(dist) ? dist : dist.metric;
let minD = Infinity;
let minArg = -1;
for (let i = 0, n = samples.length; i < n; i++) {
const d = distFn(p, samples[i]);
if (d < minD) {
minD = d;
minArg = i;
Expand All @@ -53,7 +73,7 @@ export const argminT = <T>(
p: T,
samples: T[],
key: Fn<T, ReadonlyVec>,
dist?: IDistance<ReadonlyVec>
dist?: Metric<ReadonlyVec> | IDistance<ReadonlyVec>
) => argmin(key(p), samples.map(key), dist);

/**
Expand Down

0 comments on commit 9c0f003

Please sign in to comment.