echogarden 0.0.1 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (295) hide show
  1. package/README.md +59 -1
  2. package/data/lexicons/heteronyms.json +674 -0
  3. package/data/schemas/options.json +1057 -0
  4. package/data/tables/lcid-table.json +7427 -0
  5. package/dist/alignment/DTWMfccSequenceAlignment.d.ts +2 -0
  6. package/dist/alignment/DTWMfccSequenceAlignment.js +26 -0
  7. package/dist/alignment/DTWMfccSequenceAlignment.js.map +1 -0
  8. package/dist/alignment/DTWSequenceAlignment.d.ts +5 -0
  9. package/dist/alignment/DTWSequenceAlignment.js +99 -0
  10. package/dist/alignment/DTWSequenceAlignment.js.map +1 -0
  11. package/dist/alignment/DTWSequenceAlignmentWindowed.d.ts +5 -0
  12. package/dist/alignment/DTWSequenceAlignmentWindowed.js +161 -0
  13. package/dist/alignment/DTWSequenceAlignmentWindowed.js.map +1 -0
  14. package/dist/alignment/LevenshteinSequenceAlignment.d.ts +5 -0
  15. package/dist/alignment/LevenshteinSequenceAlignment.js +102 -0
  16. package/dist/alignment/LevenshteinSequenceAlignment.js.map +1 -0
  17. package/dist/alignment/SpeechAlignment.d.ts +27 -0
  18. package/dist/alignment/SpeechAlignment.js +266 -0
  19. package/dist/alignment/SpeechAlignment.js.map +1 -0
  20. package/dist/api/API.d.ts +8 -0
  21. package/dist/api/API.js +10 -0
  22. package/dist/api/API.js.map +1 -0
  23. package/dist/api/APIOptions.d.ts +12 -0
  24. package/dist/api/APIOptions.js +2 -0
  25. package/dist/api/APIOptions.js.map +1 -0
  26. package/dist/api/Alignment.d.ts +32 -0
  27. package/dist/api/Alignment.js +134 -0
  28. package/dist/api/Alignment.js.map +1 -0
  29. package/dist/api/Denoising.d.ts +14 -0
  30. package/dist/api/Denoising.js +66 -0
  31. package/dist/api/Denoising.js.map +1 -0
  32. package/dist/api/Globals.d.ts +1 -0
  33. package/dist/api/Globals.js +2 -0
  34. package/dist/api/Globals.js.map +1 -0
  35. package/dist/api/LanguageDetection.d.ts +49 -0
  36. package/dist/api/LanguageDetection.js +118 -0
  37. package/dist/api/LanguageDetection.js.map +1 -0
  38. package/dist/api/Recognition.d.ts +49 -0
  39. package/dist/api/Recognition.js +162 -0
  40. package/dist/api/Recognition.js.map +1 -0
  41. package/dist/api/Synthesis.d.ts +125 -0
  42. package/dist/api/Synthesis.js +892 -0
  43. package/dist/api/Synthesis.js.map +1 -0
  44. package/dist/api/Translation.d.ts +25 -0
  45. package/dist/api/Translation.js +69 -0
  46. package/dist/api/Translation.js.map +1 -0
  47. package/dist/api/Vad.d.ts +25 -0
  48. package/dist/api/Vad.js +88 -0
  49. package/dist/api/Vad.js.map +1 -0
  50. package/dist/audio/AudioBufferConversion.d.ts +15 -0
  51. package/dist/audio/AudioBufferConversion.js +228 -0
  52. package/dist/audio/AudioBufferConversion.js.map +1 -0
  53. package/dist/audio/AudioPlayer.d.ts +9 -0
  54. package/dist/audio/AudioPlayer.js +232 -0
  55. package/dist/audio/AudioPlayer.js.map +1 -0
  56. package/dist/audio/AudioRecorder.d.ts +3 -0
  57. package/dist/audio/AudioRecorder.js +68 -0
  58. package/dist/audio/AudioRecorder.js.map +1 -0
  59. package/dist/audio/AudioUtilities.d.ts +48 -0
  60. package/dist/audio/AudioUtilities.js +209 -0
  61. package/dist/audio/AudioUtilities.js.map +1 -0
  62. package/dist/audio/SoxPath.d.ts +1 -0
  63. package/dist/audio/SoxPath.js +19 -0
  64. package/dist/audio/SoxPath.js.map +1 -0
  65. package/dist/cli/CLI.d.ts +8 -0
  66. package/dist/cli/CLI.js +860 -0
  67. package/dist/cli/CLI.js.map +1 -0
  68. package/dist/cli/CLIConfigFile.d.ts +3 -0
  69. package/dist/cli/CLIConfigFile.js +62 -0
  70. package/dist/cli/CLIConfigFile.js.map +1 -0
  71. package/dist/cli/CLILauncher.d.ts +2 -0
  72. package/dist/cli/CLILauncher.js +22 -0
  73. package/dist/cli/CLILauncher.js.map +1 -0
  74. package/dist/cli/CLIOptionsSchema.d.ts +5 -0
  75. package/dist/cli/CLIOptionsSchema.js +36 -0
  76. package/dist/cli/CLIOptionsSchema.js.map +1 -0
  77. package/dist/cli/CLIParser.d.ts +6 -0
  78. package/dist/cli/CLIParser.js +34 -0
  79. package/dist/cli/CLIParser.js.map +1 -0
  80. package/dist/cli/CLIStarter.d.ts +1 -0
  81. package/dist/cli/CLIStarter.js +3 -0
  82. package/dist/cli/CLIStarter.js.map +1 -0
  83. package/dist/codecs/FFMpegTranscoder.d.ts +20 -0
  84. package/dist/codecs/FFMpegTranscoder.js +169 -0
  85. package/dist/codecs/FFMpegTranscoder.js.map +1 -0
  86. package/dist/codecs/TIMITCodec.d.ts +9 -0
  87. package/dist/codecs/TIMITCodec.js +14 -0
  88. package/dist/codecs/TIMITCodec.js.map +1 -0
  89. package/dist/codecs/WaveCodec.d.ts +19 -0
  90. package/dist/codecs/WaveCodec.js +208 -0
  91. package/dist/codecs/WaveCodec.js.map +1 -0
  92. package/dist/denoising/RNNoise.d.ts +6 -0
  93. package/dist/denoising/RNNoise.js +68 -0
  94. package/dist/denoising/RNNoise.js.map +1 -0
  95. package/dist/dsp/BiquadFilter.d.ts +26 -0
  96. package/dist/dsp/BiquadFilter.js +399 -0
  97. package/dist/dsp/BiquadFilter.js.map +1 -0
  98. package/dist/dsp/FFT.d.ts +9 -0
  99. package/dist/dsp/FFT.js +135 -0
  100. package/dist/dsp/FFT.js.map +1 -0
  101. package/dist/dsp/MFCC.d.ts +25 -0
  102. package/dist/dsp/MFCC.js +162 -0
  103. package/dist/dsp/MFCC.js.map +1 -0
  104. package/dist/dsp/MelSpectogram.d.ts +19 -0
  105. package/dist/dsp/MelSpectogram.js +102 -0
  106. package/dist/dsp/MelSpectogram.js.map +1 -0
  107. package/dist/dsp/Rubberband.d.ts +52 -0
  108. package/dist/dsp/Rubberband.js +186 -0
  109. package/dist/dsp/Rubberband.js.map +1 -0
  110. package/dist/dsp/Sonic.d.ts +2 -0
  111. package/dist/dsp/Sonic.js +39 -0
  112. package/dist/dsp/Sonic.js.map +1 -0
  113. package/dist/dsp/SpeexResampler.d.ts +3 -0
  114. package/dist/dsp/SpeexResampler.js +53 -0
  115. package/dist/dsp/SpeexResampler.js.map +1 -0
  116. package/dist/math/VectorMath.d.ts +70 -0
  117. package/dist/math/VectorMath.js +564 -0
  118. package/dist/math/VectorMath.js.map +1 -0
  119. package/dist/nlp/ChineseSegmentation.d.ts +1 -0
  120. package/dist/nlp/ChineseSegmentation.js +53 -0
  121. package/dist/nlp/ChineseSegmentation.js.map +1 -0
  122. package/dist/nlp/CompromiseNLP.d.ts +15 -0
  123. package/dist/nlp/CompromiseNLP.js +66 -0
  124. package/dist/nlp/CompromiseNLP.js.map +1 -0
  125. package/dist/nlp/EspeakPhonemizer.d.ts +4 -0
  126. package/dist/nlp/EspeakPhonemizer.js +133 -0
  127. package/dist/nlp/EspeakPhonemizer.js.map +1 -0
  128. package/dist/nlp/IPA.d.ts +19 -0
  129. package/dist/nlp/IPA.js +113 -0
  130. package/dist/nlp/IPA.js.map +1 -0
  131. package/dist/nlp/JapaneseSegmentation.d.ts +1 -0
  132. package/dist/nlp/JapaneseSegmentation.js +40 -0
  133. package/dist/nlp/JapaneseSegmentation.js.map +1 -0
  134. package/dist/nlp/Lexicon.d.ts +17 -0
  135. package/dist/nlp/Lexicon.js +6 -0
  136. package/dist/nlp/Lexicon.js.map +1 -0
  137. package/dist/nlp/PhoneConversion.d.ts +6 -0
  138. package/dist/nlp/PhoneConversion.js +467 -0
  139. package/dist/nlp/PhoneConversion.js.map +1 -0
  140. package/dist/nlp/Segmentation.d.ts +41 -0
  141. package/dist/nlp/Segmentation.js +158 -0
  142. package/dist/nlp/Segmentation.js.map +1 -0
  143. package/dist/nlp/TextNormalizer.d.ts +4 -0
  144. package/dist/nlp/TextNormalizer.js +69 -0
  145. package/dist/nlp/TextNormalizer.js.map +1 -0
  146. package/dist/recognition/AmazonTranscribeSTT.d.ts +6 -0
  147. package/dist/recognition/AmazonTranscribeSTT.js +79 -0
  148. package/dist/recognition/AmazonTranscribeSTT.js.map +1 -0
  149. package/dist/recognition/AzureCognitiveServicesSTT.d.ts +7 -0
  150. package/dist/recognition/AzureCognitiveServicesSTT.js +51 -0
  151. package/dist/recognition/AzureCognitiveServicesSTT.js.map +1 -0
  152. package/dist/recognition/GoogleCloudSTT.d.ts +7 -0
  153. package/dist/recognition/GoogleCloudSTT.js +66 -0
  154. package/dist/recognition/GoogleCloudSTT.js.map +1 -0
  155. package/dist/recognition/SileroSTT.d.ts +9 -0
  156. package/dist/recognition/SileroSTT.js +125 -0
  157. package/dist/recognition/SileroSTT.js.map +1 -0
  158. package/dist/recognition/VoskSTT.d.ts +10 -0
  159. package/dist/recognition/VoskSTT.js +78 -0
  160. package/dist/recognition/VoskSTT.js.map +1 -0
  161. package/dist/recognition/WhisperSTT.d.ts +69 -0
  162. package/dist/recognition/WhisperSTT.js +977 -0
  163. package/dist/recognition/WhisperSTT.js.map +1 -0
  164. package/dist/server/Server.d.ts +1 -0
  165. package/dist/server/Server.js +18 -0
  166. package/dist/server/Server.js.map +1 -0
  167. package/dist/speech-language-detection/SileroLanguageDetection.d.ts +9 -0
  168. package/dist/speech-language-detection/SileroLanguageDetection.js +47 -0
  169. package/dist/speech-language-detection/SileroLanguageDetection.js.map +1 -0
  170. package/dist/subtitles/Subtitles.d.ts +25 -0
  171. package/dist/subtitles/Subtitles.js +286 -0
  172. package/dist/subtitles/Subtitles.js.map +1 -0
  173. package/dist/synthesis/AwsPollyTTS.d.ts +7 -0
  174. package/dist/synthesis/AwsPollyTTS.js +51 -0
  175. package/dist/synthesis/AwsPollyTTS.js.map +1 -0
  176. package/dist/synthesis/AzureCognitiveServicesTTS.d.ts +9 -0
  177. package/dist/synthesis/AzureCognitiveServicesTTS.js +103 -0
  178. package/dist/synthesis/AzureCognitiveServicesTTS.js.map +1 -0
  179. package/dist/synthesis/CoquiServerTTS.d.ts +6 -0
  180. package/dist/synthesis/CoquiServerTTS.js +22 -0
  181. package/dist/synthesis/CoquiServerTTS.js.map +1 -0
  182. package/dist/synthesis/ElevenLabsTTS.d.ts +8 -0
  183. package/dist/synthesis/ElevenLabsTTS.js +48 -0
  184. package/dist/synthesis/ElevenLabsTTS.js.map +1 -0
  185. package/dist/synthesis/EspeakTTS.d.ts +46 -0
  186. package/dist/synthesis/EspeakTTS.js +353 -0
  187. package/dist/synthesis/EspeakTTS.js.map +1 -0
  188. package/dist/synthesis/FliteTTS.d.ts +17 -0
  189. package/dist/synthesis/FliteTTS.js +326 -0
  190. package/dist/synthesis/FliteTTS.js.map +1 -0
  191. package/dist/synthesis/GoogleCloudTTS.d.ts +16 -0
  192. package/dist/synthesis/GoogleCloudTTS.js +72 -0
  193. package/dist/synthesis/GoogleCloudTTS.js.map +1 -0
  194. package/dist/synthesis/GoogleTranslateTTS.d.ts +13 -0
  195. package/dist/synthesis/GoogleTranslateTTS.js +177 -0
  196. package/dist/synthesis/GoogleTranslateTTS.js.map +1 -0
  197. package/dist/synthesis/MicrosoftEdgeTTS.d.ts +10 -0
  198. package/dist/synthesis/MicrosoftEdgeTTS.js +216 -0
  199. package/dist/synthesis/MicrosoftEdgeTTS.js.map +1 -0
  200. package/dist/synthesis/SamTTS.d.ts +4 -0
  201. package/dist/synthesis/SamTTS.js +21 -0
  202. package/dist/synthesis/SamTTS.js.map +1 -0
  203. package/dist/synthesis/SapiTTS.d.ts +9 -0
  204. package/dist/synthesis/SapiTTS.js +211 -0
  205. package/dist/synthesis/SapiTTS.js.map +1 -0
  206. package/dist/synthesis/StreamlabsPollyTTS.d.ts +12 -0
  207. package/dist/synthesis/StreamlabsPollyTTS.js +88 -0
  208. package/dist/synthesis/StreamlabsPollyTTS.js.map +1 -0
  209. package/dist/synthesis/SvoxPicoTTS.d.ts +11 -0
  210. package/dist/synthesis/SvoxPicoTTS.js +236 -0
  211. package/dist/synthesis/SvoxPicoTTS.js.map +1 -0
  212. package/dist/synthesis/VitsTTS.d.ts +27 -0
  213. package/dist/synthesis/VitsTTS.js +359 -0
  214. package/dist/synthesis/VitsTTS.js.map +1 -0
  215. package/dist/tests/Test.d.ts +1 -0
  216. package/dist/tests/Test.js +10 -0
  217. package/dist/tests/Test.js.map +1 -0
  218. package/dist/text-language-detection/FastTextLanguageDetection.d.ts +2 -0
  219. package/dist/text-language-detection/FastTextLanguageDetection.js +38 -0
  220. package/dist/text-language-detection/FastTextLanguageDetection.js.map +1 -0
  221. package/dist/text-language-detection/TinyLDLanguageDetection.d.ts +2 -0
  222. package/dist/text-language-detection/TinyLDLanguageDetection.js +12 -0
  223. package/dist/text-language-detection/TinyLDLanguageDetection.js.map +1 -0
  224. package/dist/utilities/BinaryArrayConversion.d.ts +15 -0
  225. package/dist/utilities/BinaryArrayConversion.js +115 -0
  226. package/dist/utilities/BinaryArrayConversion.js.map +1 -0
  227. package/dist/utilities/Compression.d.ts +4 -0
  228. package/dist/utilities/Compression.js +67 -0
  229. package/dist/utilities/Compression.js.map +1 -0
  230. package/dist/utilities/FileDownloader.d.ts +3 -0
  231. package/dist/utilities/FileDownloader.js +147 -0
  232. package/dist/utilities/FileDownloader.js.map +1 -0
  233. package/dist/utilities/FileSystem.d.ts +30 -0
  234. package/dist/utilities/FileSystem.js +141 -0
  235. package/dist/utilities/FileSystem.js.map +1 -0
  236. package/dist/utilities/Hashing.d.ts +10 -0
  237. package/dist/utilities/Hashing.js +169 -0
  238. package/dist/utilities/Hashing.js.map +1 -0
  239. package/dist/utilities/Locale.d.ts +9 -0
  240. package/dist/utilities/Locale.js +65 -0
  241. package/dist/utilities/Locale.js.map +1 -0
  242. package/dist/utilities/Logger.d.ts +11 -0
  243. package/dist/utilities/Logger.js +49 -0
  244. package/dist/utilities/Logger.js.map +1 -0
  245. package/dist/utilities/NdArrayUtilities.d.ts +3 -0
  246. package/dist/utilities/NdArrayUtilities.js +22 -0
  247. package/dist/utilities/NdArrayUtilities.js.map +1 -0
  248. package/dist/utilities/ObjectUtilities.d.ts +4 -0
  249. package/dist/utilities/ObjectUtilities.js +132 -0
  250. package/dist/utilities/ObjectUtilities.js.map +1 -0
  251. package/dist/utilities/OpenPromise.d.ts +6 -0
  252. package/dist/utilities/OpenPromise.js +12 -0
  253. package/dist/utilities/OpenPromise.js.map +1 -0
  254. package/dist/utilities/PackageManager.d.ts +4 -0
  255. package/dist/utilities/PackageManager.js +46 -0
  256. package/dist/utilities/PackageManager.js.map +1 -0
  257. package/dist/utilities/RandomGenerator.d.ts +35 -0
  258. package/dist/utilities/RandomGenerator.js +149 -0
  259. package/dist/utilities/RandomGenerator.js.map +1 -0
  260. package/dist/utilities/TarballMaker.d.ts +4 -0
  261. package/dist/utilities/TarballMaker.js +50 -0
  262. package/dist/utilities/TarballMaker.js.map +1 -0
  263. package/dist/utilities/Timeline.d.ts +20 -0
  264. package/dist/utilities/Timeline.js +110 -0
  265. package/dist/utilities/Timeline.js.map +1 -0
  266. package/dist/utilities/Timer.d.ts +13 -0
  267. package/dist/utilities/Timer.js +70 -0
  268. package/dist/utilities/Timer.js.map +1 -0
  269. package/dist/utilities/Utilities.d.ts +68 -0
  270. package/dist/utilities/Utilities.js +305 -0
  271. package/dist/utilities/Utilities.js.map +1 -0
  272. package/dist/utilities/WasmMemoryManager.d.ts +142 -0
  273. package/dist/utilities/WasmMemoryManager.js +407 -0
  274. package/dist/utilities/WasmMemoryManager.js.map +1 -0
  275. package/dist/utilities/WebReader.d.ts +1 -0
  276. package/dist/utilities/WebReader.js +47 -0
  277. package/dist/utilities/WebReader.js.map +1 -0
  278. package/dist/utilities/WikipediaReader.d.ts +1 -0
  279. package/dist/utilities/WikipediaReader.js +31 -0
  280. package/dist/utilities/WikipediaReader.js.map +1 -0
  281. package/dist/voice-activity-detection/SileroVAD.d.ts +13 -0
  282. package/dist/voice-activity-detection/SileroVAD.js +58 -0
  283. package/dist/voice-activity-detection/SileroVAD.js.map +1 -0
  284. package/dist/voice-activity-detection/WebRtcVAD.d.ts +3 -0
  285. package/dist/voice-activity-detection/WebRtcVAD.js +53 -0
  286. package/dist/voice-activity-detection/WebRtcVAD.js.map +1 -0
  287. package/docs/CLI.md +234 -0
  288. package/docs/Development.md +3 -0
  289. package/docs/Engines.md +80 -0
  290. package/docs/Licenses.md +37 -0
  291. package/docs/Options.md +192 -0
  292. package/docs/Roadmap.md +16 -0
  293. package/docs/Technical.md +72 -0
  294. package/package.json +119 -19
  295. package/cli.js +0 -3
