nearest.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  1. // Selectors + DOM Manipulation
  2. const getColorInputNode = () => document.getElementById("color-input");
  3. const getMetricDropdownNode = () => document.getElementById("metric");
  4. const getIncludeXToggleNode = () => document.getElementById("include-x");
  5. const getNormQYToggleNode = () => document.getElementById("norm-q-y");
  6. const getCloseCoeffSliderNode = () => document.getElementById("close-coeff");
  7. const getCloseCoeffDisplayNode = () => document.getElementById("close-coeff-display");
  8. const getLimitSliderNode = () => document.getElementById("num-poke");
  9. const getLimitDisplayNode = () => document.getElementById("num-poke-display");
  10. const getNameInputNode = () => document.getElementById("pokemon-name");
  11. const getScoreListJABNode = () => document.getElementById("best-list-jab");
  12. const getScoreListRGBNode = () => document.getElementById("best-list-rgb");
  13. const getSearchListNode = () => document.getElementById("search-list");
  14. const getHideableControlNodes = () => document.querySelectorAll(".hideable_control");
  15. const getQJABDisplay = () => document.getElementById("q-vec-jab");
  16. const getQRGBDisplay = () => document.getElementById("q-vec-rgb");
  17. const getObjFnDisplay = () => document.getElementById("obj-fn");
  18. const clearNodeContents = node => { node.innerHTML = ""; };
  19. const hideCustomControls = () => getHideableControlNodes()
  20. .forEach(n => n.setAttribute("class", "hideable_control hideable_control--hidden"));
  21. const showCustomControls = () => getHideableControlNodes()
  22. .forEach(n => n.setAttribute("class", "hideable_control"));
  23. // Vector Math
  24. const vectorDot = (u, v) => u.map((x, i) => x * v[i]).reduce((x, y) => x + y);
  25. const vectorSqMag = v => vectorDot(v, v);
  26. const vectorMag = v => Math.sqrt(vectorSqMag(v));
  27. const vectorSqDist = (u, v) => vectorSqMag(u.map((x, i) => x - v[i]));
  28. const vectorDist = (u, v) => Math.sqrt(vectorSqDist(u, v));
  29. const vectorNorm = v => { const n = vectorMag(v); return [ n, v.map(c => c / n) ]; };
  30. // Angle Math
  31. const angleDiff = (a, b) => { const raw = Math.abs(a - b); return raw < 180 ? raw : (360 - raw); };
  32. const rad2deg = 180 / Math.PI;
  33. // Pre-Compute Y Data
  34. const pokemonColorData = database.map(data => {
  35. const yRGBColor = d3.rgb(...data.yRGB);
  36. const [ yJABNorm, yJABHat ] = vectorNorm(data.yJAB);
  37. const [ yRGBNorm, yRGBHat ] = vectorNorm(data.yRGB);
  38. return {
  39. ...data,
  40. yJABHex: d3.jab(...data.yJAB).formatHex(),
  41. yJABNorm, yJABHat,
  42. yRGBHex: yRGBColor.formatHex(),
  43. yRGBNorm, yRGBHat,
  44. yHueAngleJAB: rad2deg * Math.atan2(data.yJAB[2], data.yJAB[1]),
  45. yHueAngleRGB: d3.hsl(yRGBColor).h,
  46. }
  47. });
  48. const pokemonLookup = new Fuse(pokemonColorData, { keys: [ "name" ] });
  49. // Color Calculations
  50. const getContrastingTextColor = rgb => vectorDot(rgb, [0.3, 0.6, 0.1]) >= 128 ? "#222" : "#ddd";
  51. const readColorInput = () => {
  52. const colorInput = "#" + (getColorInputNode()?.value?.replace("#", "") ?? "FFFFFF");
  53. if (colorInput.length !== 7) {
  54. return;
  55. }
  56. const rgb = d3.color(colorInput);
  57. const { J, a, b } = d3.jab(rgb);
  58. const qJAB = [ J, a, b ];
  59. const qRGB = [ rgb.r, rgb.g, rgb.b ];
  60. const [ qJABNorm, qJABHat ] = vectorNorm(qJAB);
  61. const qJABNormSq = qJABNorm * qJABNorm;
  62. const [ qRGBNorm, qRGBHat ] = vectorNorm(qRGB);
  63. const qRGBNormSq = qRGBNorm * qRGBNorm;
  64. return {
  65. qHex: rgb.formatHex(),
  66. qJAB, qJABHat, qJABNorm, qJABNormSq,
  67. qRGB, qRGBHat, qRGBNorm, qRGBNormSq,
  68. qHueAngleJAB: rad2deg * Math.atan2(b, a),
  69. qHueAngleRGB: d3.hsl(rgb).h,
  70. };
  71. };
  72. // State
  73. const state = {
  74. metric: null,
  75. includeX: null,
  76. normQY: null,
  77. closeCoeff: null,
  78. numPoke: null,
  79. searchTerm: null,
  80. targetColor: null,
  81. searchResults: null,
  82. };
  83. // Metrics
  84. const scoringMetrics = [
  85. ({ xJAB, xRGB, yJAB, yRGB }) => [
  86. xJAB - 2 * vectorDot(yJAB, state.targetColor.qJAB),
  87. xRGB - 2 * vectorDot(yRGB, state.targetColor.qRGB),
  88. ],
  89. ({ yJABHat, yRGBHat }) => [
  90. -vectorDot(yJABHat, state.targetColor.qJABHat),
  91. -vectorDot(yRGBHat, state.targetColor.qRGBHat),
  92. ],
  93. ({ yJAB, yRGB }) => [
  94. vectorSqDist(state.targetColor.qJAB, yJAB),
  95. vectorSqDist(state.targetColor.qRGB, yRGB),
  96. ],
  97. ({ yHueAngleJAB, yHueAngleRGB }) => [
  98. angleDiff(state.targetColor.qHueAngleJAB, yHueAngleJAB),
  99. angleDiff(state.targetColor.qHueAngleRGB, yHueAngleRGB),
  100. ],
  101. ({ xJAB, xRGB, yJAB, yRGB, yJABHat, yRGBHat }) => [
  102. (state.includeX ? xJAB : 0) - state.closeCoeff * vectorDot(
  103. state.normQY ? yJABHat : yJAB,
  104. state.normQY ? state.targetColor.qJABHat : state.targetColor.qJAB
  105. ),
  106. (state.includeX ? xRGB : 0) - state.closeCoeff * vectorDot(
  107. state.normQY ? yRGBHat : yRGB,
  108. state.normQY ? state.targetColor.qRGBHat : state.targetColor.qRGB
  109. ),
  110. ]
  111. ];
  112. const calcDisplayMetrics = ({
  113. xJAB, xRGB, yJAB, yRGB, yJABHat, yJABNorm, yRGBHat, yRGBNorm, yHueAngleJAB, yHueAngleRGB,
  114. }) => {
  115. // TODO - case on state.metric to avoid recalculation of subterms?
  116. const cosAngleJAB = vectorDot(state.targetColor.qJABHat, yJABHat);
  117. const yTermJAB = cosAngleJAB * yJABNorm * state.targetColor.qJABNorm;
  118. const cosAngleRGB = vectorDot(state.targetColor.qRGBHat, yRGBHat);
  119. const yTermRGB = cosAngleRGB * yRGBNorm * state.targetColor.qRGBNorm;
  120. return {
  121. stdDevRGB: Math.sqrt(xRGB - 2 * yTermRGB + state.targetColor.qRGBNormSq),
  122. stdDevJAB: Math.sqrt(xJAB - 2 * yTermJAB + state.targetColor.qJABNormSq),
  123. angleJAB: rad2deg * Math.acos(cosAngleJAB),
  124. angleRGB: rad2deg * Math.acos(cosAngleRGB),
  125. meanDistJAB: vectorDist(state.targetColor.qJAB, yJAB),
  126. meanDistRGB: vectorDist(state.targetColor.qRGB, yRGB),
  127. hueAngleJAB: angleDiff(state.targetColor.qHueAngleJAB, yHueAngleJAB),
  128. hueAngleRGB: angleDiff(state.targetColor.qHueAngleRGB, yHueAngleRGB),
  129. };
  130. };
  131. // Math Rendering
  132. const renderQVec = (q, node, sub) => {
  133. node.innerHTML = TeXZilla.toMathMLString(String.raw`\vec{q}_{\text{${sub}}} = \left(\text{${q.join(", ")}}\right)`);
  134. };
  135. const mathDefinitions = {
  136. "x-definition": String.raw`
  137. X\left(P\right) = \frac{1}{\left|P\right|}\sum_{p\in P}{\left|\left|\vec{p}\right|\right|^2}
  138. `,
  139. "y-definition": String.raw`
  140. \vec{Y}\left(P\right) = \frac{1}{\left|P\right|}\sum_{p\in P}{\vec{p}}
  141. `,
  142. "v-perp-definition": String.raw`
  143. \vec{v}_{\perp} = \text{oproj}_{\left\{\vec{J}, \vec{L}\right\}}{\vec{v}}
  144. `,
  145. "del-h-definition": String.raw`
  146. \Delta{H} = \angle \left(\vec{q}_{\perp}, \vec{Y}_{\perp}\left(P\right) \right)
  147. `,
  148. "cluster-definition": String.raw`
  149. \left\{P_1, P_2, P_3\right\} = \arg\min_{\left\{P_1, P_2, P_3\right\}} \sum_{i=1}^3 \sum_{p\inP_i} \left|\left| \vec{p} - \vec{Y}\left(P_i\right) \right|\right|^2
  150. `,
  151. "z-best-definition": String.raw`
  152. \vec{Z}_{\text{best}}\left(P\right) = \vec{Y}\left(\arg\min_{P_i} \left|\left| \vec{q} - \vec{Y}\left(P_i\right) \right|\right| \right)
  153. `,
  154. "z-worst-definition": String.raw`
  155. \vec{Z}_{\text{worst}}\left(P\right) = \vec{Y}\left(\arg\max_{P_i} \left|\left| \vec{q} - \vec{Y}\left(P_i\right) \right|\right| \right)
  156. `,
  157. "result-definition": String.raw`
  158. \left(
  159. \text{RMS}_P\left(q\right),
  160. \angle \left(\vec{q}, \vec{Y}\left(P\right)\right),
  161. \left|\left| \vec{q} - \vec{Y}\left(P\right) \right|\right|,
  162. \Delta{H}
  163. \right)
  164. `,
  165. };
  166. const metricText = [
  167. String.raw`\text{RMS}_{P}\left(q\right) ~ \arg\min_{P}\left[X\left(P\right) - 2\vec{q}\cdot \vec{Y}\left(P\right)\right]`,
  168. String.raw`\angle \left(\vec{q}, \vec{Y}\left(P\right)\right) ~ \arg\max_{P}\left[\cos\left(\angle \left(\vec{q}, \vec{Y}\left(P\right)\right)\right)\right]`,
  169. String.raw`\left|\left| \vec{q} - \vec{Y}\left(P\right) \right|\right| ~ \arg\min_{P}\left[\left|\left| \vec{q} - \vec{Y}\left(P\right) \right|\right|^2\right]`,
  170. String.raw`\Delta{H}`,
  171. ].map(s => TeXZilla.toMathML(s));
  172. const renderVec = math => String.raw`\vec{${math.charAt(0)}}${math.substr(1)}`;
  173. const renderNorm = vec => String.raw`\frac{${vec}}{\left|\left|${vec}\right|\right|}`;
  174. const updateObjective = () => {
  175. let tex = metricText?.[state.metric];
  176. if (!tex) {
  177. const { includeX, normQY, closeCoeff } = state;
  178. if (!includeX && closeCoeff === 0) {
  179. tex = TeXZilla.toMathML(String.raw`\text{Empty Metric}`);
  180. } else {
  181. const qyMod = normQY ? c => renderNorm(renderVec(c)) : renderVec;
  182. tex = TeXZilla.toMathML(String.raw`
  183. \arg
  184. \m${includeX ? "in" : "ax"}_{P}
  185. \left[
  186. ${includeX ? String.raw`X\left(P\right)` : ""}
  187. ${closeCoeff === 0 ? "" : String.raw`
  188. ${includeX ? "-" : ""}
  189. ${(includeX && closeCoeff !== 1) ? closeCoeff : ""}
  190. ${qyMod("q")}
  191. \cdot
  192. ${qyMod(String.raw`Y\left(P\right)`)}
  193. `}
  194. \right]
  195. `);
  196. }
  197. }
  198. const objFnNode = getObjFnDisplay();
  199. clearNodeContents(objFnNode);
  200. objFnNode.appendChild(tex);
  201. };
  202. // Pokemon Rendering
  203. const stripForm = ["flabebe", "floette", "florges", "vivillon", "basculin", "furfrou", "magearna"];
  204. const getSprite = pokemon => {
  205. pokemon = pokemon
  206. .replace("-alola", "-alolan")
  207. .replace("-galar", "-galarian")
  208. .replace("darmanitan-galarian", "darmanitan-galarian-standard");
  209. if (stripForm.find(s => pokemon.includes(s))) {
  210. pokemon = pokemon.replace(/-.*$/, "");
  211. }
  212. return `https://img.pokemondb.net/sprites/sword-shield/icon/${pokemon}.png`;
  213. };
  214. const renderPokemon = (data, classes = {}) => {
  215. const { name, yJAB, yJABHex, yRGB, yRGBHex } = data;
  216. const { labelClass = "", rgbClass = "", jabClass = "", tileClass = "" } = classes;
  217. let { resultsClass = "" } = classes;
  218. let displayMetrics = {};
  219. if (!state.targetColor) {
  220. // no color selected need to skip scores
  221. resultsClass = "hide";
  222. } else {
  223. displayMetrics = calcDisplayMetrics(data);
  224. }
  225. const {
  226. stdDevJAB = 0, stdDevRGB = 0,
  227. angleJAB = 0, angleRGB = 0,
  228. meanDistJAB = 0, meanDistRGB,
  229. hueAngleJAB = 0, hueAngleRGB = 0,
  230. } = displayMetrics;
  231. const titleName = name.split("-").map(part => part.charAt(0).toUpperCase() + part.substr(1)).join(" ");
  232. const textHex = getContrastingTextColor(yRGB);
  233. const rgbVec = yRGB.map(c => c.toFixed()).join(", ");
  234. const jabVec = yJAB.map(c => c.toFixed(1)).join(", ");
  235. const pkmn = document.createElement("div");
  236. pkmn.setAttribute("class", `pokemon_tile ${tileClass}`);
  237. pkmn.innerHTML = `
  238. <div class="pokemon_tile-image-wrapper">
  239. <img src="${getSprite(name)}" />
  240. </div>
  241. <div class="pokemon_tile-info_panel">
  242. <span class="pokemon_tile-pokemon_name">${titleName}</span>
  243. <div class="pokemon_tile-results">
  244. <div class="pokemon_tile-labels ${labelClass}">
  245. <span class="${jabClass}">Jab: </span>
  246. <span class="${rgbClass}">RGB: </span>
  247. </div>
  248. <div class="pokemon_tile-score_column ${resultsClass}">
  249. <span class="${jabClass}">
  250. (${stdDevJAB.toFixed(2)}, ${angleJAB.toFixed(2)}&deg;, ${meanDistJAB.toFixed(2)}, ${hueAngleJAB.toFixed(2)}&deg;)
  251. </span>
  252. <span class="${rgbClass}">
  253. (${stdDevRGB.toFixed(2)}, ${angleRGB.toFixed(2)}&deg;, ${meanDistRGB.toFixed(2)}, ${hueAngleRGB.toFixed(2)}&deg;)
  254. </span>
  255. </div>
  256. <div class="pokemon_tile-hex_column">
  257. <div class="pokemon_tile-hex_color ${jabClass}" style="background-color: ${yJABHex}; color: ${textHex}">
  258. <span>${yJABHex}</span><span class="pokemon_tile-vector">(${jabVec})</span>
  259. </div>
  260. <div class="pokemon_tile-hex_color ${rgbClass}" style="background-color: ${yRGBHex}; color: ${textHex}">
  261. <span>${yRGBHex}</span><span class="pokemon_tile-vector">(${rgbVec})</span>
  262. </div>
  263. </div>
  264. </div>
  265. </div>
  266. `;
  267. return pkmn;
  268. };
  269. const getPokemonAppender = targetList => (pokemonData, classes) => {
  270. const li = document.createElement("li");
  271. li.appendChild(renderPokemon(pokemonData, classes));
  272. targetList.appendChild(li);
  273. };
  274. // Update Search Results
  275. const renderSearch = () => {
  276. const resultsNode = getSearchListNode();
  277. const append = getPokemonAppender(resultsNode);
  278. clearNodeContents(resultsNode);
  279. state.searchResults?.forEach(pkmn => append(pkmn));
  280. };
  281. // Scoring
  282. const rescore = () => {
  283. if (!state.targetColor) {
  284. return;
  285. }
  286. const metricFn = scoringMetrics[state.metric ?? 0];
  287. // TODO might like to save this somewhere instead of recomputing when limit changes
  288. const scores = pokemonColorData.map(data => ({ ...data, scores: metricFn(data) }));
  289. const jabList = getScoreListJABNode();
  290. const appendJAB = getPokemonAppender(jabList);
  291. const rgbList = getScoreListRGBNode();
  292. const appendRGB = getPokemonAppender(rgbList);
  293. // extract best CIECAM02 results
  294. const bestJAB = scores
  295. .sort((a, b) => a.scores[0] - b.scores[0])
  296. .slice(0, state.numPoke);
  297. clearNodeContents(jabList);
  298. bestJAB.forEach(data => appendJAB(data, { labelClass: "hide", rgbClass: "hide", tileClass: "pokemon_tile--smaller" }));
  299. // extract best RGB results
  300. const bestRGB = scores
  301. .sort((a, b) => a.scores[1] - b.scores[1])
  302. .slice(0, state.numPoke);
  303. clearNodeContents(rgbList);
  304. bestRGB.forEach(data => appendRGB(data, { labelClass: "hide", jabClass: "hide", tileClass: "pokemon_tile--smaller" }));
  305. // update the rendered search results as well
  306. renderSearch();
  307. };
  308. // Listeners
  309. const onColorChanged = skipScore => {
  310. const readColor = readColorInput();
  311. if (readColor) {
  312. state.targetColor = readColor;
  313. renderQVec(state.targetColor.qJAB.map(c => c.toFixed(2)), getQJABDisplay(), "Jab");
  314. renderQVec(state.targetColor.qRGB.map(c => c.toFixed()), getQRGBDisplay(), "RGB");
  315. const textColor = getContrastingTextColor(state.targetColor.qRGB);
  316. document.querySelector("body").setAttribute("style", `background: ${state.targetColor.qHex}; color: ${textColor}`);
  317. state.targetColor
  318. if (!skipScore) {
  319. rescore();
  320. }
  321. }
  322. };
  323. const onRandomColor = () => {
  324. const color = [Math.random(), Math.random(), Math.random()].map(c => c * 255);
  325. getColorInputNode().value = d3.rgb(...color).formatHex();
  326. onColorChanged(); // triggers rescore
  327. };
  328. const onCustomControlsChanged = skipScore => {
  329. state.includeX = getIncludeXToggleNode()?.checked ?? false;
  330. state.normQY = getNormQYToggleNode()?.checked ?? false;
  331. state.closeCoeff = parseFloat(getCloseCoeffSliderNode()?.value ?? 2);
  332. getCloseCoeffDisplayNode().innerHTML = state.closeCoeff;
  333. updateObjective();
  334. if (!skipScore) {
  335. rescore();
  336. }
  337. }
  338. const onMetricChanged = skipScore => {
  339. const metric = getMetricDropdownNode()?.selectedIndex ?? 0;
  340. if (metric === state.metric) {
  341. return;
  342. }
  343. state.metric = metric;
  344. if (state.metric === 4) { // Custom
  345. showCustomControls();
  346. onCustomControlsChanged(skipScore); // triggers rescore
  347. } else {
  348. hideCustomControls();
  349. updateObjective();
  350. if (!skipScore) {
  351. rescore();
  352. }
  353. }
  354. };
  355. const onLimitChanged = skipScore => {
  356. state.numPoke = parseInt(getLimitSliderNode()?.value ?? 10);
  357. getLimitDisplayNode().textContent = state.numPoke;
  358. if (!skipScore) {
  359. // TODO don't need to rescore just need to expand
  360. rescore();
  361. }
  362. };
  363. const onSearchChanged = () => {
  364. state.searchTerm = getNameInputNode()?.value?.toLowerCase() ?? "";
  365. if (state.searchTerm.length === 0) {
  366. state.searchResults = [];
  367. } else {
  368. state.searchResults = pokemonLookup
  369. .search(state.searchTerm, { limit: 10 })
  370. .map(({ item }) => item);
  371. }
  372. renderSearch();
  373. };
  374. const onRandomPokemon = () => {
  375. getNameInputNode().value = "";
  376. state.searchResults = Array.from({ length: 10 }, () => pokemonColorData[Math.floor(Math.random() * pokemonColorData.length)]);
  377. renderSearch();
  378. };
  379. const onPageLoad = () => {
  380. // render static explanations
  381. Object.entries(mathDefinitions).forEach(([id, tex]) => {
  382. document.getElementById(id).appendChild(TeXZilla.toMathML(tex));
  383. });
  384. // fake some events but don't do any scoring
  385. onColorChanged(true);
  386. onMetricChanged(true);
  387. onLimitChanged(true);
  388. // then do a rescore directly, which will do nothing unless old data was loaded
  389. rescore();
  390. // finally render search in case rescore didn't
  391. onSearchChanged();
  392. };