import matplotlib.pyplot as plt
from py4j.java_gateway import JavaGateway
%matplotlib inline
gw = JavaGateway() # New gateway connection
bridge = gw.entry_point
# Path to Forest Fire model:
sample_models = "/Applications/NetLogo 5.0.2/models/Sample Models/"
forest_fire = "Earth Science/Fire.nlogo"
bridge.openModel(sample_models + forest_fire)
bridge.command("set density 62")
bridge.command("random-seed 0")
bridge.command("setup")
bridge.command("repeat 50 [go]")
burned_trees = bridge.report("burned-trees")
print burned_trees
4256.0
So far so good, but not very useful. A better thing to do would be to automate a parameter sweep (for example) and be able to analyze the results right away from within Python.
def run_model(bridge, density, steps):
'''
Run the forest fire model, and return the number of trees burned.
Args:
bridge: The NetLogoBridge Java object
density: Integer density percent, from 0 to 100
steps: How many steps to run
Returns:
The number of trees burned, as a float.
'''
bridge.command("set density " + str(density))
bridge.command("setup")
bridge.command("repeat " + str(steps) + " [go]")
return bridge.report("burned-trees")
burned_trees = [run_model(bridge, i, 100) for i in range(0,100)]
fig, ax = plt.subplots(figsize=(8,6))
ax.grid(True)
ax.set_xlabel("% Density", fontsize=14)
ax.set_ylabel("# of Trees Burned", fontsize=14)
plt.plot(burned_trees, linewidth=2)
[<matplotlib.lines.Line2D at 0x108627c90>]
Can the NetLogo bridge be fed into one of the Scipy optimizers?
import numpy as np
from scipy.optimize import minimize_scalar
def f(d):
return run_model(bridge, d, 50)
res = minimize_scalar(f, bounds=(1,100), method='bounded')
res
status: 0 nfev: 32 success: True fun: 81.0 x: 27.705287869232411 message: 'Solution found.'
res.x
27.705287869232411
More parameter tweaking is required in the optimizer to make sure it's configured to find the correct solution, but this shows that it works in theory.