### Play Match Execution Example Source: https://github.com/cahidarda/prisonner-s-dilemma-strategy-evolution/blob/master/_autodocs/api-reference-Match.md Illustrates the usage of the `playMatch()` method after setting up agents. This example assumes a threaded Match instance where `playMatch()` is called explicitly. ```java Match match = new Match(10); match.addNextAgents(player1, player2); match.playMatch(); // Scores are now accumulated in both agents ``` -------------------------------- ### Add Next Agents and Reuse Match Example Source: https://github.com/cahidarda/prisonner-s-dilemma-strategy-evolution/blob/master/_autodocs/api-reference-Match.md Demonstrates how to add agents to a Match instance and then play the match. This example highlights the ability to reuse the same Match object with different agent pairs by calling `addNextAgents()` multiple times. ```java Match match = new Match(10); match.addNextAgents(agent1, agent2); match.playMatch(); match.addNextAgents(agent3, agent4); match.playMatch(); // Reuse same Match with different agents ``` -------------------------------- ### Standard Run Configuration (Threaded) Source: https://github.com/cahidarda/prisonner-s-dilemma-strategy-evolution/blob/master/_autodocs/configuration.md Example configuration for a standard run, balancing simulation length and population size. Suitable for general analysis. ```java int nofGenerations = 1000; int nofAgents = 100; int nofBatches = 10; int nofGames = 10; double ratioToRemoveEachRound = 0.2; int printEach = 1; ``` -------------------------------- ### Threaded Match Initialization and Play Source: https://github.com/cahidarda/prisonner-s-dilemma-strategy-evolution/blob/master/_autodocs/api-reference-Match.md Demonstrates setting up agents and playing a match using the threaded Match constructor. This example shows how to add agents and initiate the match simulation. ```java Match match = new Match(10); Agent a1 = new Agent(); Agent a2 = new Agent(); match.addNextAgents(a1, a2); match.playMatch(); ``` -------------------------------- ### Short Test Configuration (Threaded) Source: https://github.com/cahidarda/prisonner-s-dilemma-strategy-evolution/blob/master/_autodocs/configuration.md Example configuration for a short test run, suitable for quick feedback. Uses reduced parameters for faster execution. ```java int nofGenerations = 100; int nofAgents = 50; int nofBatches = 5; int nofGames = 5; double ratioToRemoveEachRound = 0.3; int printEach = 10; ``` -------------------------------- ### CSV Output Example Source: https://github.com/cahidarda/prisonner-s-dilemma-strategy-evolution/blob/master/_autodocs/usage-guide.md An example of the CSV output generated by the simulation, showing population statistics per recorded generation. ```csv Generation,BPA-R,BPA-S,BPA-T,BPA-P,SD-R,SD-S,SD-T,SD-P,AA-R,AA-S,AA-T,AA-P,ABPA-R,ABPA-S,ABPA-T,ABPA-P 0,0.480000,0.520000,0.490000,0.510000,0.298000,0.301000,0.295000,0.299000,0.480000,0.520000,0.490000,0.510000,0.480000,0.520000,0.490000,0.510000 100,0.750000,0.350000,0.850000,0.250000,0.145000,0.142000,0.138000,0.141000,0.745000,0.355000,0.855000,0.255000,0.785000,0.315000,0.875000,0.235000 200,0.780000,0.320000,0.820000,0.280000,0.098000,0.095000,0.092000,0.096000,0.775000,0.325000,0.825000,0.275000,0.810000,0.290000,0.850000,0.260000 ``` -------------------------------- ### Sample Generation File Format (Non-Threaded) Source: https://github.com/cahidarda/prisonner-s-dilemma-strategy-evolution/blob/master/_autodocs/overview.md An example of a non-threaded generation file, showing the format for agent data. Each line represents an agent with its ID, behavior probabilities, and score. ```text 100 100 20 0.15 5421 0 0.750000 0.250000 0.900000 0.100000 2450.0 1 0.680000 0.320000 0.850000 0.150000 2380.0 ... (one agent per line) ``` -------------------------------- ### Compile and Run Threaded Simulation Source: https://github.com/cahidarda/prisonner-s-dilemma-strategy-evolution/blob/master/_autodocs/README.md Compiles all Java files for the threaded version and then runs the main executable. Assumes Java Development Kit is installed and configured. ```bash javac -d bin src-with-threads/**/*.java java -cp bin Executable.Main ``` -------------------------------- ### run() Source: https://github.com/cahidarda/prisonner-s-dilemma-strategy-evolution/blob/master/_autodocs/api-reference-Batch.md Executes all matches in this batch. This method is called when the thread associated with the batch is started. ```APIDOC ## run() ### Description Executes all matches in this batch. Called when the thread is started. Processes all matches for this batch: **For intra-group batches** (b == null): - Loops through all unique pairs (i, j) where i < j - Each pair plays a Match with `nofGames` iterations - Scores accumulate in both agents **For inter-group batches** (b != null): - Loops through all pairs where first agent from group a, second from group b - Each pair plays a Match - Every agent from a plays every agent from b (full Cartesian product) Both types reuse the same Match instance across all games, clearing scores only between different agent pairs. ### Parameters None ### Response #### Success Response (200) - **void** - Description: No return value ``` -------------------------------- ### Executing All Queued Batches Concurrently Source: https://github.com/cahidarda/prisonner-s-dilemma-strategy-evolution/blob/master/_autodocs/api-reference-Arena.md Queues multiple Batch tasks and then executes them concurrently using runArena(). This example shows how to prepare and run all matches for a generation. ```Java Arena arena = new Arena(10); // Queue multiple batches for (int i = 0; i < 10; i++) { for (int j = i + 1; j < 10; j++) { Thread t = new Thread(new Batch(agents[i], agents[j], 10)); arena.addToQueue(t); } } // Execute all concurrently arena.runArena(); // When runArena() returns, all matches are complete ``` -------------------------------- ### Get Scores Retrieval Example Source: https://github.com/cahidarda/prisonner-s-dilemma-strategy-evolution/blob/master/_autodocs/api-reference-Match.md Shows how to obtain the final scores after a match has been played using the non-threaded constructor. The scores are printed to the console. ```java Match match = new Match(agent1, agent2, 10); double[] scores = match.getScores(); System.out.printf("Agent 1: %.0f, Agent 2: %.0f%n", scores[0], scores[1]); // Example output: "Agent 1: 110.0, Agent 2: 95.0" ``` -------------------------------- ### Compile and Run Non-Threaded Simulation Source: https://github.com/cahidarda/prisonner-s-dilemma-strategy-evolution/blob/master/_autodocs/README.md Compiles all Java files for the non-threaded version and then runs the main executable. Assumes Java Development Kit is installed and configured. ```bash javac -d bin src-without-threads/**/*.java java -cp bin Classes.Main ``` -------------------------------- ### Python Plotting Example Source: https://github.com/cahidarda/prisonner-s-dilemma-strategy-evolution/blob/master/_autodocs/usage-guide.md A basic Python script using pandas and matplotlib to plot the simulation results from the generated CSV file. ```python import pandas as pd import matplotlib.pyplot as plt ``` -------------------------------- ### Large Scale Research Configuration (Threaded) Source: https://github.com/cahidarda/prisonner-s-dilemma-strategy-evolution/blob/master/_autodocs/configuration.md Example configuration for large-scale research runs. Employs extended generations, larger populations, and higher game counts for in-depth study. ```java int nofGenerations = 100000; int nofAgents = 500; int nofBatches = 20; int nofGames = 20; double ratioToRemoveEachRound = 0.15; int printEach = 100; ``` -------------------------------- ### Arena RunArena Method Source: https://github.com/cahidarda/prisonner-s-dilemma-strategy-evolution/blob/master/_autodocs/api-reference-Arena.md Starts all queued threads, waits for their completion, and then resets the queue. This method ensures all queued matches run concurrently. ```Java public void runArena() throws InterruptedException ``` -------------------------------- ### Get Agent Score Source: https://github.com/cahidarda/prisonner-s-dilemma-strategy-evolution/blob/master/_autodocs/api-reference-Agent.md Retrieves the agent's current total score. This method provides thread-safe access to the score, which is typically reset at the start of each generation. ```java double getScore() ``` ```java Agent agent = new Agent(); agent.addToScore(15); System.out.println("Score: " + agent.getScore()); // 15.0 ``` -------------------------------- ### runArena Source: https://github.com/cahidarda/prisonner-s-dilemma-strategy-evolution/blob/master/_autodocs/api-reference-Arena.md Starts all queued threads concurrently, waits for their completion, and then resets the queue. This method is crucial for executing all scheduled matches in parallel. ```APIDOC ## runArena() → void ### Description Starts all queued threads, waits for their completion, and resets the queue. This method ensures that all enqueued batch threads execute concurrently. It starts all threads, moves them to the end of the queue for potential reuse, and then calls `join()` on each thread to wait for completion. ### Method POST ### Endpoint `/arena/run` ### Parameters None ### Method Signature ```java public void runArena() throws InterruptedException ``` ### Returns - void ### Throws - `InterruptedException` if the main thread is interrupted while waiting for workers ### Example ```java Arena arena = new Arena(10); // Queue multiple batches for (int i = 0; i < 10; i++) { for (int j = i + 1; j < 10; j++) { Thread t = new Thread(new Batch(agents[i], agents[j], 10)); arena.addToQueue(t); } } // Execute all concurrently arena.runArena(); // When runArena() returns, all matches are complete ``` ``` -------------------------------- ### playMatch() Source: https://github.com/cahidarda/prisonner-s-dilemma-strategy-evolution/blob/master/_autodocs/api-reference-Match.md Executes a complete match with all four outcome scenarios. This method runs the match cycle, simulating `nofGames` iterations for each of the four distinct starting conditions. It should be called after agents have been assigned using `addNextAgents()`. ```APIDOC ## playMatch() ### Description Executes a complete match with all four outcome scenarios. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Method `playMatch()` ### Endpoint None ### Request Example ```java Match match = new Match(10); match.addNextAgents(player1, player2); match.playMatch(); ``` ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### Get Agent ID Source: https://github.com/cahidarda/prisonner-s-dilemma-strategy-evolution/blob/master/_autodocs/api-reference-Agent.md Returns the unique identifier for this agent. IDs are auto-incremented globally; each new agent receives the next available ID. ```java int getId() ``` ```java Agent agent1 = new Agent(); Agent agent2 = new Agent(); System.out.println(agent1.getId()); // e.g., 0 System.out.println(agent2.getId()); // e.g., 1 ``` -------------------------------- ### Match Structure Simulation Source: https://github.com/cahidarda/prisonner-s-dilemma-strategy-evolution/blob/master/_autodocs/configuration.md Simulates a match by playing four rounds with different starting conditions to test recovery scenarios. It begins with mutual cooperation and progresses through exploitation and mutual defection. ```java void playMatch() { playRound(3,3); // Start from R (mutual cooperation) playRound(0,5); // A got S, B got T (exploitation) playRound(5,0); // A got T, B got S (exploitation) playRound(1,1); // Start from P (mutual defection) } ``` -------------------------------- ### Get Agent Behavior Probabilities Source: https://github.com/cahidarda/prisonner-s-dilemma-strategy-evolution/blob/master/_autodocs/api-reference-Agent.md Retrieves the agent's complete behavior probability array [R, S, T, P]. The array is synchronized in the threaded version to prevent race conditions. ```java protected double[] getBehavior() ``` ```java Agent agent = new Agent(); double[] behavior = agent.getBehavior(); System.out.printf("Strategy: R=%.3f, S=%.3f, T=%.3f, P=%.3f%n", behavior[0], behavior[1], behavior[2], behavior[3]); ``` -------------------------------- ### Match Instance Creation Source: https://github.com/cahidarda/prisonner-s-dilemma-strategy-evolution/blob/master/_autodocs/api-reference-Batch.md Demonstrates the creation of a reusable Match instance within a Batch for efficient execution of multiple games. ```java m = new Match(nofGames); ``` -------------------------------- ### Main.java Configuration for Threaded Run Source: https://github.com/cahidarda/prisonner-s-dilemma-strategy-evolution/blob/master/_autodocs/overview.md Configuration parameters and the main loop for running a generation of the threaded simulation. Results are printed to a specified output. ```java int nofGenerations = 1000; int nofAgents = 100; int nofBatches = 10; int nofGames = 10; double ratioToRemoveEachRound = 0.2; Generation g = new Generation(nofAgents, nofBatches, nofGames, ratioToRemoveEachRound); for (int i = 0; i < nofGenerations; i++) { g.runGeneration(); if (i % 1 == 0 || i + 1 == nofGenerations) { g.printGenerationBPAWPAAA(output); } } ``` -------------------------------- ### Agent Initialization (Sigmoid Transformation) Source: https://github.com/cahidarda/prisonner-s-dilemma-strategy-evolution/blob/master/_autodocs/configuration.md Code snippet demonstrating agent strategy initialization using a sigmoid transformation. This method creates a bell-curved distribution of initial strategies around 0.5. ```java double val = Math.pow(Math.E, 10*(random.nextDouble() - 0.5)); behavior[i] = val/(val+1); ``` -------------------------------- ### Behavior Probability Array Initialization Source: https://github.com/cahidarda/prisonner-s-dilemma-strategy-evolution/blob/master/_autodocs/types.md Shows how to initialize a `double` array representing an agent's probabilities to cooperate based on the previous round's outcome. It uses a sigmoid transformation for realistic distributions. ```java double val = Math.pow(Math.E, 10*(random.nextDouble() - 0.5)); behavior[i] = val/(val+1); // Sigmoid transformation ``` -------------------------------- ### Agent() - Random Initialization Constructor Source: https://github.com/cahidarda/prisonner-s-dilemma-strategy-evolution/blob/master/_autodocs/api-reference-Agent.md Creates a new agent with randomly initialized behavior probabilities using a sigmoid transformation. Each behavior probability is calculated using a sigmoid function and clamped to avoid extreme values. ```java public Agent() ``` ```java double val = Math.pow(Math.E, 10*(random.nextDouble() - 0.5)); behavior[i] = val/(val+1); ``` ```java Agent agent1 = new Agent(); Agent agent2 = new Agent(); System.out.println(agent1.getId()); // Prints unique ID ``` -------------------------------- ### Typical Generation Cycle with Arena Source: https://github.com/cahidarda/prisonner-s-dilemma-strategy-evolution/blob/master/_autodocs/api-reference-Arena.md Illustrates the typical usage of the Arena class within the Generation.runGeneration() method. It shows preparing batches, queuing them, and running them concurrently. ```Java // In Generation.runGeneration() // 1. Prepare batches Arena arena = new Arena(nofGames); for (int i = 0; i < nofBatches; i++) { for (int j = i + 1; j < nofBatches; j++) { // Inter-batch matches Thread t = new Thread(new Batch(agents[i], agents[j], nofGames)); arena.addToQueue(t); } // Intra-batch matches Thread t = new Thread(new Batch(agents[i], nofGames)); arena.addToQueue(t); } // 2. Run all matches concurrently arena.runArena(); // 3. Update generation (agents' scores are now accumulated) ``` -------------------------------- ### Match(Agent agent1, Agent agent2, int nofGames) Source: https://github.com/cahidarda/prisonner-s-dilemma-strategy-evolution/blob/master/_autodocs/api-reference-Match.md Creates a match and immediately executes all four rounds. This constructor initializes two agents and directly executes a full match simulation, calculating scores upon completion. It simulates all four standard Prisoner's Dilemma outcome scenarios sequentially. ```APIDOC ## Match(Agent agent1, Agent agent2, int nofGames) ### Description Creates a match and immediately executes all four rounds. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Method Constructor ### Endpoint None ### Request Example ```java Agent agent1 = new Agent(); Agent agent2 = new Agent(); Match match = new Match(agent1, agent2, 10); double[] scores = match.getScores(); System.out.println("Agent1: " + scores[0] + ", Agent2: " + scores[1]); ``` ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### playRound Source: https://github.com/cahidarda/prisonner-s-dilemma-strategy-evolution/blob/master/_autodocs/api-reference-Match.md Executes a single round of games between two agents, simulating Prisoner's Dilemma decisions and payoff calculations based on the starting outcomes. ```APIDOC ## playRound(int outcome0, int outcome1) ### Description Executes a single round of games between the two agents, simulating `nofGames` iterations of the Prisoner's Dilemma starting from the specified outcomes. In each game, agents decide to cooperate or defect based on the previous outcome, and scores are calculated. ### Method void ### Parameters #### Path Parameters - **outcome0** (int) - Required - Starting outcome for agent a (3, 0, 5, or 1) - **outcome1** (int) - Required - Starting outcome for agent b (3, 0, 5, or 1) ### Request Example ```java // Simulate a round starting with both agents having received reward match.playRound(3, 3); // Simulate a round where agent a was tempted and agent b got sucker's payoff match.playRound(5, 0); ``` ### Response #### Success Response (void) This method does not return a value. ### Notes Maps outcome values: - 3 = R (Reward): both cooperated - 0 = S (Sucker): was exploited - 5 = T (Temptation): successfully exploited - 1 = P (Punishment): both defected ``` -------------------------------- ### Get Scores Method Source: https://github.com/cahidarda/prisonner-s-dilemma-strategy-evolution/blob/master/_autodocs/api-reference-Match.md Retrieves the accumulated scores for both agents after a match has been completed. This method returns an array containing the scores for agent1 and agent2, respectively. ```java double[] getScores() ``` -------------------------------- ### Simulation Configuration Parameters Source: https://github.com/cahidarda/prisonner-s-dilemma-strategy-evolution/blob/master/previous_results/r3/Explanation.txt These parameters define the simulation's scale and progress tracking. Adjust `nofAgents` and `nofGamesEachRound` for simulation size, `ratioToRemove` for evolutionary pressure, and `nofGenerations` and `printEvery` for simulation duration and output frequency. ```C++ int nofAgents = 100; int nofGamesEachRound = 20; double ratioToRemove = 0.3; int nofGenerations = 100000; int printEvery = 100; ``` -------------------------------- ### Document Simulation Configuration Source: https://github.com/cahidarda/prisonner-s-dilemma-strategy-evolution/blob/master/_autodocs/usage-guide.md Maintain a log of simulation parameters and the date to ensure reproducibility and track experimental conditions. ```bash echo "Population: 100, Batches: 10, Removal: 0.2" > config.txt date >> config.txt ``` -------------------------------- ### Retrieve Nth Worst Agent Source: https://github.com/cahidarda/prisonner-s-dilemma-strategy-evolution/blob/master/_autodocs/api-reference-Generation.md Fetches the agent with a specific rank based on their performance score, starting from the lowest. Rank 1 corresponds to the worst-scoring agent. ```java Agent getWorstAgent(int rank) ``` ```java Agent worst = gen.getWorstAgent(1); System.out.println("Worst agent ID: " + worst.getId()); // Remove bottom 10% manually for (int i = 0; i < 10; i++) { Agent bottom = gen.getWorstAgent(1); // Remove operation... } ``` -------------------------------- ### Recover and Continue Generation (Non-Threaded) Source: https://github.com/cahidarda/prisonner-s-dilemma-strategy-evolution/blob/master/_autodocs/overview.md Demonstrates how to restore a previous generation from a file and continue the simulation. Includes error handling for file not found exceptions. ```java // Non-threaded version only try { Generation restored = new Generation("output/g100.txt"); restored.runGeneration(); restored.updateToNextGeneration(); restored.printGeneration("output/"); } catch (FileNotFoundException e) { System.err.println("Cannot restore generation"); } ``` -------------------------------- ### Initial Strategy Generation with Sigmoid Distribution Source: https://github.com/cahidarda/prisonner-s-dilemma-strategy-evolution/blob/master/_autodocs/evolution-mechanics.md Generates an initial agent behavior using a sigmoid distribution based on a random double. This biases initial strategies towards moderate cooperation. ```java double val = Math.pow(Math.E, 10 * (random.nextDouble() - 0.5)); behavior[i] = val / (val + 1); ``` -------------------------------- ### Analyze Best Strategy Source: https://github.com/cahidarda/prisonner-s-dilemma-strategy-evolution/blob/master/_autodocs/overview.md Runs a generation and retrieves the best agent to analyze its strategy. The strategy is printed with formatted probabilities. ```java Generation gen = new Generation(100, 10, 10, 0.2); gen.runGeneration(); Agent best = gen.getBestAgent(1); double[] strategy = best.getBehavior(); System.out.printf("Best strategy: R=%.3f, S=%.3f, T=%.3f, P=%.3f%n", strategy[0], strategy[1], strategy[2], strategy[3]); ``` -------------------------------- ### Save Simulation Results with Parameters Source: https://github.com/cahidarda/prisonner-s-dilemma-strategy-evolution/blob/master/_autodocs/usage-guide.md When saving simulation output to a file, use descriptive filenames that include key parameters like agent count and removal rate for better tracking. ```bash java -cp bin Executable.Main > results_100agents_0.2removal.txt ``` ```bash java -cp bin Executable.Main > output.txt ``` -------------------------------- ### Basic Evolution Run (Threaded) Source: https://github.com/cahidarda/prisonner-s-dilemma-strategy-evolution/blob/master/_autodocs/overview.md Initializes and runs a basic evolution simulation using the threaded version. Prints generation progress to the console. ```java // Threaded version Generation gen = new Generation(100, 10, 10, 0.2); for (int i = 0; i < 1000; i++) { gen.runGeneration(); if (i % 100 == 0) System.out.println("Generation " + i); } ``` -------------------------------- ### Arena Initialization and Task Queuing Source: https://github.com/cahidarda/prisonner-s-dilemma-strategy-evolution/blob/master/_autodocs/api-reference-Arena.md Initializes an Arena and adds Batch tasks wrapped as Threads to its execution queue. Use this to prepare tasks before running the arena. ```Java Arena arena = new Arena(10); // Add batch tasks Batch batch1 = new Batch(agents1, agents2, 10); arena.addToQueue(new Thread(batch1)); // Run when ready arena.runArena(); ``` -------------------------------- ### Modify Simulation Parameters Source: https://github.com/cahidarda/prisonner-s-dilemma-strategy-evolution/blob/master/_autodocs/README.md Example of how to modify core simulation parameters within the Main.java file before recompilation and execution. This allows for customization of simulation length, population size, and selection pressure. ```java int nofGenerations = 5000; // More generations int nofAgents = 500; // Larger population double ratioToRemoveEachRound = 0.15; // Gentler selection ``` -------------------------------- ### Concurrent Batch Creation and Queuing Source: https://github.com/cahidarda/prisonner-s-dilemma-strategy-evolution/blob/master/_autodocs/api-reference-Batch.md This Java code demonstrates how to create and queue multiple Batch instances for concurrent execution within an Arena. It handles both inter-batch and intra-batch matches to ensure comprehensive agent interactions. ```java Arena arena = new Arena(nofGames); // Create inter-batch matches (O(n²) pairs) for (int i = 0; i < nofBatches; i++) { for (int j = i + 1; j < nofBatches; j++) { Thread t = new Thread(new Batch(agents[i], agents[j], nofGames)); arena.addToQueue(t); } } // Create intra-batch matches (O(n) batches) for (int i = 0; i < nofBatches; i++) { Thread t = new Thread(new Batch(agents[i], nofGames)); arena.addToQueue(t); } // All batches run concurrently arena.runArena(); ``` -------------------------------- ### Agent(int agentId, double a, double b, double c, double d) - Direct Initialization Source: https://github.com/cahidarda/prisonner-s-dilemma-strategy-evolution/blob/master/_autodocs/api-reference-Agent.md Creates an agent with explicit behavior values, used for reconstructing agents from saved state. Allows direct specification of agent ID and all behavioral parameters. ```java Agent(int agentId, double a, double b, double c, double d) ``` ```java Agent restoredAgent = new Agent(5, 0.8, 0.2, 0.9, 0.1); ``` -------------------------------- ### Play a Round of Prisoner's Dilemma Source: https://github.com/cahidarda/prisonner-s-dilemma-strategy-evolution/blob/master/_autodocs/api-reference-Match.md Executes a single round of games between two agents, starting from specified outcomes. Outcomes map to R (Reward), S (Sucker), T (Temptation), or P (Punishment). ```java void playRound(int outcome0, int outcome1) ``` ```java // Simulate a round starting with both agents having received reward match.playRound(3, 3); // Simulate a round where agent a was tempted and agent b got sucker's payoff match.playRound(5, 0); ``` -------------------------------- ### Project Structure Source: https://github.com/cahidarda/prisonner-s-dilemma-strategy-evolution/blob/master/_autodocs/README.md Overview of the project directory structure, distinguishing between threaded and sequential implementations and the location of generated documentation. ```tree prisonner-s-dilemma-strategy-evolution/ ├── src-with-threads/ Concurrent tournament implementation │ ├── Agent/ │ │ ├── Agent.java │ │ └── Generation.java │ ├── EvolutionMechanism/ │ │ ├── Arena.java │ │ ├── Batch.java │ │ └── Match.java │ └── Executable/ │ └── Main.java │ ├── src-without-threads/ Sequential tournament implementation │ └── Classes/ │ ├── Agent.java │ ├── Generation.java │ ├── Match.java │ └── Main.java │ └── output/ Generated documentation (this folder) ├── README.md This file ├── overview.md Architecture and getting started ├── usage-guide.md Practical usage examples ├── api-reference-*.md Class APIs (Agent, Generation, Match, Arena, Batch) ├── types.md Type definitions ├── configuration.md Parameter reference └── evolution-mechanics.md Evolutionary algorithm details ``` -------------------------------- ### Agent Decision Making with Behavior Probabilities Source: https://github.com/cahidarda/prisonner-s-dilemma-strategy-evolution/blob/master/_autodocs/types.md Shows how an agent uses its behavior probability array to decide whether to cooperate or defect based on the previous round's outcome. ```java int outcomeIndex; boolean cooperate = (random.nextDouble() < behavior[outcomeIndex]); ``` -------------------------------- ### Create Custom Java Program for Simulation Source: https://github.com/cahidarda/prisonner-s-dilemma-strategy-evolution/blob/master/_autodocs/usage-guide.md An advanced option to create a custom Java program for running the simulation with specific parameters and output handling. ```java import Agent.Generation; import java.io.PrintStream; import java.io.File; public class CustomEvolution { public static void main(String[] args) throws Exception { // Custom parameters int nofGenerations = 10000; int nofAgents = 500; int nofBatches = 25; int nofGames = 15; double ratioToRemoveEachRound = 0.1; // Setup output PrintStream output = new PrintStream(new File("results.csv")); output.println("Generation,BPA-R,BPA-S,BPA-T,BPA-P,SD-R,SD-S,SD-T,SD-P,AA-R,AA-S,AA-T,AA-P,ABPA-R,ABPA-S,ABPA-T,ABPA-P"); // Run simulation Generation gen = new Generation(nofAgents, nofBatches, nofGames, ratioToRemoveEachRound); for (int i = 0; i < nofGenerations; i++) { gen.runGeneration(); if (i % 100 == 0 || i + 1 == nofGenerations) { gen.printGenerationBPAWPAAA(output); System.out.println("Generation " + i); } } output.close(); System.out.println("Evolution complete. Results in results.csv"); } } ``` -------------------------------- ### Match(int nofGames) Source: https://github.com/cahidarda/prisonner-s-dilemma-strategy-evolution/blob/master/_autodocs/api-reference-Match.md Creates a new match instance for concurrent execution. This constructor initializes a match that will execute a complete round cycle with a configurable number of games per outcome scenario. It is designed for use in threaded environments where multiple matches may run concurrently. ```APIDOC ## Match(int nofGames) ### Description Creates a new match instance for concurrent execution. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Method Constructor ### Endpoint None ### Request Example ```java Match match = new Match(10); Agent a1 = new Agent(); Agent a2 = new Agent(); match.addNextAgents(a1, a2); match.playMatch(); ``` ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### Run Threaded Simulation (Default Parameters) Source: https://github.com/cahidarda/prisonner-s-dilemma-strategy-evolution/blob/master/_autodocs/usage-guide.md Executes the threaded version of the simulation with default parameters. This will run for 1000 generations with 100 agents. ```bash java -cp bin Executable.Main ``` -------------------------------- ### Run Non-Threaded Simulation (Default Parameters) Source: https://github.com/cahidarda/prisonner-s-dilemma-strategy-evolution/blob/master/_autodocs/usage-guide.md Executes the non-threaded version of the simulation with default parameters, performing a large-scale test run. ```bash java -cp bin Classes.Main ``` -------------------------------- ### Test Java Compilation Source: https://github.com/cahidarda/prisonner-s-dilemma-strategy-evolution/blob/master/_autodocs/usage-guide.md Before running lengthy simulations, verify that the Java code compiles successfully to catch errors early. This command compiles and then echoes 'Compilation OK' if successful. ```bash javac -d bin src-with-threads/**/*.java && echo "Compilation OK" ``` -------------------------------- ### Agent() Source: https://github.com/cahidarda/prisonner-s-dilemma-strategy-evolution/blob/master/_autodocs/api-reference-Agent.md Creates a new agent with randomly initialized behavior probabilities using a sigmoid transformation. This constructor initializes a unique agent ID and a behavior array, with probabilities clamped between 0.002 and 0.998. ```APIDOC ## Agent() ### Description Creates a new agent with randomly initialized behavior probabilities using a sigmoid transformation. ### Method Constructor ### Parameters None ### Returns Agent instance ### Example ```java Agent agent1 = new Agent(); Agent agent2 = new Agent(); System.out.println(agent1.getId()); ``` ``` -------------------------------- ### Compile and Run Threaded Version Source: https://github.com/cahidarda/prisonner-s-dilemma-strategy-evolution/blob/master/_autodocs/overview.md Commands to compile and run the threaded version of the simulation. The output is directed to a CSV file. ```bash cd /workspace/home/prisonner-s-dilemma-strategy-evolution # Compile javac -d bin src-with-threads/**/*.java # Run (executes 1000 generations of 100 agents) java -cp bin Executable.Main # Results output to: output/generationBPAWPAAAOutput.csv ``` -------------------------------- ### Simulation Configuration Parameters Source: https://github.com/cahidarda/prisonner-s-dilemma-strategy-evolution/blob/master/previous_results/r1/Explanation.txt These variables define the core parameters for running the simulation. Adjusting these values will impact the simulation's scale and output frequency. ```Java int nofAgents = 200; int nofGamesEachRound = 10; double ratioToRemove = 0.3; int nofGenerations = 20000; int printEvery = 100; ``` -------------------------------- ### Verify Output Directory Contents Source: https://github.com/cahidarda/prisonner-s-dilemma-strategy-evolution/blob/master/_autodocs/usage-guide.md Check the contents of the output directory to ensure the simulation generated the expected output file. This helps troubleshoot issues related to file generation or permissions. ```bash ls -la output/ # Should show: generationBPAWPAAAOutput.csv ``` -------------------------------- ### Optimize Generation Parameters for Slow Execution Source: https://github.com/cahidarda/prisonner-s-dilemma-strategy-evolution/blob/master/_autodocs/usage-guide.md Adjust `nofBatches` and `nofGames` parameters in the `Generation` constructor to improve execution speed. Increasing `nofBatches` enhances parallelism, while decreasing `nofGames` reduces computation per match. ```java // From: new Generation(500, 10, 20, 0.2) // To: new Generation(500, 20, 10, 0.2) // More parallelism, fewer games ``` -------------------------------- ### Reduce nofGenerations for Quick Testing Source: https://github.com/cahidarda/prisonner-s-dilemma-strategy-evolution/blob/master/_autodocs/usage-guide.md Shorten the simulation loop by reducing the `nofGenerations` to speed up testing and initial runs. ```java for (int i = 0; i < 100; i++) { // Was 1000 ``` -------------------------------- ### Ranked Selection for Breeding in Pseudocode Source: https://github.com/cahidarda/prisonner-s-dilemma-strategy-evolution/blob/master/_autodocs/evolution-mechanics.md This pseudocode illustrates the ranked selection process used for breeding new agents. It involves removing the worst agents and creating new ones from pairs of the best-performing agents. ```pseudocode // Remove worst agents and breed with best agents for (int i = 0; i < count; i++) { removeWorstAgent(); newAgent = new Agent( getBestAgent(i + 1), // (i+1)th best getBestAgent(i + 2) // (i+2)th best ); addAgentToGeneration(newAgent); } ``` -------------------------------- ### Test Simulation with Small Runs Source: https://github.com/cahidarda/prisonner-s-dilemma-strategy-evolution/blob/master/_autodocs/usage-guide.md Use small-scale runs to verify the simulation's behavior and output format before executing full-scale simulations. This snippet shows a loop for testing 10 generations. ```java // Test: 10 generations for (int i = 0; i < 10; i++) { gen.runGeneration(); gen.printGenerationBPAWPAAA(output); } // Verify results look reasonable, then run: // for (int i = 0; i < 10000; i++) ``` -------------------------------- ### Archive Simulation Results Source: https://github.com/cahidarda/prisonner-s-dilemma-strategy-evolution/blob/master/_autodocs/usage-guide.md Organize and store historical simulation output by creating dated directories and copying the results files into them. This ensures that past results are preserved. ```bash mkdir -p archive/$(date +%Y%m%d) cp output/generationBPAWPAAAOutput.csv archive/$(date +%Y%m%d)/ ``` -------------------------------- ### Run a Complete Generation Tournament Source: https://github.com/cahidarda/prisonner-s-dilemma-strategy-evolution/blob/master/_autodocs/api-reference-Generation.md Executes one full round of matches where every pair of agents competes once. Scores are accumulated after the tournament. ```java void runGeneration() ``` ```java Generation gen = new Generation(100, 20, 0.15); gen.runGeneration(); // All matches execute gen.updateToNextGeneration(); // Selection and breeding ``` -------------------------------- ### Plot Strategy Evolution Over Generations Source: https://github.com/cahidarda/prisonner-s-dilemma-strategy-evolution/blob/master/_autodocs/usage-guide.md Reads simulation data from a CSV file and plots the evolution of different strategies (BPA and population average) over generations. Saves the plot as a PNG image. ```python import pandas as pd import matplotlib.pyplot as plt # Read CSV df = pd.read_csv('output/generationBPAWPAAAOutput.csv') # Plot best agent strategy evolution fig, axes = plt.subplots(2, 2, figsize=(12, 10)) fig.suptitle('Strategy Evolution Over Generations') outcomes = [('R', 'BPA-R'), ('S', 'BPA-S'), ('T', 'BPA-T'), ('P', 'BPA-P')] for idx, (name, col) in enumerate(outcomes): ax = axes[idx // 2, idx % 2] ax.plot(df['Generation'], df[col], label='Best Agent') ax.plot(df['Generation'], df[f'AA-{name}'], label='Population Average') ax.set_xlabel('Generation') ax.set_ylabel(f'Cooperation Probability ({name})') ax.set_title(f'{name} Outcome Behavior') ax.legend() ax.grid(True) plt.tight_layout() plt.savefig('strategy_evolution.png', dpi=150) plt.show() ``` -------------------------------- ### runGeneration() Source: https://github.com/cahidarda/prisonner-s-dilemma-strategy-evolution/blob/master/_autodocs/api-reference-Generation.md Executes one complete round of all possible matches between agents in the current generation. This simulates a full tournament where each pair of agents plays exactly once. ```APIDOC ## runGeneration() ### Description Executes one complete round of all possible matches between agents in the current generation. This simulates a full tournament where each pair of agents plays exactly once. ### Method `void` ### Parameters None ### Returns `void` ### Description Runs a complete tournament where every pair of agents plays a match. Agents play against each other only once (using agent ID comparison to avoid duplicate matches). Scores accumulate in the agentScores TreeMap. ### Example ```java Generation gen = new Generation(100, 20, 0.15); gen.runGeneration(); // All matches execute gen.updateToNextGeneration(); // Selection and breeding ``` ``` -------------------------------- ### Generation(int nofAgents, int nofGamesEachRound, double ratioToRemoveEachGeneration) Source: https://github.com/cahidarda/prisonner-s-dilemma-strategy-evolution/blob/master/_autodocs/api-reference-Generation.md Creates a generation with sequential match execution for a non-threaded version. Initializes a population of random agents and uses a TreeMap to maintain agent-to-score mappings for sequential processing. ```APIDOC ## Generation(int nofAgents, int nofGamesEachRound, double ratioToRemoveEachGeneration) ### Description Creates a generation with sequential match execution for a non-threaded version. Initializes a population of random agents and uses a TreeMap to maintain agent-to-score mappings for sequential processing. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Method Constructor ### Endpoint None ### Request Example ```java Generation gen = new Generation( 100, // 100 agents 20, // 20 games per match 0.15 // Remove bottom 15% ); gen.runGeneration(); gen.updateToNextGeneration(); ``` ### Response #### Success Response Generation instance with population initialized #### Response Example None ``` -------------------------------- ### Load Generation State Source: https://github.com/cahidarda/prisonner-s-dilemma-strategy-evolution/blob/master/_autodocs/README.md Demonstrates how to load a previous generation's state to resume evolution. This is specific to the non-threaded version and requires the generation state file. ```java new Generation("output/g100.txt") ``` -------------------------------- ### Simulation Configuration Parameters Source: https://github.com/cahidarda/prisonner-s-dilemma-strategy-evolution/blob/master/previous_results/r2/Explanation.txt Defines the core parameters for running the Prisoner's Dilemma strategy evolution simulation. These values control the scale and output frequency of the simulation. ```C++ int nofAgents = 150; int nofGamesEachRound = 80; double ratioToRemove = 0.3; int nofGenerations = 3000; int printEvery = 50; ``` -------------------------------- ### Agent Constructor with Breeding and Mutation in Java Source: https://github.com/cahidarda/prisonner-s-dilemma-strategy-evolution/blob/master/_autodocs/evolution-mechanics.md This Java constructor creates a new agent by averaging the behavior of two parent agents and then applying a mutation. It also assigns a unique ID to the new agent. ```java Agent(Agent a1, Agent a2) { id = lastId++; behavior = new double[4]; double[] b1 = a1.getBehavior(); double[] b2 = a2.getBehavior(); for (int i = 0; i < 4; i++) { behavior[i] = (b1[i] + b2[i]) / 2; } mutate(); } ``` -------------------------------- ### Restart Evolution from Checkpoint Source: https://github.com/cahidarda/prisonner-s-dilemma-strategy-evolution/blob/master/_autodocs/usage-guide.md Restarts a simulation from a specific generation checkpoint and continues for a set number of additional generations. Outputs results to a CSV file. ```java import Classes.Generation; import java.io.PrintStream; public class RestartEvolution { public static void main(String[] args) throws Exception { // Load generation from generation 100 Generation gen = new Generation("output/g100.txt"); PrintStream output = new PrintStream("results.csv"); output.println("Generation,BPA-R,BPA-S,BPA-T,BPA-P,..."); // Continue for 500 more generations for (int i = 0; i < 500; i++) { gen.runGeneration(); gen.updateToNextGeneration(); if (i % 10 == 0) { gen.printGenerationBPAWPAAA(output); gen.printGeneration("output/"); } } output.close(); } ``` -------------------------------- ### Generation(int nofAgents, int nofBatches, int nofGames, double ratioToRemoveEachRound) Source: https://github.com/cahidarda/prisonner-s-dilemma-strategy-evolution/blob/master/_autodocs/api-reference-Generation.md Creates a new generation with specified population parameters for a threaded version. Initializes a population of randomly created agents organized into batches for concurrent processing, enabling multi-threaded tournament execution. ```APIDOC ## Generation(int nofAgents, int nofBatches, int nofGames, double ratioToRemoveEachRound) ### Description Creates a new generation with specified population parameters for a threaded version. Initializes a population of randomly created agents organized into batches for concurrent processing, enabling multi-threaded tournament execution. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Method Constructor ### Endpoint None ### Request Example ```java Generation gen = new Generation( 100, // 100 agents total 10, // 10 concurrent threads 10, // 10 games per match 0.2 // Remove bottom 20% each generation ); gen.runGeneration(); ``` ### Response #### Success Response Generation instance with population initialized #### Response Example None ``` -------------------------------- ### Queueing Multiple Batch Threads Source: https://github.com/cahidarda/prisonner-s-dilemma-strategy-evolution/blob/master/_autodocs/api-reference-Arena.md Demonstrates adding multiple Batch tasks, each wrapped in a Thread, to the Arena's queue. Threads are named for debugging purposes. ```Java Arena arena = new Arena(10); Batch batch1 = new Batch(agents1, agents2, 10); Batch batch2 = new Batch(agents2, agents3, 10); Thread t1 = new Thread(batch1); t1.setName("indexes 0, 1"); arena.addToQueue(t1); Thread t2 = new Thread(batch2); t2.setName("indexes 1, 2"); arena.addToQueue(t2); ``` -------------------------------- ### Non-Threaded Match Execution and Score Retrieval Source: https://github.com/cahidarda/prisonner-s-dilemma-strategy-evolution/blob/master/_autodocs/api-reference-Match.md Shows how to create agents, instantiate a non-threaded Match, and retrieve the calculated scores. The match runs automatically upon creation with this constructor. ```java Agent agent1 = new Agent(); Agent agent2 = new Agent(); Match match = new Match(agent1, agent2, 10); double[] scores = match.getScores(); System.out.println("Agent1: " + scores[0] + ", Agent2: " + scores[1]); ``` -------------------------------- ### Individual Generation State Output Path (Non-Threaded) Source: https://github.com/cahidarda/prisonner-s-dilemma-strategy-evolution/blob/master/_autodocs/configuration.md Defines the file path pattern for individual generation state files in the non-threaded version. The format includes generation ID and agent details. ```text output/g{generationId}.txt ``` -------------------------------- ### Compile and Run Non-Threaded Version Source: https://github.com/cahidarda/prisonner-s-dilemma-strategy-evolution/blob/master/_autodocs/overview.md Commands to compile and run the non-threaded version of the simulation. Results are saved to CSV and other generation files. ```bash cd /workspace/home/prisonner-s-dilemma-strategy-evolution # Compile javac -d bin src-without-threads/**/*.java # Run (modify testMode in Main.java as needed) java -cp bin Classes.Main # Results: output/generationBPAWPAAAOutput.csv + generation files ``` -------------------------------- ### Generation Cycle Flowchart Source: https://github.com/cahidarda/prisonner-s-dilemma-strategy-evolution/blob/master/_autodocs/overview.md Illustrates the cyclical process of the evolutionary simulation, from initialization to repetition. This cycle includes population initialization, running tournaments, ranking agents, and outputting statistics. ```plaintext ┌─────────────────────────┐ │ Initialize Population │ │ (Random Agents) │ └────────────┬────────────┘ │ ┌──────▼──────┐ │ Run Match │ │ Tournament │ └──────┬──────┘ │ ┌──────▼──────────┐ │ Rank by Score │ │ Remove Worst │ │ Breed Best │ │ Mutate │ └──────┬──────────┘ │ ┌──────▼──────┐ │Output Stats │ │ Record │ │ Behavior │ └──────┬──────┘ │ ┌────▼───┐ │Repeat? │ └────────┘ ``` -------------------------------- ### Test Mode 1: Multiple Generations (Non-Threaded) Source: https://github.com/cahidarda/prisonner-s-dilemma-strategy-evolution/blob/master/_autodocs/configuration.md Configuration for running multiple generations with detailed per-generation file output. Suitable for detailed analysis of evolution trajectories and data recovery. ```java int testMode = 1; int nofAgents = 100; int nofGamesEachRound = 20; double ratioToRemove = 0.15; int nofGenerations = 1000; int printEvery = 10; ``` -------------------------------- ### printAgentsToConsole() Source: https://github.com/cahidarda/prisonner-s-dilemma-strategy-evolution/blob/master/_autodocs/api-reference-Generation.md Outputs all agents and their current scores to the standard output for monitoring and debugging purposes. ```APIDOC ## printAgentsToConsole() ### Description Prints each agent's ID and score to the console in a simple text format. This is useful for debugging and monitoring the population's state during a simulation. ### Method void ### Parameters None ### Example ```java Generation gen = new Generation(100, 10, 10, 0.2); gen.runGeneration(); gen.printAgentsToConsole(); // Output: // Agent Id: 0 Agent Score: 245 // Agent Id: 1 Agent Score: 198 // ... ``` ``` -------------------------------- ### Batch(Agent[] a, Agent[] b, int nofGames) Source: https://github.com/cahidarda/prisonner-s-dilemma-strategy-evolution/blob/master/_autodocs/api-reference-Batch.md Creates a batch for inter-group matches where agents from group a play agents from group b. This is used for tournaments between different population subdivisions. ```APIDOC ## Batch(Agent[] a, Agent[] b, int nofGames) ### Description Creates a batch for inter-group matches (agents from group a play agents from group b). This type handles inter-batch matches between different population subdivisions. ### Parameters #### Path Parameters - **a** (Agent[]) - Required - First group of agents - **b** (Agent[]) - Required - Second group of agents - **nofGames** (int) - Required - Number of games per match ### Request Example ```java Agent[] batch1 = new Agent[10]; Agent[] batch2 = new Agent[10]; // ... initialize agents ... Batch interGroupBatch = new Batch(batch1, batch2, 10); Thread t = new Thread(interGroupBatch); arena.addToQueue(t); ``` ### Response #### Success Response (200) - **Batch instance** (Batch) - Description: Batch instance ``` -------------------------------- ### Behavior Probability Array Mutation Source: https://github.com/cahidarda/prisonner-s-dilemma-strategy-evolution/blob/master/_autodocs/types.md Demonstrates the mutation process for an agent's behavior probabilities, where each probability is adjusted by a random amount within a defined bound. ```java behavior[i] += (random.nextDouble() - 0.5) * mutationBound * 2; // where mutationBound = 0.1 ``` -------------------------------- ### Individual Generation State Format (Non-Threaded) Source: https://github.com/cahidarda/prisonner-s-dilemma-strategy-evolution/blob/master/_autodocs/configuration.md Details the format of the individual generation state files for the non-threaded version. It includes simulation parameters and per-agent data such as ID, behavior, and score. ```text generation nofAgents nofGamesEachRound ratioToRemove agentIdCounter agentId behavior[0] behavior[1] behavior[2] behavior[3] score ... (one per agent) ``` -------------------------------- ### Agent(int agentId, double a, double b, double c, double d) Source: https://github.com/cahidarda/prisonner-s-dilemma-strategy-evolution/blob/master/_autodocs/api-reference-Agent.md Creates an agent with explicit behavior values. This constructor is used for reconstructing agents from saved state, allowing direct specification of all behavioral parameters. ```APIDOC ## Agent(int agentId, double a, double b, double c, double d) ### Description Creates an agent with explicit behavior values (non-threaded version only). ### Method Constructor ### Parameters #### Path Parameters - **agentId** (int) - Required - Explicit agent ID - **a** (double) - Required - Behavior probability for R outcome - **b** (double) - Required - Behavior probability for S outcome - **c** (double) - Required - Behavior probability for T outcome - **d** (double) - Required - Behavior probability for P outcome ### Returns Agent instance with specified parameters ### Example ```java Agent restoredAgent = new Agent(5, 0.8, 0.2, 0.9, 0.1); ``` ``` -------------------------------- ### Compile and Run Custom Java Program Source: https://github.com/cahidarda/prisonner-s-dilemma-strategy-evolution/blob/master/_autodocs/usage-guide.md Compiles and executes a custom Java program designed to run the Prisoner's Dilemma simulation with user-defined parameters. ```bash javac -cp bin CustomEvolution.java java -cp bin CustomEvolution ```