import mpi.*; public class Model { public static void main (String args[]) { int node = 0; int numberOfNodes = 0; try { MPI.Init(args); node = MPI.COMM_WORLD.Rank(); numberOfNodes = MPI.COMM_WORLD.Size(); } catch (MPIException mpiE) { mpiE.printStackTrace(); } int width = 10; int height = 10; int densityLimit = 100; int numberOfAgents = 1000; int iterations = 100; Agent [] agents = null; Landscape landscape = new Landscape(); landscape.setWidth(width); landscape.setHeight(height); // Setup int nodeNumberOfAgents = 0; if (node != 0) { nodeNumberOfAgents = numberOfAgents/(numberOfNodes - 1); if (node == (numberOfNodes - 1)) { nodeNumberOfAgents = nodeNumberOfAgents + (numberOfAgents % (numberOfNodes - 1)); } agents = new Agent[nodeNumberOfAgents]; for (int i = 0; i < nodeNumberOfAgents; i++) { agents[i] = new Agent(); agents[i].setDensityLimit(densityLimit); agents[i].setLandscape(landscape); int x = (new Double(Math.random()*(double)width)).intValue(); int y = (new Double(Math.random()*(double)height)).intValue(); agents[i].setX(x); agents[i].setY(y); } landscape.setAgents(agents); } // Run int[] densities = null; for (int time = 0; time < iterations; time++) { if (node != 0) { landscape.calcDensities(); densities = landscape.getDensities(); try { MPI.COMM_WORLD.Send(densities, 0, width * height, MPI.INT, 0, 50); } catch (MPIException mpiE) { mpiE.printStackTrace(); } } else { // if node is node zero densities = new int [width][height]; for (int i = 1; i < numberOfNodes; i++) { // Get the local density from each node i. int[][] localDensities = int [width][height]; try { MPI.COMM_WORLD.Recv(localDensities, 0, width * height, MPI.INT, i, 50); } catch (MPIException mpiE) { mpiE.printStackTrace(); } // Add node i's density surface to the global surface. for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { densities[(y*width) + x] = densities[(y*width) + x] + localDensities[(y*width) + x]; } } } for (int i = 0; i < nodeNumberOfAgents; i++) { agents[i].step(); } } // Report if (node == 0) { for (int x = 0 ; x < width; x++) { for (int y = 0; y < height; y++) { System.out.print(landscape.getDensity(x,y) + " "); } System.out.println(""); } } } }