diff --git a/src/app/credExplorer/basicPagerank.js b/src/app/credExplorer/basicPagerank.js index 519553e..65249b3 100644 --- a/src/app/credExplorer/basicPagerank.js +++ b/src/app/credExplorer/basicPagerank.js @@ -9,6 +9,7 @@ import type { Distribution, SparseMarkovChain, } from "../../core/attribution/markovChain"; +import {uniformDistribution} from "../../core/attribution/markovChain"; export type PagerankResult = AddressMap<{| +address: Address, @@ -132,10 +133,6 @@ function sparseMarkovChainAction( return result; } -function uniformDistribution(n: number): Distribution { - return new Float64Array(n).fill(1 / n); -} - function findStationaryDistribution(chain: SparseMarkovChain): Distribution { let r0 = uniformDistribution(chain.length); function computeDelta(pi0, pi1) { diff --git a/src/core/attribution/markovChain.js b/src/core/attribution/markovChain.js index d36dbfd..3ea3723 100644 --- a/src/core/attribution/markovChain.js +++ b/src/core/attribution/markovChain.js @@ -65,3 +65,10 @@ export function sparseMarkovChainFromTransitionMatrix( }; }); } + +export function uniformDistribution(n: number): Distribution { + if (isNaN(n) || !isFinite(n) || n !== Math.floor(n) || n <= 0) { + throw new Error("expected positive integer, but got: " + n); + } + return new Float64Array(n).fill(1 / n); +} diff --git a/src/core/attribution/markovChain.test.js b/src/core/attribution/markovChain.test.js index b231f78..0b07197 100644 --- a/src/core/attribution/markovChain.test.js +++ b/src/core/attribution/markovChain.test.js @@ -1,6 +1,9 @@ // @flow -import {sparseMarkovChainFromTransitionMatrix} from "./markovChain"; +import { + sparseMarkovChainFromTransitionMatrix, + uniformDistribution, +} from "./markovChain"; describe("sparseMarkovChainFromTransitionMatrix", () => { it("works for a simple matrix", () => { @@ -77,3 +80,19 @@ describe("sparseMarkovChainFromTransitionMatrix", () => { ); }); }); + +describe("uniformDistribution", () => { + it("computes the uniform distribution with domain of size 1", () => { + const pi = uniformDistribution(1); + expect(pi).toEqual(new Float64Array([1])); + }); + it("computes the uniform distribution with domain of size 4", () => { + const pi = uniformDistribution(4); + expect(pi).toEqual(new Float64Array([0.25, 0.25, 0.25, 0.25])); + }); + [0, -1, Infinity, NaN, 3.5, '"beluga"', null, undefined].forEach((bad) => { + it(`fails when given domain ${String(bad)}`, () => { + expect(() => uniformDistribution((bad: any))).toThrow("positive integer"); + }); + }); +});