OpenAIの最新モデル


つい先日,OpeanAIから新しいモデルが登場した.

そこで早速使用してみた.

テーマ先日のLangton’s Antである.プロンプトは下記.

Langton's AntのシミュレーションをPythonで実装.
商品として販売できるくらい表現をリッチにして.
GIFで出力して.
エラーが出ないか全体を確認して.

(何回かエラー対応が必要であったが)出力は下記である.正直,このくらいのコードではあまり差は感じない.

# %% [code]
# Import necessary libraries
import numpy as np
import matplotlib.pyplot as plt
import imageio
from matplotlib import colors
import os

# Ensure the script runs in a clean directory for outputs
output_dir = 'langtons_ant_output'
if not os.path.exists(output_dir):
    os.makedirs(output_dir)

# Define the simulation parameters
GRID_SIZE = 101          # Use an odd number so the ant starts at the exact centre
STEPS = 11000            # Total number of simulation steps
FRAME_INTERVAL = 100     # Save a frame every FRAME_INTERVAL steps for the GIF
ANT_MARKER_SIZE = 6      # Size of the ant marker when plotting

# Define the grid
# 0 represents white, 1 represents black
grid = np.zeros((GRID_SIZE, GRID_SIZE), dtype=int)

# Define initial position (centre of the grid)
ant_x, ant_y = GRID_SIZE // 2, GRID_SIZE // 2

# Directions: 0 = up, 1 = right, 2 = down, 3 = left (clockwise)
direction = 0

# Define movements corresponding to directions
movements = {
    0: (-1, 0),  # move up
    1: (0, 1),   # move right
    2: (1, 0),   # move down
    3: (0, -1)   # move left
}

# List to store file names of the saved frames
frame_files = []

# Define a custom colour map for the grid:
# White (for cell=0) and black (for cell=1)
cmap = colors.ListedColormap(['white', 'black'])
bounds = [0, 0.5, 1]
norm = colors.BoundaryNorm(bounds, cmap.N)

# Function to plot and save the current state of the grid along with the ant's position
def save_frame(step, ant_x, ant_y):
    plt.figure(figsize=(6, 6))
    plt.imshow(grid, cmap=cmap, norm=norm, origin='upper')
    # Overlay the ant's position in a contrasting colour (e.g., red)
    plt.scatter(ant_y, ant_x, c='red', s=ANT_MARKER_SIZE**2, marker='o', edgecolors='k', linewidths=0.5)
    plt.title(f"Langton's Ant - Step {step}")
    plt.axis('off')
    # Save the figure to a file
    filename = os.path.join(output_dir, f"frame_{step:05d}.png")
    plt.savefig(filename, bbox_inches='tight')
    plt.close()
    frame_files.append(filename)

# Run the simulation
for step in range(STEPS):
    # Check the colour of the current cell
    current_cell = grid[ant_x, ant_y]
    if current_cell == 0:
        # On a white cell: turn right and flip colour to black
        direction = (direction + 1) % 4
        grid[ant_x, ant_y] = 1
    else:
        # On a black cell: turn left and flip colour to white
        direction = (direction - 1) % 4
        grid[ant_x, ant_y] = 0

    # Move the ant forward one unit in the current direction
    dx, dy = movements[direction]
    ant_x, ant_y = ant_x + dx, ant_y + dy

    # Check boundaries: if the ant goes out of bounds, we can wrap around (toroidal grid)
    ant_x %= GRID_SIZE
    ant_y %= GRID_SIZE

    # Save frame at intervals
    if step % FRAME_INTERVAL == 0:
        save_frame(step, ant_x, ant_y)

# After simulation, save the final state as a frame as well
save_frame(STEPS, ant_x, ant_y)

# Create a GIF from the saved frames
gif_filename = os.path.join(output_dir, "langtons_ant_simulation.gif")
with imageio.get_writer(gif_filename, mode='I', duration=0.1) as writer:
    for filename in frame_files:
        image = imageio.imread(filename)
        writer.append_data(image)

print(f"Simulation complete. GIF saved as {gif_filename}")

# Optional: Clean up individual frame files if not needed
# Uncomment the following lines to remove frame files after creating the GIF.
# for filename in frame_files:
#     os.remove(filename)

参考文献

  • Langton, C. G. (1986). Studying artificial life with cellular automata. Physica D: nonlinear phenomena, 22(1-3), 120-149.

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です