python调用netlogo:pynetlogo【最后有链接】

我们首先实例化指向 NetLogo 的链接,加载模型,然后在 NetLogo 中执行命令。setup

%matplotlib inline

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_style('white')
sns.set_context('talk')

import pyNetLogo

netlogo = pyNetLogo.NetLogoLink(gui=True,netlogo_home='D:/NetLogo',netlogo_version='6.0',jvm_home='D:/NetLogo/runtime/bin/server/jvm.dll')

netlogo.load_model('examples/models/Wolf Sheep Predation_v6.nlogo')
netlogo.command('setup')

我们可以使用该方法将属性从 Pandas 数据帧传递给代理, 例如,给定属性的初始值。这通过在单个函数调用中同时为多个代理设置多个属性来提高性能。write_NetLogo_attriblist

例如,我们首先将数据从 Excel 文件加载到数据帧中。每行对应于一个代理,每个属性都有列(包括所需的 NetLogo 标识符)。在本例中,我们使用 和 属性为代理设置坐标。whoxcorycor

agent_xy = pd.read_excel('examples/data/xy_DataFrame.xlsx')
agent_xy[['who','xcor','ycor','value']].head(5)
whoxcorycorvalue
00-24.000000-24.000000aaa
11-23.666667-23.666667bbb
22-23.333333-23.333333ccc
33-23.000000-23.000000aaa
44-22.666667-22.666667bbb

然后,我们可以将数据帧传递给 NetLogo,指定要更新的属性和代理类型:

netlogo.write_NetLogo_attriblist(agent_xy[['who','xcor','ycor']], 'a-sheep')

我们可以通过使用报告方法将数据从 NetLogo 返回到 Python 工作区来检查数据交换。在下面的示例中,这将返回代理的数组和坐标,并按其编号排序。然后将其绘制在常规散点图上。xcorycorsheepwho

该方法直接将字符串传递给 NetLogo 实例,以便可能需要根据 NetLogo 版本调整命令语法。链接对象的属性可用于检查当前版本。默认情况下,链接对象将使用找到的最新 NetLogo 版本。reportnetlogo_version

if netlogo.netlogo_version == '6.0':
    x = netlogo.report('map [s -> [xcor] of s] sort sheep')
    y = netlogo.report('map [s -> [ycor] of s] sort sheep')
elif netlogo.netlogo_version == '5':
    x = netlogo.report('map [[xcor] of ?1] sort sheep')
    y = netlogo.report('map [[ycor] of ?1] sort sheep')
fig, ax = plt.subplots(1)

ax.scatter(x, y, s=4)
ax.set_xlabel('xcor')
ax.set_ylabel('ycor')
ax.set_aspect('equal')
fig.set_size_inches(5,5)

plt.show()

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-9x71k9GU-1652524862642)(pynetlogo_files/pynetlogo_8_0.png)]

然后,我们可以运行 100 个基点的模型,并更新绵羊代理的 Python 坐标数组,并为每个代理的能量值返回一个额外的数组。后者绘制在每种代理类型的直方图上。

#We can use either of the following commands to run for 100 ticks:

netlogo.command('repeat 100 [go]')
#netlogo.repeat_command('go', 100)

if netlogo.netlogo_version == '6.0':
    #Return sorted arrays so that the x, y and energy properties of each agent are in the same order
    x = netlogo.report('map [s -> [xcor] of s] sort sheep')
    y = netlogo.report('map [s -> [ycor] of s] sort sheep')
    energy_sheep = netlogo.report('map [s -> [energy] of s] sort sheep')
elif netlogo.netlogo_version == '5':
    x = netlogo.report('map [[xcor] of ?1] sort sheep')
    y = netlogo.report('map [[ycor] of ?1] sort sheep')
    energy_sheep = netlogo.report('map [[energy] of ?1] sort sheep')

energy_wolves = netlogo.report('[energy] of wolves') #NetLogo returns these in random order
from mpl_toolkits.axes_grid1 import make_axes_locatable

fig, ax = plt.subplots(1, 2)

sc = ax[0].scatter(x, y, s=50, c=energy_sheep,
                   cmap=plt.cm.coolwarm)
ax[0].set_xlabel('xcor')
ax[0].set_ylabel('ycor')
ax[0].set_aspect('equal')
divider = make_axes_locatable(ax[0])
cax = divider.append_axes('right', size='5%', pad=0.1)
cbar = plt.colorbar(sc, cax=cax, orientation='vertical')
cbar.set_label('Energy of sheep')

sns.distplot(energy_sheep, kde=False, bins=10,
             ax=ax[1], label='Sheep')
sns.distplot(energy_wolves, kde=False, bins=10,
             ax=ax[1], label='Wolves')
ax[1].set_xlabel('Energy')
ax[1].set_ylabel('Counts')
ax[1].legend()
fig.set_size_inches(14,5)

plt.show()

d:\anaconda3\envs\py9\lib\site-packages\seaborn\distributions.py:2619: FutureWarning: `distplot` is a deprecated function and will be removed in a future version. Please adapt your code to use either `displot` (a figure-level function with similar flexibility) or `histplot` (an axes-level function for histograms).
  warnings.warn(msg, FutureWarning)

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-j558Idoo-1652524862644)(pynetlogo_files/pynetlogo_11_1.png)]

