distinct.ts 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  1. /**
  2. * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
  3. *
  4. * @author Alexander Rose <alexander.rose@weirdbyte.de>
  5. *
  6. * adapted from https://github.com/internalfx/distinct-colors (ISC License Copyright (c) 2015, InternalFX Inc.)
  7. * which is heavily inspired by http://tools.medialab.sciences-po.fr/iwanthue/
  8. */
  9. import { Lab } from './spaces/lab';
  10. import { Hcl } from './spaces/hcl';
  11. import { deepClone } from '../../mol-util/object';
  12. import { deepEqual } from '../../mol-util';
  13. import { arraySum } from '../../mol-util/array';
  14. import { ParamDefinition as PD } from '../../mol-util/param-definition';
  15. import { ColorNames } from './names';
  16. export const DistinctColorsParams = {
  17. hue: PD.Interval([1, 360], { min: 0, max: 360, step: 1 }),
  18. chroma: PD.Interval([40, 70], { min: 0, max: 100, step: 1 }),
  19. luminance: PD.Interval([15, 85], { min: 0, max: 100, step: 1 }),
  20. clusteringStepCount: PD.Numeric(50, { min: 10, max: 200, step: 1 }, { isHidden: true }),
  21. minSampleCount: PD.Numeric(800, { min: 100, max: 5000, step: 100 }, { isHidden: true })
  22. };
  23. export type DistinctColorsParams = typeof DistinctColorsParams
  24. export type DistinctColorsProps = PD.Values<typeof DistinctColorsParams>
  25. function distance(colorA: Lab, colorB: Lab) {
  26. return Math.sqrt(
  27. Math.pow(Math.abs(colorA[0] - colorB[0]), 2) +
  28. Math.pow(Math.abs(colorA[1] - colorB[1]), 2) +
  29. Math.pow(Math.abs(colorA[2] - colorB[2]), 2)
  30. );
  31. }
  32. const LabTolerance = 2;
  33. const tmpCheckColorHcl = [0, 0, 0] as Hcl;
  34. const tmpCheckColorLab = [0, 0, 0] as Lab;
  35. function checkColor(lab: Lab, props: DistinctColorsProps) {
  36. Lab.toHcl(tmpCheckColorHcl, lab);
  37. // roundtrip to RGB for conversion tolerance testing
  38. Lab.fromColor(tmpCheckColorLab, Lab.toColor(lab));
  39. return (
  40. tmpCheckColorHcl[0] >= props.hue[0] &&
  41. tmpCheckColorHcl[0] <= props.hue[1] &&
  42. tmpCheckColorHcl[1] >= props.chroma[0] &&
  43. tmpCheckColorHcl[1] <= props.chroma[1] &&
  44. tmpCheckColorHcl[2] >= props.luminance[0] &&
  45. tmpCheckColorHcl[2] <= props.luminance[1] &&
  46. tmpCheckColorLab[0] >= (lab[0] - LabTolerance) &&
  47. tmpCheckColorLab[0] <= (lab[0] + LabTolerance) &&
  48. tmpCheckColorLab[1] >= (lab[1] - LabTolerance) &&
  49. tmpCheckColorLab[1] <= (lab[1] + LabTolerance) &&
  50. tmpCheckColorLab[2] >= (lab[2] - LabTolerance) &&
  51. tmpCheckColorLab[2] <= (lab[2] + LabTolerance)
  52. );
  53. }
  54. function sortByContrast(colors: Lab[]) {
  55. const unsortedColors = colors.slice(0);
  56. const sortedColors = [unsortedColors.shift()!];
  57. while (unsortedColors.length > 0) {
  58. const lastColor = sortedColors[sortedColors.length - 1];
  59. let nearest = 0;
  60. let maxDist = Number.MIN_SAFE_INTEGER;
  61. for (let i = 0; i < unsortedColors.length; ++i) {
  62. const dist = distance(lastColor, unsortedColors[i]);
  63. if (dist > maxDist) {
  64. maxDist = dist;
  65. nearest = i;
  66. }
  67. }
  68. sortedColors.push(unsortedColors.splice(nearest, 1)[0]);
  69. }
  70. return sortedColors;
  71. }
  72. function getSamples(count: number, p: DistinctColorsProps) {
  73. const samples = new Map<string, Lab>();
  74. const rangeDivider = Math.cbrt(count) * 1.001;
  75. const hStep = (p.hue[1] - p.hue[0]) / rangeDivider;
  76. const cStep = (p.chroma[1] - p.chroma[0]) / rangeDivider;
  77. const lStep = (p.luminance[1] - p.luminance[0]) / rangeDivider;
  78. for (let h = p.hue[0]; h <= p.hue[1]; h += hStep) {
  79. for (let c = p.chroma[0]; c <= p.chroma[1]; c += cStep) {
  80. for (let l = p.luminance[0]; l <= p.luminance[1]; l += lStep) {
  81. const lab = Lab.fromHcl(Lab(), Hcl.create(h, c, l));
  82. if (checkColor(lab, p)) samples.set(lab.toString(), lab);
  83. }
  84. }
  85. }
  86. return Array.from(samples.values());
  87. }
  88. /**
  89. * Create a list of visually distinct colors
  90. */
  91. export function distinctColors(count: number, props: Partial<DistinctColorsProps> = {}) {
  92. const p = { ...PD.getDefaultValues(DistinctColorsParams), ...props };
  93. if (count <= 0) return [];
  94. const samples = getSamples(Math.max(p.minSampleCount, count * 5), p);
  95. if (samples.length < count) {
  96. console.warn('Not enough samples to generate distinct colors, increase sample count.');
  97. return (new Array(count)).fill(ColorNames.lightgrey);
  98. }
  99. const colors: Lab[] = [];
  100. const zonesProto: (Lab[])[] = [];
  101. const sliceSize = Math.floor(samples.length / count);
  102. for (let i = 0; i < samples.length; i += sliceSize) {
  103. colors.push(samples[i]);
  104. zonesProto.push([]);
  105. if (colors.length >= count) break;
  106. }
  107. for (let step = 1; step <= p.clusteringStepCount; ++step) {
  108. const zones = deepClone(zonesProto);
  109. // Find closest color for each sample
  110. for (let i = 0; i < samples.length; ++i) {
  111. let minDist = Number.MAX_SAFE_INTEGER;
  112. let nearest = 0;
  113. for (let j = 0; j < colors.length; j++) {
  114. const dist = distance(samples[i], colors[j]);
  115. if (dist < minDist) {
  116. minDist = dist;
  117. nearest = j;
  118. }
  119. }
  120. zones[nearest].push(samples[i]);
  121. }
  122. const lastColors = deepClone(colors);
  123. for (let i = 0; i < zones.length; ++i) {
  124. const zone = zones[i];
  125. const size = zone.length;
  126. const Ls: number[] = [];
  127. const As: number[] = [];
  128. const Bs: number[] = [];
  129. for (const sample of zone) {
  130. Ls.push(sample[0]);
  131. As.push(sample[1]);
  132. Bs.push(sample[2]);
  133. }
  134. const lAvg = arraySum(Ls) / size;
  135. const aAvg = arraySum(As) / size;
  136. const bAvg = arraySum(Bs) / size;
  137. colors[i] = [lAvg, aAvg, bAvg] as Lab;
  138. }
  139. if (deepEqual(lastColors, colors)) break;
  140. }
  141. return sortByContrast(colors).map(c => Lab.toColor(c));
  142. }