explore.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. #!/usr/bin/env python3
  2. import csv
  3. import math
  4. from collections import defaultdict
  5. # include X
  6. include_x = False
  7. # normalize q and Y
  8. normalize = True
  9. # closeness coefficient
  10. closeness = 2
  11. # step size within RGB color space
  12. step = 4
  13. data = []
  14. with open("database.csv") as infile:
  15. for name, *nums in csv.reader(infile, delimiter=",", quotechar="'"):
  16. data.append((name, *[float(n) for n in nums]))
  17. counts = defaultdict(int)
  18. results = {}
  19. try:
  20. with open("best.csv") as infile:
  21. for r, g, b, name, score in csv.reader(infile, delimiter=",", quotechar="'"):
  22. results[(int(r), int(g), int(b))] = (name, float(score))
  23. except:
  24. pass # file not found, assume no prior results
  25. for r in range(0, 256, step):
  26. for g in range(0, 256, step):
  27. for b in range(0, 256, step):
  28. if (known := results.get((r, g, b), None)) is not None:
  29. counts[known[0]] += 1
  30. continue
  31. norm_color = math.sqrt(r * r + g * g + b * b)
  32. if norm_color == 0:
  33. continue
  34. best_score = None
  35. best_name = None
  36. for name, x, yr, yg, yb in data:
  37. norm = (norm_color * math.sqrt(yr * yr + yg * yg + yb * yb)) if normalize else 1
  38. score = (x if include_x else 0) - (closeness * (r * yr + g * yg + b * yb) / norm)
  39. if best_score is None or score < best_score:
  40. best_score = score
  41. best_name = name
  42. results[(r, g, b)] = (best_name, best_score)
  43. counts[best_name] += 1
  44. with open("best.csv", "w") as outfile:
  45. csv.writer(outfile, delimiter=",", quotechar="'").writerows((*k, *v) for k, v in results.items())
  46. with open("counts.csv", "w") as outfile:
  47. csv.writer(outfile, delimiter=",", quotechar="'").writerows(counts.items())
  48. print(f"Top ten most hit:")
  49. for k in sorted(list(counts), key=counts.get, reverse=True)[:10]:
  50. print(f"{k} - {counts[k]}")