def test_walkway(n):
    pos_left = ((np.random.random((n, 2)) - 0.5) * 2.0) * np.array([25.0, 5.0])
    pos_right = ((np.random.random((n, 2)) - 0.5) * 2.0) * np.array([25.0, 5.0])

    x_vel_left = np.random.normal(1.34, 0.26, size=(n, 1))
    x_vel_right = np.random.normal(-1.34, 0.26, size=(n, 1))
    x_destination_left = 100.0 * np.ones((n, 1))
    x_destination_right = -100.0 * np.ones((n, 1))

    zeros = np.zeros((n, 1))

    state_left = np.concatenate(
        (pos_left, x_vel_left, zeros, x_destination_left, zeros), axis=-1)
    state_right = np.concatenate(
        (pos_right, x_vel_right, zeros, x_destination_right, zeros), axis=-1)
    initial_state = np.concatenate((state_left, state_right))

    space = [
        np.array([(x, 5) for x in np.linspace(-25, 25, num=5000)]),
        np.array([(x, -5) for x in np.linspace(-25, 25, num=5000)]),
    ]
    s = socialforce.Simulator(initial_state, socialforce.PedSpacePotential(space))
    states = []
    for _ in range(250):
        state = s.step().state
        # periodic boundary conditions
        state[state[:, 0] > 25, 0] -= 50
        state[state[:, 0] < -25, 0] += 50

        states.append(state.copy())
    states = np.stack(states)

    with visualize(states, space, 'docs/walkway_{}.gif'.format(n)) as _:
        pass
Esempio n. 2
0
def test_r_aB():
    state = np.array([
        [0.0, 0.0, 0.0, 0.0, 0.0, 1.0],
        [1.0, 0.0, 0.0, 0.0, 1.0, 1.0],
    ])
    space = [np.array([[0.0, 100.0], [0.0, 0.5]])]
    r_aB = socialforce.PedSpacePotential(space).r_aB(state)
    assert r_aB.tolist() == [
        [[0.0, -0.5]],
        [[1.0, -0.5]],
    ]
def test_separator():
    initial_state = np.array([
        [-10.0, -0.0, 1.0, 0.0, 10.0, 0.0],
    ])
    space = [
        np.array([(i, i) for i in np.linspace(-1, 4.0)]),
    ]
    s = socialforce.Simulator(initial_state, socialforce.PedSpacePotential(space))
    states = np.stack([s.step().state.copy() for _ in range(80)])

    # visualize
    with visualize(states, space, 'docs/separator.gif') as ax:
        ax.set_xlim(-10, 10)
def test_gate():
    initial_state = np.array([
        [-9.0, -0.0, 1.0, 0.0, 10.0, 0.0],
        [-10.0, -1.5, 1.0, 0.0, 10.0, 0.0],
        [-10.0, -2.0, 1.0, 0.0, 10.0, 0.0],
        [-10.0, -2.5, 1.0, 0.0, 10.0, 0.0],
        [-10.0, -3.0, 1.0, 0.0, 10.0, 0.0],
        [10.0, 1.0, -1.0, 0.0, -10.0, 0.0],
        [10.0, 2.0, -1.0, 0.0, -10.0, 0.0],
        [10.0, 3.0, -1.0, 0.0, -10.0, 0.0],
        [10.0, 4.0, -1.0, 0.0, -10.0, 0.0],
        [10.0, 5.0, -1.0, 0.0, -10.0, 0.0],
    ])
    space = [
        np.array([(0.0, y) for y in np.linspace(-10, -0.7, 1000)]),
        np.array([(0.0, y) for y in np.linspace(0.7, 10, 1000)]),
    ]
    s = socialforce.Simulator(initial_state, socialforce.PedSpacePotential(space))
    states = np.stack([s.step().state.copy() for _ in range(150)])

    with visualize(states, space, 'docs/gate.gif') as _:
        pass
