Skip to content

Commit

Permalink
feat: diversity function
Browse files Browse the repository at this point in the history
  • Loading branch information
songc04 authored and Re-st committed Nov 6, 2023
1 parent 9571c7d commit aead9dd
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
Empty file removed src/stat/diversity.ts
Empty file.
36 changes: 36 additions & 0 deletions src/utils/diversity.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
const count = (data: number[] | string[], stair = 0): {[key: string | number]:number} => {
let count : {[key: string | number]:number} = {};
data.forEach((d)=>{
if (stair > 0) {
if (typeof d === 'string'){
console.log("stair is not defined for string data");
return {};
}
else d = Math.floor(d / stair);
}
if (count[d] === undefined) count[d] = 0;
count[d] += 1;
});
return count;
}

// opts := 0 -> no normalization
// otherwise -> normalize
export const gini_simpson = (data: number[] | string[], stair = 0, opts = 0): number => {
const n = data.length;
let cnt = count(data, stair);
let sum = 0;
sum = Object.values(cnt).reduce((a,b) => a+b*(b-1));
sum = 1 - sum / (n*(n-1));
if (opts > 0) sum = sum / (1 - 1/opts);
return sum;
}

export const shannon = (data: number[] | string[], stair = 0): number => {
const n = data.length;
let cnt = count(data, stair);
let sum = 0;
sum = Object.values(cnt).reduce((a,b) => a+b*Math.log(b));
sum = -sum / n;
return sum;
}

0 comments on commit aead9dd

Please sign in to comment.