@adriansteffan/reactive 0.1.2 → 0.1.4

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.
@@ -1,4 +1,4 @@
1
- import { W as e } from "./mod-Bb_FAy0j.js";
1
+ import { W as e } from "./mod-DHUjIRfF.js";
2
2
  class s extends e {
3
3
  async enable() {
4
4
  console.log("Immersive mode is only available on Android");
@@ -1,4 +1,4 @@
1
- import { W as P, b as x, E } from "./mod-Bb_FAy0j.js";
1
+ import { W as P, b as x, E } from "./mod-DHUjIRfF.js";
2
2
  function m(w) {
3
3
  const e = w.split("/").filter((t) => t !== "."), r = [];
4
4
  return e.forEach((t) => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@adriansteffan/reactive",
3
- "version": "0.1.2",
3
+ "version": "0.1.4",
4
4
  "type": "module",
5
5
  "scripts": {
6
6
  "dev": "vite",
@@ -40,9 +40,16 @@
40
40
  "@capacitor/filesystem": "^7.0.0",
41
41
  "@capacitor/share": "^7.0.0",
42
42
  "@capacitor/status-bar": "^7.0.0",
43
+ "@stdlib/random-base-mt19937": "^0.2.3",
44
+ "@stdlib/random-base-normal": "^0.2.2",
45
+ "@stdlib/random-base-poisson": "^0.2.2",
46
+ "@stdlib/random-base-uniform": "^0.2.3",
47
+ "@stdlib/stats-base-dists-normal-quantile": "^0.3.1",
48
+ "@stdlib/stats-base-dists-poisson-quantile": "^0.2.3",
43
49
  "@tanstack/react-query": "^5.61.3",
44
50
  "@tanstack/react-query-devtools": "^5.61.3",
45
51
  "@zip.js/zip.js": "^2.7.53",
52
+ "halton": "^1.0.0",
46
53
  "motion": "^12.38.0",
47
54
  "react": "^18.2.0",
48
55
  "react-dom": "^18.2.0",
@@ -16,6 +16,7 @@ import {
16
16
  import { BaseComponentProps, isFullscreen, now } from '../utils/common';
17
17
  import { registerSimulation, ParticipantState } from '../utils/simulation';
18
18
  import { registerFlattener, arrayFlattener } from '../utils/upload';
19
+ import { uniform } from '../utils/distributions';
19
20
 
20
21
  registerFlattener('CanvasBlock', 'canvas', arrayFlattener);
21
22
 
@@ -557,12 +558,12 @@ registerSimulation('CanvasBlock', (trialProps, experimentState, simulators, part
557
558
  respondToSlide: (slide: any, participant: any) => {
558
559
  const keys = slide.allowedKeys;
559
560
  if (keys === true) {
560
- return { key: ' ', reactionTime: 200 + Math.random() * 600, participantState: participant };
561
+ return { key: ' ', reactionTime: uniform(200, 800), participantState: participant };
561
562
  }
562
563
  if (Array.isArray(keys) && keys.length > 0) {
563
564
  return {
564
- key: keys[Math.floor(Math.random() * keys.length)],
565
- reactionTime: 200 + Math.random() * 600,
565
+ key: keys[Math.floor(uniform(0, keys.length))],
566
+ reactionTime: uniform(200, 800),
566
567
  participantState: participant,
567
568
  };
568
569
  }
@@ -2,12 +2,13 @@ import { BaseComponentProps } from '../mod';
2
2
  import { useState } from 'react';
3
3
  import { registerSimulation } from '../utils/simulation';
4
4
  import { registerFlattener } from '../utils/upload';
5
+ import { uniform } from '../utils/distributions';
5
6
 
6
7
  registerFlattener('PlainInput', 'session');
7
8
 
8
9
  registerSimulation('PlainInput', (trialProps, _experimentState, simulators, participant) => {
9
10
  const result = simulators.respond(trialProps, participant);
10
- const typingDuration = String(result.value).length * (50 + Math.random() * 100);
11
+ const typingDuration = String(result.value).length * uniform(50, 150);
11
12
  return {
12
13
  responseData: { value: result.value },
13
14
  participantState: result.participantState,
@@ -5,6 +5,7 @@ import { ContrastLight } from 'survey-core/themes';
5
5
  import 'survey-core/survey-core.min.css';
6
6
  import { registerSimulation } from '../utils/simulation';
7
7
  import { registerFlattener } from '../utils/upload';
8
+ import { uniform } from '../utils/distributions';
8
9
 
9
10
  registerFlattener('Quest', 'session');
10
11
 
@@ -28,21 +29,21 @@ registerSimulation('Quest', (trialProps, _experimentState, simulators, participa
28
29
  switch (question.type) {
29
30
  case 'rating': {
30
31
  const min = question.rateMin ?? 1, max = question.rateMax ?? 5;
31
- value = min + Math.floor(Math.random() * (max - min + 1));
32
+ value = min + Math.floor(uniform(0, max - min + 1));
32
33
  break;
33
34
  }
34
- case 'boolean': value = Math.random() > 0.5; break;
35
+ case 'boolean': value = uniform(0, 1) > 0.5; break;
35
36
  case 'text': case 'comment': value = 'simulated_response'; break;
36
37
  case 'radiogroup': case 'dropdown': {
37
- const c = question.choices?.[Math.floor(Math.random() * (question.choices?.length || 0))];
38
+ const c = question.choices?.[Math.floor(uniform(0, question.choices?.length || 0))];
38
39
  value = c !== undefined ? (typeof c === 'object' ? c.value : c) : null;
39
40
  break;
40
41
  }
41
42
  case 'checkbox': {
42
43
  if (question.choices?.length) {
43
- const n = 1 + Math.floor(Math.random() * question.choices.length);
44
+ const n = 1 + Math.floor(uniform(0, question.choices.length));
44
45
  value = [...question.choices]
45
- .sort(() => Math.random() - 0.5).slice(0, n)
46
+ .sort(() => uniform(0, 1) - 0.5).slice(0, n)
46
47
  .map((c: any) => typeof c === 'object' ? c.value : c);
47
48
  }
48
49
  break;
@@ -51,7 +52,7 @@ registerSimulation('Quest', (trialProps, _experimentState, simulators, participa
51
52
  if (question.rows?.length && question.columns?.length) {
52
53
  value = Object.fromEntries(
53
54
  question.rows.map((r: any) => {
54
- const col = question.columns[Math.floor(Math.random() * question.columns.length)];
55
+ const col = question.columns[Math.floor(uniform(0, question.columns.length))];
55
56
  return [typeof r === 'object' ? r.value : r, typeof col === 'object' ? col.value : col];
56
57
  }),
57
58
  );
@@ -60,7 +61,7 @@ registerSimulation('Quest', (trialProps, _experimentState, simulators, participa
60
61
  }
61
62
  default: value = null;
62
63
  }
63
- return { value, participantState: participant, duration: 1000 + Math.random() * 4000 };
64
+ return { value, participantState: participant, duration: uniform(1000, 5000) };
64
65
  },
65
66
  });
66
67
 
@@ -11,6 +11,7 @@ import type { CSSProperties } from 'react';
11
11
  import { BaseComponentProps, shuffle } from '../mod';
12
12
  import { registerSimulation } from '../utils/simulation';
13
13
  import { registerFlattener } from '../utils/upload';
14
+ import { simulateDDMTrial, mapDDMChoice } from '../utils/ddm';
14
15
 
15
16
  registerFlattener('RandomDotKinematogram', 'rdk');
16
17
 
@@ -47,39 +48,49 @@ const RDK_DEFAULTS = {
47
48
  };
48
49
 
49
50
  registerSimulation('RandomDotKinematogram', (trialProps, _experimentState, simulators, participant) => {
50
- const result = simulators.respond(trialProps, participant);
51
- const fixation = trialProps.fixationTime ?? RDK_DEFAULTS.fixationTime;
52
- const trialDuration = trialProps.duration ?? RDK_DEFAULTS.duration;
53
- const responseEndsTrial = trialProps.responseEndsTrial ?? RDK_DEFAULTS.responseEndsTrial;
54
- const rt = result.value.rt;
55
- // If the participant responded and responseEndsTrial is true, the trial ends at the response.
56
- // Otherwise, the full duration plays out.
51
+ const merged: any = { ...RDK_DEFAULTS, ...trialProps };
52
+ const result = simulators.respond(merged, participant);
53
+ const { rt, response } = result.value;
54
+
55
+ const fixation = merged.fixationTime ?? RDK_DEFAULTS.fixationTime;
56
+ const trialDuration = merged.duration ?? RDK_DEFAULTS.duration;
57
+ const responseEndsTrial = merged.responseEndsTrial ?? RDK_DEFAULTS.responseEndsTrial;
57
58
  const elapsed = (responseEndsTrial && rt != null) ? rt : trialDuration;
59
+
60
+ const correctKeys = Array.isArray(merged.correctResponse)
61
+ ? merged.correctResponse.map((c: string) => c.toLowerCase())
62
+ : merged.correctResponse ? [merged.correctResponse.toLowerCase()] : null;
63
+
58
64
  return {
59
- responseData: result.value,
65
+ responseData: {
66
+ ...merged,
67
+ rt,
68
+ response,
69
+ correct: response && correctKeys ? correctKeys.includes(response.toLowerCase()) : null,
70
+ framesDisplayed: 0,
71
+ measuredRefreshRate: null,
72
+ },
60
73
  participantState: result.participantState,
61
74
  duration: fixation + elapsed,
62
75
  };
63
76
  }, {
64
77
  respond: (trialProps: any, participant: any) => {
65
- const merged = { ...RDK_DEFAULTS, ...trialProps };
66
- const rawRt = 200 + Math.random() * 600;
67
- const maxRt = merged.duration ?? RDK_DEFAULTS.duration;
68
- const responded = merged.validKeys.length > 0 && rawRt <= maxRt;
69
- const key = responded ? merged.validKeys[Math.floor(Math.random() * merged.validKeys.length)] : null;
70
- const rt = responded ? rawRt : null;
71
- const correctKeys = Array.isArray(merged.correctResponse)
72
- ? merged.correctResponse.map((c: string) => c.toLowerCase())
73
- : merged.correctResponse ? [merged.correctResponse.toLowerCase()] : null;
78
+ const ddm = simulateDDMTrial({
79
+ driftRate: 0.00074 * (trialProps.coherence ?? RDK_DEFAULTS.coherence),
80
+ boundaries: 0.0555,
81
+ startingPoint: 0,
82
+ noiseLevel: 0.00316,
83
+ sensoryDelay: { type: 'uniform', min: 150, max: 250 },
84
+ motorDelay: { type: 'uniform', min: 130, max: 210 },
85
+ timeLimit: trialProps.duration ?? RDK_DEFAULTS.duration,
86
+ stimOffset: trialProps.stimulusDuration ?? trialProps.duration ?? RDK_DEFAULTS.duration,
87
+ postStimStrategy: { type: 'continue' },
88
+ });
89
+
90
+ const key = mapDDMChoice(ddm.choice, trialProps.validKeys, trialProps.correctResponse);
91
+
74
92
  return {
75
- value: {
76
- ...merged,
77
- rt,
78
- response: key,
79
- correct: key && correctKeys ? correctKeys.includes(key) : null,
80
- framesDisplayed: 0,
81
- measuredRefreshRate: null,
82
- },
93
+ value: { rt: key ? ddm.rt : null, response: key },
83
94
  participantState: participant,
84
95
  };
85
96
  },
@@ -2,6 +2,7 @@ import React, { useEffect, useRef } from 'react';
2
2
  import { BaseComponentProps, now } from '../mod';
3
3
  import { registerSimulation } from '../utils/simulation';
4
4
  import { registerFlattener } from '../utils/upload';
5
+ import { uniform } from '../utils/distributions';
5
6
 
6
7
  registerFlattener('Text', 'text');
7
8
 
@@ -10,7 +11,7 @@ registerSimulation('Text', (trialProps, _experimentState, simulators, participan
10
11
  return { responseData: result.value, participantState: result.participantState, duration: result.value.reactionTime };
11
12
  }, {
12
13
  respond: (_input: any, participant: any) => ({
13
- value: { key: 'button', reactionTime: 500 + Math.random() * 1500 },
14
+ value: { key: 'button', reactionTime: uniform(500, 2000) },
14
15
  participantState: participant,
15
16
  }),
16
17
  });
@@ -16,9 +16,10 @@ import { BlobWriter, TextReader, ZipWriter } from '@zip.js/zip.js';
16
16
  import { Filesystem, Directory, Encoding } from '@capacitor/filesystem';
17
17
  import { buildUploadFiles, convertArrayOfObjectsToCSV } from '../utils/upload';
18
18
  import { registerSimulation, getBackendUrl, getInitialParticipant } from '../utils/simulation';
19
+ import { uniform } from '../utils/distributions';
19
20
 
20
21
  registerSimulation('Upload', async (trialProps, experimentState, _simulators, participant) => {
21
- const sessionID = trialProps.sessionID || `sim_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
22
+ const sessionID = trialProps.sessionID || `sim_${Date.now()}_${Math.floor(uniform(0, 36 ** 6)).toString(36)}`;
22
23
  const files = buildUploadFiles({
23
24
  sessionID,
24
25
  data: experimentState.data || [],
package/src/mod.tsx CHANGED
@@ -6,6 +6,10 @@ export * from './utils/array';
6
6
  export * from './utils/common';
7
7
  export * from './utils/simulation';
8
8
  export { registerFlattener, arrayFlattener } from './utils/upload';
9
+ export { normal, poisson, uniform, seedDistributions, sobol, halton, sampleParticipants } from './utils/distributions';
10
+ export type { DimensionSpec, UniformSpec, NormalSpec, PoissonSpec, SamplingMethod } from './utils/distributions';
11
+ export { simulateDDMTrial, mapDDMChoice } from './utils/ddm';
12
+ export type { DDMTrialParams, DDMTrialResult, ParameterDef, NormalDist, UniformDist, BoundaryDef, CollapseDef, PostStimStrategyDef, ContinueStrategy, CollapseStrategy, SnapshotStrategy } from './utils/ddm';
9
13
  export * from './components';
10
14
 
11
15
  export * from 'react-toastify';
@@ -1,3 +1,5 @@
1
+ import { uniform } from './distributions';
2
+
1
3
  declare global {
2
4
  interface Array<T> {
3
5
  /**
@@ -36,7 +38,7 @@ export function sample<T>(array: T[], n: number = 1): T[] {
36
38
  }
37
39
 
38
40
  for (let i = 0; i < n; i++) {
39
- const randomIndex = Math.floor(Math.random() * array.length);
41
+ const randomIndex = Math.floor(uniform(0, 1) * array.length);
40
42
  result.push(array[randomIndex]);
41
43
  }
42
44
 
@@ -50,7 +52,7 @@ export function shuffle<T>(array: T[]): T[] {
50
52
  const result = [...array];
51
53
 
52
54
  for (let i = result.length - 1; i >= 0; i--) {
53
- const j = Math.floor(Math.random() * (i + 1));
55
+ const j = Math.floor(uniform(0, 1) * (i + 1));
54
56
  [result[i], result[j]] = [result[j], result[i]];
55
57
  }
56
58
  return result;
@@ -0,0 +1,233 @@
1
+ import { describe, it, expect, beforeEach } from 'vitest';
2
+ import { simulateDDMTrial, mapDDMChoice } from './ddm';
3
+ import { seedDistributions } from './distributions';
4
+
5
+ beforeEach(() => {
6
+ seedDistributions(42);
7
+ });
8
+
9
+ const baseParams = {
10
+ driftRate: 0.003,
11
+ boundaries: 0.1 as const,
12
+ startingPoint: 0,
13
+ noiseLevel: 0.003,
14
+ timeLimit: 2000,
15
+ stimOffset: 2000,
16
+ postStimStrategy: { type: 'continue' as const },
17
+ };
18
+
19
+ describe('simulateDDMTrial', () => {
20
+ it('returns a valid result shape', () => {
21
+ const result = simulateDDMTrial(baseParams);
22
+ expect([0, 1, null]).toContain(result.choice);
23
+ expect(result.rt).toBeGreaterThan(0);
24
+ expect(typeof result.finalEvidence).toBe('number');
25
+ expect(result.isContaminated).toBe(false);
26
+ });
27
+
28
+ it('is reproducible with the same seed', () => {
29
+ seedDistributions(99);
30
+ const a = simulateDDMTrial(baseParams);
31
+ seedDistributions(99);
32
+ const b = simulateDDMTrial(baseParams);
33
+ expect(a).toEqual(b);
34
+ });
35
+
36
+ it('rt includes sensory and motor delays', () => {
37
+ const result = simulateDDMTrial({
38
+ ...baseParams,
39
+ driftRate: 1, // very high drift for instant decision
40
+ sensoryDelay: 100,
41
+ motorDelay: 50,
42
+ });
43
+ expect(result.rt).toBeGreaterThanOrEqual(150);
44
+ });
45
+
46
+ it('clamps sensory and motor delays to >= 0', () => {
47
+ const result = simulateDDMTrial({
48
+ ...baseParams,
49
+ driftRate: 1,
50
+ sensoryDelay: { type: 'normal', mean: -1000, sd: 1 },
51
+ motorDelay: { type: 'normal', mean: -1000, sd: 1 },
52
+ });
53
+ expect(result.rt).toBeGreaterThanOrEqual(0);
54
+ });
55
+
56
+ it('clamps noise level to >= 0', () => {
57
+ // Should not throw even with a negative noise param
58
+ const result = simulateDDMTrial({
59
+ ...baseParams,
60
+ noiseLevel: { type: 'normal', mean: -10, sd: 0.1 },
61
+ });
62
+ expect(result).toBeDefined();
63
+ });
64
+
65
+ it('returns null choice on timeout', () => {
66
+ const result = simulateDDMTrial({
67
+ ...baseParams,
68
+ driftRate: 0,
69
+ noiseLevel: 0, // no noise, no drift — never reaches boundary
70
+ timeLimit: 100,
71
+ });
72
+ expect(result.choice).toBeNull();
73
+ expect(result.rt).toBe(100);
74
+ });
75
+
76
+ it('supports asymmetric boundaries', () => {
77
+ const result = simulateDDMTrial({
78
+ ...baseParams,
79
+ boundaries: [-0.05, 0.2], // lower closer, upper farther
80
+ driftRate: 0,
81
+ noiseLevel: 0.01,
82
+ });
83
+ expect([0, 1, null]).toContain(result.choice);
84
+ });
85
+
86
+ it('contamination returns isContaminated with valid rt', () => {
87
+ const result = simulateDDMTrial({ ...baseParams, contaminationRate: 1.0 });
88
+ expect(result.isContaminated).toBe(true);
89
+ expect(result.rt).toBeGreaterThanOrEqual(0);
90
+ expect(result.rt).toBeLessThanOrEqual(baseParams.timeLimit);
91
+ });
92
+
93
+ it('contamination sets finalEvidence to startingPoint', () => {
94
+ const result = simulateDDMTrial({
95
+ ...baseParams,
96
+ startingPoint: 0.05,
97
+ contaminationRate: 1.0,
98
+ });
99
+ expect(result.isContaminated).toBe(true);
100
+ expect(result.finalEvidence).toBe(0.05);
101
+ });
102
+ });
103
+
104
+ describe('snapshot strategy', () => {
105
+ it('forces choice at stimOffset based on boundary proximity', () => {
106
+ const result = simulateDDMTrial({
107
+ ...baseParams,
108
+ driftRate: 0.01, // positive drift, evidence moves toward upper
109
+ stimOffset: 50,
110
+ postStimStrategy: { type: 'snapshot' },
111
+ });
112
+ expect([0, 1]).toContain(result.choice);
113
+ expect(result.isContaminated).toBe(false);
114
+ });
115
+
116
+ it('rt reflects stimOffset timing, not timeLimit', () => {
117
+ const result = simulateDDMTrial({
118
+ ...baseParams,
119
+ driftRate: 0.0001, // slow drift, won't hit boundary before stimOffset
120
+ noiseLevel: 0.0001,
121
+ sensoryDelay: 0,
122
+ motorDelay: 100,
123
+ stimOffset: 200,
124
+ timeLimit: 5000,
125
+ postStimStrategy: { type: 'snapshot' },
126
+ });
127
+ // rt should be around stimOffset + motorDelay, not timeLimit
128
+ expect(result.rt).toBeLessThan(5000);
129
+ expect(result.rt).toBeGreaterThanOrEqual(200);
130
+ });
131
+ });
132
+
133
+ describe('continue strategy', () => {
134
+ it('defaults to zero drift after stimOffset', () => {
135
+ // With zero drift and no noise after stimOffset, evidence should freeze
136
+ const result = simulateDDMTrial({
137
+ ...baseParams,
138
+ driftRate: 0,
139
+ noiseLevel: 0,
140
+ stimOffset: 10,
141
+ timeLimit: 100,
142
+ postStimStrategy: { type: 'continue' },
143
+ });
144
+ expect(result.choice).toBeNull(); // no drift, no noise — timeout
145
+ });
146
+
147
+ });
148
+
149
+ describe('collapse strategy', () => {
150
+ it('eventually forces a decision', () => {
151
+ const result = simulateDDMTrial({
152
+ ...baseParams,
153
+ driftRate: 0,
154
+ noiseLevel: 0.001,
155
+ stimOffset: 0,
156
+ timeLimit: 10000,
157
+ postStimStrategy: {
158
+ type: 'collapse',
159
+ collapseDef: { rate: 0.001 },
160
+ },
161
+ });
162
+ // Boundaries collapse, must eventually reach evidence
163
+ expect([0, 1]).toContain(result.choice);
164
+ });
165
+
166
+ it('respects collapse delay', () => {
167
+ const fast = simulateDDMTrial({
168
+ ...baseParams,
169
+ driftRate: 0,
170
+ noiseLevel: 0.0001,
171
+ stimOffset: 0,
172
+ timeLimit: 10000,
173
+ postStimStrategy: {
174
+ type: 'collapse',
175
+ collapseDef: { rate: 0.001, delay: 0 },
176
+ },
177
+ });
178
+ const delayed = simulateDDMTrial({
179
+ ...baseParams,
180
+ driftRate: 0,
181
+ noiseLevel: 0.0001,
182
+ stimOffset: 0,
183
+ timeLimit: 10000,
184
+ postStimStrategy: {
185
+ type: 'collapse',
186
+ collapseDef: { rate: 0.001, delay: 500 },
187
+ },
188
+ });
189
+ // Delayed collapse should take longer (or at least not be faster)
190
+ expect(delayed.rt).toBeGreaterThanOrEqual(fast.rt);
191
+ });
192
+ });
193
+
194
+ describe('mapDDMChoice', () => {
195
+ it('returns null for null choice', () => {
196
+ expect(mapDDMChoice(null, ['a', 'b'])).toBeNull();
197
+ });
198
+
199
+ it('returns null for empty validKeys', () => {
200
+ expect(mapDDMChoice(1, [])).toBeNull();
201
+ });
202
+
203
+ it('maps choice 1 to correct key', () => {
204
+ const key = mapDDMChoice(1, ['a', 'b'], 'a');
205
+ expect(key).toBe('a');
206
+ });
207
+
208
+ it('maps choice 0 to incorrect key', () => {
209
+ const key = mapDDMChoice(0, ['a', 'b'], 'a');
210
+ expect(key).toBe('b');
211
+ });
212
+
213
+ it('handles case-insensitive correctResponse', () => {
214
+ const key = mapDDMChoice(1, ['A', 'b'], 'a');
215
+ expect(key?.toLowerCase()).toBe('a');
216
+ });
217
+
218
+ it('handles array correctResponse', () => {
219
+ const key = mapDDMChoice(1, ['a', 'b', 'c'], ['a', 'b']);
220
+ expect(['a', 'b']).toContain(key);
221
+ });
222
+
223
+ it('returns random key when no correctResponse', () => {
224
+ const key = mapDDMChoice(1, ['a', 'b']);
225
+ expect(['a', 'b']).toContain(key);
226
+ });
227
+
228
+ it('falls back to any key when no matching keys for choice', () => {
229
+ // choice 0 (incorrect), but all keys are correct — no wrong keys available
230
+ const key = mapDDMChoice(0, ['a'], 'a');
231
+ expect(key).toBe('a');
232
+ });
233
+ });