Advertisement
Guest User

Untitled

a guest
Mar 24th, 2017
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.23 KB | None | 0 0
  1. #Import libraries for simulation
  2. import tensorflow as tf
  3. import numpy as np
  4.  
  5. #Imports for visualization
  6. import PIL.Image
  7. from io import BytesIO
  8. from IPython.display import clear_output, Image, display
  9.  
  10. #A function for displaying the state of the pond's surface as an image.
  11. def DisplayArray(a, fmt='jpeg', rng=[0,1]):
  12. """Display an array as a picture."""
  13. a = (a - rng[0])/float(rng[1] - rng[0])*255
  14. a = np.uint8(np.clip(a, 0, 255))
  15. f = BytesIO()
  16. PIL.Image.fromarray(a).save(f, fmt)
  17. clear_output(wait = True)
  18. display(Image(data=f.getvalue()))
  19.  
  20. sess = tf.InteractiveSession()
  21.  
  22. def make_kernel(a):
  23. """Transform a 2D array into a convolution kernel"""
  24. a = np.asarray(a)
  25. a = a.reshape(list(a.shape) + [1,1])
  26. return tf.constant(a, dtype=1)
  27.  
  28. def simple_conv(x, k):
  29. """A simplified 2D convolution operation"""
  30. x = tf.expand_dims(tf.expand_dims(x, 0), -1)
  31. y = tf.nn.depthwise_conv2d(x, k, [1, 1, 1, 1], padding='SAME')
  32. return y[0, :, :, 0]
  33.  
  34. def laplace(x):
  35. """Compute the 2D laplacian of an array"""
  36. laplace_k = make_kernel([[0.5, 1.0, 0.5],
  37. [1.0, -6., 1.0],
  38. [0.5, 1.0, 0.5]])
  39. return simple_conv(x, laplace_k)
  40.  
  41. N = 500
  42.  
  43. # Initial Conditions -- some rain drops hit a pond
  44.  
  45. # Set everything to zero
  46. u_init = np.zeros([N, N], dtype=np.float32)
  47. ut_init = np.zeros([N, N], dtype=np.float32)
  48.  
  49. # Some rain drops hit a pond at random points
  50. for n in range(40):
  51. a,b = np.random.randint(0, N, 2)
  52. u_init[a,b] = np.random.uniform()
  53.  
  54. DisplayArray(u_init, rng=[-0.1, 0.1])
  55.  
  56. # Parameters:
  57. # eps -- time resolution
  58. # damping -- wave damping
  59. eps = tf.placeholder(tf.float32, shape=())
  60. damping = tf.placeholder(tf.float32, shape=())
  61.  
  62. # Create variables for simulation state
  63. U = tf.Variable(u_init)
  64. Ut = tf.Variable(ut_init)
  65.  
  66. # Discretized PDE update rules
  67. U_ = U + eps * Ut
  68. Ut_ = Ut + eps * (laplace(U) - damping * Ut)
  69.  
  70. # Operation to update the state
  71. step = tf.group(
  72. U.assign(U_),
  73. Ut.assign(Ut_))
  74.  
  75. # Initialize state to initial conditions
  76. tf.global_variables_initializer().run()
  77.  
  78. # Run 1000 steps of PDE
  79. for i in range(1000):
  80. # Step simulation
  81. step.run({eps: 0.03, damping: 0.04})
  82. DisplayArray(U.eval(), rng=[-0.1, 0.1])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement