Skip to content

Commit c49506d

Browse files
committed
Javascript implementation of TriadicMemory, uses ndarray for implementation, uses Jest for some basic testing.
1 parent 6183299 commit c49506d

File tree

9 files changed

+8947
-0
lines changed

9 files changed

+8947
-0
lines changed

.gitignore

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Javascript/coverage
2+
Javascript/node_modules

Javascript/.babelrc

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
{
2+
"presets": [
3+
["@babel/preset-env"]
4+
],
5+
"env": {
6+
"test": {
7+
"plugins": ["@babel/plugin-transform-modules-commonjs"]
8+
}
9+
}
10+
}

Javascript/SDRUtils.js

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
import ndarray from "ndarray";
2+
3+
const ONE_HALF_MINUS_EPSILON = 0.5-Number.MIN_VALUE;
4+
5+
class SDRUtils {
6+
static buildLinearEncoderDecoder(minValue, maxValue, sdrSize, sdrWidth) {
7+
return [
8+
SDRUtils.buildLinearEncoder(minValue, maxValue, sdrSize, sdrWidth),
9+
SDRUtils.buildLinearDecoder(minValue, maxValue, sdrSize, sdrWidth)
10+
];
11+
}
12+
13+
static buildLinearEncoder(minValue, maxValue, sdrSize, sdrWidth) {
14+
const bitRange = sdrSize-sdrWidth;
15+
const valueRange = maxValue - minValue;
16+
17+
return (value) => {
18+
const firstBit = Math.floor(bitRange*(value-minValue)/valueRange + ONE_HALF_MINUS_EPSILON);
19+
return SDRUtils.range(firstBit, firstBit+sdrWidth);
20+
};
21+
}
22+
23+
static buildLinearDecoder(minValue, maxValue, sdrSize, sdrWidth) {
24+
const bitRange = sdrSize-sdrWidth;
25+
const valueRange = maxValue - minValue;
26+
return (sdr, rounded=true) => {
27+
const decoded = (sdr[0]-ONE_HALF_MINUS_EPSILON)*valueRange/bitRange + minValue;
28+
return rounded ? Math.round(decoded) : decoded;
29+
}
30+
}
31+
32+
static range(start, end, step=1) {
33+
return Array.from(new Array(end-start), (_,i) => i*step + start);
34+
}
35+
}
36+
37+
export default SDRUtils;