Esempio n. 5
0
    def get_scene(self, agent_states):
        """
        Generate Sequence of Scene with obstacle-setting of the desired Input-Scene. For this, the input-scene-op.jpg image is read in an the obstacles are approximated accordingly.
        :param scene: Name of input-scene
        :param nr_agents: Number of agents that will be constantly in scene. Whenever an agent is leaving the scene, a new agent will spawn
        :param nr_scenes: Number of Frames/Scenes in Sequence
        :param image_path: Path to input-image for obstacle approximation
        :param dataset_path: Path to output-txt-file (generated dataset)
        :param create_background: Boolean - if True, create background image for sequence
        :param create_video: Boolean - if True, create .mp4-file which visualizes the sequence
        :return: Dataset (txt-file) and if chosen video and background image
        """

        # agents have state vectors of the form (x, y, v_x, v_y, d_x, d_y, [tau])

        print("Start generating scenes for dataset %s..." % (self.scenario))

        # Initialize state for each agent
        self.initial_state = self.initialize_agents(self.v_max, self.v_min, self.nr_agents, agent_states, self.a, self.b, setting="random")

        # Get boundaries
        initialize = random_initialization(self.scenario, self.v_max, self.v_min, a=self.a, b=self.b, tau=0.5)
        self.total_y_min = initialize.total_y_min
        self.total_y_max = initialize.total_y_max
        self.total_x_min = initialize.total_x_min
        self.total_x_max = initialize.total_x_max


        # Initialize space according to input image
        space = self.initialize_space(self.image_path, self.create_background, self.scaling)

        # Get Socialforce Simulator
        s = socialforce.Simulator(self.initial_state, ped_space=socialforce.PedSpacePotential(space, u0=self.U0, r=self.r), v0=self.V0, sigma=self.sigma)

        # Get Array for scene numbers and agents
        scene = np.zeros(self.nr_agents)
        agents = np.arange(self.nr_agents) + 1

        # Concatenate arrays with respective x-y-coordinates
        dataset = np.concatenate((scene.reshape(self.nr_agents, 1), agents.reshape(self.nr_agents, 1), s.state[:, 0:2]), axis=1)

        # Create txt-file for dataset
        print("Create dataset as txt-file for scenario: %s" % (self.scenario))
        file = open(self.dataset_path, "w")
        np.savetxt(file, dataset, fmt="%.2f", delimiter="\t")
        file.close()

        file = open(self.dataset_path, "a")

        # Calculate states of each agent for every scene in the dataset
        states = []
        agent_list = []
        states.append(s.state.copy())

        for _ in range(self.nr_scenes):
            state = s.step().state
            agent_list.append(agents.copy())
            scene += 1

            # Avoid oscillations of pedestrians -> Agents that have been at the same place for a longer period of time are exit the scene and new agents enter it
            oscillation_length = 20  # corresponds to: 20 * 0.4 = 8 seconds

            if _ >= oscillation_length:
                dist = np.linalg.norm(states[_][:, 0:2] - states[_ - oscillation_length][:, 0:2], axis=1)
                agent_cond = agent_list[_] == agent_list[_ - oscillation_length]
                add_cond = (dist[:] < 0.8) & agent_cond
            else:
                add_cond = np.ones((state.shape[0])) > 1

            # Boundary conditions - Determine when agents leave the scene
            condition = (state[:, 0] > self.total_x_max + self.threshold) | (state[:, 0] < self.total_x_min - self.threshold) | (state[:, 1] > self.total_y_max + self.threshold) | (state[:, 1] < self.total_y_min - self.threshold) | add_cond

            agents[np.argwhere(condition)] = (max(agents) + np.arange(len(np.argwhere(condition))) + 1).reshape(-1, 1)

            # Generate new Agents when old Agents left the scene
            if len(state[condition]) != 0:
                state[condition] = (np.stack(initialize.initialize_state(agents[np.argwhere(condition)][i, :]) for i in range(len(state[condition])))).squeeze()

            dataset = np.concatenate((scene.reshape(self.nr_agents, 1), agents.reshape(self.nr_agents, 1), state[:, 0:2]), axis=1)
            np.savetxt(file, dataset, fmt="%.2f", delimiter="\t")

            states.append(state.copy())

        file.close()
        states = np.stack(states)
        print("Dataset created.")

        # Show animation of simulation
        if self.show_animation:
            print("Start creating video for visualization of simulated scenario " + str(self.scenario) + "...")
            with self.animate_scenes(states=states, space=space, sim=s) as _:
                pass

            print("Video created.")
Esempio n. 6
0
def gate(n, door_width, velocity, printGif, printPng):
    door_x = 0.0  # 门的横坐标
    destination = [3.0, 0.0]  # 目的地坐标
    range_x = [-10, door_x]  # 初始状态人群位置的x范围
    range_y = [-6.0, 6.0]  # 初始状态人群位置的y范围
    vel_x = velocity  # x方向速度
    vel_y = velocity  # y方向速度

    x_pos = np.random.random((n, 1)) * np.array([range_x[0]])
    y_pos = ((np.random.random((n, 1)) - 0.5) * 2.0) * np.array(([range_y[1]]))
    x_vel = np.full((n, 1), vel_x)
    y_vel = np.full((n, 1), vel_y)
    x_dest = np.full((n, 1), destination[0])
    y_dest = np.full((n, 1), destination[1])
    initial_state = np.concatenate(
        (x_pos, y_pos, x_vel, y_vel, x_dest, y_dest), axis=-1)
    print(initial_state)

    space = [
        np.array([(door_x, y)
                  for y in np.linspace(-10, -door_width / 2, 1000)]),
        np.array([(door_x, y) for y in np.linspace(door_width / 2, 10, 1000)]),
    ]
    s = socialforce.Simulator(initial_state,
                              socialforce.PedSpacePotential(space))

    # 判断是否所有人都通过了门
    states = []
    i = 0
    while True:
        i += 1
        state = s.step().state.copy()
        states.append(state)
        end = True
        for sta in state:
            if sta[0] < 0:
                end = False
            else:
                sta[0] += 5.0
        if end:
            # print("terminate when time is ", i)
            break

    states = np.stack(states)

    if printGif:
        # 生成动态图,比较慢so我先注释掉
        with visualize(states, space,
                       'out/gate{}-{}.gif'.format(n, door_width)) as _:
            pass
    if printPng:
        # 生成路线图
        with socialforce.show.canvas('out/gate{}-{}.png'.format(
                n, door_width)) as ax:
            ax.set_xlabel('x [m]')
            ax.set_ylabel('y [m]')
            for ped in range(len(initial_state)):
                x = states[:, ped, 0]
                y = states[:, ped, 1]
                ax.plot(x, y, '-o')
            ax.set_title("evacuate time {}".format(i))
            ax.legend()
    return i