### Install Numpy and Statistics with Pip Source: https://github.com/pdturney/autopoiesis/blob/master/README.txt After installing Python, use pip to install the Numpy and Statistics libraries. These are required by Model-S for numerical functions. ```bash cd \Python27\Scripts pip install numpy pip install statistics ``` -------------------------------- ### Initialize and Manipulate Seed Objects Source: https://context7.com/pdturney/autopoiesis/llms.txt Demonstrates creating a Seed instance, randomizing its state, calculating properties, and performing geometric transformations. ```python import model_classes as mclass import model_parameters as mparam import numpy as np # Create a new empty seed with dimensions 5x5 for a population of 200 seed = mclass.Seed(xspan=5, yspan=5, pop_size=200) # Randomly initialize cells with 37.5% density (state 1 = living) seed.randomize(seed_density=0.375) # Update the count of living cells seed.num_living = seed.count_ones() # Calculate seed properties print(f"Seed dimensions: {seed.xspan} x {seed.yspan}") print(f"Living cells: {seed.num_living}") print(f"Density: {seed.density():.4f}") print(f"Fitness: {seed.fitness():.3f}") # Calculated from competition history # Create a randomly rotated copy (0, 90, 180, or 270 degrees with optional flip) rotated_seed = seed.random_rotate() # Create a shuffled copy (same dimensions and density, different pattern) shuffled_seed = seed.shuffle() # Convert from red (state 1) to blue (state 2) for Immigration Game seed_copy = copy.deepcopy(seed) seed_copy.red2blue() ``` -------------------------------- ### Build Initial Competition History Source: https://context7.com/pdturney/autopoiesis/llms.txt Populates the initial competition and similarity records for all pairs of seeds in the population. This involves running trials to assess fitness and calculating pairwise similarities. ```python import golly as g import model_classes as mclass import model_functions as mfunc import model_parameters as mparam import random as rand # Build initial competition history (all seeds vs all seeds) for i in range(mparam.pop_size): for j in range(i + 1): mfunc.update_history(g, population, i, j, mparam.width_factor, mparam.height_factor, mparam.time_factor, mparam.num_trials) mfunc.update_similarity(population, i, j) ``` -------------------------------- ### Initialize Population Source: https://context7.com/pdturney/autopoiesis/llms.txt Initializes the simulation population with a specified number of seeds, dimensions, and cell density. This is a foundational step for the evolutionary model. ```python import golly as g import model_classes as mclass import model_functions as mfunc import model_parameters as mparam import random as rand # Set random seed for reproducibility (or -1 for automatic) if mparam.random_seed >= 0: rand.seed(mparam.random_seed) # Initialize population population = mfunc.initialize_population( mparam.pop_size, # 200 seeds mparam.s_xspan, # Initial width: 5 mparam.s_yspan, # Initial height: 5 mparam.seed_density # Initial density: 0.375 ) ``` -------------------------------- ### View Contest Visualization Script Source: https://context7.com/pdturney/autopoiesis/llms.txt Provides an interactive visualization of Immigration Game competitions. It loads two selected seeds (pickles), sets up a Golly universe, and runs the competition step-by-step, determining and printing the winner based on population growth. ```python import golly as g import model_functions as mfunc import model_parameters as mparam import pickle # GUI dialogs to select two pickle files path1 = g.opendialog("Select first seed file", "(*.bin)|*.bin") path2 = g.opendialog("Select second seed file", "(*.bin)|*.bin") # Load seeds (pickles are sorted by fitness, index 0 = best) handle1 = open(path1, "rb") seed1 = pickle.load(handle1)[0] # Top seed from first pickle handle1.close() handle2 = open(path2, "rb") seed2 = pickle.load(handle2)[0] # Top seed from second pickle handle2.close() # Competition loop with visualization while True: # Random rotation for variety s1 = seed1.random_rotate() s2 = seed2.random_rotate() s2.red2blue() # Convert to blue (state 2) # Set up Golly toroidal universe [g_width, g_height, g_time] = mfunc.dimensions(s1, s2, mparam.width_factor, mparam.height_factor, mparam.time_factor) g.setalgo("QuickLife") g.new("Immigration") g.setrule(f"Immigration:T{g_width},{g_height}") # Insert seeds into universe [g_xmin, g_xmax, g_ymin, g_ymax] = mfunc.get_minmax(g) s1.insert(g, g_xmin, -1, g_ymin, g_ymax) # Red on left s2.insert(g, +1, g_xmax, g_ymin, g_ymax) # Blue on right # Run and display competition step-by-step for t in range(g_time): g.run(1) g.update() # Count final populations and determine winner [count1, count2] = mfunc.count_pops(g) # Adjust for growth (final - initial) growth1 = max(0, count1 - s1.num_living) growth2 = max(0, count2 - s2.num_living) if growth1 > growth2: print(f"Red wins! Growth: {growth1} vs {growth2}") elif growth2 > growth1: print(f"Blue wins! Growth: {growth2} vs {growth1}") else: print(f"Tie! Growth: {growth1} each") ``` -------------------------------- ### Configure Model-S Simulation Parameters Source: https://context7.com/pdturney/autopoiesis/llms.txt Defines the simulation environment, population constraints, and evolutionary operators for the Model-S framework. ```python # Experiment type (1-4) experiment_type_num = 4 # 1 = uniform asexual (bit-flip only, fixed size) # 2 = variable asexual (mutation with size changes) # 3 = sexual (crossover + mutation) # 4 = symbiotic (fusion + fission + sexual) # Random seed (-1 for automatic, >=0 for reproducible) random_seed = -1 # Output directory for logs and pickles log_directory = "../experiments/run1" # Population parameters pop_size = 200 # Fixed population size num_generations = 100 # Number of generations run_length = num_generations * pop_size # Total births # Seed dimensions s_xspan = 5 # Initial seed width s_yspan = 5 # Initial seed height min_s_xspan = 5 # Minimum seed width min_s_yspan = 5 # Minimum seed height # Seed initialization seed_density = 0.375 # Initial density of living cells # Competition parameters num_trials = 2 # Trials per seed pair width_factor = 6.0 # Toroid width multiplier height_factor = 3.0 # Toroid height multiplier time_factor = 6.0 # Game duration multiplier # Selection tournament_size = 2 # Tournament selection size elite_size = 50 # Elite sample size for archiving # Mutation probabilities (must sum to 1.0) prob_grow = 0.2 # Probability to grow prob_flip = 0.6 # Probability to flip bits prob_shrink = 0.2 # Probability to shrink mutation_rate = 0.01 # Bit-flip probability per cell # Sexual reproduction min_similarity = 0.80 # Minimum similarity for mating max_similarity = 0.99 # Maximum similarity for mating # Symbiosis prob_fission = 0.01 # Probability of fission prob_fusion = 0.005 # Probability of fusion fusion_test_flag = 0 # Shuffle test (0=normal, 1=shuffle one seed) immediate_symbiosis_flag = 1 # Require immediate fitness gain from fusion # Seed area limits (prevent runaway growth) max_area_first = 120 # Max area at generation 0 max_area_last = 170 # Max area at final generation ``` -------------------------------- ### Compare Populations with Random Individuals Source: https://github.com/pdturney/autopoiesis/blob/master/README.txt Python script to compare simulation run samples against randomly generated individuals. Competitors have the same dimensions and density, ensuring comparison is based on structure. ```python compare_random.py -- compare populations with random individuals ``` -------------------------------- ### Initialize Population Source: https://context7.com/pdturney/autopoiesis/llms.txt Initializes a collection of Seed objects for simulation using the population initialization function. ```python import model_functions as mfunc import model_parameters as mparam # Initialize a population of 200 seeds # Each seed is 5x5 with approximately 37.5% living cells pop_size = 200 s_xspan = 5 s_yspan = 5 seed_density = 0.375 population = mfunc.initialize_population(pop_size, s_xspan, s_yspan, seed_density) print(f"Population size: {len(population)}") print(f"First seed dimensions: {population[0].xspan} x {population[0].yspan}") print(f"First seed living cells: {population[0].num_living}") # Each seed has: # - cells: numpy array of 0s and 1s # - history: array tracking competition results # - similarities: array tracking similarity to other seeds # - address: position in population array # - num_living: count of living cells ``` -------------------------------- ### Execute Reproduction Methods Source: https://context7.com/pdturney/autopoiesis/llms.txt Supports four reproduction strategies: uniform asexual, variable asexual, sexual, and symbiotic. Each method updates the population and replaces the least fit member. ```python import golly as g import model_functions as mfunc import model_parameters as mparam # Common parameters max_seed_area = 150 # Maximum allowed seed area n = 100 # Current generation number # Assume candidate_seed is selected via tournament # Assume population (pop) has initialized history # 1. Uniform Asexual: bit-flip mutation only, fixed size [pop, message] = mfunc.uniform_asexual(candidate_seed, pop, n) print(message) # 2. Variable Asexual: mutation with possible size changes [pop, message] = mfunc.variable_asexual(candidate_seed, pop, n, max_seed_area) print(message) # 3. Sexual: crossover between similar seeds, then mutation # Finds a mate with similarity between min_similarity (0.80) and max_similarity (0.99) [pop, message] = mfunc.sexual(candidate_seed, pop, n, max_seed_area) print(message) # 4. Symbiotic: includes fusion (joining seeds) and fission (splitting seeds) # prob_fission = 0.01, prob_fusion = 0.005 [pop, message] = mfunc.symbiotic(candidate_seed, pop, n, max_seed_area) print(message) # All methods: # - Create a child from the candidate parent(s) # - Replace the least fit member of the population # - Build competition history for the new child # - Return updated population and status message ``` -------------------------------- ### View an Immigration Game Source: https://github.com/pdturney/autopoiesis/blob/master/README.txt Python script that allows users to select samples and have individuals compete against each other in an Immigration Game, providing a detailed view of individual games. ```python view_contest.py -- see an Immigration Game played ``` -------------------------------- ### Configure Windows Group Policy for Updates Source: https://github.com/pdturney/autopoiesis/blob/master/README.txt Instructions for setting Windows Group Policy to prevent automatic restarts during simulation runs. This requires Windows 10 Pro or higher. ```text Local Computer Policy > Computer Configuration > Administrative Templates > Windows Components > Windows Update - Configure Automatic Updates = Enabled = 2 = Notify before downloading and installing any updates - No auto-restart with logged on users for scheduled automatic updates instalations = Enabled ``` -------------------------------- ### Run Immigration Game Competition Source: https://context7.com/pdturney/autopoiesis/llms.txt Executes a competition between two seeds in a toroidal universe. Requires initialized Seed objects with non-zero living cell counts. ```python import golly as g import model_functions as mfunc # Competition parameters width_factor = 6.0 # Toroid width = max_seed_size * width_factor height_factor = 3.0 # Toroid height = max_seed_size * height_factor time_factor = 6.0 # Game duration = (width + height) * time_factor num_trials = 2 # Number of competition rounds (averaged) # Assume seed1 and seed2 are initialized Seed objects with num_living > 0 # Returns normalized scores: [score1, score2] where each is between 0.0 and 1.0 [score1, score2] = mfunc.score_pair(g, seed1, seed2, width_factor, height_factor, time_factor, num_trials) print(f"Seed 1 score: {score1:.3f}") print(f"Seed 2 score: {score2:.3f}") if score1 > score2: print("Seed 1 wins!") elif score2 > score1: print("Seed 2 wins!") else: print("It's a tie!") # Scores are based on cell growth (final count - initial count) # Winner determination: # - score = 1.0 for a win # - score = 0.5 for a tie # - score = 0.0 for a loss # Final scores are averaged across num_trials ``` -------------------------------- ### Perform Seed Mutation Operations Source: https://context7.com/pdturney/autopoiesis/llms.txt Shows how to apply probabilistic mutations or direct structural changes like growing and shrinking to a Seed object. ```python import model_classes as mclass import copy # Create and initialize a seed seed = mclass.Seed(xspan=5, yspan=5, pop_size=200) seed.randomize(0.375) seed.num_living = seed.count_ones() # Mutation parameters prob_grow = 0.2 # 20% chance to grow (add row/column) prob_flip = 0.6 # 60% chance to flip bits prob_shrink = 0.2 # 20% chance to shrink (remove row/column) seed_density = 0.375 # Density for new cells when growing mutation_rate = 0.01 # Probability of flipping each bit # Create a mutated copy mutant = seed.mutate(prob_grow, prob_flip, prob_shrink, seed_density, mutation_rate) mutant.num_living = mutant.count_ones() print(f"Original: {seed.xspan}x{seed.yspan}, {seed.num_living} living cells") print(f"Mutant: {mutant.xspan}x{mutant.yspan}, {mutant.num_living} living cells") # Direct bit-flip mutation (always flips at least one bit) seed_copy = copy.deepcopy(seed) seed_copy.flip_bits(mutation_rate=0.01) # Direct grow operation (adds one row or column with random cells) seed_copy.grow(seed_density=0.375) # Direct shrink operation (removes one row or column if above minimum size) seed_copy.shrink() ``` -------------------------------- ### Compare Populations with Different Parameters Source: https://github.com/pdturney/autopoiesis/blob/master/README.txt Python script for comparing two simulation runs that used different parameter settings. It compares individuals from the same generation (N) across the two runs. ```python compare_types.py -- compare populations with different parameters ``` -------------------------------- ### Model Parameters Configuration Source: https://context7.com/pdturney/autopoiesis/llms.txt This file contains all configurable parameters for experiments, controlling evolution type, population settings, mutation rates, and symbiosis behavior. It serves as the central configuration hub for the Autopoiesis project. ```python # model_parameters.py - Key configuration options ``` -------------------------------- ### Load Archived Elite Seeds Source: https://context7.com/pdturney/autopoiesis/llms.txt Loads a previously archived sample of elite seeds from a binary pickle file. The loaded sample is sorted by decreasing fitness, with the most fit seed at index 0. ```python import model_functions as mfunc import pickle # Later, load the archived elite sample pickle_path = f"{log_directory}/{log_name}-pickle-{run_id_number}.bin" handle = open(pickle_path, "rb") elite_sample = pickle.load(handle) handle.close() print(f"Loaded {len(elite_sample)} elite seeds") print(f"Top seed fitness: {elite_sample[0].fitness():.3f}") # Elite sample is sorted by decreasing fitness # elite_sample[0] is the most fit seed # elite_sample[-1] is the least fit among the elite ``` -------------------------------- ### Run Model-S Simulation Source: https://github.com/pdturney/autopoiesis/blob/master/README.txt The main Python script to run a simulation and evolve a population. It relies on supporting modules and a rule file. Configuration is done via model_parameters.py. ```python run_model.py -- run a simulation; evolve a population ``` -------------------------------- ### Calculate Average Densities Source: https://github.com/pdturney/autopoiesis/blob/master/README.txt Python script to calculate the average densities (number of 1s / area) of individuals from simulation samples. Suggests a preferred range of densities. ```python measure_densities.py -- calculate the average densities ``` -------------------------------- ### Compare Generations Analysis Script Source: https://context7.com/pdturney/autopoiesis/llms.txt Analyzes evolutionary progress by comparing seeds from earlier generations against the final generation. It loads pickle files containing population data and calculates average fitness scores for comparison. ```python import golly as g import model_functions as mfunc import model_parameters as mparam import pickle # Select pickle directory via GUI [pickle_dir, analysis_dir, sorted_pickle_names, smallest_pickle_size] = mfunc.choose_pickles(g) # Load final generation pickles for comparison baseline final_num = smallest_pickle_size final_pickles = [] for run in range(len(sorted_pickle_names)): pickle_name = sorted_pickle_names[run] path = f"{pickle_dir}{pickle_name}-pickle-{final_num}.bin" handle = open(path, "rb") final_pickles.append(pickle.load(handle)) handle.close() # Compare each generation to the final generation for gen in range(final_num + 1): for run in range(len(sorted_pickle_names)): # Load generation sample pickle_name = sorted_pickle_names[run] path = f"{pickle_dir}{pickle_name}-pickle-{gen}.bin" handle = open(path, "rb") gen_sample = pickle.load(handle) handle.close() # Compare each seed in gen_sample against each in final_sample total_fitness = 0.0 count = 0 for seed_x in gen_sample: for seed_z in final_pickles[run]: [score_x, score_z] = mfunc.score_pair(g, seed_x, seed_z, mparam.width_factor, mparam.height_factor, mparam.time_factor, mparam.num_trials) total_fitness += score_x count += 1 avg_fitness = total_fitness / count print(f"Generation {gen}, Run {run}: {avg_fitness:.4f}") ``` -------------------------------- ### Compare Populations Across Generations Source: https://github.com/pdturney/autopoiesis/blob/master/README.txt Python script to compare population samples across different generations of a simulation run. It pits individuals from earlier generations against those from later generations. ```python compare_generations.py -- compare populations across generations ``` -------------------------------- ### Evaluate Fitness and Perform Selection Source: https://context7.com/pdturney/autopoiesis/llms.txt Calculates seed fitness based on competition history and selects parents for reproduction. Uses tournament selection to identify the best candidates. ```python import model_functions as mfunc import model_parameters as mparam # Assume population is an initialized list of seeds with history # Get a random sample of tournament_size seeds tournament_size = 2 tournament_sample = mfunc.random_sample(population, tournament_size) # Find the most fit seed in the tournament sample best_seed = mfunc.find_best_seed(tournament_sample) print(f"Tournament winner fitness: {best_seed.fitness():.3f}") # Find the least fit seed (for replacement during reproduction) worst_seed = mfunc.find_worst_seed(population) print(f"Least fit seed fitness: {worst_seed.fitness():.3f}") # Calculate average fitness of the population avg_fitness = mfunc.average_fitness(population) print(f"Average population fitness: {avg_fitness:.3f}") # Find the top elite_size most fit seeds elite_size = 50 elite = mfunc.find_top_seeds(population, elite_size) print(f"Elite sample size: {len(elite)}") print(f"Top seed fitness: {elite[0].fitness():.3f}") ``` -------------------------------- ### Calculate Average Areas of Individuals Source: https://github.com/pdturney/autopoiesis/blob/master/README.txt Python script to calculate the average areas (rows * columns) of individuals from simulation samples. Expected to show growth over generations. ```python measure_areas.py -- calculate the average areas of individuals ``` -------------------------------- ### Evolutionary Algorithm Loop Source: https://context7.com/pdturney/autopoiesis/llms.txt This loop manages the core evolutionary process, including archiving elite individuals, tournament selection, and reproduction based on experiment type. It calculates the average fitness of the final population. ```python for n in range(mparam.run_length + 1): # Archive elite every generation (every pop_size births) if (n % mparam.pop_size) == 0: run_id = n // mparam.pop_size mfunc.archive_elite(population, mparam.elite_size, mparam.log_directory, log_name, run_id) # Tournament selection tournament_sample = mfunc.random_sample(population, mparam.tournament_size) candidate = mfunc.find_best_seed(tournament_sample) # Reproduce based on experiment type (1-4) if mparam.experiment_type_num == 4: # Symbiotic [population, message] = mfunc.symbiotic(candidate, population, n, max_seed_area) # Output: Average fitness of final population avg_fitness = mfunc.average_fitness(population) print(f"Final average fitness: {avg_fitness:.3f}") ``` -------------------------------- ### Perform Crossover (Mating) Operation Source: https://context7.com/pdturney/autopoiesis/llms.txt Combines genetic material from two parent seeds of identical dimensions using single-point crossover. Parents must have the same xspan and yspan. ```python import model_functions as mfunc # Parents must have identical dimensions # Assume parent1 and parent2 are seeds with same xspan and yspan # Crossover creates a child combining parts of both parents # Single crossover point splits on either X or Y axis child = mfunc.mate(parent1, parent2) print(f"Parent 1: {parent1.xspan}x{parent1.yspan}, {parent1.count_ones()} ones") print(f"Parent 2: {parent2.xspan}x{parent2.yspan}, {parent2.count_ones()} ones") print(f"Child: {child.xspan}x{child.yspan}, {child.count_ones()} ones") # Crossover process: # 1. Randomly swap which parent is "top/left" vs "bottom/right" # 2. Randomly choose to split on X-axis (left/right) or Y-axis (top/bottom) ``` -------------------------------- ### Find Similar Seeds for Mating Source: https://context7.com/pdturney/autopoiesis/llms.txt Identifies seeds within a population that meet specific similarity thresholds for sexual reproduction. Seeds must be similar but not identical. ```python import model_functions as mfunc # Find similar seeds for mating (same species) # Seeds must be similar but not identical for sexual reproduction min_similarity = 0.80 # At least 80% similar max_similarity = 0.99 # At most 99% similar (not clones) similar_seeds = mfunc.find_similar_seeds(target_seed, population, min_similarity, max_similarity) print(f"Found {len(similar_seeds)} potential mates") ``` -------------------------------- ### Calculate Standard Deviation of Fitness Source: https://github.com/pdturney/autopoiesis/blob/master/README.txt Python script to calculate the standard deviation of fitness in simulation samples, indicating the diversity within the samples. ```python measure_diversities.py -- calculate the standard deviation of fitness ``` -------------------------------- ### Archive Elite Seeds Source: https://context7.com/pdturney/autopoiesis/llms.txt Saves the top-performing seeds from a population to a binary pickle file. This function is used for later analysis and requires specifying the population, the number of elite seeds to save, and a naming convention for the log file. ```python import model_functions as mfunc import pickle # Save the elite (most fit) seeds from the population elite_size = 50 log_directory = "../experiments/run1" log_name = "log-2020-01-15-10h-30m-00s" run_id_number = 50 # Generation number # Creates file: log_directory/log_name-pickle-50.bin mfunc.archive_elite(population, elite_size, log_directory, log_name, run_id_number) ``` -------------------------------- ### Calculate Seed Similarity Source: https://context7.com/pdturney/autopoiesis/llms.txt Measures bit-wise agreement between two seeds. Returns 0.0 if seeds have different dimensions, otherwise returns the ratio of matching cells. Used to determine species membership for sexual reproduction. ```python import model_functions as mfunc # Calculate similarity between two seeds # Returns 0.0 if seeds have different dimensions # Returns ratio of matching cells if same dimensions sim = mfunc.similarity(seed1, seed2) print(f"Similarity: {sim:.4f}") ``` -------------------------------- ### Fusion Operation Source: https://context7.com/pdturney/autopoiesis/llms.txt Joins two seeds horizontally with a gap column. Used when the prob_fusion probability triggers. The process involves selecting seeds, rotating them, placing them side-by-side, and optionally enforcing a fitness threshold for the fused seed. ```python import golly as g import model_functions as mfunc # FUSION: Join two seeds horizontally with a gap column # Used when prob_fusion probability triggers (default 0.5%) [pop, message] = mfunc.fusion(candidate_seed, pop, n, max_seed_area) ``` -------------------------------- ### Fission Operation Source: https://context7.com/pdturney/autopoiesis/llms.txt Splits a seed at its sparsest column. Used when the prob_fission probability triggers. The seed is divided into two parts, and one part is selected if it meets size criteria. ```python import golly as g import model_functions as mfunc # FISSION: Split a seed at its sparsest column # Used when prob_fission probability triggers (default 1%) [pop, message] = mfunc.fission(candidate_seed, pop, n, max_seed_area) ``` -------------------------------- ### Update Similarity Records Source: https://context7.com/pdturney/autopoiesis/llms.txt Updates the similarity records between two seeds in the population. This operation is symmetric, updating records for both seeds involved. ```python import model_functions as mfunc # Update similarity records between two seeds in population mfunc.update_similarity(population, i, j) # This updates both pop[i].similarities[j] and pop[j].similarities[i] ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.