Javascript/TriadicMemory.js

Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
import ndarray from "ndarray";
2+
import ops from "ndarray-ops";
3+
4+
class TriadicMemory {
5+
constructor(n, p) {
6+
this.mem = ndarray((new Uint8Array(n*n*n)).fill(0), [n,n,n]);
7+
this.p = p;
8+
}
9+
10+
get n() { return this.mem.shape[0]; }
11+
12+
store(x, y, z) { TriadicMemory.storeXYZ(this.mem,x,y,z); }
13+
remove(x, y, z) { TriadicMemory.removeXYZ(this.mem,x,y,z); }
14+
15+
query(x, y, z=null) {
16+
return (
17+
z === null ? TriadicMemory.queryZ(this.mem,this.p,x,y) : (
18+
x === null ? TriadicMemory.queryX(this.mem,this.p,y,z) :
19+
TriadicMemory.queryY(this.mem,this.p,x,z))
20+
);
21+
}
22+
23+
static storeXYZ(mem, x, y, z) {
24+
for (const ax of x) {
25+
for (const ay of y) {
26+
for (const az of z) {
27+
mem.set(ax,ay,az, mem.get(ax,ay,az)+1);
28+
}
29+
}
30+
}
31+
}
32+
33+
static removeXYZ(mem, x, y, z) {
34+
for (const ax of x) {
35+
for (const ay of y) {
36+
for (const az of z) {
37+
mem.set(ax,ay,az, Math.max(0,mem.get(ax,ay,az)-1));
38+
}
39+
}
40+
}
41+
}
42+
43+
static queryZ(mem, p, x, y) {
44+
const n = mem.shape[0];
45+
const sums = ndarray(new Uint32Array(n).fill(0));
46+
for (const ax of x) {
47+
for (const ay of y) {
48+
ops.addeq(sums, mem.pick(ax,ay,null));
49+
}
50+
}
51+
return TriadicMemory.sumsToSDR(sums.data, p);
52+
}
53+
static queryY(mem, p, x, z) {
54+
const n = mem.shape[0];
55+
const sums = ndarray(new Uint32Array(n).fill(0));
56+
for (const ax of x) {
57+
for (const az of z) {
58+
ops.addeq(sums, mem.pick(ax,null,az));
59+
}
60+
}
61+
return TriadicMemory.sumsToSDR(sums.data, p);
62+
}
63+
static queryX(mem, p, y, z) {
64+
const n = mem.shape[0];
65+
const sums = ndarray(new Uint32Array(n).fill(0));
66+
for (const ay of y) {
67+
for (const az of z) {
68+
ops.addeq(sums, mem.pick(null,ay,az));
69+
}
70+
}
71+
return TriadicMemory.sumsToSDR(sums.data, p);
72+
}
73+
74+
/**
75+
* Convert from an array of associative counters (sum) into a sparse, binary
76+
* representation with a maximum number of 1s equal to p.
77+
* @param {Array} sums
78+
* @param {Integer} p
79+
* @returns {Array} The sparse representation as an array of indicies into sums
80+
* where the indicies i are all values where sums[i] >= the threshold defined by p.
81+
*/
82+
static sumsToSDR(sums, p) {
83+
const ssums = [...sums];
84+
ssums.sort();
85+
const sumsLen = ssums.length;
86+
const threshold = Math.max(1, ssums[sumsLen-p]);
87+
const result = [];
88+
for (let i = 0; i < sumsLen; i++) {
89+
if (sums[i] >= threshold) { result.push(i); }
90+
}
91+
return result;
92+
}
93+
94+
}
95+
96+
export default TriadicMemory;

Javascript/jest.config.js

