Skip to content

moggan1337/Genesis

Repository files navigation

Genesis - Living Simulation Engine

Version License TypeScript Node

Overview

Genesis is a sophisticated living simulation engine that brings artificial life to your computer. It combines cellular automata, genetic programming, neural networks, and ecological dynamics to create a sandbox where digital organisms evolve, compete, form societies, and exhibit emergent behaviors—all driven by the same fundamental principles that govern life on Earth.

╔═══════════════════════════════════════════════════════════════════════════════╗
║                                                                               ║
║     ██████╗ ███████╗███████╗███████╗███████╗     ██████╗██╗      ██████╗ ███████╗   ║
║    ██╔═══██╗██╔════╝██╔════╝██╔════╝██╔════╝    ██╔════╝██║     ██╔═══██╗██╔════╝   ║
║    ██║   ██║█████╗  ███████╗███████╗█████╗      ██║     ██║     ██║   ██║███████╗   ║
║    ██║   ██║██╔══╝  ╚════██║╚════██║██╔══╝      ██║     ██║     ██║   ██║╚════██║   ║
║    ╚██████╔╝███████╗███████║███████║███████╗    ╚██████╗███████╗╚██████╔╝███████║   ║
║     ╚═════╝ ╚══════╝╚══════╝╚══════╝╚══════╝     ╚═════╝╚══════╝ ╚═════╝ ╚══════╝   ║
║                                                                               ║
║                    L I V I N G   S I M U L A T I O N   E N G I N E            ║
║                        with Emergent Behavior & Evolution                     ║
║                                                                               ║
╚═══════════════════════════════════════════════════════════════════════════════╝

🎬 Demo

Genesis Demo

Living simulation with evolving digital organisms

Screenshots

Component Preview
World View world
Organism Panel organisms
Evolution Stats stats

Visual Description

World view shows cellular grid with organisms moving and interacting. Organism panel displays selected creature genetics and neural network. Evolution stats show population graphs and fitness curves.


Table of Contents

  1. Features
  2. Quick Start
  3. Core Concepts
  4. Architecture
  5. API Reference
  6. Configuration
  7. Examples
  8. Emergent Behaviors
  9. Benchmarks
  10. Contributing
  11. License

Features

🧬 Genetic Programming

  • 16 Gene Types: Metabolism, speed, size, aggression, vision range, energy storage, and more
  • Chromosome System: 4 chromosomes per organism with crossover and mutation
  • Mutation Types: Point mutations, duplications, inversions, and deletions
  • Fitness Evaluation: Multi-objective fitness combining survival, reproduction, and adaptation

🧠 Neural Networks as Brains

  • Evolved Architectures: Each entity has a neural network "brain"
  • Hebbian Learning: "Neurons that fire together, wire together"
  • Multiple Networks: Decision, prediction, and value networks working together
  • Working Memory: Short-term memory for decision making

🌍 Environmental Physics & Chemistry

  • Thermodynamics: Temperature-dependent metabolism (Q10 model)
  • Fluid Dynamics: Movement through environment
  • Chemical Reactions: Photosynthesis, respiration, decomposition
  • Resource Diffusion: Nutrients and energy flow through the ecosystem

🦠 Digital Organisms

  • 6 Entity Types: Producers, Herbivores, Carnivores, Predators, Decomposers, Symbionts
  • Metabolism: Energy consumption based on size and temperature
  • Reproduction: Asexual and sexual reproduction with mutation
  • Death: Natural death from starvation, injury, or old age

🌿 Ecosystem Dynamics

  • Predator-Prey Cycles: Lotka-Volterra dynamics
  • Food Chains: Trophic levels with energy transfer efficiency
  • Symbiosis: Mutualistic relationships between organisms
  • Competition: Resource competition drives natural selection

✨ Emergent Behaviors

  • Flocking: Coordinated movement patterns
  • Hunting Coordination: Pack hunting strategies
  • Territory Formation: Spatial organization
  • Collective Defense: Group defensive behaviors
  • Migration: Seasonal population movements

Quick Start

Installation

# Clone the repository
git clone https://github.com/moggan1337/Genesis.git
cd Genesis

# Install dependencies
npm install

# Build the project
npm run build

Running the Demo

# Run the basic demo
npm run run:demo

# Run the ecosystem demo (extended)
npm run run:ecosystem

# Run benchmarks
npm run benchmark

Basic Usage

import { GenesisSimulation } from './src/index';

