{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\nfrom tqdm import tqdm_notebook\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test = pd.read_csv(\"../input/conways-reverse-game-of-life-2020/test.csv\", index_col=0)\ntest.head()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Observe the train data"},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"trainData = pd.read_csv(\"../input/conways-reverse-game-of-life-2020/train.csv\", index_col=0)\ntrainData.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"trainData.info()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"trainData.duplicated().sum()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(\"Number before dropping : %d \" % trainData.shape[0])\ntrainData = trainData.drop(index=trainData[trainData.duplicated()].index)\nprint(\"Number after dropping : %d \" % trainData.shape[0])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"trainData.head()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Review Rules\n1. Overpopulation: if a living cell is surrounded by more than three living cells, it dies.\n2. Stasis: if a living cell is surrounded by two or three living cells, it survives.\n3. Underpopulation: if a living cell is surrounded by fewer than two living cells, it dies.\n4. Reproduction: if a dead cell is surrounded by exactly three cells, it becomes a live cell."},{"metadata":{"trusted":true},"cell_type":"code","source":"N_ROWS = 25\nN_COLS = 25\ndef getFlowBoards(index):\n    start = trainData.iloc[index][1:626].to_numpy()\n    startBoard = start.reshape(25, 25)\n    boards = {0: startBoard}\n    tmp = np.array(startBoard, copy=True)\n    delta = trainData.iloc[index][0]\n    for i in range(delta):\n        for row in range(N_ROWS):\n            for col in range(N_COLS):\n                current = boards[i][row][col]\n                arround = boards[i].take(range(row-1,row+2),mode='wrap', axis=0).take(range(col-1,col+2),mode='wrap',axis=1)\n                arroundSum = arround.sum()\n                arroundSum = arroundSum - current\n                if current == 0 and arroundSum == 3:\n                    tmp[row][col] = 1\n                elif current == 1:\n                    if arroundSum > 3 or arroundSum < 2:\n                        tmp[row][col] = 0\n                    else:\n                        tmp[row][col] = 1\n        boards[i + 1] = np.array(tmp, copy=True)\n    return boards;\n\ndef plotBoards(boards):\n    colors = ['white','black'] \n    cmap = mpl.colors.ListedColormap(colors)\n    plt.rcParams['figure.figsize'] = (15.0, 15.0) \n    plt.figure()\n    size = len(boards)\n    for key, value in boards.items():\n        plt.subplot(1,size,key + 1)\n        plt.xlabel(key)\n        plt.imshow(value ,cmap = cmap)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plotBoards(getFlowBoards(0))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plotBoards(getFlowBoards(1))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plotBoards(getFlowBoards(2))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plotBoards(getFlowBoards(3))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plotBoards(getFlowBoards(4))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Valid and Generate More Boards"},{"metadata":{"trusted":true},"cell_type":"code","source":"def getMovedBoard(start, delta):\n    board = np.array(start, copy=True)\n    tmp = np.array(start, copy=True)\n    for i in range(delta):\n        for row in range(N_ROWS):\n            for col in range(N_COLS):\n                current = board[row][col]\n                arround = board.take(range(row-1,row+2),mode='wrap', axis=0).take(range(col-1,col+2),mode='wrap',axis=1)\n                arroundSum = arround.sum()\n                arroundSum = arroundSum - current\n                if current == 0 and arroundSum == 3:\n                    tmp[row][col] = 1\n                elif current == 1:\n                    if arroundSum > 3 or arroundSum < 2:\n                        tmp[row][col] = 0\n                    else:\n                        tmp[row][col] = 1\n        board = np.array(tmp, copy=True)\n    return board;","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"total = trainData.shape[0]\n# validBoards = {}\ndelta1TrainSource = []\ndelta1TrainTarget = []\ndelta2TrainSource = []\ndelta2TrainTarget = []\ndelta3TrainSource = []\ndelta3TrainTarget = []\ndelta4TrainSource = []\ndelta4TrainTarget = []\ndelta5TrainSource = []\ndelta5TrainTarget = []\n\nfor i in tqdm_notebook(range(total)):\n    delta = trainData.iloc[i][0]\n    \n    startData = trainData.iloc[i][1:626].to_numpy()\n    start = startData.reshape(25, 25)\n    \n    stopData = trainData.iloc[i][626:].to_numpy()\n    stop = stopData.reshape(25, 25)\n    \n#     if (np.array_equal(getMovedBoard(start, delta), stop)):\n#         validBoards[i] = start\n    if (delta == 1):\n        delta1TrainSource.append(stop)\n        delta1TrainTarget.append(start)\n    if (delta == 2):\n        delta2TrainSource.append(stop)\n        delta2TrainTarget.append(start)\n    if (delta == 3):\n        delta3TrainSource.append(stop)\n        delta3TrainTarget.append(start)\n    if (delta == 4):\n        delta4TrainSource.append(stop)\n        delta4TrainTarget.append(start)\n    if (delta == 5):\n        delta5TrainSource.append(stop)\n        delta5TrainTarget.append(start)\n            \nprint(\"number of delta 1 data = {0}\".format(len(delta1TrainSource)))\nprint(\"number of delta 2 data = {0}\".format(len(delta2TrainSource)))\nprint(\"number of delta 3 data = {0}\".format(len(delta3TrainSource)))\nprint(\"number of delta 4 data = {0}\".format(len(delta4TrainSource)))\nprint(\"number of delta 5 data = {0}\".format(len(delta5TrainSource)))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Save to CSV"},{"metadata":{"trusted":true},"cell_type":"code","source":"trainSource = np.array([delta1TrainSource, delta2TrainSource, delta3TrainSource, delta4TrainSource, delta5TrainSource])\ntrainTarget = np.array([delta1TrainTarget, delta2TrainTarget, delta3TrainTarget, delta4TrainTarget, delta5TrainTarget])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"for i in tqdm_notebook(range(5)):\n    pd.DataFrame(data=np.array(trainSource[i]).reshape(-1, 625), columns=['start_' + str(_) for _ in range(0, 625)]).to_csv(\"train_delta{}_source.csv\".format(i+1))\n    pd.DataFrame(data=np.array(trainTarget[i]).reshape(-1, 625), columns=['start_' + str(_) for _ in range(0, 625)]).to_csv(\"train_delta{}_target.csv\".format(i+1))","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat":4,"nbformat_minor":4}