Lines changed: 196 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,196 @@
1+
/*
2+
* For a detailed explanation regarding each configuration property, visit:
3+
* https://jestjs.io/docs/configuration
4+
*/
5+
6+
module.exports = {
7+
// All imported modules in your tests should be mocked automatically
8+
// automock: false,
9+
10+
// Stop running tests after `n` failures
11+
// bail: 0,
12+
13+
// The directory where Jest should store its cached dependency information
14+
// cacheDirectory: "/private/var/folders/wc/wl4w92ts1978fq13g19708680000gn/T/jest_dx",
15+
16+
// Automatically clear mock calls, instances, contexts and results before every test
17+
clearMocks: true,
18+
19+
// Indicates whether the coverage information should be collected while executing the test
20+
collectCoverage: true,
21+
22+
// An array of glob patterns indicating a set of files for which coverage information should be collected
23+
// collectCoverageFrom: undefined,
24+
25+
// The directory where Jest should output its coverage files
26+
coverageDirectory: "coverage",
27+
28+
// An array of regexp pattern strings used to skip coverage collection
29+
// coveragePathIgnorePatterns: [
30+
// "/node_modules/"
31+
// ],
32+
33+
// Indicates which provider should be used to instrument code for coverage
34+
// coverageProvider: "babel",
35+
36+
// A list of reporter names that Jest uses when writing coverage reports
37+
// coverageReporters: [
38+
// "json",
39+
// "text",
40+
// "lcov",
41+
// "clover"
42+
// ],
43+
44+
// An object that configures minimum threshold enforcement for coverage results
45+
// coverageThreshold: undefined,
46+
47+
// A path to a custom dependency extractor
48+
// dependencyExtractor: undefined,
49+
50+
// Make calling deprecated APIs throw helpful error messages
51+
// errorOnDeprecated: false,
52+
53+
// The default configuration for fake timers
54+
// fakeTimers: {
55+
// "enableGlobally": false
56+
// },
57+
58+
// Force coverage collection from ignored files using an array of glob patterns
59+
// forceCoverageMatch: [],
60+
61+
// A path to a module which exports an async function that is triggered once before all test suites
62+
// globalSetup: undefined,
63+
64+
// A path to a module which exports an async function that is triggered once after all test suites
65+
// globalTeardown: undefined,
66+
67+
// A set of global variables that need to be available in all test environments
68+
// globals: {},
69+
70+
// The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers.
71+
// maxWorkers: "50%",
72+
73+
// An array of directory names to be searched recursively up from the requiring module's location
74+
// moduleDirectories: [
75+
// "node_modules"
76+
// ],
77+
78+
// An array of file extensions your modules use
79+
// moduleFileExtensions: [
80+
// "js",
81+
// "mjs",
82+
// "cjs",
83+
// "jsx",
84+
// "ts",
85+
// "tsx",
86+
// "json",
87+
// "node"
88+
// ],
89+
90+
// A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module
91+
// moduleNameMapper: {},
92+
93+
// An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader
94+
// modulePathIgnorePatterns: [],
95+
96+
// Activates notifications for test results
97+
// notify: false,
98+
99+
// An enum that specifies notification mode. Requires { notify: true }
100+
// notifyMode: "failure-change",
101+
102+
// A preset that is used as a base for Jest's configuration
103+
// preset: undefined,
104+
105+
// Run tests from one or more projects
106+
// projects: undefined,
107+
108+
// Use this configuration option to add custom reporters to Jest
109+
reporters: [
110+
"default",
111+
],
112+
113+
// Automatically reset mock state before every test
114+
// resetMocks: false,
115+
116+
// Reset the module registry before running each individual test
117+
// resetModules: false,
118+
119+
// A path to a custom resolver
120+
// resolver: undefined,
121+
122+
// Automatically restore mock state and implementation before every test
123+
// restoreMocks: false,
124+
125+
// The root directory that Jest should scan for tests and modules within
126+
// rootDir: undefined,
127+
128+
// A list of paths to directories that Jest should use to search for files in
129+
// roots: [
130+
// "<rootDir>"
131+
// ],
132+
133+
// Allows you to use a custom runner instead of Jest's default test runner
134+
// runner: "jest-runner",
135+
136+
// The paths to modules that run some code to configure or set up the testing environment before each test
137+
// setupFiles: [],
138+
139+
// A list of paths to modules that run some code to configure or set up the testing framework before each test
140+
// setupFilesAfterEnv: [],
141+
142+
// The number of seconds after which a test is considered as slow and reported as such in the results.
143+
// slowTestThreshold: 5,
144+
145+
// A list of paths to snapshot serializer modules Jest should use for snapshot testing
146+
// snapshotSerializers: [],
147+
148+
// The test environment that will be used for testing
149+
// testEnvironment: "jest-environment-node",
150+
151+
// Options that will be passed to the testEnvironment
152+
// testEnvironmentOptions: {},
153+
154+
// Adds a location field to test results
155+
// testLocationInResults: false,
156+
157+
// The glob patterns Jest uses to detect test files
158+
testMatch: [
159+
"**/tests/**/*.[jt]s?(x)"
160+
],
161+
162+
// An array of regexp pattern strings that are matched against all test paths, matched tests are skipped
163+
// testPathIgnorePatterns: [
164+
// "/node_modules/"
165+
// ],
166+
167+
// The regexp pattern or array of patterns that Jest uses to detect test files
168+
// testRegex: [],
169+
170+
// This option allows the use of a custom results processor
171+
// testResultsProcessor: undefined,
172+
173+
// This option allows use of a custom test runner
174+
// testRunner: "jest-circus/runner",
175+
176+
// A map from regular expressions to paths to transformers
177+
// transform: undefined,
178+
179+
// An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation
180+
// transformIgnorePatterns: [
181+
// "/node_modules/",
182+
// "\\.pnp\\.[^\\/]+$"
183+
// ],
184+
185+
// An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them
186+
// unmockedModulePathPatterns: undefined,
187+
188+
// Indicates whether each individual test should be reported during the run
189+
// verbose: undefined,
190+
191+
// An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode
192+
// watchPathIgnorePatterns: [],
193+
194+
// Whether to use watchman for file crawling
195+
// watchman: true,
196+
};

0 commit comments

Comments
 (0)