explore.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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 = (
  38. (norm_color * math.sqrt(yr * yr + yg * yg + yb * yb))
  39. if normalize
  40. else 1
  41. )
  42. score = (x if include_x else 0) - (
  43. closeness * (r * yr + g * yg + b * yb) / norm
  44. )
  45. if best_score is None or score < best_score:
  46. best_score = score
  47. best_name = name
  48. results[(r, g, b)] = (best_name, best_score)
  49. counts[best_name] += 1
  50. with open("best.csv", "w") as outfile:
  51. csv.writer(outfile, delimiter=",", quotechar="'").writerows(
  52. (*k, *v) for k, v in results.items()
  53. )
  54. with open("counts.csv", "w") as outfile:
  55. csv.writer(outfile, delimiter=",", quotechar="'").writerows(counts.items())
  56. print(f"Top ten most hit:")
  57. for k in sorted(list(counts), key=counts.get, reverse=True)[:10]:
  58. print(f"{k} - {counts[k]}")