// Create a simulation with custom configuration
const simulation = new GenesisSimulation({
  width: 100,
  height: 100,
  tickRate: 60,           // Ticks per second
  populationSize: 50,     // Initial population
  maxEntities: 200,       // Maximum entities
  enableEvolution: true,   // Enable natural selection
  enableNeuralNetworks: true, // Enable neural evolution
});

// Listen to simulation events
simulation.on('tick', (result) => {
  console.log(`Tick: ${result.tick}, Entities: ${result.entityCount}`);
});

// Start the simulation
simulation.start();

// Stop after 10 seconds
setTimeout(() => simulation.stop(), 10000);

Core Concepts

Cellular Automata

The simulation grid forms the foundation of Genesis, extending Conway's Game of Life with environmental factors:

import { Grid } from './src/core/World';

// Create a grid
const grid = new Grid(200, 200, 'optional-seed');

// Get and modify cells
const cell = grid.getCell(50, 50);
cell.temperature = 25;
cell.humidity = 60;
cell.resources.set(ResourceType.ENERGY, 100);

// Get neighbors (Moore or Von Neumann)
const mooreNeighbors = grid.getMooreNeighbors(50, 50);  // 8 neighbors
const vonNeumannNeighbors = grid.getVonNeumannNeighbors(50, 50);  // 4 neighbors

// Diffuse resources across the grid
grid.diffuseResources(0.1);

Grid Features:

  • Perlin noise-based terrain generation
  • Temperature and humidity gradients
  • Resource distribution and diffusion
  • Day/night cycles affecting energy
  • Weather events (rain, drought, storms)

Genetic Programming

Organisms in Genesis have genomes that evolve over time:

import { GeneticCode } from './src/genetics/Genetics';
import { GeneType } from './src/core/types';

// Create a random genome
const genome = new GeneticCode();

// Get gene values
const speed = genome.getValue(GeneType.SPEED);
const size = genome.getValue(GeneType.SIZE);
const aggression = genome.getValue(GeneType.AGGRESSION);

// Mutate the genome
const mutations = genome.mutate(0.1, currentTick);  // 10% mutation rate

// Crossover with another genome
const parent2 = new GeneticCode();
const { offspring1, offspring2 } = genome.crossover(parent2);

// Clone for reproduction
const childGenome = genome.clone();

Gene Types:

Gene Range Description
METABOLISM 0.1 - 2.0 Energy consumption rate
SPEED 0.1 - 5.0 Movement speed
SIZE 0.5 - 10.0 Body size
AGGRESSION 0 - 1.0 Tendency to attack
VISION_RANGE 1 - 20 Detection distance
ENERGY_STORAGE 10 - 500 Maximum energy
DEFENSE 0 - 1.0 Damage reduction
ATTACK 0 - 1.0 Damage dealt
REPRODUCTION 0.01 - 0.5 Reproduction rate
LIFESPAN 100 - 10000 Maximum age
SYMBIOSIS 0 - 1.0 Symbiosis affinity

Neural Networks

Each organism has a neural network brain that processes sensory input and generates behavior:

import { NeuralNetwork, EvolvedBrain } from './src/neural/NeuralNetwork';

// Create a neural network
const brain = new EvolvedBrain(
  inputSize = 10,    // Sensory inputs
  outputSize = 4,     // Movement/action outputs
  memorySize = 5      // Working memory size
);

// Process sensory input
const { decisions, predictions, value } = brain.process([
  0.5,  // Nearest threat distance
  0.8,  // Nearest food distance
  0.3,  // Temperature preference
  0.7,  // Humidity preference
  0.5,  // Time of day
  0.2,  // Population density
  0.9,  // Energy level
  0.1,  // Age
  0.0,  // Symbiont nearby
  0.5,  // Random noise
]);

// Apply decision
// decisions[0], decisions[1] = movement direction
// decisions[2], decisions[3] = action choices

// Learn from experience
brain.learn(inputs, expectedOutputs, reward);

Network Architecture:

  • Multiple specialized networks (decision, prediction, value)
  • Working memory with decay
  • Hebbian learning for association
  • Mutation and crossover for evolution

Environmental Physics

The physics engine handles movement, collisions, and environmental effects:

import { PhysicsEngine, ChemistryEngine, Thermodynamics } from './src/physics/Physics';

// Create physics engine
const physics = new PhysicsEngine({
  gravity: { x: 0, y: 9.81 },
  friction: 0.1,
  restitution: 0.8,
});

