import numpy as np
arr1 = np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12]])
print(arr1)
arr1[1,2]
arr1[1][2]
arr1[-1,1]
arr1[1:3,1:3]
np.shape(arr1)
np.sum(arr1)
np.mean(arr1)
np.transpose(arr1)
arr2 = np.zeros((5,4),dtype=int)
print(arr2)
type(arr2[0,0])
arr3 = np.ones((3,3),dtype=int)
print(arr3)
np.concatenate([arr1,arr3],axis=1)
np.concatenate([arr1,arr2])
arr2[:3,:3] = arr3
print(arr2)
arr1[:2,:2] = 18
print(arr1)
arr2[:3,:] = arr1
print(arr2)
Exercise: Write a function which will create an $ n \times n $ array of zeros with a $ k \times k $ block of ones in the middle.
"""
n is the size of the array
k is the size of the block of ones
"""
def bullseye(n,k):
arr = np.zeros((n,n),dtype = int)
ones = np.ones((k,k),dtype = int)
m = (n-k)//2
arr[m:m+k,m:m+k] = ones
return arr
B = bullseye(10,3)
print(B)
Exercise: Write a function that adds up the entries neighboring a given location in an array.
"""
arr is an m by n array of numbers
entry is the location (i,j)
"""
def neighbor_sum(arr,entry):
m,n = np.shape(arr)
padd = np.zeros((m+1,n+1),dtype=int)
padd[1:,1:] = arr
i,j = entry
square = padd[i:i+3,j:j+3]
summ = np.sum(square) - arr[i,j]
return summ
neighbor_sum(B,(4,4))
Exercise: Write a function that updates each entry of an array with the sum of its neighbors modulo $ k $.
"""
arr is an m by n array of integers between 0 and k
k is the modulus for the sum
"""
def update(arr,k):
m,n = np.shape(arr)
new_arr = np.zeros((m,n),dtype=int)
for i in range(m):
for j in range(n):
summ = neighbor_sum(arr,(i,j))%k
new_arr[i,j] = summ
return new_arr
update(B,8)
import matplotlib.pyplot as plt
plt.imshow(arr1)
plt.show()
print(arr1)
plt.imshow(arr1,cmap='inferno')
plt.show()
plt.imshow(arr1,cmap='gray')
from matplotlib import colors
cmap = colors.ListedColormap(['palegreen', 'green', 'orange', 'black'])
arr4 = np.random.randint(-1,3,(4,4))
plt.imshow(arr4,cmap=cmap,vmin=-1,vmax=2)
plt.show()
%matplotlib notebook
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from matplotlib import colors
x = bullseye(10,3) # Initial configuration of the array
fig = plt.figure(figsize = (6,6))
ax = plt.subplot(111)
plt.title("Deterministic cellular automata (modulo 3)")
#cmap = colors.ListedColormap(['palegreen', 'green', 'orange', 'black'])
im = ax.imshow(x, cmap = 'inferno', vmin=0, vmax=3)
def animate(i):
global x
x=update(x,3)
im.set_data(x)
return im
anim = FuncAnimation(fig=fig, func=animate, interval=300, blit=True, repeat=False)
plt.show()
Evolution of a 2D grid of 0s and 1s. Here are the rules
Exercise: Write an update function that will update an array of 0s and 1s according to the rules from Conway's game of life.
Exercise: Write a function to produce a random array of 0s and 1s with each entry having probability $ p $ of being a 1.
Exercise: Animate the game of life using a random starting configuration.