### Install EvoGym from Source Source: https://github.com/evolutiongym/evogym/blob/main/README.md Install EvoGym locally after cloning the repository. This command installs the package in editable mode. ```shell pip install -e . ``` -------------------------------- ### Basic EvoGym Simulation Example Source: https://github.com/evolutiongym/evogym/blob/main/README.md This script demonstrates creating a random robot, initializing the Walker-v0 environment, and running a simulation with random actions. A visualization window will open. ```python import gymnasium as gym import evogym.envs from evogym import sample_robot if __name__ == '__main__': body, connections = sample_robot((5,5)) env = gym.make('Walker-v0', body=body, render_mode='human') env.reset() while True: action = env.action_space.sample() ob, reward, terminated, truncated, info = env.step(action) if terminated or truncated: env.reset() env.close() ``` -------------------------------- ### Install EvoGym using pip Source: https://github.com/evolutiongym/evogym/blob/main/README.md Install the EvoGym library using pip. This command upgrades the installation if a previous version exists. ```shell pip install evogym --upgrade ``` -------------------------------- ### Install Linux Dependencies Source: https://github.com/evolutiongym/evogym/blob/main/README.md On Linux systems, install necessary development packages for graphics and OpenGL support. ```shell sudo apt-get install xorg-dev libglu1-mesa-dev ``` -------------------------------- ### Install Python Requirements Source: https://github.com/evolutiongym/evogym/blob/main/README.md Install the necessary Python packages for EvoGym. For development, additional requirements are needed. ```shell pip install -r requirements.txt ``` ```shell pip install -r requirements-dev.txt ``` -------------------------------- ### Run EvoGym Installation Test Source: https://github.com/evolutiongym/evogym/blob/main/README.md Execute a Python script to test the EvoGym installation by running a simulation with a random robot. ```shell python gym_test.py ``` -------------------------------- ### Resolve Conda libGL Error Source: https://github.com/evolutiongym/evogym/blob/main/README.md If encountering a libGL error with MESA-LOADER on Linux when using Conda, install the libstdcxx-ng package from conda-forge. ```shell conda install -c conda-forge libstdcxx-ng ``` -------------------------------- ### Initialize EvoSim and run simulation Source: https://context7.com/evolutiongym/evogym/llms.txt Sets up an EvoWorld from a JSON file, adds a robot, and initializes EvoSim. It then runs a simulation for a specified number of steps, applying random actions and checking for instability. ```python from evogym import EvoWorld, EvoSim, sample_robot import numpy as np import os world = EvoWorld.from_json(os.path.join('world_data', 'simple_environment.json')) body, connections = sample_robot((5, 5)) world.add_from_array('robot', body, 3, 1, connections=connections) sim = EvoSim(world) sim.reset() print("actuator count:", sim.get_dim_action_space('robot')) print("actuator indices:", sim.get_actuator_indices('robot')) for step in range(200): action = np.random.uniform(0.6, 1.6, size=(sim.get_dim_action_space('robot'),)) sim.set_action('robot', action) unstable = sim.step() if unstable: print(f"Simulation unstable at step {step}") break t = sim.get_time() pos = sim.object_pos_at_time(t, 'robot') # shape (2, n_points) vel = sim.object_vel_at_time(t, 'robot') # shape (2, n_points) ort = sim.object_orientation_at_time(t, 'robot') # float, radians [0, 2π] print("robot CoM x:", np.mean(pos[0])) print("robot orientation (rad):", round(ort, 3)) sim.reset() # revert to time 0 ``` -------------------------------- ### Render EvoGym Simulator Options Source: https://github.com/evolutiongym/evogym/blob/main/tutorials/README.md Execute this command to explore different rendering options for the EvoGym simulator. This is useful for understanding visualization capabilities. ```bash python .\rendering_options.py --render-option to-debug-screen ``` -------------------------------- ### Initialize EvoViewer and render simulation Source: https://context7.com/evolutiongym/evogym/llms.txt Configures EvoViewer to render an EvoSim instance, either to the screen or as a NumPy array. It sets up camera tracking for a specified object and runs the simulation for a set number of steps. ```python from evogym import EvoWorld, EvoSim, EvoViewer, sample_robot import numpy as np import os world = EvoWorld.from_json(os.path.join('world_data', 'simple_environment.json')) body, connections = sample_robot((5, 5)) world.add_from_array('robot', body, 3, 1, connections=connections) sim = EvoSim(world) sim.reset() viewer = EvoViewer( sim, target_rps=50, # cap rendering at 50 fps pos=(12, 4), # camera center in voxel units view_size=(40, 20), # viewbox size in voxels resolution=(1200, 600), # output pixel resolution ) viewer.track_objects('robot') # camera follows the robot for _ in range(300): sim.set_action('robot', np.random.uniform(0.6, 1.6, size=(sim.get_dim_action_space('robot'),))) sim.step() # Render to screen viewer.render('screen') # --- OR --- capture as NumPy array (e.g., for video saving) # img = viewer.render('img') # shape (H, W, 3) uint8 RGB viewer.close() ``` -------------------------------- ### Visualize Simple Environment Source: https://github.com/evolutiongym/evogym/blob/main/tutorials/README.md Run this command to visualize the custom environment defined in `envs/simple_env.py`. Ensure the environment is registered in `envs/__init__.py`. ```bash python .\visualize_simple_env.py ``` -------------------------------- ### Benchmark Environments via gym.make Source: https://context7.com/evolutiongym/evogym/llms.txt Utilize built-in EvoGym environments registered with gymnasium. Environments accept a robot body array and optional connections at construction. Render modes follow the gymnasium standard. ```python import gymnasium as gym import evogym.envs # registers all environments from evogym import sample_robot # Available environment IDs (subset): # Locomotion: Walker-v0, BridgeWalker-v0, BidirectionalWalker-v0, # CaveCrawler-v0, UpStepper-v0, DownStepper-v0, # ObstacleTraverser-v0/v1, Hurdler-v0, GapJumper-v0, # PlatformJumper-v0, Climber-v0/v1/v2, Flipper-v0, Jumper-v0 # Manipulation: Carrier-v0/v1, Pusher-v0/v1, Thrower-v0, Lifter-v0, # BeamToppler-v0, BeamSlider-v0 # Shape change: AreaMaximizer-v0, AreaMinimizer-v0, HeightMaximizer-v0, # Balancer-v0/v1 body, connections = sample_robot((5, 5)) env = gym.make('Walker-v0', body=body, render_mode='rgb_array') obs, info = env.reset() total_reward = 0.0 for step in range(1000): action = env.action_space.sample() # random policy obs, reward, terminated, truncated, info = env.step(action) total_reward += reward if terminated or truncated: obs, info = env.reset() print(f"Total reward: {total_reward:.3f}") env.close() # Headless (server) usage — no display required env_headless = gym.make('Climber-v0', body=body, render_mode=None) obs, _ = env_headless.reset() env_headless.close() ``` -------------------------------- ### Create Custom Gymnasium Environment with EvoGymBase Source: https://context7.com/evolutiongym/evogym/llms.txt Extend EvoGymBase to create custom tasks by overriding step() and reset(). It exposes simulator measurement methods and handles rendering automatically. Requires importing necessary modules and defining the environment's action and observation spaces. ```python from gymnasium import spaces from evogym import EvoWorld from evogym.envs import EvoGymBase from typing import Optional, Dict, Any, Tuple import numpy as np import os class MyWalkerEnv(EvoGymBase): def __init__(self, body: np.ndarray, connections=None, render_mode=None, render_options=None): world = EvoWorld.from_json(os.path.join('world_data', 'simple_walker_env.json')) world.add_from_array('robot', body, 1, 1, connections=connections) super().__init__(world=world, render_mode=render_mode, render_options=render_options) n_act = self.get_actuator_indices('robot').size obs_size = self.reset()[0].size self.action_space = spaces.Box(0.6, 1.6, shape=(n_act,), dtype=float) self.observation_space = spaces.Box(-100.0, 100.0, shape=(obs_size,), dtype=float) self.default_viewer.track_objects('robot') def step(self, action) -> Tuple[np.ndarray, float, bool, bool, dict]: pos_before = self.object_pos_at_time(self.get_time(), 'robot') unstable = super().step({'robot': action}) pos_after = self.object_pos_at_time(self.get_time(), 'robot') reward = np.mean(pos_after[0]) - np.mean(pos_before[0]) # x-displacement if unstable: reward -= 3.0 terminated = np.mean(pos_after[0]) > 28 or unstable obs = np.concatenate([self.get_vel_com_obs('robot'), self.get_relative_pos_obs('robot')]) return obs, reward, terminated, False, {} def reset(self, seed=None, options=None): super().reset(seed=seed, options=options) obs = np.concatenate([self.get_vel_com_obs('robot'), self.get_relative_pos_obs('robot')]) return obs, {} # Usage from evogym import sample_robot body, connections = sample_robot((5, 5)) env = MyWalkerEnv(body, connections, render_mode='human') obs, _ = env.reset() for _ in range(500): obs, reward, terminated, truncated, info = env.step(env.action_space.sample()) if terminated or truncated: obs, _ = env.reset() env.close() ``` -------------------------------- ### Run PPO Control Optimization Source: https://github.com/evolutiongym/evogym/blob/main/examples/README.md Trains a robot's policy in the Walker-v0 environment using PPO. Customize training with --help. For serious runs, increase total-timesteps significantly. ```shell python run_ppo.py --n-envs 4 --n-eval-envs 4 --n-evals 4 --eval-interval 10000 --total-timesteps 100000 ``` -------------------------------- ### Run CPPN-NEAT Co-Design Source: https://github.com/evolutiongym/evogym/blob/main/examples/README.md Executes CPPN-NEAT for co-design. Core parameters include experiment name, environment, population size, structure shape, max evaluations, and number of cores. ```shell python run_cppn_neat.py --eval-interval 10000 --total-timesteps 100000 ``` -------------------------------- ### Visualize Co-Design Results Source: https://github.com/evolutiongym/evogym/blob/main/examples/README.md Visualizes results from co-design experiments. Ensure the correct environment name is used and follow on-screen instructions. ```shell python visualize.py --env-name "Walker-v0" ``` -------------------------------- ### Include Directories and Link Libraries for Simulator Module Source: https://github.com/evolutiongym/evogym/blob/main/evogym/simulator/SimulatorCPP/CMakeLists.txt This section specifies the include paths for the simulator module and links against essential libraries such as GLEW, GLFW, and platform-specific libraries on Windows. It also sets the C++ standard library and enables verbose makefile output. ```cmake target_include_directories(simulator_cpp PRIVATE ${EXTERNAL_HEADER}) target_include_directories(simulator_cpp PRIVATE ${SOURCE_DIR}/) target_link_libraries(simulator_cpp PRIVATE glew) target_link_libraries(simulator_cpp PRIVATE glfw) if(WIN32) target_link_libraries(simulator_cpp PRIVATE kernel32) target_link_libraries(simulator_cpp PRIVATE opengl32) target_link_libraries(simulator_cpp PRIVATE gdi32) target_link_libraries(simulator_cpp PRIVATE user32) target_link_libraries(simulator_cpp PRIVATE shell32) endif() set(CMAKE_CXX_STANDARD_LIBRARIES -ldl) set(CMAKE_VERBOSE_MAKEFILE ON) ``` -------------------------------- ### Create Environment in Headless Mode Source: https://github.com/evolutiongym/evogym/blob/main/README.md When running in headless mode (e.g., on a server without rendering), ensure environments are created with render_mode=None. ```python # Envs are created with render_mode=None (None by default) env = gym.make('Walker-v0', body=body, render_mode=None) ``` -------------------------------- ### Run Full Test Suite Source: https://github.com/evolutiongym/evogym/blob/main/README.md Navigate to the 'tests' directory and run the full test suite using pytest. ```shell cd tests pytest -s -v -n auto ``` -------------------------------- ### Add SimulatorCPP Subdirectory and Linker Flags Source: https://github.com/evolutiongym/evogym/blob/main/evogym/simulator/CMakeLists.txt Includes the SimulatorCPP build directory and sets the C++ standard libraries to include libdl. Optionally enables verbose makefile output. ```cmake add_subdirectory(SimulatorCPP/) set(CMAKE_CXX_STANDARD_LIBRARIES -ldl) # set(CMAKE_VERBOSE_MAKEFILE ON) ``` -------------------------------- ### Find and Configure OpenGL and GLEW Source: https://github.com/evolutiongym/evogym/blob/main/evogym/simulator/CMakeLists.txt Locates the OpenGL and GLEW libraries, setting up include paths and library locations for GLEW. This is typically done on UNIX systems. ```cmake if(UNIX) find_package(OpenGL REQUIRED) set(CMAKE_MODULE_PATH ${PROJECT_SOURCE_DIR}) set(GLEW_INCLUDE_DIR ${PROJECT_SOURCE_DIR}/externals/glew/include) set(GLEW_LIBRARY ${PROJECT_SOURCE_DIR}/externals/glew/lib/libGLEW.*) find_package(GLEW REQUIRED) endif() ``` -------------------------------- ### Print VOXEL_TYPES and Build a Robot Body Source: https://context7.com/evolutiongym/evogym/llms.txt Demonstrates how to access and use the VOXEL_TYPES dictionary to define a robot's body structure. Asserts connectivity and actuator presence, then retrieves full connectivity information. ```python from evogym import VOXEL_TYPES import numpy as np print(VOXEL_TYPES) # {'EMPTY': 0, 'RIGID': 1, 'SOFT': 2, 'H_ACT': 3, 'V_ACT': 4, 'FIXED': 5} # Build a hand-crafted 3×3 robot: rigid shell with vertical actuator core E = VOXEL_TYPES['EMPTY'] R = VOXEL_TYPES['RIGID'] V = VOXEL_TYPES['V_ACT'] H = VOXEL_TYPES['H_ACT'] body = np.array([ [R, R, R], [R, V, R], [R, H, R], ], dtype=float) from evogym import is_connected, has_actuator, get_full_connectivity assert is_connected(body) and has_actuator(body) connections = get_full_connectivity(body) # shape (2, 8) ``` -------------------------------- ### Configure Target Properties for Output Directories Source: https://github.com/evolutiongym/evogym/blob/main/evogym/simulator/SimulatorCPP/CMakeLists.txt These commented-out lines show how to set the output directories for the compiled module's archive, library, and runtime files. Uncomment and modify as needed for specific build configurations. ```cmake # set_target_properties(simulator_cpp # PROPERTIES # ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/evogym" # LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/evogym" # RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/evogym" # ) ``` -------------------------------- ### Sample Robot Structure with EvoGym Source: https://context7.com/evolutiongym/evogym/llms.txt Samples a random robot body and its connectivity. Can use default or custom voxel type probabilities. Ensure the sampled robot is connected and has actuators for valid use. ```python from evogym import sample_robot, VOXEL_TYPES import numpy as np # Sample a random 5×5 robot with default voxel probabilities body, connections = sample_robot((5, 5)) print("body shape:", body.shape) # (5, 5) print("connections shape:", connections.shape) # (2, k) # Sample with a custom distribution: bias toward actuators pd = np.array([0.4, 0.1, 0.1, 0.2, 0.2]) # [empty, rigid, soft, h_act, v_act] body2, connections2 = sample_robot((3, 3), pd=pd) print("voxel types present:", np.unique(body2)) # Expected output: subset of [0. 1. 2. 3. 4.] ``` -------------------------------- ### EvoWorld: Specify and Manipulate Environment Layout Source: https://context7.com/evolutiongym/evogym/llms.txt Manages the voxel grid of a scene, allowing environments to be loaded from JSON or built programmatically. Supports adding, inspecting, translating, moving, and removing robot objects within the world. ```python from evogym import EvoWorld, sample_robot import os import numpy as np # --- Load from JSON (recommended for benchmark envs) --- world = EvoWorld.from_json(os.path.join('world_data', 'simple_environment.json')) # --- Add a randomly sampled robot to the world --- body, connections = sample_robot((5, 5)) world.add_from_array( name='robot', structure=body, x=3, # bottom-left x position (voxel units) y=1, # bottom-left y position (voxel units) connections=connections, ) # --- Inspect the world --- world.pretty_print() # Console output (abbreviated): # 1 | R R R R R R . . # 0 | F F F F F F F F # -------------------------- # 0 1 2 3 4 5 6 7 8 # --- Manipulate objects --- world.translate_object('robot', dx=2, dy=0) # shift robot 2 voxels right world.move_object('robot', x=5, y=1) # move robot to absolute position removed = world.remove_object('robot') # remove and return the WorldObject ``` -------------------------------- ### Observation Helper Methods in EvoGymBase Source: https://context7.com/evolutiongym/evogym/llms.txt EvoGymBase provides convenience methods for constructing observations from simulation state, mirroring those used in built-in benchmark environments. These include center-of-mass position/velocity, relative positions, orientation, and terrain profiles. ```python # Inside a custom EvoGymBase subclass: # Center-of-mass position (2,) com_pos = self.get_pos_com_obs('robot') # Center-of-mass velocity (2,) com_vel = self.get_vel_com_obs('robot') # Point-mass positions relative to CoM (2*n_points,) rel_pos = self.get_relative_pos_obs('robot') # Orientation in radians (1,) ort = self.get_ort_obs('robot') # Terrain profile below the robot — distances to floor for each column (2*sight_dist+1,) floor = self.get_floor_obs('robot', terrain_list=['terrain'], sight_dist=5, sight_range=5) # Terrain profile above the robot — distances to ceiling for each column (2*sight_dist+1,) ceil = self.get_ceil_obs('robot', terrain_list=['ceiling', 'terrain'], sight_dist=5, sight_range=5) # Compose full observation vector obs = np.concatenate([com_vel, rel_pos, floor, ceil]) ``` -------------------------------- ### Include External Libraries and Define Project Paths Source: https://github.com/evolutiongym/evogym/blob/main/evogym/simulator/CMakeLists.txt Adds external libraries as a subdirectory and exposes the project and graphics codebase source directories as preprocessor definitions. ```cmake set(EXTERNAL_ROOT ${PROJECT_SOURCE_DIR}/externals) add_subdirectory(${EXTERNAL_ROOT}) get_directory_property(EXTERNAL_HEADER DIRECTORY ${EXTERNAL_ROOT} DEFINITION EXTERNAL_HEADER) # Expose PROJECT_DIR to the source code. add_definitions(-DPROJECT_DIR="${PROJECT_SOURCE_DIR}") add_definitions(-DGRAPHICS_CODEBASE_SOURCE_DIR="${CMAKE_CURRENT_LIST_DIR}") include_directories(${EXTERNAL_HEADER}) ``` -------------------------------- ### Run Lite Test Suite Source: https://github.com/evolutiongym/evogym/blob/main/README.md Navigate to the 'tests' directory and run the lite test suite using pytest with the '-m lite' flag. ```shell cd tests pytest -s -v -n auto -m lite ``` -------------------------------- ### Configure GLEW Static Library Source: https://github.com/evolutiongym/evogym/blob/main/evogym/simulator/externals/CMakeLists.txt Defines the source files and headers for the GLEW library and creates a static library target. It also links the library against the OpenGL library. ```cmake ### GLEW ### set(GLEW_SOURCE glew/src/glew.c ) set(GLEW_HEADERS ) add_library(glew STATIC ${GLEW_SOURCE} ${GLEW_INCLUDE} ) target_link_libraries(glew ${OPENGL_LIBRARY} ) ``` -------------------------------- ### Compute Default Voxel Connections Source: https://context7.com/evolutiongym/evogym/llms.txt Generates a connectivity array for a robot body, assuming all adjacent non-empty voxels are connected. This is the default behavior for `sample_robot` and `EvoWorld.add_from_array` when connections are not explicitly provided. ```python from evogym import get_full_connectivity, VOXEL_TYPES import numpy as np body = np.array([ [VOXEL_TYPES['RIGID'], VOXEL_TYPES['H_ACT']], [VOXEL_TYPES['V_ACT'], VOXEL_TYPES['RIGID']], ]) connections = get_full_connectivity(body) print("connections:", connections) # Each column is a pair of flat indices into body.flatten() # e.g., array([[0, 0, 1, 2], # [1, 2, 3, 3]]) ``` -------------------------------- ### Avoid Rendering in Headless Mode Source: https://github.com/evolutiongym/evogym/blob/main/README.md If using the low-level API in headless mode, do not call EvoViewer.render() as this initializes rendering libraries. ```python # If using the low-level api, do not call EvoViewer.render() world = EvoWorld.from_json(os.path.join('world_data', 'simple_environment.json')) sim = EvoSim(world) viewer = EvoViewer(sim) viewer.render('img') # <-- Rendering libraries are initialized; do not call this ``` -------------------------------- ### Clone EvoGym Repository Source: https://github.com/evolutiongym/evogym/blob/main/README.md Clone the EvoGym repository including its submodules. This is required for building from source. ```shell git clone --recurse-submodules https://github.com/EvolutionGym/evogym.git ``` -------------------------------- ### Set C++ Standard and External Header Paths Source: https://github.com/evolutiongym/evogym/blob/main/evogym/simulator/externals/CMakeLists.txt Configures the C++ standard to C++11 and defines a list of external header directories. These paths are then included in the build process. ```cmake set(CMAKE_CXX_STANDARD 11) set(EXTERNAL_HEADER "${CMAKE_CURRENT_LIST_DIR}/eigen" "${CMAKE_CURRENT_LIST_DIR}/glew/include" "${CMAKE_CURRENT_LIST_DIR}/glfw/include/GLFW" ) include_directories(${EXTERNAL_HEADER}) ``` -------------------------------- ### Generate Gifs from Co-Design Experiments Source: https://github.com/evolutiongym/evogym/blob/main/examples/README.md Generates GIFs from co-design experiments. Parameters like resolution, experiment names, load directory, generations, and ranks can be configured within the script. ```python my_job = Job( name = 'ga_walking_experiment_gifs', experiment_names= ['ga_walking_experiment'], env_names = ['Walker-v0'], load_dir = exp_root, ranks = [i for i in range(5)] organize_by_generation=True, ) ``` -------------------------------- ### Add GLFW Subdirectory and Include Directories Source: https://github.com/evolutiongym/evogym/blob/main/evogym/simulator/externals/CMakeLists.txt Includes the GLFW library as a subdirectory and adds its include paths. This makes GLFW's headers available for use in the project. ```cmake ### GLFW ### add_subdirectory(glfw) include_directories( glfw/include/GLFW/ glew/include/ eigen/ ) ``` -------------------------------- ### EvoWorld Source: https://context7.com/evolutiongym/evogym/llms.txt Represents the voxel grid of a scene, allowing for the creation and manipulation of environments. Worlds can be loaded from JSON files or constructed programmatically by adding objects defined by NumPy arrays. It supports adding, inspecting, and transforming objects within the world. ```APIDOC ## `EvoWorld` — Specify the environment layout `EvoWorld` stores the voxel grid of an entire scene, including the terrain and any robot objects. Environments can be loaded from `.json` files (created with the EvoGym Design Tool) or built programmatically by adding objects from NumPy arrays. ```python from evogym import EvoWorld, sample_robot import os import numpy as np # --- Load from JSON (recommended for benchmark envs) --- world = EvoWorld.from_json(os.path.join('world_data', 'simple_environment.json')) # --- Add a randomly sampled robot to the world --- body, connections = sample_robot((5, 5)) world.add_from_array( name='robot', structure=body, x=3, # bottom-left x position (voxel units) y=1, # bottom-left y position (voxel units) connections=connections, ) # --- Inspect the world --- world.pretty_print() # Console output (abbreviated): # 1 | R R R R R R . . # 0 | F F F F F F F F # -------------------------- # 0 1 2 3 4 5 6 7 8 # --- Manipulate objects --- world.translate_object('robot', dx=2, dy=0) # shift robot 2 voxels right world.move_object('robot', x=5, y=1) # move robot to absolute position removed = world.remove_object('robot') # remove and return the WorldObject ``` ``` -------------------------------- ### Run Bayesian Optimization Co-Design Source: https://github.com/evolutiongym/evogym/blob/main/examples/README.md Executes Bayesian optimization for co-design. Core parameters include experiment name, environment, population size, structure shape, max evaluations, and number of cores. ```shell python run_bo.py --eval-interval 10000 --total-timesteps 100000 ``` -------------------------------- ### Add pybind11 Subdirectory Source: https://github.com/evolutiongym/evogym/blob/main/evogym/simulator/externals/CMakeLists.txt Includes the pybind11 library as a subdirectory. This allows pybind11 to be built and linked with the project. ```cmake # pybind11 add_subdirectory(pybind11) ``` -------------------------------- ### Run Genetic Algorithm Co-Design Source: https://github.com/evolutiongym/evogym/blob/main/examples/README.md Executes the genetic algorithm for co-design. Core parameters include experiment name, environment, population size, structure shape, max evaluations, and number of cores. ```shell python run_ga.py --eval-interval 10000 --total-timesteps 100000 ``` -------------------------------- ### get_full_connectivity Source: https://context7.com/evolutiongym/evogym/llms.txt Computes the default connectivity array for a given robot body. It assumes all adjacent (4-directional) non-empty voxels are connected. This is the default behavior used by `sample_robot` and `EvoWorld.add_from_array` when no explicit connections are provided. ```APIDOC ## `get_full_connectivity` — Compute default voxel connections Returns a `(2, k)` connections array assuming all adjacent (4-directional) non-empty voxels are connected. This is the default used by `sample_robot` and `EvoWorld.add_from_array` when `connections=None`. ```python from evogym import get_full_connectivity, VOXEL_TYPES import numpy as np body = np.array([ [VOXEL_TYPES['RIGID'], VOXEL_TYPES['H_ACT']], [VOXEL_TYPES['V_ACT'], VOXEL_TYPES['RIGID']], ]) connections = get_full_connectivity(body) print("connections:", connections) # Each column is a pair of flat indices into body.flatten() # e.g., array([[0, 0, 1, 2], # [1, 2, 3, 3]]) ``` ``` -------------------------------- ### Define Preprocessor Definitions Source: https://github.com/evolutiongym/evogym/blob/main/evogym/simulator/externals/CMakeLists.txt Adds preprocessor definitions for the project. These flags control various aspects of the build, such as static linking and disabling specific features. ```cmake add_definitions( -DTW_STATIC -DTW_NO_LIB_PRAGMA -DTW_NO_DIRECT3D -DGLEW_STATIC -D_CRT_SECURE_NO_WARNINGS ) ``` -------------------------------- ### Set C++ Standard and Suppress Warnings Source: https://github.com/evolutiongym/evogym/blob/main/evogym/simulator/CMakeLists.txt Configures the C++ standard to C++11 and suppresses specific security warnings. Also adds GCC coverage flags on UNIX systems. ```cmake cmake_minimum_required(VERSION 3.1.0) set(CMAKE_SUPPRESS_REGENERATION true) set(CMAKE_POSITION_INDEPENDENT_CODE ON) project(simulator_cpp) # Enable C++ 11 set(CMAKE_CXX_STANDARD 11) # Suppress warnings. add_definitions( -D_CRT_SECURE_NO_WARNINGS ) if(UNIX) set(GCC_COVERAGE_COMPILE_FLAGS "-Wno-format") add_definitions(${GCC_COVERAGE_COMPILE_FLAGS}) endif() ``` -------------------------------- ### sample_robot Source: https://context7.com/evolutiongym/evogym/llms.txt Randomly samples a valid robot structure, returning its body and connectivity arrays. It ensures the sampled structure is connected and contains at least one actuator. An optional probability distribution for voxel types can be provided. ```APIDOC ## `sample_robot` — Randomly sample a valid robot structure Returns a randomly sampled robot body array and its connectivity array. Sampling continues until a connected structure containing at least one actuator is produced. An optional probability distribution over the five voxel types can be supplied. ```python from evogym import sample_robot, VOXEL_TYPES import numpy as np # Sample a random 5x5 robot with default voxel probabilities body, connections = sample_robot((5, 5)) print("body shape:", body.shape) # (5, 5) print("connections shape:", connections.shape) # (2, k) # Sample with a custom distribution: bias toward actuators pd = np.array([0.4, 0.1, 0.1, 0.2, 0.2]) # [empty, rigid, soft, h_act, v_act] body2, connections2 = sample_robot((3, 3), pd=pd) print("voxel types present:", np.unique(body2)) # Expected output: subset of [0. 1. 2. 3. 4.] ``` ``` -------------------------------- ### Create WorldObject from NumPy array Source: https://context7.com/evolutiongym/evogym/llms.txt Defines a WorldObject using a NumPy array for its structure. Sets the object's initial position and demonstrates renaming and copying. ```python from evogym import VOXEL_TYPES from evogym.world import WorldObject import numpy as np R, H, V = VOXEL_TYPES['RIGID'], VOXEL_TYPES['H_ACT'], VOXEL_TYPES['V_ACT'] structure = np.array([ [R, H, R], [R, V, R], ]) obj = WorldObject.from_array('my_robot', structure) obj.set_pos(2, 1) print(obj) # Size (3, 2) object named my_robot at (2, 1). print(obj.get_structure().shape) # (2, 3) print(obj.get_connections().shape) # (2, k) # Rename and copy obj.rename('walker') obj_copy = obj.copy() print(obj_copy.get_name()) # walker ``` -------------------------------- ### Define C++ Python Module with pybind11 Source: https://github.com/evolutiongym/evogym/blob/main/evogym/simulator/SimulatorCPP/CMakeLists.txt This snippet defines a C++ extension module for Python using pybind11. It automatically discovers header and source files, excluding specific files like PythonBindings.cpp, and then builds the module. ```cmake set(SOURCE_DIR ${CMAKE_CURRENT_LIST_DIR}) file(GLOB_RECURSE HEADER ${SOURCE_DIR}/*.h) file(GLOB_RECURSE SOURCE ${SOURCE_DIR}/*.cpp) list(REMOVE_ITEM SOURCE ${SOURCE_DIR}/PythonBindings.cpp) pybind11_add_module(simulator_cpp PythonBindings.cpp ${HEADER} ${SOURCE}) ``` -------------------------------- ### Set Minimum CMake Version and Suppress Regeneration Source: https://github.com/evolutiongym/evogym/blob/main/evogym/simulator/externals/CMakeLists.txt Sets the minimum required CMake version to 3.1 and suppresses regeneration to avoid issues with Visual Studio 2017. This ensures consistent build behavior. ```cmake cmake_minimum_required(VERSION 3.1) # Do not want to generate zeor_check because they cause messy folders in # visual studio 2017. set(CMAKE_SUPPRESS_REGENERATION true) ``` -------------------------------- ### Validate Robot Structure Connectivity and Actuators Source: https://context7.com/evolutiongym/evogym/llms.txt Checks if all non-empty voxels in a robot structure form a single connected component using flood-fill. Also verifies the presence of at least one horizontal or vertical actuator. ```python from evogym import is_connected, has_actuator, VOXEL_TYPES import numpy as np EMPTY, RIGID, SOFT, H_ACT, V_ACT = ( VOXEL_TYPES['EMPTY'], VOXEL_TYPES['RIGID'], VOXEL_TYPES['SOFT'], VOXEL_TYPES['H_ACT'], VOXEL_TYPES['V_ACT'], ) valid_body = np.array([ [RIGID, H_ACT, RIGID], [RIGID, V_ACT, RIGID], ]) disconnected = np.array([ [RIGID, EMPTY, RIGID], [EMPTY, EMPTY, EMPTY], ]) print(is_connected(valid_body)) # True print(has_actuator(valid_body)) # True print(is_connected(disconnected)) # False print(has_actuator(disconnected)) # False ``` -------------------------------- ### is_connected / has_actuator Source: https://context7.com/evolutiongym/evogym/llms.txt Validates a robot structure. `is_connected` checks if all non-empty voxels form a single connected component using flood-fill. `has_actuator` verifies the presence of at least one horizontal or vertical actuator voxel. These functions are useful for validating manually mutated structures. ```APIDOC ## `is_connected` / `has_actuator` — Validate a robot structure `is_connected` runs a flood-fill to verify all non-empty voxels form a single connected component. `has_actuator` checks whether the structure contains at least one horizontal (`H_ACT`) or vertical (`V_ACT`) actuator voxel. Both are used internally by `sample_robot` and are useful when mutating structures manually. ```python from evogym import is_connected, has_actuator, VOXEL_TYPES import numpy as np EMPTY, RIGID, SOFT, H_ACT, V_ACT = ( VOXEL_TYPES['EMPTY'], VOXEL_TYPES['RIGID'], VOXEL_TYPES['SOFT'], VOXEL_TYPES['H_ACT'], VOXEL_TYPES['V_ACT'], ) valid_body = np.array([ [RIGID, H_ACT, RIGID], [RIGID, V_ACT, RIGID], ]) disconnected = np.array([ [RIGID, EMPTY, RIGID], [EMPTY, EMPTY, EMPTY], ]) print(is_connected(valid_body)) # True print(has_actuator(valid_body)) # True print(is_connected(disconnected)) # False print(has_actuator(disconnected)) # False ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.