nearest.js 15 KB

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