// Add a physics body
physics.addBody({
  id: 'entity_1',
  position: { x: 10, y: 10 },
  velocity: { x: 1, y: 0 },
  acceleration: { x: 0, y: 0 },
  mass: 1.0,
  radius: 0.5,
  isStatic: false,
});

// Update physics
physics.update(deltaTime);

// Chemistry engine for biochemical reactions
const chemistry = new ChemistryEngine();

// Simulate photosynthesis
const photosynthesis = chemistry.simulatePhotosynthesis(
  co2Conc, waterConc, lightIntensity
);

// Calculate metabolic rate with temperature
const metabolicRate = Thermodynamics.calculateMetabolicRate(
  bodyMass, temperature, Q10 = 2.0
);

Ecosystem Dynamics

The ecosystem manages all organisms and their interactions:

import { Ecosystem } from './src/ecosystem/Ecosystem';

// Create ecosystem
const ecosystem = new Ecosystem(grid, {
  initialProducers: 50,
  initialHerbivores: 30,
  initialCarnivores: 10,
  initialDecomposers: 15,
  carryingCapacity: 500,
});

// Main update loop
ecosystem.update(deltaTime);

// Get statistics
const stats = ecosystem.getStatistics();
console.log(`
  Biodiversity: ${stats.biodiversityIndex.toFixed(3)}
  Food Chain: ${stats.foodChainLength} levels
  Energy Efficiency: ${stats.energyEfficiency.toFixed(3)}
  Stability: ${(stats.stability * 100).toFixed(1)}%
`);

// Get food chain information
const foodChain = ecosystem.getFoodChain();

Architecture

Genesis/
├── src/
│   ├── core/
│   │   ├── types.ts          # TypeScript interfaces and types
│   │   └── World.ts           # Cellular automata grid system
│   ├── genetics/
│   │   └── Genetics.ts        # Genetic code, mutations, crossover
│   ├── neural/
│   │   └── NeuralNetwork.ts   # Neural networks and evolved brains
│   ├── physics/
│   │   └── Physics.ts         # Physics, chemistry, thermodynamics
│   ├── entities/
│   │   └── Entity.ts          # Digital organisms and behaviors
│   ├── evolution/
│   │   └── Evolution.ts       # Natural selection, coevolution
│   ├── ecosystem/
│   │   └── Ecosystem.ts       # Ecosystem dynamics
│   ├── environment/
│   │   └── Environment.ts     # Environment and rendering
│   └── index.ts               # Main simulation engine
├── tests/
│   └── simulation.test.ts     # Unit tests
├── benchmarks/
│   └── benchmark.ts           # Performance benchmarks
├── demo.ts                    # Basic demo
├── ecosystem-demo.ts          # Extended ecosystem demo
└── package.json

API Reference

GenesisSimulation

Main simulation class that orchestrates all systems.

// Constructor
new GenesisSimulation(config?: Partial<SimulationConfig>)

// Control methods
simulation.start()           // Start the simulation
simulation.stop()            // Stop the simulation
simulation.pause()           // Pause the simulation
simulation.resume()          // Resume the simulation
simulation.step()           // Execute one tick
simulation.reset(config?)    // Reset with optional new config

// Entity management
simulation.spawnEntity(type, x, y, geneticCode?)
simulation.removeEntity(id)
simulation.getEntity(id)
simulation.getAllEntities()

// Neural network control
simulation.trainEntityBrain(entityId, inputs, expectedOutputs)
simulation.evolveBrains()

// Statistics
simulation.getTickResult()
simulation.getHistory()
simulation.getStatistics()

// Rendering
simulation.initializeRenderer(container?)
simulation.render()
simulation.renderASCII()

Grid

Cellular automata grid with terrain and resources.

// Creation
new Grid(width, height, seed?)

// Cell access
grid.getCell(x, y)
grid.setCell(x, y, cell)
grid.getNeighborCells(x, y, radius)
grid.getMooreNeighbors(x, y)    // 8 neighbors
grid.getVonNeumannNeighbors(x, y)  // 4 neighbors

// Environment
grid.updateCellTemperature(x, y, delta)
grid.updateCellHumidity(x, y, delta)
grid.diffuseResources(rate)
grid.applyWeatherCycle(dayLength, tick)

// Queries
grid.getAverageTemperature()
grid.getAverageHumidity()
grid.getTotalResource(resource)
grid.getDimensions()

// Serialization
grid.serialize()
Grid.deserialize(data)

GeneticCode

Genetic programming system for evolution.

// Creation
new GeneticCode()                      // Random
new GeneticCode(existingGenome)         // From genome

