-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpoisson-viz.tsx
262 lines (238 loc) · 8.98 KB
/
poisson-viz.tsx
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
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
import React, { useState, useCallback } from 'react';
import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer } from 'recharts';
import { Card, CardHeader, CardTitle, CardContent } from '@/components/ui/card';
const PoissonCalculator = () => {
const [params, setParams] = useState({
copyNumber: 30,
sampleSize: 8000,
totalSpecies: 350000,
meanCopies: 30
});
const calculatePoissonSamples = useCallback((lambda, sampleSize, totalSpecies = 350000, meanCopies = 30) => {
const factorial = (n) => {
if (n === 0) return 1;
let result = 1;
for (let i = 1; i <= n; i++) result *= i;
return result;
};
let sumExp = -Infinity;
const maxK = Math.min(1000, lambda * 5);
for (let k = 0; k <= maxK; k++) {
const logPoisson = k * Math.log(lambda) - lambda - Math.log(factorial(k));
const probMiss = Math.pow(1 - k/(totalSpecies * meanCopies), sampleSize);
const logProbMiss = Math.log(Math.max(probMiss, 1e-308));
const logTerm = logPoisson + logProbMiss;
sumExp = Math.log(Math.exp(sumExp) + Math.exp(logTerm));
}
return Math.ceil(Math.log(0.05) / sumExp);
}, []);
const calculateCaptureProb = useCallback((copyNum, sampleSize, numSamples, totalSpecies, meanCopies) => {
// For each sample, probability of missing is (1 - k/(N*M))^S
const probMissSingle = Math.pow(1 - copyNum/(totalSpecies * meanCopies), sampleSize);
// Probability of missing in all samples
const probMissAll = Math.pow(probMissSingle, numSamples);
// Return probability of capturing in at least one sample
return (1 - probMissAll) * 100;
}, []);
const handleCalculate = useCallback((e) => {
e.preventDefault();
// Calculate required samples
const samplesNeeded = calculatePoissonSamples(
params.copyNumber,
params.sampleSize,
params.totalSpecies,
params.meanCopies
);
// Generate probability curve data
const probData = [];
const maxCopyNum = params.copyNumber * 2; // Show up to 2x the target copy number
for (let copyNum = 1; copyNum <= maxCopyNum; copyNum++) {
const prob = calculateCaptureProb(
copyNum,
params.sampleSize,
samplesNeeded,
params.totalSpecies,
params.meanCopies
);
probData.push({
copyNumber: copyNum,
probability: prob
});
}
setResult({
samplesNeeded,
probData
});
}, [params, calculatePoissonSamples, calculateCaptureProb]);
const [result, setResult] = useState(null);
const handleInputChange = useCallback((e) => {
const { name, value } = e.target;
setParams(prev => ({
...prev,
[name]: Number(value)
}));
}, []);
return (
<div className="w-full max-w-4xl mx-auto p-4">
<Card>
<CardHeader>
<CardTitle>Poisson Sample Size Calculator</CardTitle>
</CardHeader>
<CardContent>
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
<form onSubmit={handleCalculate} className="space-y-6">
<div className="space-y-4">
<div>
<label className="block text-sm font-medium mb-1">
Minimum Copy Number per Species (λ)
</label>
<input
type="number"
name="copyNumber"
value={params.copyNumber}
onChange={handleInputChange}
min="1"
className="w-full p-2 border rounded"
required
/>
</div>
<div>
<label className="block text-sm font-medium mb-1">
Phage per Sample
</label>
<input
type="number"
name="sampleSize"
value={params.sampleSize}
onChange={handleInputChange}
min="1"
className="w-full p-2 border rounded"
required
/>
</div>
<div>
<label className="block text-sm font-medium mb-1">
Total Number of Species
</label>
<input
type="number"
name="totalSpecies"
value={params.totalSpecies}
onChange={handleInputChange}
min="1"
className="w-full p-2 border rounded"
required
/>
</div>
<div>
<label className="block text-sm font-medium mb-1">
Mean Copies per Species
</label>
<input
type="number"
name="meanCopies"
value={params.meanCopies}
onChange={handleInputChange}
min="1"
className="w-full p-2 border rounded"
required
/>
</div>
</div>
<button
type="submit"
className="w-full bg-blue-500 text-white py-2 px-4 rounded hover:bg-blue-600 transition-colors"
>
Calculate
</button>
{result && (
<div className="mt-6 p-4 bg-gray-50 rounded-lg">
<h3 className="text-lg font-medium mb-2">Results</h3>
<p className="text-2xl font-bold text-blue-600">
{result.samplesNeeded.toLocaleString()} samples needed
</p>
<p className="mt-2 text-sm text-gray-600">
This will give you a 95% probability of capturing species with {params.copyNumber} or more copies.
</p>
</div>
)}
</form>
{result && (
<div className="h-96">
<h3 className="text-lg font-medium mb-4">Detection Probability by Copy Number</h3>
<ResponsiveContainer width="100%" height="100%">
<LineChart
data={result.probData}
margin={{ top: 20, right: 30, left: 20, bottom: 40 }}
>
<CartesianGrid strokeDasharray="3 3" />
<XAxis
dataKey="copyNumber"
label={{
value: 'Copy Number',
position: 'bottom',
offset: 20
}}
/>
<YAxis
label={{
value: 'Detection Probability (%)',
angle: -90,
position: 'insideLeft',
offset: 0
}}
domain={[0, 100]}
/>
<Tooltip
formatter={(value) => [`${value.toFixed(1)}%`, 'Probability']}
labelFormatter={(value) => `${value} copies`}
/>
<Line
type="monotone"
dataKey="probability"
stroke="#2563eb"
strokeWidth={2}
dot={false}
/>
{/* Add reference line at 95% */}
<Line
type="monotone"
dataKey={() => 95}
stroke="#dc2626"
strokeDasharray="3 3"
strokeWidth={1}
dot={false}
/>
</LineChart>
</ResponsiveContainer>
</div>
)}
</div>
<div className="mt-8 space-y-4 text-sm text-gray-600">
<div className="bg-gray-50 p-4 rounded-lg">
<div className="mb-2 font-medium">Formula Used:</div>
<div className="font-mono text-xs">
n = ⌈ln(0.05) / ln(Σ[(λᵏe⁻ᵏ/k!) × (1 - k/(N×M))ˢ])⌉
</div>
<div className="mt-2 text-xs">
Probability of detection in n samples = 1 - (1 - k/(N×M))^(S×n)
</div>
</div>
<div>
<p className="font-medium mb-1">Where:</p>
<ul className="list-disc pl-6 space-y-1">
<li>λ (lambda): Minimum copy number per species</li>
<li>N: Total number of species</li>
<li>M: Mean copies per species</li>
<li>S: Sample size (phage per sample)</li>
<li>n: Number of samples needed</li>
<li>k: Copy number (for probability curve)</li>
</ul>
</div>
</div>
</CardContent>
</Card>
</div>
);
};
export default PoissonCalculator;