Guest User

Untitled

a guest
Jan 20th, 2019
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.71 KB | None | 0 0
  1. #!/usr/bin/env python3
  2.  
  3. import sys
  4. import numpy as np
  5.  
  6.  
  7. def lament(*args, **kwargs):
  8. return print(*args, file=sys.stderr, **kwargs)
  9.  
  10.  
  11. def colorize(x):
  12. return x * 17 % 256
  13.  
  14.  
  15. def render(row, scale):
  16. grays = colorize(row)
  17. if scale > 1:
  18. grays = np.repeat(grays, scale)
  19. line = " ".join(str(x) for x in grays)
  20. for y in range(scale):
  21. print(line)
  22.  
  23.  
  24. def limit(row): # in-place
  25. row[row < 0] = 0
  26. row[row > 15] = 15
  27. return row
  28.  
  29.  
  30. def initialize(width):
  31. row = np.zeros(width, int)
  32. value = 0
  33. for i in range(width):
  34. if np.random.randint(8) == 0: # only change values occasionally
  35. value = np.random.randint(16)
  36. row[i] = value
  37. limit(row)
  38. return row
  39.  
  40.  
  41. name, args = sys.argv[0], sys.argv[1:]
  42.  
  43. if len(args) == 0:
  44. rule_lut = None
  45. elif len(args) == 16:
  46. rule_lut = [int(x.strip(",")) for x in args]
  47. else:
  48. lament(f"usage: {name}")
  49. lament(f"usage: {name} {{rules 1 through 16}}")
  50. sys.exit(1)
  51.  
  52. scale = 3
  53. width, height = 960 // scale, 960 // scale
  54.  
  55. if rule_lut is None:
  56. rule_lut = np.random.randint(-2, 2 + 1, size=(4, 4))
  57. lament(" ".join(f"{x:+2}" for x in rule_lut.flat))
  58. else:
  59. rule_lut = np.array(rule_lut).reshape(4, 4)
  60.  
  61. print("P2") # magic code for an ascii Portable GrayMap (PGM) file
  62. print(width * scale, height * scale)
  63. print(255) # maximum color value
  64.  
  65. row = initialize(width)
  66.  
  67. for i in range(height):
  68. # left, center, right:
  69. L = np.roll(row, 1)
  70. C = row.copy()
  71. R = np.roll(row, -1)
  72.  
  73. diffusion = (L + C + C + R + 2) // 4
  74.  
  75. # v = [0,1,2,3,1,0,3,2,2,3,0,1,3,2,1,0][V]
  76. y = (L ^ (L >> 2)) % 4
  77. x = (R ^ (R >> 2)) % 4
  78.  
  79. delta = rule_lut[y, x]
  80. row = diffusion + delta
  81.  
  82. limit(row)
  83. render(row, scale)
Add Comment
Please, Sign In to add comment