Py.Cafe

LunnyRia/

boid-flocking-simulation

Boid Flocking Simulation

DocsPricing
  • agents.py
  • app.py
  • model.py
  • requirements.txt
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
from mesa.examples.basic.boid_flockers.model import BoidFlockers
from mesa.visualization import Slider, SolaraViz, make_space_component
import numpy as np

def boid_draw(agent):
    # calculate angle according to directions [x,y]
    directions = agent.direction
    angle = np.arctan2(directions[1], directions[0])
    angle = np.degrees(angle)
    angle = (angle + 360) % 360

    # define the marker as triangle
    # bird = {"size": 20, "marker": (3, 1, angle)}
    bird = {"size": 20}
    
    neighbors = len(agent.neighbors)
    if neighbors <= 1:
        bird.update({"color": "red"})
    elif neighbors >= 2:
        bird.update({"color": "green"})
    
    return bird


model_params = {
    "seed": {
        "type": "InputText",
        "value": 42,
        "label": "Random Seed",
    },
    "population": Slider(
        label="Number of boids",
        value=100,
        min=10,
        max=200,
        step=10,
    ),
    "width": 100,
    "height": 100,
    "speed": Slider(
        label="Speed of Boids",
        value=5,
        min=1,
        max=20,
        step=1,
    ),
    "vision": Slider(
        label="Vision of Bird (radius)",
        value=10,
        min=1,
        max=50,
        step=1,
    ),
    "separation": Slider(
        label="Minimum Separation",
        value=2,
        min=1,
        max=20,
        step=1,
    ),
}

model = BoidFlockers()

page = SolaraViz(
    model,
    components=[make_space_component(agent_portrayal=boid_draw, backend="matplotlib")],
    model_params=model_params,
    name="Boid Flocking Model",
    play_interval=100,
)
page  # noqa