import dash
from dash import dcc, html
from dash.dependencies import Input, Output, State
import plotly.graph_objs as go
import numpy as np
# Initialize the Dash app
app = dash.Dash(__name__)
# Initial parameters
initial_num_fish = 50
initial_velocity = 0.1
num_fish = initial_num_fish
velocity = initial_velocity
# Initialize fish positions and velocities
positions = np.random.rand(num_fish, 3) * 10
velocities = (np.random.rand(num_fish, 3) - 0.5) * velocity
# Define the layout of the app
app.layout = html.Div([
html.H1("3D Swarm of Fish Simulation", style={'textAlign': 'center'}),
html.Div([
html.Label("Number of Fish:"),
dcc.Slider(
id='num-fish-slider',
min=10, max=1000, step=1, value=initial_num_fish,
marks={i: str(i) for i in range(10, 1001, 100)}
),
html.Label("Fish Velocity:"),
dcc.Slider(
id='velocity-slider',
min=0.01, max=1, step=0.01, value=initial_velocity,
marks={i/100: str(i/100) for i in range(1, 101, 10)}
),
], style={'margin': '0 20px'}),
dcc.Graph(id='fish-graph'),
dcc.Interval(id='interval-component', interval=100, n_intervals=0)
], style={'margin': '0', 'padding': '0'})
# Function to update fish positions
def update_positions():
global positions, velocities, num_fish, velocity
positions += velocities
# Simple boundary conditions
for i in range(num_fish):
for j in range(3):
if positions[i, j] > 10:
positions[i, j] = 10
velocities[i, j] *= -1
elif positions[i, j] < 0:
positions[i, j] = 0
velocities[i, j] *= -1
# Define the callback to update the graph
@app.callback(
Output('fish-graph', 'figure'),
[Input('interval-component', 'n_intervals')],
[State('num-fish-slider', 'value'), State('velocity-slider', 'value')]
)
def update_graph(n, new_num_fish, new_velocity):
global positions, velocities, num_fish, velocity
if new_num_fish != num_fish:
num_fish = new_num_fish
positions = np.random.rand(num_fish, 3) * 10
velocities = (np.random.rand(num_fish, 3) - 0.5) * new_velocity
if new_velocity != velocity:
velocity = new_velocity
velocities = (np.random.rand(num_fish, 3) - 0.5) * new_velocity
update_positions()
scatter = go.Scatter3d(
x=positions[:, 0],
y=positions[:, 1],
z=positions[:, 2],
mode='markers',
marker=dict(size=5, color=['red'] + ['blue'] * (num_fish - 1)) # First fish is red, others are blue
)
layout = go.Layout(
scene=dict(
xaxis=dict(range=[0, 10], color='white', showbackground=False, gridcolor='white', zerolinecolor='white'),
yaxis=dict(range=[0, 10], color='white', showbackground=False, gridcolor='white', zerolinecolor='white'),
zaxis=dict(range=[0, 10], color='white', showbackground=False, gridcolor='white', zerolinecolor='white'),
bgcolor='rgb(0, 0, 50)'
),
margin=dict(l=0, r=0, b=0, t=0),
paper_bgcolor='rgb(0, 0, 50)'
)
return {'data': [scatter], 'layout': layout}
# Run the app
if __name__ == '__main__':
app.run_server(debug=True)