@@ -0,0 +1,53 @@
1
+ import { cloneRawAudio } from "../audio/AudioUtilities.js";
2
+ import { WasmMemoryManager } from "../utilities/WasmMemoryManager.js";
3
+ let speexResamplerInstance;
4
+ export async function resampleAudioSpeex(rawAudio, outSampleRate, quality = 0) {
5
+ const channelCount = rawAudio.audioChannels.length;
6
+ const inSampleRate = rawAudio.sampleRate;
7
+ if (inSampleRate == outSampleRate) {
8
+ return cloneRawAudio(rawAudio);
9
+ }
10
+ const m = await getSpeexResamplerInstance();
11
+ const wasmMemory = new WasmMemoryManager(m);
12
+ function speexResultCodeToString(resultCode) {
13
+ const errorStrPtr = m._speex_resampler_strerror(resultCode);
14
+ const errorStrRef = wasmMemory.wrapUint8Array(errorStrPtr, 1024);
15
+ const message = errorStrRef.readAsNullTerminatedUtf8String();
16
+ return message;
17
+ }
18
+ const initErrRef = wasmMemory.allocInt32();
19
+ const resamplerState = m._speex_resampler_init(channelCount, inSampleRate, outSampleRate, quality, initErrRef.address);
20
+ let resultCode = initErrRef.value;
21
+ if (resultCode != 0) {
22
+ throw new Error(`Speex resampler failed while initializing with code ${resultCode}: ${speexResultCodeToString(resultCode)}`);
23
+ }
24
+ const resampledAudio = { audioChannels: [], sampleRate: outSampleRate };
25
+ for (let channelIndex = 0; channelIndex < channelCount; channelIndex++) {
26
+ const channelSamples = rawAudio.audioChannels[channelIndex];
27
+ const inSampleCount = channelSamples.length;
28
+ const inSampleCountRef = wasmMemory.allocInt32();
29
+ inSampleCountRef.value = inSampleCount;
30
+ const outSampleCount = Math.floor((inSampleCount / inSampleRate) * outSampleRate);
31
+ const outSampleCountRef = wasmMemory.allocInt32();
32
+ outSampleCountRef.value = outSampleCount;
33
+ const inSamplesRef = wasmMemory.allocFloat32Array(inSampleCount);
34
+ inSamplesRef.view.set(channelSamples);
35
+ const outSamplesRef = wasmMemory.allocFloat32Array(outSampleCount);
36
+ resultCode = m._speex_resampler_process_float(resamplerState, channelIndex, inSamplesRef.address, inSampleCountRef.address, outSamplesRef.address, outSampleCountRef.address);
37
+ if (resultCode != 0) {
38
+ throw new Error(`Speex resampler failed while resampling with code ${resultCode}: ${speexResultCodeToString(resultCode)}`);
39
+ }
40
+ resampledAudio.audioChannels.push(outSamplesRef.view.slice());
41
+ }
42
+ m._speex_resampler_destroy(resamplerState);
43
+ wasmMemory.freeAll();
44
+ return resampledAudio;
45
+ }
46
+ export async function getSpeexResamplerInstance() {
47
+ if (!speexResamplerInstance) {
48
+ const { default: SpeexResamplerInitializer } = await import('@echogarden/speex-resampler-wasm');
49
+ speexResamplerInstance = await SpeexResamplerInitializer();
50
+ }
51
+ return speexResamplerInstance;
52
+ }
53
+ //# sourceMappingURL=SpeexResampler.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"SpeexResampler.js","sourceRoot":"","sources":["../../src/dsp/SpeexResampler.ts"],"names":[],"mappings":"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"}
@@ -0,0 +1,70 @@
1
+ export declare function covarianceMatrixOfSamples(samples: number[][], weights?: number[], biased?: boolean): {
2
+ covarianceMatrix: number[][];
3
+ mean: number[];
4
+ };
5
+ export declare function covarianceMatrixOfCenteredSamples(centeredSamples: number[][], biased?: boolean, diagonalRegularizationAmount?: number): number[][];
6
+ export declare function weightedCovarianceMatrixOfCenteredSamples(centeredSamples: number[][], weights: number[], diagonalRegularizationAmount?: number): number[][];
7
+ export declare function centerVectors(vectors: number[][], weights?: number[]): {
8
+ centeredVectors: number[][];
9
+ mean: number[];
10
+ };
11
+ export declare function centerVector(vector: number[]): number[];
12
+ export declare function scaleToSumTo1(vector: number[]): number[];
13
+ export declare function normalizeVector(vector: number[], kind?: "population" | "sample"): {
14
+ normalizedVector: number[];
15
+ mean: number;
16
+ stdDeviation: number;
17
+ };
18
+ export declare function normalizeVectors(vectors: number[][], kind?: "population" | "sample"): {
19
+ normalizedVectors: number[][];
20
+ mean: number[];
21
+ stdDeviation: number[];
22
+ };
23
+ export declare function deNormalizeVectors(normalizedVectors: number[][], originalMean: number[], originalStdDeviation: number[]): number[][];
24
+ export declare function meanOfVectors(vectors: number[][]): number[];
25
+ export declare function weightedMeanOfVectors(vectors: number[][], weights: number[]): number[];
26
+ export declare function stdDeviationOfVectors(vectors: number[][], kind?: "population" | "sample", mean?: number[]): number[];
27
+ export declare function varianceOfVectors(vectors: number[][], kind?: "population" | "sample", mean?: number[]): number[];
28
+ export declare function meanOfVector(vector: number[]): number;
29
+ export declare function medianOfVector(vector: number[]): number;
30
+ export declare function stdDeviationOfVector(vector: number[], kind?: "population" | "sample", mean?: number): number;
31
+ export declare function varianceOfVector(vector: number[], kind?: "population" | "sample", mean?: number): number;
32
+ export declare function logOfVector(vector: number[], minVal?: number): number[];
33
+ export declare function expOfVector(vector: number[]): number[];
34
+ export declare function transpose(matrix: number[][]): number[][];
35
+ export declare function movingAverageOfWindow3(vector: number[]): number[];
36
+ export declare function averageMeanSquaredError(actual: number[][], expected: number[][]): number;
37
+ export declare function meanSquaredError(actual: number[], expected: number[]): number;
38
+ export declare function eucledianDistance(vector1: number[], vector2: number[]): number;
39
+ export declare function squaredEucledianDistance(vector1: number[], vector2: number[]): number;
40
+ export declare function cosineDistance(vector1: number[], vector2: number[]): number;
41
+ export declare function cosineSimilarity(vector1: number[], vector2: number[]): number;
42
+ export declare function minkowskiDistance(vector1: number[], vector2: number[], power: number): number;
43
+ export declare function cosineDistancePrecomputedMagnitudes(vector1: number[], vector2: number[], magnitude1: number, magnitude2: number): number;
44
+ export declare function cosineSimilarityPrecomputedMagnitudes(vector1: number[], vector2: number[], magnitude1: number, magnitude2: number): number;
45
+ export declare function subtractVectors(vector1: number[], vector2: number[]): number[];
46
+ export declare function sumVector(vector: number[]): number;
47
+ export declare function dotProduct(vector1: number[], vector2: number[]): number;
48
+ export declare function magnitude(vector: number[]): number;
49
+ export declare function maxValue(vector: number[]): number;
50
+ export declare function indexOfMax(vector: number[]): number;
51
+ export declare function minValue(vector: number[]): number;
52
+ export declare function indexOfMin(vector: number[]): number;
53
+ export declare function exponentialSmoothingMeanOfVectors(vectors: number[][], smoothingFactor: number): number[];
54
+ export declare function sigmoid(x: number): number;
55
+ export declare function softMax(vector: number[], temperature?: number): number[];
56
+ export declare function hammingDistance(value1: number, value2: number, bitLength?: number): number;
57
+ export declare function medianFilter(vector: number[], width: number): any[];
58
+ export declare function createVectorArray(vectorCount: number, featureCount: number, initialValue?: number): number[][];
59
+ export declare function createVector(elementCount: number, initialValue?: number): number[];
60
+ export declare function createVectorForIntegerRange(start: number, end: number): number[];
61
+ export declare function zeroIfNaN(val: number): number;
62
+ export declare function logSumExp(values: number[], minVal?: number): number;
63
+ export declare function sumExp(values: number[]): number;
64
+ export declare function logSoftmax(values: number[], minVal?: number): number[];
65
+ export declare class IncrementalMean {
66
+ currentElementCount: number;
67
+ currentMean: number;
68
+ addValueToMean(value: number): void;
69
+ }
70
+ export type DistanceFunction = (a: number[], b: number[]) => number;
@@ -0,0 +1,564 @@
1
+ import createMedianFilter from 'moving-median';
2
+ export function covarianceMatrixOfSamples(samples, weights, biased = false) {
3
+ if (samples.length == 0) {
4
+ throw new Error("No vectors given");
5
+ }
6
+ const { centeredVectors: centeredSamples, mean } = centerVectors(samples, weights);
7
+ let covarianceMatrix;
8
+ if (weights) {
9
+ covarianceMatrix = weightedCovarianceMatrixOfCenteredSamples(centeredSamples, weights);
10
+ }
11
+ else {
12
+ covarianceMatrix = covarianceMatrixOfCenteredSamples(centeredSamples, biased);
13
+ }
14
+ return { covarianceMatrix, mean };
15
+ }
16
+ export function covarianceMatrixOfCenteredSamples(centeredSamples, biased = false, diagonalRegularizationAmount = 1e-6) {
17
+ const sampleCount = centeredSamples.length;
18
+ if (sampleCount == 0) {
19
+ throw new Error("No vectors given");
20
+ }
21
+ const sampleSizeMetric = biased || sampleCount == 1 ? sampleCount : sampleCount - 1;
22
+ const featureCount = centeredSamples[0].length;
23
+ const covarianceMatrix = createVectorArray(featureCount, featureCount);
24
+ if (sampleCount == 1) {
25
+ return covarianceMatrix;
26
+ }
27
+ for (let i = 0; i < featureCount; i++) {
28
+ for (let j = 0; j < featureCount; j++) {
29
+ if (i > j) {
30
+ covarianceMatrix[i][j] = covarianceMatrix[j][i];
31
+ continue;
32
+ }
33
+ let matrixElement = 0.0;
34
+ for (const sample of centeredSamples) {
35
+ matrixElement += sample[i] * sample[j];
36
+ }
37
+ matrixElement /= sampleSizeMetric;
38
+ if (i == j) {
39
+ matrixElement += diagonalRegularizationAmount;
40
+ }
41
+ covarianceMatrix[i][j] = matrixElement;
42
+ }
43
+ }
44
+ return covarianceMatrix;
45
+ }
46
+ export function weightedCovarianceMatrixOfCenteredSamples(centeredSamples, weights, diagonalRegularizationAmount = 1e-6) {
47
+ const sampleCount = centeredSamples.length;
48
+ if (sampleCount == 0) {
49
+ throw new Error("No vectors given");
50
+ }
51
+ const featureCount = centeredSamples[0].length;
52
+ const covarianceMatrix = createVectorArray(featureCount, featureCount);
53
+ if (sampleCount == 1) {
54
+ return covarianceMatrix;
55
+ }
56
+ for (let i = 0; i < featureCount; i++) {
57
+ for (let j = 0; j < featureCount; j++) {
58
+ if (i > j) {
59
+ covarianceMatrix[i][j] = covarianceMatrix[j][i];
60
+ continue;
61
+ }
62
+ let matrixElement = 0.0;
63
+ for (let sampleIndex = 0; sampleIndex < sampleCount; sampleIndex++) {
64
+ const sample = centeredSamples[sampleIndex];
65
+ const weight = weights[sampleIndex];
66
+ matrixElement += weight * (sample[i] * sample[j]);
67
+ }
68
+ if (i == j) {
69
+ matrixElement += diagonalRegularizationAmount;
70
+ }
71
+ covarianceMatrix[i][j] = matrixElement;
72
+ }
73
+ }
74
+ return covarianceMatrix;
75
+ }
76
+ export function centerVectors(vectors, weights) {
77
+ const vectorCount = vectors.length;
78
+ if (vectorCount == 0) {
79
+ return { centeredVectors: [], mean: [] };
80
+ }
81
+ let mean;
82
+ if (weights) {
83
+ mean = weightedMeanOfVectors(vectors, weights);
84
+ }
85
+ else {
86
+ mean = meanOfVectors(vectors);
87
+ }
88
+ const centeredVectors = new Array(vectorCount);
89
+ for (let i = 0; i < vectorCount; i++) {
90
+ centeredVectors[i] = subtractVectors(vectors[i], mean);
91
+ }
92
+ return { centeredVectors, mean };
93
+ }
94
+ export function centerVector(vector) {
95
+ const mean = meanOfVector(vector);
96
+ const centeredVector = new Array(vector.length);
97
+ for (let i = 0; i < vector.length; i++) {
98
+ centeredVector[i] = vector[i] - mean;
99
+ }
100
+ return centeredVector;
101
+ }
102
+ export function scaleToSumTo1(vector) {
103
+ if (vector.length == 0) {
104
+ return [];
105
+ }
106
+ if (vector.length == 1) {
107
+ return [1];
108
+ }
109
+ const minValue = vector[indexOfMin(vector)];
110
+ const scaledVector = vector.slice();
111
+ if (minValue < 0) {
112
+ const addedOffset = -minValue * 2;
113
+ for (let i = 0; i < scaledVector.length; i++) {
114
+ scaledVector[i] += addedOffset;
115
+ }
116
+ }
117
+ const sum = sumVector(scaledVector);
118
+ if (sum == 0) {
119
+ return scaledVector;
120
+ }
121
+ if (sum == Infinity) {
122
+ throw new Error("Vector sum is infinite");
123
+ }
124
+ for (let i = 0; i < vector.length; i++) {
125
+ scaledVector[i] /= sum;
126
+ scaledVector[i] = zeroIfNaN(scaledVector[i]);
127
+ }
128
+ return scaledVector;
129
+ }
130
+ export function normalizeVector(vector, kind = "population") {
131
+ if (vector.length == 0) {
132
+ throw new Error("Vector is empty");
133
+ }
134
+ const mean = meanOfVector(vector);
135
+ const stdDeviation = stdDeviationOfVector(vector, kind, mean);
136
+ const normalizedVector = createVector(vector.length);
137
+ for (let i = 0; i < vector.length; i++) {
138
+ normalizedVector[i] = (vector[i] - mean) / stdDeviation;
139
+ normalizedVector[i] = zeroIfNaN(normalizedVector[i]);
140
+ }
141
+ return { normalizedVector, mean, stdDeviation };
142
+ }
143
+ export function normalizeVectors(vectors, kind = "population") {
144
+ const vectorCount = vectors.length;
145
+ if (vectorCount == 0) {
146
+ return { normalizedVectors: [], mean: [], stdDeviation: [] };
147
+ }
148
+ const featureCount = vectors[0].length;
149
+ const mean = meanOfVectors(vectors);
150
+ const stdDeviation = stdDeviationOfVectors(vectors, kind, mean);
151
+ const normalizedVectors = [];
152
+ for (const vector of vectors) {
153
+ const normalizedVector = createVector(featureCount);
154
+ for (let featureIndex = 0; featureIndex < featureCount; featureIndex++) {
155
+ normalizedVector[featureIndex] = (vector[featureIndex] - mean[featureIndex]) / stdDeviation[featureIndex];
156
+ normalizedVector[featureIndex] = zeroIfNaN(normalizedVector[featureIndex]);
157
+ }
158
+ normalizedVectors.push(normalizedVector);
159
+ }
160
+ return { normalizedVectors, mean, stdDeviation };
161
+ }
162
+ export function deNormalizeVectors(normalizedVectors, originalMean, originalStdDeviation) {
163
+ const vectorCount = normalizeVectors.length;
164
+ if (vectorCount == 0) {
165
+ return [];
166
+ }
167
+ const featureCount = normalizedVectors[0].length;
168
+ const deNormalizedVectors = [];
169
+ for (const normalizedVector of normalizedVectors) {
170
+ const deNormalizedVector = createVector(featureCount);
171
+ for (let featureIndex = 0; featureIndex < featureCount; featureIndex++) {
172
+ deNormalizedVector[featureIndex] = originalMean[featureIndex] + (normalizedVector[featureIndex] * originalStdDeviation[featureIndex]);
173
+ }
174
+ deNormalizedVectors.push(deNormalizedVector);
175
+ }
176
+ return deNormalizedVectors;
177
+ }
178
+ export function meanOfVectors(vectors) {
179
+ const vectorCount = vectors.length;
180
+ if (vectorCount == 0) {
181
+ return [];
182
+ }
183
+ const featureCount = vectors[0].length;
184
+ const result = createVector(featureCount);
185
+ for (const vector of vectors) {
186
+ for (let featureIndex = 0; featureIndex < featureCount; featureIndex++) {
187
+ result[featureIndex] += vector[featureIndex];
188
+ }
189
+ }
190
+ for (let featureIndex = 0; featureIndex < featureCount; featureIndex++) {
191
+ result[featureIndex] /= vectorCount;
192
+ }
193
+ return result;
194
+ }
195
+ export function weightedMeanOfVectors(vectors, weights) {
196
+ const vectorCount = vectors.length;
197
+ if (vectorCount == 0) {
198
+ return [];
199
+ }
200
+ const featureCount = vectors[0].length;
201
+ const result = createVector(featureCount);
202
+ for (let vectorIndex = 0; vectorIndex < vectorCount; vectorIndex++) {
203
+ const vector = vectors[vectorIndex];
204
+ const vectorWeight = weights[vectorIndex];
205
+ for (let featureIndex = 0; featureIndex < featureCount; featureIndex++) {
206
+ result[featureIndex] += vectorWeight * vector[featureIndex];
207
+ }
208
+ }
209
+ return result;
210
+ }
211
+ export function stdDeviationOfVectors(vectors, kind = "population", mean) {
212
+ return varianceOfVectors(vectors, kind, mean).map(v => Math.sqrt(v));
213
+ }
214
+ export function varianceOfVectors(vectors, kind = "population", mean) {
215
+ const vectorCount = vectors.length;
216
+ if (vectorCount == 0) {
217
+ return [];
218
+ }
219
+ const sampleSizeMetric = kind == "population" || vectorCount == 1 ? vectorCount : vectorCount - 1;
220
+ const featureCount = vectors[0].length;
221
+ if (!mean) {
222
+ mean = meanOfVectors(vectors);
223
+ }
224
+ const result = createVector(featureCount);
225
+ for (const vector of vectors) {
226
+ for (let i = 0; i < featureCount; i++) {
227
+ result[i] += (vector[i] - mean[i]) ** 2;
228
+ }
229
+ }
230
+ for (let i = 0; i < featureCount; i++) {
231
+ result[i] /= sampleSizeMetric;
232
+ }
233
+ return result;
234
+ }
235
+ export function meanOfVector(vector) {
236
+ if (vector.length == 0) {
237
+ throw new Error("Vector is empty");
238
+ }
239
+ return sumVector(vector) / vector.length;
240
+ }
241
+ export function medianOfVector(vector) {
242
+ if (vector.length == 0) {
243
+ throw new Error("Vector is empty");
244
+ }
245
+ return vector[Math.floor(vector.length / 2)];
246
+ }
247
+ export function stdDeviationOfVector(vector, kind = "population", mean) {
248
+ return Math.sqrt(varianceOfVector(vector, kind, mean));
249
+ }
250
+ export function varianceOfVector(vector, kind = "population", mean) {
251
+ if (vector.length == 0) {
252
+ throw new Error("Vector is empty");
253
+ }
254
+ const sampleSizeMetric = kind == "population" || vector.length == 1 ? vector.length : vector.length - 1;
255
+ if (mean == null) {
256
+ mean = meanOfVector(vector);
257
+ }
258
+ let result = 0.0;
259
+ for (const value of vector) {
260
+ result += (value - mean) ** 2;
261
+ }
262
+ return result / sampleSizeMetric;
263
+ }
264
+ export function logOfVector(vector, minVal = 1e-40) {
265
+ return vector.map(value => Math.log(minVal + value));
266
+ }
267
+ export function expOfVector(vector) {
268
+ return vector.map(value => Math.exp(value));
269
+ }
270
+ export function transpose(matrix) {
271
+ const vectorCount = matrix.length;
272
+ const featureCount = matrix[0].length;
273
+ const transposedMatrix = createVectorArray(featureCount, vectorCount);
274
+ for (let i = 0; i < vectorCount; i++) {
275
+ for (let j = 0; j < featureCount; j++) {
276
+ transposedMatrix[j][i] = matrix[i][j];
277
+ }
278
+ }
279
+ return transposedMatrix;
280
+ }
281
+ export function movingAverageOfWindow3(vector) {
282
+ const elementCount = vector.length;
283
+ if (elementCount == 0) {
284
+ return [];
285
+ }
286
+ if (elementCount == 1) {
287
+ return vector.slice();
288
+ }
289
+ const result = [];
290
+ result.push((vector[0] + vector[0] + vector[1]) / 3);
291
+ for (let i = 1; i < elementCount - 1; i++) {
292
+ result.push((vector[i - 1] + vector[i] + vector[i + 1]) / 3);
293
+ }
294
+ result.push((vector[elementCount - 2] + vector[elementCount - 1] + vector[elementCount - 1]) / 3);
295
+ return result;
296
+ }
297
+ export function averageMeanSquaredError(actual, expected) {
298
+ if (actual.length != expected.length) {
299
+ throw new Error("Vectors are not the same length");
300
+ }
301
+ const vectorCount = actual.length;
302
+ if (vectorCount == 0) {
303
+ return 0;
304
+ }
305
+ let sum = 0.0;
306
+ for (let i = 0; i < vectorCount; i++) {
307
+ sum += meanSquaredError(actual[i], expected[i]);
308
+ }
309
+ return sum / vectorCount;
310
+ }
311
+ export function meanSquaredError(actual, expected) {
312
+ if (actual.length != expected.length) {
313
+ throw new Error("Vectors are not the same length");
314
+ }
315
+ const featureCount = actual.length;
316
+ if (featureCount == 0) {
317
+ return 0;
318
+ }
319
+ let sum = 0.0;
320
+ for (let i = 0; i < featureCount; i++) {
321
+ sum += (actual[i] - expected[i]) ** 2;
322
+ }
323
+ return sum / featureCount;
324
+ }
325
+ export function eucledianDistance(vector1, vector2) {
326
+ return Math.sqrt(squaredEucledianDistance(vector1, vector2));
327
+ }
328
+ export function squaredEucledianDistance(vector1, vector2) {
329
+ if (vector1.length != vector2.length) {
330
+ throw new Error("Vectors are not the same length");
331
+ }
332
+ const elementCount = vector1.length;
333
+ if (elementCount == 0) {
334
+ return 0;
335
+ }
336
+ let sum = 0.0;
337
+ for (let i = 0; i < elementCount; i++) {
338
+ sum += (vector1[i] - vector2[i]) ** 2;
339
+ }
340
+ return sum;
341
+ }
342
+ export function cosineDistance(vector1, vector2) {
343
+ return 1 - cosineSimilarity(vector1, vector2);
344
+ }
345
+ export function cosineSimilarity(vector1, vector2) {
346
+ if (vector1.length != vector2.length) {
347
+ throw new Error("Vectors are not the same length");
348
+ }
349
+ if (vector1.length == 0) {
350
+ return 0;
351
+ }
352
+ const elementCount = vector1.length;
353
+ let dotProduct = 0.0;
354
+ let squaredMagnitude1 = 0.0;
355
+ let squaredMagnitude2 = 0.0;
356
+ for (let i = 0; i < elementCount; i++) {
357
+ dotProduct += vector1[i] * vector2[i];
358
+ squaredMagnitude1 += vector1[i] ** 2;
359
+ squaredMagnitude2 += vector2[i] ** 2;
360
+ }
361
+ const result = dotProduct / (Math.sqrt(squaredMagnitude1) * Math.sqrt(squaredMagnitude2));
362
+ return zeroIfNaN(result);
363
+ }
364
+ export function minkowskiDistance(vector1, vector2, power) {
365
+ if (vector1.length != vector2.length) {
366
+ throw new Error("Vectors are not the same length");
367
+ }
368
+ const elementCount = vector1.length;
369
+ if (elementCount == 0) {
370
+ return 0;
371
+ }
372
+ let sum = 0.0;
373
+ for (let i = 0; i < elementCount; i++) {
374
+ sum += Math.abs(vector1[i] - vector2[i]) ** power;
375
+ }
376
+ return sum ** (1 / power);
377
+ }
378
+ export function cosineDistancePrecomputedMagnitudes(vector1, vector2, magnitude1, magnitude2) {
379
+ return 1 - cosineSimilarityPrecomputedMagnitudes(vector1, vector2, magnitude1, magnitude2);
380
+ }
381
+ export function cosineSimilarityPrecomputedMagnitudes(vector1, vector2, magnitude1, magnitude2) {
382
+ if (vector1.length != vector2.length) {
383
+ throw new Error("Vectors are not the same length");
384
+ }
385
+ if (vector1.length == 0) {
386
+ return 0;
387
+ }
388
+ const featureCount = vector1.length;
389
+ let dotProduct = 0.0;
390
+ for (let i = 0; i < featureCount; i++) {
391
+ dotProduct += vector1[i] * vector2[i];
392
+ }
393
+ const result = dotProduct / (magnitude1 * magnitude2);
394
+ return zeroIfNaN(result);
395
+ }
396
+ export function subtractVectors(vector1, vector2) {
397
+ if (vector1.length != vector2.length) {
398
+ throw new Error("Vectors are not the same length");
399
+ }
400
+ const result = createVector(vector1.length);
401
+ for (let i = 0; i < vector1.length; i++) {
402
+ result[i] = vector1[i] - vector2[i];
403
+ }
404
+ return result;
405
+ }
406
+ export function sumVector(vector) {
407
+ let result = 0.0;
408
+ for (let i = 0; i < vector.length; i++) {
409
+ result += vector[i];
410
+ }
411
+ return result;
412
+ }
413
+ export function dotProduct(vector1, vector2) {
414
+ if (vector1.length != vector2.length) {
415
+ throw new Error("Vectors are not the same length");
416
+ }
417
+ const elementCount = vector1.length;
418
+ let result = 0.0;
419
+ for (let i = 0; i < elementCount; i++) {
420
+ result += vector1[i] * vector2[i];
421
+ }
422
+ return result;
423
+ }
424
+ export function magnitude(vector) {
425
+ const featureCount = vector.length;
426
+ let squaredMagnitude = 0.0;
427
+ for (let i = 0; i < featureCount; i++) {
428
+ squaredMagnitude += vector[i] ** 2;
429
+ }
430
+ return Math.sqrt(squaredMagnitude);
431
+ }
432
+ export function maxValue(vector) {
433
+ return vector[indexOfMax(vector)];
434
+ }
435
+ export function indexOfMax(vector) {
436
+ let maxValue = -Infinity;
437
+ let result = -1;
438
+ for (let i = 0; i < vector.length; i++) {
439
+ if (vector[i] > maxValue) {
440
+ maxValue = vector[i];
441
+ result = i;
442
+ }
443
+ }
444
+ return result;
445
+ }
446
+ export function minValue(vector) {
447
+ return vector[indexOfMin(vector)];
448
+ }
449
+ export function indexOfMin(vector) {
450
+ let minValue = Infinity;
451
+ let result = -1;
452
+ for (let i = 0; i < vector.length; i++) {
453
+ if (vector[i] < minValue) {
454
+ minValue = vector[i];
455
+ result = i;
456
+ }
457
+ }
458
+ return result;
459
+ }
460
+ export function exponentialSmoothingMeanOfVectors(vectors, smoothingFactor) {
461
+ const vectorCount = vectors.length;
462
+ if (vectorCount == 0) {
463
+ return [];
464
+ }
465
+ const featureCount = vectors[0].length;
466
+ const currentEstimate = createVector(featureCount);
467
+ for (let i = 0; i < vectorCount; i++) {
468
+ for (let j = 0; j < featureCount; j++) {
469
+ const value = vectors[i][j];
470
+ currentEstimate[j] = (smoothingFactor * value) + ((1 - smoothingFactor) * currentEstimate[j]);
471
+ }
472
+ }
473
+ return currentEstimate;
474
+ }
475
+ export function sigmoid(x) {
476
+ const result = 1 / (1 + Math.exp(-x));
477
+ return zeroIfNaN(result);
478
+ }
479
+ export function softMax(vector, temperature = 1.0) {
480
+ if (vector.length == 0) {
481
+ return [];
482
+ }
483
+ const result = [];
484
+ let sumOfExponentiatedValues = 0.0;
485
+ for (const value of vector) {
486
+ const eToValue = Math.exp(value / temperature);
487
+ sumOfExponentiatedValues += eToValue;
488
+ result.push(eToValue);
489
+ }
490
+ for (let i = 0; i < result.length; i++) {
491
+ result[i] /= sumOfExponentiatedValues;
492
+ result[i] = zeroIfNaN(result[i]);
493
+ }
494
+ return result;
495
+ }
496
+ export function hammingDistance(value1, value2, bitLength = 32) {
497
+ let valueXor = value1 ^ value2;
498
+ let result = 0;
499
+ for (let i = 0; i < bitLength; i++) {
500
+ result += valueXor & 1;
501
+ valueXor = valueXor >> 1;
502
+ }
503
+ return result;
504
+ }
505
+ export function medianFilter(vector, width) {
506
+ const filter = createMedianFilter(width);
507
+ const result = [];
508
+ for (let i = 0; i < vector.length; i++) {
509
+ result.push(filter(vector[i]));
510
+ }
511
+ return result;
512
+ }
513
+ export function createVectorArray(vectorCount, featureCount, initialValue = 0.0) {
514
+ const result = new Array(vectorCount);
515
+ for (let i = 0; i < vectorCount; i++) {
516
+ result[i] = createVector(featureCount, initialValue);
517
+ }
518
+ return result;
519
+ }
520
+ export function createVector(elementCount, initialValue = 0.0) {
521
+ const result = new Array(elementCount);
522
+ for (let i = 0; i < elementCount; i++) {
523
+ result[i] = initialValue;
524
+ }
525
+ return result;
526
+ }
527
+ export function createVectorForIntegerRange(start, end) {
528
+ const newVector = [];
529
+ for (let i = start; i < end; i++) {
530
+ newVector.push(i);
531
+ }
532
+ return newVector;
533
+ }
534
+ export function zeroIfNaN(val) {
535
+ if (isNaN(val)) {
536
+ return 0;
537
+ }
538
+ else {
539
+ return val;
540
+ }
541
+ }
542
+ export function logSumExp(values, minVal = 1e-40) {
543
+ return Math.log(minVal + sumExp(values));
544
+ }
545
+ export function sumExp(values) {
546
+ let sumOfExp = 0;
547
+ for (const value of values) {
548
+ sumOfExp += Math.exp(value);
549
+ }
550
+ return sumOfExp;
551
+ }
552
+ export function logSoftmax(values, minVal = 1e-40) {
553
+ const softMaxOfValues = softMax(values);
554
+ return logOfVector(softMaxOfValues, minVal);
555
+ }
556
+ export class IncrementalMean {
557
+ currentElementCount = 0;
558
+ currentMean = 0.0;
559
+ addValueToMean(value) {
560
+ this.currentElementCount += 1;
561
+ this.currentMean += (value + this.currentMean) / this.currentElementCount;
562
+ }
563
+ }
564
+ //# sourceMappingURL=VectorMath.js.map