ライフゲーム / Python / 全セルのムーア近傍の和を求める / scipy.signal.convolve()
畳み込み演算の函数がいろいろあるのでそれを利用する。ここではscipy.signal.convolve()
を使ってみる。
import numpy as np from scipy.signal import convolve def toTorus(mat, matTorused): mat = np.array(mat , dtype="uint8") matTorused = np.array(matTorused, dtype="uint8") matTorused[1:-1, 1:-1] = mat matTorused[0,:], matTorused[-1,:] = matTorused[-2,:], matTorused[1,:] matTorused[:,0], matTorused[:,-1] = matTorused[:,-2], matTorused[:,1] return matTorused def mooreSum(matTorused): matTorused = np.array(matTorused, dtype="uint8") return convolve(matTorused, [[1,1,1], [1,0,1], [1,1,1]], mode="same")[1:-1, 1:-1] # 最外周を除いて返す。 if __name__ == "__main__": # この排列aを現世代排列とする。 numOfRows, numOfCols = 5, 10 a = np.random.randint(0, 2, [numOfRows, numOfCols], dtype="uint8") # 一回り大きい排列Aを用意しておく。 A = np.empty(np.asarray(a.shape)+2, dtype="uint8") torused = toTorus(a, A) moore = mooreSum(torused) print(a) print(moore)
実行結果: