Example #1
0
  @Override
  public void start() {
    super.start();

    environment =
        new Continuous2D(1.0, config.getEnvironmentWidth(), config.getEnvironmentHeight());
    drawProxy = new DrawProxy(environment.getWidth(), environment.getHeight());
    environment.setObjectLocation(drawProxy, new Double2D());

    physicsWorld = new World(new Vec2());
    placementArea =
        new PlacementArea((float) environment.getWidth(), (float) environment.getHeight());
    placementArea.setSeed(config.getSimulationSeed());
    schedule.reset();
    System.gc();

    physicsWorld.setContactListener(contactListener);

    // Create ALL the objects
    createWalls();
    createTargetArea();
    robotFactory.placeInstances(
        placementArea.new ForType<>(), physicsWorld, config.getTargetAreaPlacement());
    config.getResourceFactory().placeInstances(placementArea.new ForType<>(), physicsWorld);

    // Now actually add the objects that have been placed to the world and schedule
    for (PhysicalObject object : placementArea.getPlacedObjects()) {
      drawProxy.registerDrawable(object.getPortrayal());
      schedule.scheduleRepeating(object);
    }

    schedule.scheduleRepeating(
        simState -> physicsWorld.step(TIME_STEP, VELOCITY_ITERATIONS, POSITION_ITERATIONS));
  }
Example #2
0
  /*
   * This method is called to wind down the simulation.
   */
  public void finish() {
    super.finish();

    System.out.println("Terminating the simulation");

    /*
     * write CSV and XML output from simulation
     */
    File csvDataFile =
        new File(resultFilePath + "/" + description + "/" + runFilePath + "/simOutputData.csv");
    System.out.println("Output written to " + csvDataFile);

    // File xmlDataFile = new File(resultFilePath + "/" + description + "/Results/" + runFilePath +
    // "/simOutputData.xml");

    PrintWriter dataOutput;

    try {
      dataOutput = new PrintWriter(csvDataFile);
      dataOutput.print(dataStore.compileTableToString());
      dataOutput.close();

      //	dataStore.compileXMLOutput(xmlDataFile);
    } catch (Exception e) {
      e.printStackTrace();
    }

    System.out.println("Run took " + (System.currentTimeMillis() - startTime) + " milliseconds");
  }
Example #3
0
  /** Implements simulation initialization */
  public void start() {
    // Start the simulation
    super.start();

    // Clear the field of food and robots
    field.clear();

    // Reset the scores
    score[0] = score[1] = 0;

    // Add our team of robots to the field and activate them
    Team team = new Team(field, false, strategy);
    schedule.scheduleRepeating(team);

    // Add the opposing team of robots to the field and activate them
    Team opposingTeam = new Team(field, true, baselineStrategy);
    schedule.scheduleRepeating(opposingTeam);

    // Add some randomly distributed food to the field
    for (int t = 0; t < nTreats; t++) {
      // Select a random but empty location
      Double2D treatLocation;
      do {
        treatLocation =
            new Double2D(
                field.getWidth() * (random.nextDouble() * 0.8 + 0.1),
                field.getHeight() * (random.nextDouble() * 0.8 + 0.1));
      } while (field.getObjectsWithinDistance(treatLocation, Treat.treatSize).size() > 0);
      Treat treat = new Treat();
      field.setObjectLocation(treat, treatLocation);
    }
  }
Example #4
0
  /**
   * This method is called to start the simulation. the run parameters are copied to the results
   * output directory. The run output file is created ready for writing.
   */
  public void start() {
    super.start(); // call supertype's start method.

    // System.out.println("In main on CBSimulation class");

    // need to read the parameter file
    readParameters(true);

    // And I want to write the random number seed used for this run - for record keeping

    PrintWriter dataOutput;

    new File(resultFilePath + "/" + description + "/" + runFilePath).mkdirs();
    File runSeedFile =
        new File(resultFilePath + "/" + description + "/" + runFilePath + "/simRunSeed");
    System.out.println("Creating output file " + runSeedFile.getName());

    String paramCopyFile =
        resultFilePath + "/" + description + "/" + runFilePath + "/" + paramCopyName;
    copyFile(xmlFileLocation, paramCopyFile);

    try {
      dataOutput = new PrintWriter(runSeedFile);
      dataOutput.print(seed);
      dataOutput.close();
    } catch (Exception e) {
      e.printStackTrace();
    }

    // I'll need to instantiate the data store here
    // I'll schedule it from the constructor...
    dataStore = new DataStore(this);
    // System.out.println("Created DataStore object " + dataStore);

  }
Example #5
0
  /** Finish the simulation and clean up */
  public void finish() {
    super.finish();
    try {

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Example #6
0
  /** Resets and starts a simulation */
  public void start() {
    super.start(); // clear out the schedule

    // make new grids
    createGrids();
    for (int x = 0; x < gridWidth; x++)
      for (int y = 0; y < gridHeight; y++) {
        schedule.scheduleRepeating(new Agent(x, y));
      }
  }
Example #7
0
  @Override
  public void start() {
    super.start();

    agents.clear(); // remove any agents from previous runs

    // add agents to the simulation
    addAgents();

    // ensure both GeomFields Color same area
    agents.setMBR(county.getMBR());
  }
Example #8
0
  public void start() {
    super.start();

    // clear the yard
    yard.clear();

    // clear the buddies
    buddies.clear();

    // add some students to the yard
    for (int i = 0; i < numStudents; i++) {
      Student student = new Student();
      yard.setObjectLocation(
          student,
          new Double2D(
              yard.getWidth() * 0.5 + random.nextDouble() - 0.5,
              yard.getHeight() * 0.5 + random.nextDouble() - 0.5));

      buddies.addNode(student);
      schedule.scheduleRepeating(student);
    }

    // define like/dislike relationships
    Bag students = buddies.getAllNodes();
    for (int i = 0; i < students.size(); i++) {
      Object student = students.get(i);

      // who does he like?
      Object studentB = null;
      do {
        studentB = students.get(random.nextInt(students.numObjs));
      } while (student == studentB);
      double buddiness = random.nextDouble();
      buddies.addEdge(student, studentB, new Double(buddiness));

      // who does he dislike?
      do {
        studentB = students.get(random.nextInt(students.numObjs));
      } while (student == studentB);
      buddiness = random.nextDouble();
      buddies.addEdge(student, studentB, new Double(-buddiness));
    }
  }
Example #9
0
 @Override
 public void setSeed(long seed) {
   super.setSeed(seed);
   config.setSimulationSeed(seed);
 }
Example #10
0
  /** Read in data and set up the simulation */
  public void start() {
    super.start();
    try {

      GeomVectorField populationLayer = new GeomVectorField(grid_width, grid_height);

      //////////////////////////////////////////////
      ///////////// READING IN DATA ////////////////
      //////////////////////////////////////////////

      readInVectorLayer(baseLayer, dirName + "haiti/haiti_meters.shp", "area", new Bag());
      readInVectorLayer(
          populationLayer,
          dirName + "population/popCentroids_meters.shp",
          "residential areas",
          new Bag());
      readInVectorLayer(roadLayer, dirName + "roads/roads_meters.shp", "road network", new Bag());
      readInVectorLayer(
          waterwayLayer, dirName + "waterways/rivers_meters.shp", "waterways", new Bag());
      readInVectorLayer(
          medicalLayer,
          dirName + "healthFacilities/health_meters.shp",
          "health facilities",
          new Bag());

      //////////////////////////////////////////////
      ////////////////// CLEANUP ///////////////////
      //////////////////////////////////////////////

      // standardize the MBRs so that the visualization lines up

      MBR = roadLayer.getMBR();
      //			MBR.init(740000, 780000, 2000000, 2040000); // 35 22
      MBR.init(740000, 779000, 2009000, 2034000); // 35 22
      //			MBR.init(750000, 772000, 2009500, 2028500); // 22 18
      //			MBR.init(756000, 766000, 2015500, 2022500);
      roadLayer.setMBR(MBR);
      // baseLayer.setMBR(MBR);

      this.grid_width = roadLayer.fieldWidth;
      this.grid_height = roadLayer.fieldHeight;

      // base layer

      landArea = (Geometry) ((MasonGeometry) baseLayer.getGeometries().get(0)).geometry.clone();
      for (Object o : baseLayer.getGeometries()) {
        MasonGeometry g = (MasonGeometry) o;
        landArea = landArea.union(g.geometry);
      }

      // clean up the road network

      System.out.print("Cleaning the road network...");

      roads =
          NetworkUtilities.multipartNetworkCleanup(roadLayer, roadNodes, resolution, fa, random, 0);
      roadNodes = roads.getAllNodes();
      testNetworkForIssues(roads);

      /*			// set up roads as being "open" and assemble the list of potential terminii
      			roadLayer = new GeomVectorField(grid_width, grid_height);
      			for(Object o: roadNodes){
      				GeoNode n = (GeoNode) o;
      				networkLayer.addGeometry(n);

      				boolean potential_terminus = false;

      				// check all roads out of the nodes
      				for(Object ed: roads.getEdgesOut(n)){

      					// set it as being (initially, at least) "open"
      					ListEdge edge = (ListEdge) ed;
      					((MasonGeometry)edge.info).addStringAttribute("open", "OPEN");
      					networkEdgeLayer.addGeometry( (MasonGeometry) edge.info);
      					roadLayer.addGeometry((MasonGeometry) edge.info);
      					((MasonGeometry)edge.info).addAttribute("ListEdge", edge);

      					String type = ((MasonGeometry)edge.info).getStringAttribute("highway");
      					if(type.equals("motorway") || type.equals("primary") || type.equals("trunk"))
      						potential_terminus = true;
      				}

      				// check to see if it's a terminus
      				if(potential_terminus && !MBR.contains(n.geometry.getCoordinate()) && roads.getEdges(n, null).size() == 1){
      					terminus_points.add(n);
      				}

      			}
      */
      // reset MBRS in case it got messed up during all the manipulation
      roadLayer.setMBR(MBR);
      networkLayer.setMBR(MBR);
      networkEdgeLayer.setMBR(MBR);
      waterwayLayer.setMBR(MBR);
      baseLayer.setMBR(MBR);
      medicalLayer.setMBR(MBR);
      humanLayer.setMBR(MBR);
      homesLayer.setMBR(MBR);
      diseasesLayer.setMBR(MBR);

      System.out.println("done");

      /////////////////////
      ///////// Clean up roads for Agents to use ///////////
      /////////////////////

      /*	Network majorRoads = extractMajorRoads();
      		testNetworkForIssues(majorRoads);

      		// assemble list of secondary versus local roads
      		ArrayList <Edge> myEdges = new ArrayList <Edge> ();
      		GeomVectorField secondaryRoadsLayer = new GeomVectorField(grid_width, grid_height);
      		GeomVectorField localRoadsLayer = new GeomVectorField(grid_width, grid_height);
      		for(Object o: majorRoads.allNodes){

      			majorRoadNodesLayer.addGeometry((GeoNode)o);

      			for(Object e: roads.getEdges(o, null)){
      				Edge ed = (Edge) e;

      				myEdges.add(ed);

      				String type = ((MasonGeometry)ed.getInfo()).getStringAttribute("highway");
      				if(type.equals("secondary"))
      						secondaryRoadsLayer.addGeometry((MasonGeometry) ed.getInfo());
      				else if(type.equals("local"))
      						localRoadsLayer.addGeometry((MasonGeometry) ed.getInfo());
      			}
      		}

      */ System.gc();

      //////////////////////////////////////////////
      ////////////////// AGENTS ///////////////////
      //////////////////////////////////////////////

      // set up the agents in the simulation
      setupAgents(populationLayer);
      humanLayer.setMBR(MBR);
      homesLayer.setMBR(MBR);

      /*			// for each of the Agents, set up relevant, environment-specific information
      			int aindex = 0;
      			for(Human a: humans){

      				if(a.familiarRoadNetwork == null){

      					// the Human knows about major roads
      					Network familiar = majorRoads.cloneGraph();

      					// connect the major network to the Human's location
      					connectToMajorNetwork(a.getNode(), familiar);

      					a.familiarRoadNetwork = familiar;

      					// add local roads into the network
      					for(Object o: humanLayer.getObjectsWithinDistance(a, 50)){
      						Human b = (Human) o;
      						if(b == a || b.familiarRoadNetwork != null || b.getNode() != a.getNode()) continue;
      						b.familiarRoadNetwork = familiar.cloneGraph();
      					}

      				}

      				// connect the Human's work into its personal network
      				if(a.getWork() != null)
      					connectToMajorNetwork(getClosestGeoNode(a.getWork()), a.familiarRoadNetwork);

      				// set up its basic paths (fast and quicker and recomputing each time)
      				a.setupPaths();

      				if(aindex % 100 == 0){ // print report of progress
      					System.out.println("..." + aindex + " of " + humans.size());
      				}
      				aindex++;
      			}
      */
      //			Disease d = new Disease();
      Cholera d = new Cholera();
      HumanTeleporter h = humans.get(random.nextInt(humans.size()));
      h.acquireDisease(d);

      // seed the simulation randomly
      //			seedRandom(System.currentTimeMillis());

      // schedule the reporter to run
      //			setupReporter();

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Example #11
0
  @Override
  public void start() {
    super.start();
    init();

    for (Student s : students) schedule.scheduleRepeating(s, 0, 1.0);

    for (School s : schools) schedule.scheduleRepeating(s, 1, 1.0);

    for (Household h : households) schedule.scheduleRepeating(h, 2, 1.0);

    // at step 20, begin the infection
    schedule.scheduleOnce(
        20,
        3,
        new Steppable() {
          public void step(SimState state) {
            beginInfection();
          }
        });

    // containment strategy: if any school has an outbreak, close all the schools
    schedule.scheduleRepeating(
        0,
        4,
        new Steppable() {
          public void step(SimState state) {
            if (closeSchoolUponOutbreak || closeAllSchoolsUponOutbreak)
              for (School s : schools)
                if (s.getProportionOfHomeboundStudents()
                    > outbreakThreshold) { // if any school has an outbreak
                  s.closed = true;
                  if (closeAllSchoolsUponOutbreak) {
                    for (School s2 : schools) // close all the schools
                    s2.closed = true;
                    break;
                  }
                }
          }
        });

    // check for end condition and terminate
    schedule.scheduleRepeating(
        0,
        5,
        new Steppable() {
          public void step(SimState state) {
            sCount = 0;
            iCount = 0;
            rCount = 0;
            for (Student s : students) {
              switch (s.status) {
                case SUSCEPTIBLE:
                  sCount++;
                  break;
                case INFECTED:
                  iCount++;
                  break;
                case RECOVERED:
                  rCount++;
                  break;
              }
            }

            if ((iCount == 0) && (rCount > 0)) {
              // System.out.format("Step %d. Total people infected: %d   out of: %d\n",
              // state.schedule.getSteps(), rCount, students.size());
              System.out.format(
                  "%d, %d, %d, %d, %d, %f, %b, %b, %f, %d, %d\n",
                  schedule.getSteps(),
                  numHouseholds,
                  numInitialInfections,
                  diseaseDuration,
                  incubationPeriod,
                  diseaseTransmissionProb,
                  closeSchoolUponOutbreak,
                  closeAllSchoolsUponOutbreak,
                  outbreakThreshold,
                  rCount,
                  students.size());
              state.kill();
            }
          }
        });
  }
Example #12
0
  // HEATMAPS
  public void start() {
    super.start();
    try {

      String foutDir =
          "/Users/swise/Dissertation/Colorado/finalLegionResults/nofire/processed/heatmaps";
      String dataDir =
          "/Users/swise/Dissertation/Colorado/finalLegionResults/nofire/heatmaps"; // -1";

      // go through each of the relevant files and read in the data

      File folder = new File(dataDir);
      File[] runFiles = folder.listFiles();

      HashMap<String, DoubleGrid2D> differentRuns = new HashMap<String, DoubleGrid2D>();

      for (File f : runFiles) {

        String filename = f.getName();
        if (!filename.endsWith(fileType)) // only specific kinds of files
        continue;

        // the group of runs to which this result belongs
        String runGroup = filename.substring(7, filename.lastIndexOf("_"));

        // Open the file as an input stream
        FileInputStream fstream;
        fstream = new FileInputStream(f.getAbsoluteFile());

        // Convert our input stream to a BufferedReader
        BufferedReader d = new BufferedReader(new InputStreamReader(fstream));

        String s = d.readLine(); // get rid of the header (MAYBE)

        DoubleGrid2D myGrid = differentRuns.get(runGroup);
        if (myGrid == null) {
          String[] bits = s.split("\t");
          myGrid = new DoubleGrid2D(Integer.parseInt(bits[0]), Integer.parseInt(bits[1]));
          differentRuns.put(runGroup, myGrid);
        }

        int row = 0;
        // read in the file line by line
        while ((s = d.readLine()) != null) {

          String[] bits = s.split("\t"); // split into columns
          int col = 0;
          for (String bit : bits) {
            int i = Integer.parseInt(bit);
            myGrid.field[row][col] += i;
            col++;
          }
          row++;
        }

        fstream.close();
      }

      for (String runGroup : differentRuns.keySet()) {

        // Open the file for output
        BufferedWriter w = new BufferedWriter(new FileWriter(foutDir + "/" + runGroup + ".txt"));

        DoubleGrid2D myGrid = differentRuns.get(runGroup);

        for (int row = 0; row < myGrid.getWidth(); row++) {
          for (int col = 0; col < myGrid.getHeight(); col++) {
            w.write(myGrid.field[row][col] + "\t");
          }
          w.newLine();
        }

        w.close();
      }

    } catch (Exception e) {
    }
  }