该方法返回一个 Pandas 数据帧,其中包含一个或多个报告器在给定数量的价格变动中报告的值。默认情况下,这假设模型使用“go”NetLogo 命令运行;这可以通过传递可选参数来设置。repeat_reportgo

数据帧按价格变动编制索引,并为每个报告器标记列。在这种情况下,我们跟踪超过200个蜱虫的狼和羊代理的数量;结果首先绘制为时间的函数。然后将狼代理人的数量绘制为绵羊代理人数量的函数,以近似相空间图。

counts = netlogo.repeat_report(['count wolves','count sheep'], 200, go='go')
fig, (ax1, ax2) = plt.subplots(1, 2)

counts.plot(ax=ax1, use_index=True, legend=True)
ax1.set_xlabel('Ticks')
ax1.set_ylabel('Counts')

ax2.plot(counts['count wolves'], counts['count sheep'])
ax2.set_xlabel('Wolves')
ax2.set_ylabel('Sheep')
fig.set_size_inches(12,5)
plt.tight_layout()
plt.show()

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-0q6kZANX-1652524862645)(pynetlogo_files/pynetlogo_14_0.png)]

该方法还可以与返回 NetLogo 列表的报告器一起使用。在这种情况下,列表将转换为 numpy 数组。例如,我们跟踪狼和羊代理在5个蜱虫上的能量,并绘制数据帧中记录的最终刻度时狼的能量分布。repeat_report

为了说明不同的数据类型,我们还跟踪报告器(它跨绵羊代理返回字符串属性,转换为numpy对象数组),(返回单个数字变量)和(返回单个字符串变量)。[sheep_str] of sheepcount sheepglob_str

energy_df = netlogo.repeat_report(['[energy] of wolves',
                                   '[energy] of sheep',
                                   '[sheep_str] of sheep',
                                   'count sheep',
                                   'glob_str'], 5)

fig, ax = plt.subplots(1)

sns.distplot(energy_df['[energy] of wolves'].iloc[-1], kde=False, bins=20, ax=ax)
ax.set_xlabel('Energy')
ax.set_ylabel('Counts')
fig.set_size_inches(4,4)

plt.show()
d:\anaconda3\envs\py9\lib\site-packages\pyNetLogo\core.py:602: VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do this, you must specify 'dtype=object' when creating the ndarray.
  result = np.array([np.array(e.split(),
d:\anaconda3\envs\py9\lib\site-packages\pyNetLogo\core.py:606: VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do this, you must specify 'dtype=object' when creating the ndarray.
  result = np.array([np.array([b.strip('"')
d:\anaconda3\envs\py9\lib\site-packages\seaborn\distributions.py:2619: FutureWarning: `distplot` is a deprecated function and will be removed in a future version. Please adapt your code to use either `displot` (a figure-level function with similar flexibility) or `histplot` (an axes-level function for histograms).
  warnings.warn(msg, FutureWarning)

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-HVNwaEKC-1652524862645)(pynetlogo_files/pynetlogo_16_1.png)]

energy_df.head()
[energy] of wolves[energy] of sheep[sheep_str] of sheepcount sheepglob_str
305.0[22.009727835655212, 23.2806453704834, 5.12650...[35.634368896484375, 12.642822265625, 13.94987...[sheep, sheep, sheep, sheep, sheep, sheep, she...142.0global
306.0[34.966749370098114, 22.52888834476471, 4.1265...[12.724678993225098, 0.8940131664276123, 39.65...[sheep, sheep, sheep, sheep, sheep, sheep, she...139.0global
307.0[26.74847984313965, 3.999619960784912, 45.6639...[30.60993194580078, 5.73723030090332, 5.079662...[sheep, sheep, sheep, sheep, sheep, sheep, she...138.0global
308.0[81.13100171089172, 0.08269596099853516, 8.874...[21.017112731933594, 29.8840389251709, 14.3289...[sheep, sheep, sheep, sheep, sheep, sheep, she...138.0global
309.0[9.504863917827606, 15.259727835655212, 22.175...[11.578887939453125, 3.228648841381073, 2.4744...[sheep, sheep, sheep, sheep, sheep, sheep, she...125.0global

该方法可用于返回一个数据帧,该数据帧(对于此示例)包含每个 NetLogo 修补程序的属性。此数据帧实质上复制了 NetLogo 环境,列标签对应于 xcor 补丁坐标,索引位于 pycor 坐标之后。patch_reportcountdown
[11.578887939453125, 3.228648841381073, 2.4744…
[sheep, sheep, sheep, sheep, sheep, sheep, she…
125.0
global

该方法可用于返回一个数据帧,该数据帧(对于此示例)包含每个 NetLogo 修补程序的属性。此数据帧实质上复制了 NetLogo 环境,列标签对应于 xcor 补丁坐标,索引位于 pycor 坐标之后。patch_reportcountdown

pynetlogo:

https://pynetlogo.readthedocs.io/en/latest/install.html

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值