/** * 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); }