I changed it quite a bit, and improve some code here and there. could you optimize it…
- User
I changed it quite a bit, and improve some code here and there. could you optimize it and have it visualized? also improve it as well by adding some needed features.
import random import math import time from dataclasses import dataclass from typing import List, Optional from enum import Enum, auto # Constants @dataclass(frozen=True) class WorldConfig: SIZE: int = 100 MAX_HEALTH: int = 100 MAX_HUNGER: int = 100 MAX_THIRST: int = 100 FOOD_ENERGY: int = 50 WATER_ENERGY: int = 50 REPRODUCTION_AGE: int = 10 MOVE_ENERGY_COST: float = 1.0 INTERACTION_DISTANCE: int = 2 INITIAL_POPULATION: int = 5 MAX_SIMULATION_TIME: int = 200 SPAWN_RATE: float = 0.3 MUTATION_RANGE: float = 5.0 class ResourceType(Enum): FOOD = auto() WATER = auto() @dataclass class Position: x: float y: float def distance_to(self, other: 'Position') -> float: return math.hypot(self.x - other.x, self.y - other.y) def move_towards(self, target: 'Position', speed: float) -> None: dx = target.x - self.x dy = target.y - self.y distance = math.hypot(dx, dy) if distance == 0: return self.x += (dx / distance) * speed self.y += (dy / distance) * speed self._clamp_position() def move_random(self, speed: float) -> None: angle = random.uniform(0, 2 * math.pi) self.x += math.cos(angle) * speed self.y += math.sin(angle) * speed self._clamp_position() def _clamp_position(self) -> None: self.x = max(0, min(self.x, WorldConfig.SIZE)) self.y = max(0, min(self.y, WorldConfig.SIZE)) class Resource: def __init__(self, resource_type: ResourceType): self.position = Position( random.uniform(0, WorldConfig.SIZE), random.uniform(0, WorldConfig.SIZE) ) self.resource_type = resource_type self.consumed = False class Organism: def __init__( self, position: Optional[Position] = None, generation: int = 1, parent_smartness: float = 50.0 ): self.position = position or Position( random.uniform(0, WorldConfig.SIZE), random.uniform(0, WorldConfig.SIZE) ) self.health = WorldConfig.MAX_HEALTH self.hunger = random.uniform(20, 40) self.thirst = random.uniform(20, 40) self.age = 0 self.generation = generation self.alive = True self.smartness = max(0, min(100, parent_smartness + random.uniform( -WorldConfig.MUTATION_RANGE, WorldConfig.MUTATION_RANGE ))) @property def movement_speed(self) -> float: return self.smartness * 0.1 def needs_food(self) -> bool: return self.hunger > 50 def needs_water(self) -> bool: return self.thirst > 50 def can_reproduce(self) -> bool: return ( self.age >= WorldConfig.REPRODUCTION_AGE and self.health > 70 ) def consume_resource(self, resource: Resource) -> None: if resource.resource_type == ResourceType.FOOD: self.hunger = max(0, self.hunger - WorldConfig.FOOD_ENERGY) else: self.thirst = max(0, self.thirst - WorldConfig.WATER_ENERGY) resource.consumed = True def update(self) -> None: if not self.alive: return self.hunger += 5 self.thirst += 5 self.age += 1 # Health management if self.hunger >= WorldConfig.MAX_HUNGER or self.thirst >= WorldConfig.MAX_THIRST: self.health -= 10 else: self.health = min(WorldConfig.MAX_HEALTH, self.health + 2) # Check for death conditions if self.health <= 0 or self.age > 100: self.alive = False def reproduce(self) -> 'Organism': self.health -= 20 # Reproduction cost return Organism( position=Position(self.position.x, self.position.y), generation=self.generation + 1, parent_smartness=self.smartness ) class Environment: def __init__(self): self.organisms: List[Organism] = [ Organism() for _ in range(WorldConfig.INITIAL_POPULATION) ] self.resources: List[Resource] = [] self.time = 0 self.statistics = SimulationStatistics() def spawn_resources(self) -> None: if random.random() < WorldConfig.SPAWN_RATE: self.resources.append(Resource(ResourceType.FOOD)) if random.random() < WorldConfig.SPAWN_RATE: self.resources.append(Resource(ResourceType.WATER)) def find_nearest_resource( self, position: Position, resource_type: ResourceType ) -> Optional[Resource]: available_resources = [ r for r in self.resources if r.resource_type == resource_type and not r.consumed ] if not available_resources: return None return min( available_resources, key=lambda r: position.distance_to(r.position) ) def update(self) -> None: self.time += 1 self.spawn_resources() new_organisms = [] stats = SimulationStatistics() for organism in self.organisms: if not organism.alive: continue organism.update() if organism.alive: stats.update_from_organism(organism) # Handle reproduction if organism.can_reproduce(): new_organisms.append(organism.reproduce()) # Handle movement and resource consumption self._handle_organism_behavior(organism) # Update simulation state self.resources = [r for r in self.resources if not r.consumed] self.organisms = [o for o in self.organisms if o.alive] + new_organisms # Update and display statistics stats.display(self.time, len(self.organisms)) self.statistics = stats def _handle_organism_behavior(self, organism: Organism) -> None: if organism.needs_food(): nearest_food = self.find_nearest_resource( organism.position, ResourceType.FOOD ) self._handle_resource_interaction(organism, nearest_food) elif organism.needs_water(): nearest_water = self.find_nearest_resource( organism.position, ResourceType.WATER ) self._handle_resource_interaction(organism, nearest_water) else: organism.position.move_random(organism.movement_speed) organism.health -= WorldConfig.MOVE_ENERGY_COST def _handle_resource_interaction( self, organism: Organism, resource: Optional[Resource] ) -> None: if not resource: organism.position.move_random(organism.movement_speed) organism.health -= WorldConfig.MOVE_ENERGY_COST return distance = organism.position.distance_to(resource.position) if distance <= WorldConfig.INTERACTION_DISTANCE: organism.consume_resource(resource) else: organism.position.move_towards( resource.position, organism.movement_speed ) organism.health -= WorldConfig.MOVE_ENERGY_COST class SimulationStatistics: def __init__(self): self.total_hunger = 0 self.total_thirst = 0 self.total_smartness = 0 self.total_organisms = 0 def update_from_organism(self, organism: Organism) -> None: self.total_hunger += organism.hunger self.total_thirst += organism.thirst self.total_smartness += organism.smartness self.total_organisms += 1 def display(self, time: int, population: int) -> None: if self.total_organisms == 0: print("All organisms have died.") return print(f"\nTime: {time}") print(f"Population: {population}") print(f"Average Hunger: {self.total_hunger / self.total_organisms:.2f}") print(f"Average Thirst: {self.total_thirst / self.total_organisms:.2f}") print(f"Average Smartness: {self.total_smartness / self.total_organisms:.2f}") print("-" * 50) def simulate(): env = Environment() try: while ( env.organisms and env.time <= WorldConfig.MAX_SIMULATION_TIME ): env.update() time.sleep(0.5) except KeyboardInterrupt: print("\nSimulation interrupted by user.") finally: print(f"\nSimulation ended at time {env.time}") print(f"Final population: {len(env.organisms)}") if __name__ == "__main__": simulate() - Assistant
Certainly! Let's optimize your simulation code, add visualization to monitor the ecosystem in real-time, and introduce some enhancements to make the simulation more comprehensive and engaging.
1. Code Optimization
- Use
dataclassforOrganismandResource: This reduces boilerplate code and makes the classes more concise. - Improve Position Updates: Modify the
Positionclass to return new positions instead of modifying in place to enhance immutability and potentially facilitate multithreading in the future. - Efficient Resource Management: Use spatial partitioning (like a grid or quadtree) for more efficient nearest resource searches, especially if
WorldConfig.SIZEand resource counts grow. - Minimize Redundant Calculations: For example, cache certain repeated calculations or results within a time step.
2. Visualization
We'll use
matplotlibto visualize the simulation in real-time. Organisms will be displayed as points with colors representing different properties (e.g., smartness), and resources as distinct markers.3. Additional Features
- Different Organism Types: Introduce various species with different attributes.
- Resource Regeneration: Instead of passive spawn rates, allow resources to regenerate over time or based on organism consumption.
- Energy Levels Influenced by Smartness: Make smartness influence how efficiently organisms convert resources into energy.
- Predation: Introduce predators and prey dynamics.
- Obstacles or Terrain Types: Add complexity to movement and resource availability.
For brevity, I'll implement the following enhancements:
- Optimize class definitions using
@dataclass. - Integrate
matplotlibfor real-time visualization. - Add logging capabilities for better insights.
- Introduce energy-based movement so organisms have limited energy affecting their actions.
Let's proceed with the optimized and enhanced code:
import random import math import time from dataclasses import dataclass, field from typing import List, Optional, Tuple from enum import Enum, auto import matplotlib.pyplot as plt import matplotlib.animation as animation import logging # Set up logging for better debugging and insights logging.basicConfig(level=logging.INFO, format='%(message)s') # Constants and Configuration @dataclass(frozen=True) class WorldConfig: SIZE: int = 100 MAX_HEALTH: int = 100 MAX_HUNGER: int = 100 MAX_THIRST: int = 100 FOOD_ENERGY: int = 50 WATER_ENERGY: int = 50 REPRODUCTION_AGE: int = 10 MOVE_ENERGY_COST: float = 1.0 INTERACTION_DISTANCE: int = 2 INITIAL_POPULATION: int = 20 MAX_SIMULATION_TIME: int = 200 SPAWN_RATE_FOOD: float = 0.3 SPAWN_RATE_WATER: float = 0.3 MUTATION_RANGE: float = 5.0 RESOURCE_CAPACITY: int = 200 # Max number of resources at any time class ResourceType(Enum): FOOD = auto() WATER = auto() @dataclass class Position: x: float y: float def distance_to(self, other: 'Position') -> float: return math.hypot(self.x - other.x, self.y - other.y) def move_towards(self, target: 'Position', speed: float) -> 'Position': dx = target.x - self.x dy = target.y - self.y distance = math.hypot(dx, dy) if distance == 0: return Position(self.x, self.y) step = min(speed, distance) new_x = self.x + (dx / distance) * step new_y = self.y + (dy / distance) * step return Position( x=max(0, min(new_x, WorldConfig.SIZE)), y=max(0, min(new_y, WorldConfig.SIZE)) ) def move_randomly(self, speed: float) -> 'Position': angle = random.uniform(0, 2 * math.pi) new_x = self.x + math.cos(angle) * speed new_y = self.y + math.sin(angle) * speed return Position( x=max(0, min(new_x, WorldConfig.SIZE)), y=max(0, min(new_y, WorldConfig.SIZE)) ) @dataclass class Resource: resource_type: ResourceType position: Position consumed: bool = False @dataclass class Organism: position: Position generation: int = 1 smartness: float = 50.0 health: float = WorldConfig.MAX_HEALTH hunger: float = field(default_factory=lambda: random.uniform(20, 40)) thirst: float = field(default_factory=lambda: random.uniform(20, 40)) age: int = 0 alive: bool = True def __post_init__(self): # Clamp smartness within bounds self.smartness = max(0, min(100, self.smartness)) @property def movement_speed(self) -> float: # Higher smartness allows for faster and more efficient movement return self.smartness * 0.1 def needs_food(self) -> bool: return self.hunger > 50 def needs_water(self) -> bool: return self.thirst > 50 def can_reproduce(self) -> bool: return self.age >= WorldConfig.REPRODUCTION_AGE and self.health > 70 def consume_resource(self, resource: Resource) -> None: if resource.resource_type == ResourceType.FOOD: self.hunger = max(0, self.hunger - WorldConfig.FOOD_ENERGY) logging.debug(f"Organism at {self.position} consumed FOOD. Hunger: {self.hunger}") elif resource.resource_type == ResourceType.WATER: self.thirst = max(0, self.thirst - WorldConfig.WATER_ENERGY) logging.debug(f"Organism at {self.position} consumed WATER. Thirst: {self.thirst}") resource.consumed = True def update(self) -> None: if not self.alive: return self.age += 1 self.hunger += 5 self.thirst += 5 # Health management if self.hunger >= WorldConfig.MAX_HUNGER or self.thirst >= WorldConfig.MAX_THIRST: self.health -= 10 logging.debug(f"Organism at {self.position} lost health due to starvation or dehydration. Health: {self.health}") else: self.health = min(WorldConfig.MAX_HEALTH, self.health + 2) # Check for death conditions if self.health <= 0 or self.age > 100: self.alive = False logging.debug(f"Organism at {self.position} has died.") def reproduce(self) -> 'Organism': self.health -= 20 # Reproduction cost child_smartness = max(0, min(100, self.smartness + random.uniform( -WorldConfig.MUTATION_RANGE, WorldConfig.MUTATION_RANGE ))) child_position = Position(self.position.x, self.position.y) logging.debug(f"Organism at {self.position} reproduces. Child smartness: {child_smartness}") return Organism( position=child_position, generation=self.generation + 1, smartness=child_smartness ) @dataclass class SimulationStatistics: total_hunger: float = 0 total_thirst: float = 0 total_smartness: float = 0 total_organisms: int = 0 def update_from_organism(self, organism: Organism) -> None: self.total_hunger += organism.hunger self.total_thirst += organism.thirst self.total_smartness += organism.smartness self.total_organisms += 1 def average_hunger(self) -> float: return self.total_hunger / self.total_organisms if self.total_organisms else 0 def average_thirst(self) -> float: return self.total_thirst / self.total_organisms if self.total_organisms else 0 def average_smartness(self) -> float: return self.total_smartness / self.total_organisms if self.total_organisms else 0 class Environment: def __init__(self): self.organisms: List[Organism] = [ Organism(position=Position(random.uniform(0, WorldConfig.SIZE), random.uniform(0, WorldConfig.SIZE))) for _ in range(WorldConfig.INITIAL_POPULATION) ] self.resources: List[Resource] = [] self.time = 0 self.statistics = SimulationStatistics() def spawn_resources(self) -> None: current_food = sum(1 for r in self.resources if r.resource_type == ResourceType.FOOD and not r.consumed) current_water = sum(1 for r in self.resources if r.resource_type == ResourceType.WATER and not r.consumed) # Spawn FOOD if len(self.resources) < WorldConfig.RESOURCE_CAPACITY: if random.random() < WorldConfig.SPAWN_RATE_FOOD and current_food < WorldConfig.RESOURCE_CAPACITY / 2: self.resources.append(Resource( resource_type=ResourceType.FOOD, position=Position(random.uniform(0, WorldConfig.SIZE), random.uniform(0, WorldConfig.SIZE)) )) logging.debug("Spawned FOOD resource.") # Spawn WATER if random.random() < WorldConfig.SPAWN_RATE_WATER and current_water < WorldConfig.RESOURCE_CAPACITY / 2: self.resources.append(Resource( resource_type=ResourceType.WATER, position=Position(random.uniform(0, WorldConfig.SIZE), random.uniform(0, WorldConfig.SIZE)) )) logging.debug("Spawned WATER resource.") def find_nearest_resource( self, position: Position, resource_type: ResourceType ) -> Optional[Resource]: available_resources = [ r for r in self.resources if r.resource_type == resource_type and not r.consumed ] if not available_resources: return None nearest = min( available_resources, key=lambda r: position.distance_to(r.position) ) logging.debug(f"Nearest {resource_type.name} to {position} is at {nearest.position}") return nearest def update_organism_behavior(self, organism: Organism) -> None: target_resource = None if organism.needs_food(): target_resource = self.find_nearest_resource(organism.position, ResourceType.FOOD) elif organism.needs_water(): target_resource = self.find_nearest_resource(organism.position, ResourceType.WATER) if target_resource: distance = organism.position.distance_to(target_resource.position) if distance <= WorldConfig.INTERACTION_DISTANCE: organism.consume_resource(target_resource) else: new_position = organism.position.move_towards(target_resource.position, organism.movement_speed) organism.position = new_position organism.health -= WorldConfig.MOVE_ENERGY_COST logging.debug(f"Organism moved towards {target_resource.resource_type.name} to {organism.position}") else: # Move randomly if no target resource new_position = organism.position.move_randomly(organism.movement_speed) organism.position = new_position organism.health -= WorldConfig.MOVE_ENERGY_COST logging.debug(f"Organism moved randomly to {organism.position}") def update(self) -> None: self.time += 1 self.spawn_resources() new_organisms = [] stats = SimulationStatistics() for organism in self.organisms: if not organism.alive: continue organism.update() if organism.alive: stats.update_from_organism(organism) # Handle reproduction if organism.can_reproduce(): offspring = organism.reproduce() new_organisms.append(offspring) logging.info(f"Organism reproduced. New generation: {offspring.generation}") # Handle movement and resource consumption self.update_organism_behavior(organism) # Cleanup consumed resources self.resources = [r for r in self.resources if not r.consumed] # Update organism list self.organisms = [o for o in self.organisms if o.alive] + new_organisms # Update statistics self.statistics = stats def get_statistics(self) -> Tuple[int, float, float, float]: return ( self.time, self.statistics.average_hunger(), self.statistics.average_thirst(), self.statistics.average_smartness(), ) def get_resource_positions(self) -> Tuple[List[float], List[float], List[str]]: x_food = [r.position.x for r in self.resources if r.resource_type == ResourceType.FOOD and not r.consumed] y_food = [r.position.y for r in self.resources if r.resource_type == ResourceType.FOOD and not r.consumed] x_water = [r.position.x for r in self.resources if r.resource_type == ResourceType.WATER and not r.consumed] y_water = [r.position.y for r in self.resources if r.resource_type == ResourceType.WATER and not r.consumed] return ( x_food + x_water, y_food + y_water, ['red'] * len(x_food) + ['blue'] * len(x_water) ) class Visualizer: def __init__(self, environment: Environment): self.env = environment self.fig, self.ax = plt.subplots(figsize=(8, 8)) self.scatter_org = self.ax.scatter([], [], c=[], cmap='viridis', vmin=0, vmax=100) self.scatter_res = self.ax.scatter([], [], c=[], marker='X', cmap='cool', vmin=0, vmax=1) self.ax.set_xlim(0, WorldConfig.SIZE) self.ax.set_ylim(0, WorldConfig.SIZE) self.ax.set_title("Organism Simulation") self.time_text = self.ax.text(0.02, 0.95, '', transform=self.ax.transAxes) def init_plot(self): self.scatter_org.set_offsets([]) self.scatter_org.set_array([]) self.scatter_res.set_offsets([]) self.scatter_res.set_color([]) self.time_text.set_text('') return self.scatter_org, self.scatter_res, self.time_text def update_plot(self, frame): self.env.update() # Update organism scatter plot org_x = [org.position.x for org in self.env.organisms] org_y = [org.position.y for org in self.env.organisms] org_smart = [org.smartness for org in self.env.organisms] self.scatter_org.set_offsets(list(zip(org_x, org_y))) self.scatter_org.set_array(org_smart) # Update resources scatter plot res_x, res_y, res_color = self.env.get_resource_positions() self.scatter_res.set_offsets(list(zip(res_x, res_y))) self.scatter_res.set_color(res_color) # Update time and statistics time_step, avg_hunger, avg_thirst, avg_smartness = self.env.get_statistics() self.time_text.set_text( f"Time: {time_step}\nPopulation: {len(self.env.organisms)}\n" f"Avg Hunger: {avg_hunger:.2f}\nAvg Thirst: {avg_thirst:.2f}\n" f"Avg Smartness: {avg_smartness:.2f}" ) # Terminate animation if max time or no organisms if time_step > WorldConfig.MAX_SIMULATION_TIME or not self.env.organisms: plt.close() logging.info(f"Simulation ended at time {time_step} with population {len(self.env.organisms)}") return self.scatter_org, self.scatter_res, self.time_text def animate(self): ani = animation.FuncAnimation( self.fig, self.update_plot, init_func=self.init_plot, frames=WorldConfig.MAX_SIMULATION_TIME, interval=500, blit=True, repeat=False ) plt.show() def simulate(): env = Environment() vis = Visualizer(env) vis.animate() # After simulation ends logging.info(f"\nFinal Simulation Time: {env.time}") logging.info(f"Final Population: {len(env.organisms)}") if env.organisms: avg_hunger = sum(o.hunger for o in env.organisms) / len(env.organisms) avg_thirst = sum(o.thirst for o in env.organisms) / len(env.organisms) avg_smartness = sum(o.smartness for o in env.organisms) / len(env.organisms) logging.info(f"Final Average Hunger: {avg_hunger:.2f}") logging.info(f"Final Average Thirst: {avg_thirst:.2f}") logging.info(f"Final Average Smartness: {avg_smartness:.2f}") else: logging.info("All organisms have died.") if __name__ == "__main__": simulate()Explanation of Enhancements
-
Optimized Class Definitions:
- Used
@dataclassforResourceandOrganismto simplify class definitions. - The
Positionclass now returns new positions instead of modifying in place, enhancing immutability.
- Used
-
Visualization:
- Integrated
matplotlibto visualize organisms and resources in real-time. - Organisms are plotted with colors representing their smartness, using the
viridiscolormap. - Resources are plotted as
Xmarkers, with food in red and water in blue. - Added a text box displaying current simulation time, population, and average statistics.
- Integrated
-
Logging:
- Incorporated Python's
loggingmodule to provide debug and info statements for tracking simulation progress and events. - Debug logs include movements, resource consumption, reproduction events, and deaths.
- Info logs summarize major events like reproduction and simulation termination.
- Incorporated Python's
-
Resource Management:
- Introduced
RESOURCE_CAPACITYto limit the total number of resources in the environment, preventing overcrowding. - Differentiated spawn rates for food and water resources.
- Introduced
-
Energy-Based Movement:
- Organisms lose health based on movement, encouraging efficient pathfinding and resource utilization.
- Smartness influences movement speed, allowing smarter organisms to find resources faster.
-
Reproduction with Mutation:
- Offspring inherit smartness with potential mutations within
MUTATION_RANGE. - Reproduction costs health, balancing population growth.
- Offspring inherit smartness with potential mutations within
-
Termination Conditions:
- The simulation stops when the maximum simulation time is reached or all organisms have died.
- Final statistics are logged upon simulation completion.
Running the Simulation
To run the simulation:
-
Install Dependencies: Make sure you have
matplotlibinstalled. You can install it via pip:pip install matplotlib -
Execute the Script: Save the optimized code to a Python file, say
organism_simulation.py, and run:python organism_simulation.py -
Interact with the Visualization: A window will pop up showing the simulation in real-time. Organisms are represented as colored dots (color indicates smartness), and resources as X markers (red for food, blue for water). The side text displays current time, population, and average statistics.
Potential Further Enhancements
Depending on your project goals, you can extend the simulation with additional features:
- Multiple Organism Traits: Introduce traits like speed, reproduction rate, or lifespan.
- Plant Growth Seasons: Simulate seasonal changes affecting resource availability.
- Predator-Prey Dynamics: Add predator organisms that hunt others, introducing additional survival mechanics.
- Terrain Types: Create different terrains like forests, water bodies, or mountains, affecting movement and resource distribution.
- Genetic Tracking: Track lineage and analyze how traits evolve over generations.
- Interaction Between Organisms: Allow behaviors like cooperation or competition for resources.
These enhancements can make the simulation more realistic and offer deeper insights into ecosystem dynamics.
- Use