我的 Python 散景图未在浏览器中显示:“raise ProtocolError(”令牌已过期。

My Python Bokeh plot not displaying in browser: "raise ProtocolError("Token is expired.")

提问人:Vondoe79 提问时间:11/2/2023 最后编辑:Abhiram AkellaVondoe79 更新时间:11/2/2023 访问量:90

问:

我正在联系一个基于 Python 代理的示例代码,我一直在研究以模拟灾难期间的疏散。在大多数情况下,我的逻辑似乎在按预期运作。但是,我的交互式模拟图遇到了一个问题,它的行为不符合预期。

我对 Python 中的库比较陌生。我的目的是在浏览器中显示交互式绘图,但不幸的是,它在将近一个小时后继续超时。bokeh

我在下面包含了我的完整代码供您参考。

我将非常感谢您能提供的任何帮助。

先谢谢你。

from mesa import Agent, Model
from mesa.time import RandomActivation
from mesa.space import MultiGrid
from mesa.datacollection import DataCollector
import random
from bokeh.plotting import figure, show, curdoc
from bokeh.models import ColumnDataSource
# from bokeh.io import push_notebook
from bokeh.io import push_notebook, output_notebook
from bokeh.layouts import column
from bokeh.server.server import Server


class Person(Agent):
    """
    A class representing a person in the evacuation model.
    """

    def __init__(self, unique_id, model):
        """
        Initialize a person agent.

        Args:
            unique_id (int): Unique identifier for the agent.
            model: Reference to the model containing the agent.
        """
        super().__init__(unique_id, model)
        self.evacuated = False

    def move(self):
        """
        Move the person agent to a random neighboring cell if within grid boundaries and not evacuated.
        """
        if not self.evacuated:
            possible_moves = self.model.grid.get_neighborhood(
                self.pos,
                moore=True,
                include_center=False
            )
            new_position = random.choice(possible_moves)
            if self.model.grid.is_cell_empty(new_position):
                self.model.grid.move_agent(self, new_position)

    def step(self):
        """
        Method called in each step of the model's execution.
        """
        if not self.evacuated:
            self.move()
            x, y = self.pos
            if x < 0 or x >= self.model.grid.width or y < 0 or y >= self.model.grid.height:
                self.evacuated = True


class EvacuationModel(Model):
    """
    A class representing the evacuation model.
    """

    def __init__(self, width, height, num_agents):
        """
        Initialize the evacuation model.

        Args:
            width (int): Width of the grid.
            height (int): Height of the grid.
            num_agents (int): Number of person agents in the model.
        """
        self.num_agents = num_agents
        self.grid = MultiGrid(width, height, True)
        self.schedule = RandomActivation(self)

        # Create agents
        for i in range(self.num_agents):
            agent = Person(i, self)
            x = random.randrange(self.grid.width)
            y = random.randrange(self.grid.height)
            self.grid.place_agent(agent, (x, y))
            self.schedule.add(agent)

        # Bokeh setup
        self.source = ColumnDataSource(data={'x': [], 'y': [], 'evacuated': []})
        self.plot = figure(width=800, height=800, title='Agent Evacuation Process',
                           x_range=[0, self.grid.width], y_range=[0, self.grid.height])
        self.plot.square(x='x', y='y', source=self.source, size=20, color='blue')

        self.datacollector = DataCollector(
            agent_reporters={"Evacuated": "evacuated"}
        )

    def step(self):
        """
        Method called in each step of the model's execution.
        Collects data and advances the model by one step.
        """
        self.datacollector.collect(self)
        self.schedule.step()

        # Update Bokeh data
        agent_data = [{'x': agent.pos[0], 'y': agent.pos[1], 'evacuated': agent.evacuated} for agent in
                      self.schedule.agents]
        self.source.data = {'x': [data['x'] for data in agent_data],
                            'y': [data['y'] for data in agent_data],
                            'evacuated': [data['evacuated'] for data in agent_data]}
        push_notebook()


# Set up the server
def modify_doc(doc):
    width = 10
    height = 10
    num_agents = 50

    evacuation_model = EvacuationModel(width, height, num_agents)

    # Run the simulation for 10 steps with interactive plotting
    output_notebook()
    show(evacuation_model.plot, notebook_handle=True)

    for i in range(10):
        evacuation_model.step()


# To access the visualization, run this server code in your Python environment
server = Server({'/': modify_doc}, num_procs=1)
server.start()

if __name__ == '__main__':
    print('Opening Bokeh application on http://localhost:5006/')
    server.io_loop.add_callback(server.show, "/")
    server.io_loop.start()
python-3.x 散景

评论

0赞 bigreddot 11/2/2023
这段代码有很多问题。,并且通常不适用于散景服务器应用程序。更重要的是,您的函数实际上不会修改文档。通常,它会调用添加一些散景对象来显示。目前还不清楚你期望如何使用它,或者让它为用户工作,这在指向你的建议或文档方面很重要。output_notebookshowpush_notebookmodify_docdoc.add_root
0赞 Vondoe79 11/2/2023
@bigreddot \ 感谢您的评论。但是,您能否澄清一下您关于 、 和 的第一条评论?我见过其他人在散景库中使用这些。你是在暗示这些不是散景原生的吗?我的代码中的用法不正确?output_notebookshowpush_notebook
0赞 bigreddot 11/2/2023
不,我不是这么说的。它们是散景的一部分,但它们不用于散景服务器应用程序,而这似乎是您尝试创建的,因为您正在使用 和 .这些函数通常仅用于独立的散景输出(即没有服务器的静态 HTML+JS 输出)。Servermodify_doc
0赞 bigreddot 11/2/2023
澄清一下:上面的“那些函数”是指 、 和 。output_notebookshowpush_notebook
0赞 Vondoe79 11/3/2023
@bigreddot \ 我很欣赏这些澄清。

答: 暂无答案