nearest.js 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621
  1. // Selectors + DOM Manipulation
  2. const getColorInputNode = () => document.getElementById("color-input");
  3. const getMetricDropdownNode = () => document.getElementById("metric");
  4. const getClusterChoiceDropdownNode = () => document.getElementById("image-summary");
  5. const getClusterScaleToggleNode = () => document.getElementById("scale-by-cluster-size");
  6. const getClusterMeanWarning = () => document.getElementById("cluster-mean-warning");
  7. const getIncludeXToggleNode = () => document.getElementById("include-x");
  8. const getNormQYToggleNode = () => document.getElementById("norm-q-y");
  9. const getCloseCoeffSliderNode = () => document.getElementById("close-coeff");
  10. const getCloseCoeffDisplayNode = () => document.getElementById("close-coeff-display");
  11. const getLimitSliderNode = () => document.getElementById("num-poke");
  12. const getLimitDisplayNode = () => document.getElementById("num-poke-display");
  13. const getNameInputNode = () => document.getElementById("pokemon-name");
  14. const getScoreListJABNode = () => document.getElementById("best-list-jab");
  15. const getScoreListRGBNode = () => document.getElementById("best-list-rgb");
  16. const getSearchSpaceDisplayNode = () => document.getElementById("search-space-display");
  17. const getSearchListNode = () => document.getElementById("search-list");
  18. const getHideableControlNodes = () => document.querySelectorAll(".hideable_control");
  19. const getQJABDisplay = () => document.getElementById("q-vec-jab");
  20. const getQRGBDisplay = () => document.getElementById("q-vec-rgb");
  21. const getObjFnDisplay = () => document.getElementById("obj-fn");
  22. const clearNodeContents = node => { node.innerHTML = ""; };
  23. const hideCustomControls = () => getHideableControlNodes()
  24. .forEach(n => n.setAttribute("class", "hideable_control hideable_control--hidden"));
  25. const showCustomControls = () => getHideableControlNodes()
  26. .forEach(n => n.setAttribute("class", "hideable_control"));
  27. // Vector Math
  28. const vectorDot = (u, v) => u.map((x, i) => x * v[i]).reduce((x, y) => x + y);
  29. const vectorSqMag = v => vectorDot(v, v);
  30. const vectorMag = v => Math.sqrt(vectorSqMag(v));
  31. const vectorSqDist = (u, v) => vectorSqMag(u.map((x, i) => x - v[i]));
  32. const vectorDist = (u, v) => Math.sqrt(vectorSqDist(u, v));
  33. const vectorNorm = v => { const n = vectorMag(v); return [ n, v.map(c => c / n) ]; };
  34. // Angle Math
  35. const angleDiff = (a, b) => { const raw = Math.abs(a - b); return raw < 180 ? raw : (360 - raw); };
  36. const rad2deg = 180 / Math.PI;
  37. // Conversions
  38. const jab2hex = jab => d3.jab(...jab).formatHex();
  39. const rgb2hex = rgb => d3.rgb(...rgb).formatHex();
  40. const jab2hue = ([, a, b]) => rad2deg * Math.atan2(b, a);
  41. const rgb2hue = rgb => d3.hsl(d3.rgb(...rgb)).h || 0;
  42. const hex2rgb = hex => {
  43. const { r, g, b } = d3.color(hex);
  44. return [r, g, b];
  45. };
  46. // Arg Compare
  47. const argComp = comp => ra => ra.map((x, i) => [x, i]).reduce((a, b) => comp(a[0], b[0]) > 0 ? b : a)[1];
  48. const argMin = argComp((a, b) => a - b);
  49. const argMax = argComp((a, b) => b - a);
  50. // Pre-Compute Data
  51. const computeVectorData = (vector, toHex, toHue) => {
  52. const [ magnitude, unit ] = vectorNorm(vector);
  53. return {
  54. vector,
  55. magnitude,
  56. magSq: magnitude * magnitude,
  57. unit,
  58. hex: toHex(vector),
  59. hue: toHue(vector),
  60. };
  61. };
  62. const computeStats = (inertia, trueMeanVec, kMeanStruct, toHex, toHue) => ({
  63. inertia,
  64. trueMean: computeVectorData(trueMeanVec, toHex, toHue),
  65. kMeans: kMeanStruct.slice(0, 3).map(z => computeVectorData(z, toHex, toHue)),
  66. kWeights: kMeanStruct[3],
  67. largestCluster: argMax(kMeanStruct[3]),
  68. smallestCluster: argMin(kMeanStruct[3]),
  69. });
  70. const pokemonColorData = database.map(({
  71. name, xJAB, xRGB, yJAB, yRGB, zJAB, zRGB,
  72. }) => ({
  73. name,
  74. jabStats: computeStats(xJAB, yJAB, zJAB, jab2hex, jab2hue),
  75. rgbStats: computeStats(xRGB, yRGB, zRGB, rgb2hex, rgb2hue),
  76. }));
  77. const pokemonLookup = new Fuse(pokemonColorData, { keys: [ "name" ] });
  78. // Color Calculations
  79. const getContrastingTextColor = rgb => vectorDot(rgb, [0.3, 0.6, 0.1]) >= 128 ? "#222" : "#ddd";
  80. const readColorInput = () => {
  81. const colorInput = "#" + (getColorInputNode()?.value?.replace("#", "") ?? "FFFFFF");
  82. if (colorInput.length !== 7) {
  83. return;
  84. }
  85. const rgb = d3.color(colorInput);
  86. const { J, a, b } = d3.jab(rgb);
  87. return {
  88. jabData: computeVectorData([ J, a, b ], jab2hex, jab2hue),
  89. rgbData: computeVectorData([ rgb.r, rgb.g, rgb.b ], rgb2hex, rgb2hue),
  90. };
  91. };
  92. // State
  93. const state = {
  94. metric: null,
  95. clusterChoice: null,
  96. includeScale: null,
  97. includeX: null,
  98. normQY: null,
  99. closeCoeff: null,
  100. numPoke: null,
  101. searchTerm: null,
  102. searchSpace: null,
  103. targetColor: null,
  104. searchResults: null,
  105. clusterToggles: {},
  106. };
  107. // Metrics
  108. const getBestKMean = (stats, q) => argMin(stats.kMeans.map((z, i) => vectorSqDist(z.vector, q.vector) / stats.kWeights[i]));
  109. const getWorstKMean = (stats, q) => argMax(stats.kMeans.map((z, i) => vectorSqDist(z.vector, q.vector) / stats.kWeights[i]));
  110. const getScale = weight => state.includeScale ? (1 / weight) : 1;
  111. const summarySelectors = [
  112. // true mean
  113. stats => [stats.trueMean, 1],
  114. // largest cluster
  115. stats => [stats.kMeans[stats.largestCluster], getScale(stats.kWeights[stats.largestCluster])],
  116. // smallest cluster
  117. stats => [stats.kMeans[stats.smallestCluster], getScale(stats.kWeights[stats.smallestCluster])],
  118. // best fit cluster
  119. (stats, q) => {
  120. const best = getBestKMean(stats, q);
  121. return [stats.kMeans[best], getScale(stats.kWeights[best])];
  122. },
  123. // worst fit cluster
  124. (stats, q) => {
  125. const worst = getWorstKMean(stats, q);
  126. return [stats.kMeans[worst], getScale(stats.kWeights[worst])];
  127. },
  128. ];
  129. const selectedSummary = (stats, q) => summarySelectors[state.clusterChoice](stats, q);
  130. const metrics = [
  131. // RMS
  132. (stats, q) => {
  133. const [ mean, scale ] = selectedSummary(stats, q);
  134. return (stats.inertia - 2 * vectorDot(mean.vector, q.vector)) * scale;
  135. },
  136. // mean angle
  137. (stats, q) => {
  138. const [ mean, scale ] = selectedSummary(stats, q);
  139. // divide by scale since we're negative
  140. return -vectorDot(mean.unit, q.unit) / scale
  141. },
  142. // mean dist
  143. (stats, q) => {
  144. const [ mean, scale ] = selectedSummary(stats, q);
  145. // TODO I know there's some way to avoid recalculation here but I'm just too lazy right now
  146. return vectorSqDist(mean.vector, q.vector) * scale;
  147. },
  148. // hue angle
  149. (stats, q) => {
  150. const [ mean, scale ] = selectedSummary(stats, q);
  151. return angleDiff(mean.hue, q.hue) * scale;
  152. },
  153. // max inertia
  154. (stats, q) => {
  155. const [ , scale ] = selectedSummary(stats, q);
  156. // divide by scale since we're negative
  157. return -stats.inertia / scale;
  158. },
  159. // custom
  160. (stats, q) => {
  161. const [ mean, scale ] = selectedSummary(stats, q);
  162. return (
  163. (state.includeX ? stats.inertia : 0)
  164. -
  165. state.closeCoeff * vectorDot(
  166. mean[state.normQY ? "unit" : "vector"],
  167. state.normQY ? q.unit : q.vector,
  168. )
  169. ) * scale;
  170. },
  171. ];
  172. const scorePokemon = pkmn => ({
  173. jab: metrics[state.metric](pkmn.jabStats, state.targetColor.jabData),
  174. rgb: metrics[state.metric](pkmn.rgbStats, state.targetColor.rgbData),
  175. });
  176. const calcDisplayMetrics = (meanData, q) => ({
  177. theta: rad2deg * Math.acos(vectorDot(q.unit, meanData.unit)),
  178. delta: vectorDist(q.vector, meanData.vector),
  179. phi: angleDiff(q.hue, meanData.hue),
  180. });
  181. // Math Rendering
  182. const renderQVec = (q, node, sub) => {
  183. node.innerHTML = TeXZilla.toMathMLString(String.raw`\vec{q}_{\text{${sub}}} = \left(\text{${q.join(", ")}}\right)`);
  184. };
  185. const mathArgBest = (mxn, arg) => `\\underset{${arg}}{\\arg\\${mxn}}`;
  186. const mathDefinitions = {
  187. "main-definition": String.raw`
  188. \begin{aligned}
  189. \vec{\mu}\left(P\right) &= \frac{1}{\left|P\right|}\sum_{p\in P}{\vec{p}} \\
  190. I\left(P\right) &= \frac{1}{\left|P\right|}\sum_{p\in P}{\left|\left|\vec{p}\right|\right|^2} \\
  191. \delta\left(P\right) &= \left|\left| \vec{q} - \vec{\mu}\left(P\right) \right|\right| \\
  192. \end{aligned}
  193. `,
  194. "angle-definition": String.raw`
  195. \begin{aligned}
  196. \theta\left(P\right) &= \angle \left(\vec{q}, \vec{\mu}\left(P\right)\right) \\
  197. \vec{x}_{\perp} &= \text{oproj}_{\left\{\vec{J}, \vec{L}\right\}}{\vec{x}} \\
  198. \phi\left(P\right) &= \angle \left(\vec{q}_{\perp}, \vec{\mu}\left(P\right)_{\perp} \right)
  199. \end{aligned}
  200. `,
  201. "rms-definition": String.raw`
  202. \sigma\left(P\right) = \sqrt{E\left[\left(\vec{q} - P\right)^2\right]} = \sqrt{\frac{1}{|P|}\sum_{p \in P}{\left|\left|\vec{p} - \vec{q}\right|\right|^2}}
  203. `,
  204. "cluster-definition": String.raw`
  205. \begin{aligned}
  206. \left\{P_1, P_2, P_3\right\} &= ${mathArgBest("max", String.raw`\left\{P_1, P_2, P_3\right\}`)} \sum_{i=1}^3 \sum_{p\inP_i} \left|\left| \vec{p} - \vec{\mu}\left(P_i\right) \right|\right|^2 \\
  207. \pi_i &= \frac{\left|P_i\right|}{\left|P\right|} \\
  208. M\left(P\right) &= ${mathArgBest("max", "P_i")} \left( \left|P_i\right| \right) \\
  209. m\left(P\right) &= ${mathArgBest("min", "P_i")} \left( \left|P_i\right| \right) \\
  210. \alpha\left(P\right) &= ${mathArgBest("min", "P_i")} \left[ \frac{1}{\pi_i} \left|\left| \vec{q} - \vec{\mu}\left(P_i\right) \right|\right| \right] \\
  211. \omega\left(P\right) &= ${mathArgBest("max", "P_i")} \left[ \frac{1}{\pi_i} \left|\left| \vec{q} - \vec{\mu}\left(P_i\right) \right|\right| \right]
  212. \end{aligned}
  213. `,
  214. };
  215. const includeScaleFactor = () => state.clusterChoice > 0 && state.includeScale
  216. const metricText = [
  217. muArg => String.raw`
  218. ${mathArgBest("min", "P")}\left[
  219. ${includeScaleFactor() ? String.raw`\frac{\left|P\right|}{\left|${muArg}\right|}\left(` : ""}
  220. I\left(P\right) - 2\vec{q}\cdot \vec{\mu}\left(${muArg}\right)
  221. ${includeScaleFactor() ? String.raw`\right)` : ""}
  222. \right]`,
  223. muArg => String.raw`${mathArgBest("min", "P")}\left[-${includeScaleFactor() ? String.raw`\frac{\left|${muArg}\right|}{\left|P\right|}` : ""}\cos\left(\angle \left(\vec{q}, \vec{\mu}\left(${muArg}\right)\right)\right)\right]`,
  224. muArg => String.raw`${mathArgBest("min", "P")}\left[${includeScaleFactor() ? String.raw`\frac{\left|P\right|}{\left|${muArg}\right|}` : ""}\left|\left| \vec{q} - \vec{\mu}\left(${muArg}\right) \right|\right|^2\right]`,
  225. muArg => String.raw`${mathArgBest("min", "P")}\left[${includeScaleFactor() ? String.raw`\frac{\left|P\right|}{\left|${muArg}\right|}` : ""}\angle \left(\vec{q}_{\perp}, \vec{\mu}\left(${muArg}\right)_{\perp} \right)\right]`,
  226. muArg => String.raw`${mathArgBest("min", "P")}\left[-${includeScaleFactor() ? String.raw`\frac{\left|${muArg}\right|}{\left|P\right|}` : ""}I\left(P\right)\right]`,
  227. ].map(s => muArg => TeXZilla.toMathML(s(muArg)));
  228. const muArgs = [
  229. "P",
  230. String.raw`M\left(P\right)`,
  231. String.raw`m\left(P\right)`,
  232. String.raw`\alpha\left(P\right)`,
  233. String.raw`\omega\left(P\right)`,
  234. ];
  235. const renderVec = math => String.raw`\vec{${math.charAt(0)}}${math.substr(1)}`;
  236. const renderNorm = vec => String.raw`\frac{${vec}}{\left|\left|${vec}\right|\right|}`;
  237. const updateObjective = () => {
  238. const muArg = muArgs[state.clusterChoice];
  239. let tex = metricText?.[state.metric]?.(muArg);
  240. if (!tex) {
  241. const { includeX, normQY, closeCoeff } = state;
  242. if (!includeX && closeCoeff === 0) {
  243. tex = TeXZilla.toMathML(String.raw`\text{Malamar-ness}`);
  244. } else {
  245. const qyMod = normQY ? renderNorm : c => c;
  246. tex = TeXZilla.toMathML(String.raw`
  247. ${mathArgBest("min", "P")}
  248. \left[
  249. ${includeX ? String.raw`I\left(P\right)` : ""}
  250. ${closeCoeff === 0 ? "" : String.raw`
  251. -
  252. ${closeCoeff}
  253. ${qyMod("\\vec{q}")}
  254. \cdot
  255. ${qyMod(String.raw`\vec{\mu}\left(${muArg}\right)`)}
  256. `}
  257. \right]
  258. `);
  259. }
  260. }
  261. const objFnNode = getObjFnDisplay();
  262. clearNodeContents(objFnNode);
  263. objFnNode.appendChild(tex);
  264. };
  265. // Pokemon Rendering
  266. const stripForm = ["flabebe", "floette", "florges", "vivillon", "basculin", "furfrou", "magearna"];
  267. const getSprite = pokemon => {
  268. pokemon = pokemon
  269. .replace("-alola", "-alolan")
  270. .replace("-galar", "-galarian")
  271. .replace("darmanitan-galarian", "darmanitan-galarian-standard");
  272. if (stripForm.find(s => pokemon.includes(s))) {
  273. pokemon = pokemon.replace(/-.*$/, "");
  274. }
  275. return `https://img.pokemondb.net/sprites/sword-shield/icon/${pokemon}.png`;
  276. };
  277. // TODO make the M m alpha omega labels more visible
  278. const renderCluster = ({
  279. index, big, small, best, worst, pi, theta, delta, phi, hex, vector,
  280. }) => `
  281. <div
  282. class="pkmn_tile-cluster"
  283. style="grid-area: k${index + 1}; color: ${getContrastingTextColor(hex2rgb(hex))}; background-color: ${hex};"
  284. >
  285. <div class="pkmn_tile-cluster-top_label" style="grid-area: bigm;">${index === big ? "M" : ""}</div>
  286. <div class="pkmn_tile-cluster-top_label" style="grid-area: litm;">${index === small ? "m" : ""}</div>
  287. <div class="pkmn_tile-cluster-top_label" style="grid-area: alp;">${index === best ? "α" : ""}</div>
  288. <div class="pkmn_tile-cluster-top_label " style="grid-area: omg;">${index === worst ? "ω" : ""}</div>
  289. <div class="pkmn_tile-cluster-stat_label" style="grid-area: mu;">μ =</div>
  290. <div class="pkmn_tile-cluster-stat_label" style="grid-area: pi;">π =</div>
  291. <div class="pkmn_tile-cluster-stat_label" style="grid-area: th;">θ =</div>
  292. <div class="pkmn_tile-cluster-stat_label" style="grid-area: dl;">δ =</div>
  293. <div class="pkmn_tile-cluster-stat_label" style="grid-area: ph;">ϕ =</div>
  294. <div style="grid-area: mux">${hex}</div>
  295. <div style="grid-area: muv; justify-self: center;">(${vector.map(c => c.toFixed(2)).join(", ")})</div>
  296. <div style="grid-area: piv">${(pi * 100).toFixed(1)}%</div>
  297. <div style="grid-area: thv">${theta.toFixed(2)}°</div>
  298. <div style="grid-area: dlv">${delta.toFixed(2)}</div>
  299. <div style="grid-area: phv">${phi.toFixed(2)}°</div>
  300. </div>
  301. `;
  302. const getPokemonRenderer = targetList => (name, stats, q, score, idPostfix) => {
  303. let sigma, metrics, kMeanInfo, kMeanResults;
  304. if (q) {
  305. sigma = Math.sqrt(stats.inertia - 2 * vectorDot(stats.trueMean.vector, q.vector) + q.magSq)
  306. metrics = calcDisplayMetrics(stats.trueMean, q)
  307. kMeanInfo = {
  308. big: stats.largestCluster,
  309. small: stats.smallestCluster,
  310. best: getBestKMean(stats, q),
  311. worst: getWorstKMean(stats, q), // TODO yeah yeah this is a recalc whatever
  312. };
  313. kMeanResults = stats.kMeans.map(k => calcDisplayMetrics(k, q));
  314. } else {
  315. // no target color, just do all zeros
  316. sigma = 0;
  317. metrics = { theta: 0, delta: 0, phi: 0 };
  318. kMeanInfo = { big: 0, small: 0, best: 0, worst: 0 };
  319. kMeanResults = [ metrics, metrics, metrics ];
  320. }
  321. const clusterToggleId = `reveal_clusters-${name}-${idPostfix}`;
  322. const li = document.createElement("li");
  323. li.innerHTML = `
  324. <div class="pkmn_tile">
  325. <img class="pkmn_tile-img" src="${getSprite(name)}" />
  326. <span class="pkmn_tile-name">
  327. ${name.split("-").map(part => part.charAt(0).toUpperCase() + part.substr(1)).join(" ")}
  328. </span>
  329. <div class="pkmn_tile-fn">
  330. ${score.toFixed(3)}
  331. </div>
  332. <input
  333. type="checkbox"
  334. ${state.clusterToggles?.[clusterToggleId] ? "checked" : ""}
  335. id="${clusterToggleId}"
  336. onchange="state.clusterToggles['${clusterToggleId}'] = event.target.checked"
  337. class="pkmn_tile-reveal_clusters"
  338. role="button"
  339. >
  340. <label class="pkmn_tile-reveal_clusters_label" for="${clusterToggleId}">
  341. <div class="pkmn_tile-reveal_clusters_label--closed">►</div>
  342. <div class="pkmn_tile-reveal_clusters_label--open">▼</div>
  343. </label>
  344. <div
  345. class="pkmn_tile-true_mean"
  346. style="color: ${getContrastingTextColor(hex2rgb(stats.trueMean.hex))}; background-color: ${stats.trueMean.hex};"
  347. >
  348. <div class="pkmn_tile-true_mean-value">
  349. <div class="pkmn_tile-true_mean-mu_label">μ =</div>
  350. <div class="pkmn_tile-true_mean-mu_hex">${stats.trueMean.hex}</div>
  351. <div class="pkmn_tile-true_mean-mu_vec">
  352. (${stats.trueMean.vector.map(c => c.toFixed(2)).join(", ")})
  353. </div>
  354. </div>
  355. <div class="pkmn_tile-true_mean-stat pkmn_tile-true_mean-inertia">
  356. 𝖨 = ${stats.inertia.toFixed(2)}
  357. </div>
  358. <div class="pkmn_tile-true_mean-stat pkmn_tile-true_mean-stat-sigma">
  359. σ = ${sigma.toFixed(2)}
  360. </div>
  361. <div class="pkmn_tile-true_mean-stat pkmn_tile-true_mean-stat-theta">
  362. θ = ${metrics.theta.toFixed(2)}°
  363. </div>
  364. <div class="pkmn_tile-true_mean-stat pkmn_tile-true_mean-stat-delta">
  365. δ = ${metrics.delta.toFixed(2)}
  366. </div>
  367. <div class="pkmn_tile-true_mean-stat pkmn_tile-true_mean-stat-phi">
  368. ϕ = ${metrics.phi.toFixed(2)}°
  369. </div>
  370. </div>
  371. ${stats.kMeans.map((data, index) => renderCluster({
  372. index,
  373. ...kMeanInfo,
  374. pi: stats.kWeights[index],
  375. ...kMeanResults[index],
  376. hex: data.hex,
  377. vector: data.vector,
  378. })).join("\n")}
  379. </div>
  380. `;
  381. targetList.appendChild(li);
  382. };
  383. // Update Search Results
  384. const renderSearch = () => {
  385. const resultsNode = getSearchListNode();
  386. const append = getPokemonRenderer(resultsNode);
  387. clearNodeContents(resultsNode);
  388. const argMapper = state.searchSpace === "RGB"
  389. ? pkmn => [pkmn.rgbStats, state.targetColor?.rgbData, state.targetColor ? scorePokemon(pkmn).rgb : 0]
  390. : pkmn => [pkmn.jabStats, state.targetColor?.jabData, state.targetColor ? scorePokemon(pkmn).jab : 0]
  391. state.searchResults?.forEach(pkmn => append(
  392. pkmn.name, ...argMapper(pkmn), "search"
  393. ));
  394. };
  395. // Scoring
  396. const rescore = () => {
  397. if (!state.targetColor) {
  398. return;
  399. }
  400. // TODO might like to save this somewhere instead of recomputing when limit changes
  401. const scores = pokemonColorData.map(data => ({ ...data, scores: scorePokemon(data) }));
  402. const jabList = getScoreListJABNode();
  403. const appendJAB = getPokemonRenderer(jabList);
  404. const rgbList = getScoreListRGBNode();
  405. const appendRGB = getPokemonRenderer(rgbList);
  406. // extract best CIECAM02 results
  407. const bestJAB = scores
  408. .sort((a, b) => a.scores.jab - b.scores.jab)
  409. .slice(0, state.numPoke);
  410. clearNodeContents(jabList);
  411. bestJAB.forEach(data => appendJAB(
  412. data.name, data.jabStats, state.targetColor.jabData, data.scores.jab, "jab"
  413. ));
  414. // extract best RGB results
  415. const bestRGB = scores
  416. .sort((a, b) => a.scores.rgb - b.scores.rgb)
  417. .slice(0, state.numPoke);
  418. clearNodeContents(rgbList);
  419. bestRGB.forEach(data => appendRGB(
  420. data.name, data.rgbStats, state.targetColor.rgbData, data.scores.rgb, "rgb"
  421. ));
  422. // update the rendered search results as well
  423. renderSearch();
  424. };
  425. // Listeners
  426. const onColorChanged = skipScore => {
  427. const readColor = readColorInput();
  428. if (readColor) {
  429. state.targetColor = readColor;
  430. renderQVec(state.targetColor.jabData.vector.map(c => c.toFixed(3)), getQJABDisplay(), "Jab");
  431. renderQVec(state.targetColor.rgbData.vector.map(c => c.toFixed()), getQRGBDisplay(), "RGB");
  432. const rootElem = document.querySelector(":root");
  433. rootElem.style.setProperty("--background", state.targetColor.rgbData.hex);
  434. rootElem.style.setProperty("--highlight", getContrastingTextColor(state.targetColor.rgbData.vector));
  435. if (!skipScore) {
  436. rescore();
  437. }
  438. }
  439. };
  440. const onRandomColor = () => {
  441. const color = [Math.random(), Math.random(), Math.random()].map(c => c * 255);
  442. getColorInputNode().value = d3.rgb(...color).formatHex();
  443. onColorChanged(); // triggers rescore
  444. };
  445. const onCustomControlsChanged = skipScore => {
  446. state.includeX = getIncludeXToggleNode()?.checked ?? false;
  447. state.normQY = getNormQYToggleNode()?.checked ?? false;
  448. state.closeCoeff = parseFloat(getCloseCoeffSliderNode()?.value ?? 2);
  449. getCloseCoeffDisplayNode().innerHTML = state.closeCoeff;
  450. updateObjective();
  451. if (!skipScore) {
  452. rescore();
  453. }
  454. }
  455. const checkClusterMeanWarning = () => {
  456. const warning = getClusterMeanWarning();
  457. const unhidden = warning.getAttribute("class").replaceAll("hide", "");
  458. if (state.clusterChoice !== 0 && (state.metric === 0 || state.metric === 4)) {
  459. warning.setAttribute("class", unhidden);
  460. } else {
  461. warning.setAttribute("class", unhidden + " hide");
  462. }
  463. }
  464. const checkScaleByClusterToggle = () => {
  465. const toggle = getClusterScaleToggleNode()?.parentNode;
  466. const unhidden = toggle.getAttribute("class").replaceAll("hide", "");
  467. if (state.clusterChoice !== 0) {
  468. toggle.setAttribute("class", unhidden);
  469. } else {
  470. toggle.setAttribute("class", unhidden + " hide");
  471. }
  472. }
  473. const onScaleByClusterChanged = skipScore => {
  474. state.includeScale = getClusterScaleToggleNode()?.checked ?? true;
  475. updateObjective();
  476. if (!skipScore) {
  477. rescore();
  478. }
  479. }
  480. const onClusterChoiceChanged = skipScore => {
  481. const clusterChoice = getClusterChoiceDropdownNode()?.selectedIndex ?? 0;
  482. if (clusterChoice === state.clusterChoice) {
  483. return;
  484. }
  485. state.clusterChoice = clusterChoice;
  486. checkClusterMeanWarning();
  487. checkScaleByClusterToggle();
  488. updateObjective();
  489. if (!skipScore) {
  490. rescore();
  491. }
  492. }
  493. const onMetricChanged = skipScore => {
  494. const metric = getMetricDropdownNode()?.selectedIndex ?? 0;
  495. if (metric === state.metric) {
  496. return;
  497. }
  498. state.metric = metric;
  499. checkClusterMeanWarning();
  500. checkScaleByClusterToggle();
  501. if (state.metric === 5) { // Custom
  502. showCustomControls();
  503. onCustomControlsChanged(skipScore); // triggers rescore
  504. } else {
  505. hideCustomControls();
  506. updateObjective();
  507. if (!skipScore) {
  508. rescore();
  509. }
  510. }
  511. };
  512. const onLimitChanged = skipScore => {
  513. state.numPoke = parseInt(getLimitSliderNode()?.value ?? 10);
  514. getLimitDisplayNode().textContent = state.numPoke;
  515. if (!skipScore) {
  516. // TODO don't need to rescore just need to expand
  517. rescore();
  518. }
  519. };
  520. const onSearchChanged = () => {
  521. state.searchTerm = getNameInputNode()?.value?.toLowerCase() ?? "";
  522. if (state.searchTerm.length === 0) {
  523. state.searchResults = [];
  524. } else {
  525. state.searchResults = pokemonLookup
  526. .search(state.searchTerm, { limit: 10 })
  527. .map(({ item }) => item);
  528. }
  529. renderSearch();
  530. };
  531. const onSearchSpaceChanged = () => {
  532. const old = state.searchSpace ?? "Jab";
  533. state.searchSpace = old === "RGB" ? "Jab" : "RGB";
  534. getSearchSpaceDisplayNode().textContent = old;
  535. renderSearch();
  536. };
  537. const onRandomPokemon = () => {
  538. getNameInputNode().value = "";
  539. state.searchResults = Array.from({ length: 10 }, () => pokemonColorData[Math.floor(Math.random() * pokemonColorData.length)]);
  540. renderSearch();
  541. };
  542. const onPageLoad = () => {
  543. // render static explanations
  544. Object.entries(mathDefinitions).forEach(([id, tex]) => {
  545. document.getElementById(id)?.appendChild(TeXZilla.toMathML(tex));
  546. });
  547. // fake some events but don't do any scoring
  548. onColorChanged(true);
  549. onMetricChanged(true);
  550. onClusterChoiceChanged(true);
  551. onScaleByClusterChanged(true);
  552. onLimitChanged(true);
  553. // then do a rescore directly, which will do nothing unless old data was loaded
  554. rescore();
  555. // finally render search in case rescore didn't
  556. onSearchChanged();
  557. };