// Gene access
genome.getGene(type)                   // Get single gene
genome.getAllGenes()                   // Get all genes
genome.getValue(type, default?)        // Get gene value

// Evolution
genome.mutate(rate, tick)              // Apply mutations
genome.crossover(other)                // Crossover with another
genome.clone()                         // Clone the genome

// Analysis
genome.getDiversityScore(other)         // Genetic distance
genome.getMutationHistory()            // Mutation log
genome.toGenome()                      // Convert to Genome type

EntityFactory

Factory for creating digital organisms.

// Entity creation
EntityFactory.create(type, position, geneticCode?)
EntityFactory.createProducer(position, geneticCode?)
EntityFactory.createHerbivore(position, geneticCode?)
EntityFactory.createCarnivore(position, geneticCode?)
EntityFactory.createDecomposer(position, geneticCode?)
EntityFactory.createPredator(position, geneticCode?)

// Reproduction
EntityFactory.reproduce(parent, childPosition)

Configuration

interface SimulationConfig {
  width: number;                    // Grid width (default: 200)
  height: number;                  // Grid height (default: 200)
  tickRate: number;                // Ticks per second (default: 60)
  mutationRate: number;             // Mutation probability (default: 0.01)
  crossoverRate: number;           // Crossover probability (default: 0.7)
  populationSize: number;          // Initial population (default: 100)
  maxEntities: number;             // Maximum entities (default: 500)
  energyTransferEfficiency: number; // Energy transfer rate (default: 0.3)
  temperatureBase: number;          // Base temperature (default: 20)
  humidityBase: number;             // Base humidity (default: 50)
  enablePhysics: boolean;           // Enable physics (default: true)
  enableChemistry: boolean;         // Enable chemistry (default: true)
  enableEvolution: boolean;         // Enable evolution (default: true)
  enableNeuralNetworks: boolean;    // Enable neural nets (default: true)
}

interface EcosystemConfig {
  initialProducers: number;         // Initial producers (default: 50)
  initialHerbivores: number;        // Initial herbivores (default: 30)
  initialCarnivores: number;         // Initial carnivores (default: 10)
  initialDecomposers: number;       // Initial decomposers (default: 15)
  resourceRegenerationRate: number; // Resource regen rate (default: 0.01)
  maxResources: number;             // Maximum resources (default: 1000)
  carryingCapacity: number;         // Max population (default: 500)
  seasonalCycleLength: number;       // Season length (default: 1000)
}

interface EnvironmentConfig {
  temperature: number;             // Current temperature
  humidity: number;                 // Current humidity
  radiation: number;                // Radiation level
  lightIntensity: number;          // Light level (0-1)
  dayLength: number;                // Day cycle length (default: 100)
  yearLength: number;               // Year cycle length (default: 1000)
  climateType: ClimateType;         // Tropical, Temperate, Arctic, etc.
}

Examples

Basic Simulation

import { GenesisSimulation } from './src/index';

const sim = new GenesisSimulation({
  width: 100,
  height: 100,
  tickRate: 30,
  populationSize: 50,
});

sim.on('tick', (result) => {
  if (result.tick % 100 === 0) {
    console.log(`
      Tick: ${result.tick}
      Entities: ${result.entityCount}
      Biodiversity: ${result.speciesDiversity.toFixed(3)}
    `);
  }
});

sim.start();

setTimeout(() => {
  sim.stop();
  console.log('Simulation complete!');
}, 30000);

Custom Entity Types

import { EntityFactory, EntityMetabolism } from './src/entities/Entity';
import { GeneticCode } from './src/genetics/Genetics';
import { GeneType } from './src/core/types';

// Create a custom genome
const customGenome = new GeneticCode();
customGenome.setValue(GeneType.SPEED, 3.0);
customGenome.setValue(GeneType.AGGRESSION, 0.8);
customGenome.setValue(GeneType.SIZE, 2.5);

// Create entity with custom genome
const superPredator = EntityFactory.createPredator(
  { x: 50, y: 50 },
  customGenome
);

// Modify behavior
superPredator.energy = superPredator.phenotype.energyStorage; // Full energy

Event-Driven Simulation

const sim = new GenesisSimulation();

// Listen for various events
sim.on('start', () => console.log('Simulation started!'));
sim.on('stop', () => console.log('Simulation stopped!'));
sim.on('tick:100', (result) => console.log('Reached tick 100!'));
sim.on('tick', (result) => {
  // Check for emergent behavior
  if (result.speciesDiversity > 2.0) {
    console.log('High biodiversity detected!');
  }
});

