gauss = (x, m, s) => Math.exp(-0.5 * ((x - m) / s) ** 2) / (s * Math.sqrt(2 * Math.PI))
coef = {
const L = Math.log((sA / sC) * ((1 - pA) / pA));
return {
a: sA ** 2 - sC ** 2,
b: 2 * (sC ** 2 * muA - sA ** 2 * muC),
c: sA ** 2 * muC ** 2 - sC ** 2 * muA ** 2 - 2 * sA ** 2 * sC ** 2 * L
};
}
quad = x => coef.a * x * x + coef.b * x + coef.c
grid = d3.range(-6, 8.001, 0.02)
regions = {
const out = [];
for (const x of grid) {
const cls = quad(x) >= 0 ? "A" : "C";
const last = out[out.length - 1];
if (last && last.cls === cls) last.x2 = x; else out.push({cls, x1: x, x2: x});
}
return out;
}
weighted = grid.flatMap(x => [
{x, y: pA * gauss(x, muA, sA), cls: "A"},
{x, y: (1 - pA) * gauss(x, muC, sC), cls: "C"}
])
ymax = d3.max(weighted, d => d.y) * 1.15
classColors = ({domain: ["A", "C"], range: ["#3C7DD9", "#C0392B"]})
qDomain = {
const m = d3.max(grid, d => Math.abs(quad(d)));
const top = d3.max(grid, quad);
return top > 0 ? [-2 * top, 1.5 * top] : [-m, m * 0.2];
}
Plot.plot({
width: 1300, height: 420, marginLeft: 70,
style: {fontSize: "20px"},
x: {label: "x", domain: [-6, 8]},
y: {label: "p(x | k) p(k)", domain: [0, ymax]},
color: {...classColors, legend: false},
marks: [
Plot.rect(regions, {x1: "x1", x2: "x2", y1: 0, y2: ymax, fill: "cls", fillOpacity: 0.12}),
Plot.text(regions, {x: d => (d.x1 + d.x2) / 2, y: ymax * 0.92, text: "cls", fill: "cls", fontSize: 40, fontWeight: "bold"}),
Plot.line(weighted, {x: "x", y: "y", stroke: "cls", strokeWidth: 4}),
Plot.ruleY([0])
]
})