File size: 5,572 Bytes
b136cbe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
/**
 * Validation script to test balanced sampling algorithm
 * Simulates thousands of participants and verifies equal distribution of trials
 */

const fs = require('fs');

// Load survey data
const surveyData = JSON.parse(fs.readFileSync('./public/survey_data.json', 'utf8'));

const TRIALS_PER_PARTICIPANT = 20;
const NUM_SIMULATIONS = 10000; // Simulate 10,000 participants

/**
 * Simulates the balanced sampling algorithm for one participant
 */
function assignTrials(participantNumber, allSamples) {
  const totalTrials = allSamples.length;
  const numBlocks = Math.ceil(totalTrials / TRIALS_PER_PARTICIPANT);

  // Determine which block this participant gets (round-robin)
  const blockIndex = participantNumber % numBlocks;

  // Get the trials for this block
  const startIdx = blockIndex * TRIALS_PER_PARTICIPANT;
  const endIdx = Math.min(startIdx + TRIALS_PER_PARTICIPANT, totalTrials);
  let blockTrials = allSamples.slice(startIdx, endIdx);

  // If the last block has fewer than 20 trials, wrap around to fill it
  if (blockTrials.length < TRIALS_PER_PARTICIPANT) {
    const needed = TRIALS_PER_PARTICIPANT - blockTrials.length;
    blockTrials = [...blockTrials, ...allSamples.slice(0, needed)];
  }

  // Shuffle within the block to randomize order (Fisher-Yates)
  const shuffled = [...blockTrials];
  for (let i = shuffled.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
  }

  return shuffled.map(sample => sample.id);
}

/**
 * Run the simulation
 */
function runSimulation() {
  console.log('='.repeat(70));
  console.log('BALANCED SAMPLING VALIDATION');
  console.log('='.repeat(70));
  console.log(`Total trials in dataset: ${surveyData.length}`);
  console.log(`Trials per participant: ${TRIALS_PER_PARTICIPANT}`);
  console.log(`Number of blocks: ${Math.ceil(surveyData.length / TRIALS_PER_PARTICIPANT)}`);
  console.log(`Simulating ${NUM_SIMULATIONS} participants...`);
  console.log('='.repeat(70));
  console.log();

  // Track how many times each trial is assigned
  const trialCounts = {};
  surveyData.forEach(sample => {
    trialCounts[sample.id] = 0;
  });

  // Simulate participants
  for (let i = 0; i < NUM_SIMULATIONS; i++) {
    const assignedTrials = assignTrials(i, surveyData);
    assignedTrials.forEach(trialId => {
      trialCounts[trialId]++;
    });
  }

  // Calculate statistics
  const counts = Object.values(trialCounts);
  const mean = counts.reduce((a, b) => a + b, 0) / counts.length;
  const variance = counts.reduce((sum, count) => sum + Math.pow(count - mean, 2), 0) / counts.length;
  const stdDev = Math.sqrt(variance);
  const min = Math.min(...counts);
  const max = Math.max(...counts);
  const range = max - min;
  const coefficientOfVariation = (stdDev / mean) * 100;

  // Display results
  console.log('DISTRIBUTION STATISTICS:');
  console.log('-'.repeat(70));
  console.log(`Expected count per trial: ${mean.toFixed(2)}`);
  console.log(`Minimum count: ${min}`);
  console.log(`Maximum count: ${max}`);
  console.log(`Range: ${range}`);
  console.log(`Standard deviation: ${stdDev.toFixed(4)}`);
  console.log(`Coefficient of variation: ${coefficientOfVariation.toFixed(4)}%`);
  console.log();

  // Show distribution histogram
  console.log('DISTRIBUTION HISTOGRAM:');
  console.log('-'.repeat(70));
  const histogram = {};
  counts.forEach(count => {
    histogram[count] = (histogram[count] || 0) + 1;
  });

  Object.keys(histogram).sort((a, b) => a - b).forEach(count => {
    const bar = '█'.repeat(Math.ceil(histogram[count] / 2));
    console.log(`${count.padStart(6)} assignments: ${bar} (${histogram[count]} trials)`);
  });
  console.log();

  // Show individual trial counts (first 20 trials)
  console.log('SAMPLE TRIAL COUNTS (First 20 trials):');
  console.log('-'.repeat(70));
  for (let i = 0; i < Math.min(20, surveyData.length); i++) {
    const trialId = surveyData[i].id;
    const count = trialCounts[trialId];
    const deviation = ((count - mean) / mean * 100).toFixed(2);
    const bar = '▓'.repeat(Math.ceil(count / 50));
    console.log(`Trial ${String(trialId).padStart(3)}: ${String(count).padStart(5)} ${bar} (${deviation > 0 ? '+' : ''}${deviation}%)`);
  }
  console.log();

  // Validation
  console.log('VALIDATION RESULTS:');
  console.log('-'.repeat(70));

  const tolerance = mean * 0.05; // Allow 5% deviation
  const isBalanced = range <= tolerance;

  if (isBalanced) {
    console.log('✓ PASS: Distribution is well-balanced!');
    console.log(`  All trials are within ${(tolerance / mean * 100).toFixed(1)}% of expected count.`);
  } else {
    console.log('✗ FAIL: Distribution is imbalanced!');
    console.log(`  Range (${range}) exceeds tolerance (${tolerance.toFixed(2)}).`);
  }
  console.log();

  // Perfect balance check
  if (stdDev < 0.01) {
    console.log('✓ PERFECT: All trials have exactly the same count!');
    console.log('  This indicates perfect balanced sampling.');
  } else {
    console.log(`  Note: Small variations (σ=${stdDev.toFixed(4)}) are expected due to`);
    console.log(`  wrap-around when total trials is not a multiple of ${TRIALS_PER_PARTICIPANT}.`);
  }

  console.log();
  console.log('='.repeat(70));

  return {
    mean,
    stdDev,
    min,
    max,
    range,
    coefficientOfVariation,
    isBalanced
  };
}

// Run the simulation
try {
  const results = runSimulation();
  process.exit(results.isBalanced ? 0 : 1);
} catch (error) {
  console.error('Error running simulation:', error);
  process.exit(1);
}