// Custom event
sim.emit('customEvent', { data: 'example' });

ASCII Visualization

const sim = new GenesisSimulation();
sim.start();

setInterval(() => {
  console.clear();
  console.log(sim.renderASCII());
}, 100);

Emergent Behaviors

Genesis is designed to observe and quantify emergent behaviors:

Detected Behaviors

Behavior Description Detection Method
Flocking Coordinated movement of groups Velocity alignment > 80%
Hunting Coordination Pack hunting strategies Multiple predators surrounding prey
Territory Formation Spatial clustering Low variance in position distribution
Migration Coordinated population movement Consistent directional velocity
Collective Defense Group defensive formations Grouped entities with high defense
Symbiosis Mutualistic relationships Entities sharing resources

Example Output

🔬 Emergent Behavior Detected!
Type: HUNTING_COORDINATION
Description: 5 predator entities coordinating to surround prey
Entities: [entity_42, entity_55, entity_67, entity_71, entity_89]
Strength: 0.87
Tick: 1523

Custom Behavior Detection

import { EmergentBehaviorDetector } from './src/evolution/Evolution';

const detector = new EmergentBehaviorDetector(0.7);  // 70% threshold

// Detect behaviors each tick
const behaviors = detector.detectBehaviors(entities);

// Access history
const flockingHistory = detector.getBehaviorHistory(EmergentBehaviorType.FLOCKING);

Benchmarks

Performance characteristics (measured on modern hardware):

Grid Operations

Operation Performance
Cell retrieval ~50,000 ops/sec
Neighbor retrieval ~25,000 ops/sec
Resource diffusion (100x100) ~2,000 ops/sec
Grid creation (500x500) ~100 ops/sec

Neural Networks

Network Size Forward Pass Ops/sec
Small (8-16-4) 0.1ms ~100,000
Medium (20-32-24-16-8) 0.2ms ~50,000
Large (50-64-48-32-16-20) 0.8ms ~12,000

Full Simulation

Configuration Per Tick
50x50 grid, 50 entities ~5ms
100x100 grid, 200 entities ~20ms
200x200 grid, 500 entities ~80ms

Running Benchmarks

npm run benchmark

API Examples

Training Entity Brains

const sim = new GenesisSimulation();

// Get an entity
const entity = sim.getEntity('entity_42');

// Define training data
const inputs = [
  [0.5, 0.3, 0.8, 0.1, 0.9, 0.2, 0.7, 0.4, 0.6, 0.3],
  [0.2, 0.7, 0.1, 0.9, 0.3, 0.8, 0.4, 0.6, 0.5, 0.1],
  // ... more training examples
];

const expectedOutputs = [
  [1, 0, 0, 0],  // Flee
  [0, 1, 0, 0],  // Chase food
  // ... corresponding outputs
];

// Train the entity's brain
for (let i = 0; i < inputs.length; i++) {
  sim.trainEntityBrain('entity_42', inputs[i], expectedOutputs[i]);
}

Serialization and State

const sim = new GenesisSimulation();
sim.start();

// ... run simulation ...

// Serialize current state
const state = sim.serialize();

// Later, restore state
const restoredSim = JSON.parse(state);
// Note: Full deserialization requires additional implementation

Performance Tips

  1. Grid Size: Larger grids use more memory but enable more complex behaviors
  2. Entity Count: Balance between population size and tick rate
  3. Neural Networks: Smaller networks are faster but less capable
  4. Physics: Disable if not needed (enablePhysics: false)
  5. Rendering: Use ASCII mode for headless environments

Contributing

Contributions are welcome! Please read our guidelines and submit pull requests.

# Run tests
npm test

# Run with coverage
npm run test:coverage

# Lint code
npm run lint

# Format code
npm run format

Roadmap

  • v1.1: GUI visualization with real-time controls
  • v1.2: Multi-species evolution tracking
  • v1.3: GPU acceleration for large simulations
  • v2.0: 3D environment support
  • v2.1: Cultural evolution layer
  • v2.2: Language and communication systems

References

  1. Conway's Game of Life: Cellular automata foundation
  2. Lotka-Volterra Equations: Predator-prey dynamics
  3. Genetic Algorithms: Evolution and selection
  4. Neural Networks: Learning and decision making
  5. Ecosystem Ecology: Energy flow and trophic levels

License

MIT License - See LICENSE for details.


Genesis - Where digital life evolves ✨

About

Living Simulation Engine with Emergent Behavior - Digital Organisms, Evolution, and Ecosystem Dynamics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors