convert.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. const jab2hex = jab => d3.jab(...jab).formatHex();
  2. const rgb2hex = rgb => d3.rgb(...rgb).formatHex();
  3. const jab2hue = jab => d3.jch(d3.jab(...jab)).h || 0;
  4. const rgb2hue = rgb => d3.hsl(d3.rgb(...rgb)).h || 0;
  5. const jab2lit = ([j]) => j / 100;
  6. const rgb2lit = rgb => d3.hsl(d3.rgb(...rgb)).l || 0;
  7. const jab2chroma = jab => d3.jch(d3.jab(...jab)).C / 100;
  8. const rgb2chroma = rgb => d3.jch(d3.rgb(...rgb)).C / 100;
  9. const buildVectorData = (vector, toHue, toLightness, toChroma, toHex) => {
  10. const sqMag = vectorDot(vector, vector);
  11. const mag = Math.sqrt(sqMag);
  12. const unit = vector.map(c => c / mag);
  13. const hue = toHue(vector);
  14. const lightness = toLightness(vector);
  15. const chroma = toChroma(vector);
  16. const hex = toHex(vector);
  17. return { vector, sqMag, mag, unit, hue, lightness, chroma, hex };
  18. };
  19. const calcImportance = (chroma, lightness, proportion) =>
  20. chroma // used linearly
  21. - Math.abs((lightness / 0.75) - 1) // reduce contribution for overly light color - probably a highlight
  22. + 0.5 * Math.tanh(10 * (proportion - 0.25)) // steep ramp centered around 25%
  23. const buildClusterData = (size, inertia, mu1, mu2, mu3, nu1, nu2, nu3, totalSize, toHue, toLightness, toChroma, toHex) => {
  24. const mu = buildVectorData([mu1, mu2, mu3], toHue, toLightness, toChroma, toHex);
  25. const nu = [nu1, nu2, nu3];
  26. const proportion = size / totalSize;
  27. const importance = calcImportance(mu.chroma, mu.lightness, proportion);
  28. return {
  29. size, inertia, mu, nu,
  30. proportion, importance,
  31. muNuAngle: rad2deg * Math.acos(vectorDot(mu.unit, nu) / vectorMag(nu)),
  32. };
  33. };
  34. const buildPokemonData = ([name, size, ...values]) => ({
  35. name,
  36. jab: {
  37. total: buildClusterData(size, ...values.slice(0, 7), size, jab2hue, jab2lit, jab2chroma, jab2hex),
  38. clusters: [
  39. buildClusterData(...values.slice(7, 15), size, jab2hue, jab2lit, jab2chroma, jab2hex),
  40. buildClusterData(...values.slice(15, 23), size, jab2hue, jab2lit, jab2chroma, jab2hex),
  41. buildClusterData(...values.slice(23, 31), size, jab2hue, jab2lit, jab2chroma, jab2hex),
  42. ],
  43. },
  44. rgb: {
  45. total: buildClusterData(size, ...values.slice(31, 38), size, rgb2hue, rgb2lit, rgb2chroma, rgb2hex),
  46. clusters: [
  47. buildClusterData(...values.slice(38, 46), size, rgb2hue, rgb2lit, rgb2chroma, rgb2hex),
  48. buildClusterData(...values.slice(46, 54), size, rgb2hue, rgb2lit, rgb2chroma, rgb2hex),
  49. buildClusterData(...values.slice(54, 62), size, rgb2hue, rgb2lit, rgb2chroma, rgb2hex),
  50. ],
  51. },
  52. });
  53. const pokemonData = databaseV2.map(row => buildPokemonData(row));