Пример #1
0
def main(args):
    # Create image directory if it does not exist.
    image_directory = "img"
    if not os.path.exists(image_directory):
        os.makedirs(image_directory)

    loader = sfm.ParameterLoader(args.file)
    world = loader.world
    world.update()

    world.add_measurement(average_speed)
    figure = world.plot()

    figure.savefig("{}/0.png".format(image_directory),
                   bbox_inches='tight',
                   pad_inches=0.1)
    figure.clear()
    plt.close(figure)

    for step in range(args.steps):
        print("Step {}".format(step + 1))
        if not world.step():
            break
        world.update()
        if step % 5 == 4:
            figure = world.plot()
            figure.savefig("{}/{}.png".format(image_directory,
                                              (step + 1) // 5),
                           bbox_inches='tight',
                           pad_inches=0.1)
            figure.clear()
            plt.close(figure)

    np.savetxt("measurements.txt", world.measurements)
Пример #2
0
def main(args):
    loader = sfm.ParameterLoader(args.file)
    world = loader.world
    world.update()
    global timeLeft
    global perpetrated

    if args.test == 1:
        world.add_measurement(imo1Leaving)
    elif args.test == 4:
        world.add_measurement(imo4timeToLeaveRoom)
    elif args.test == 6:
        world.add_measurement(imo6perpetratingCorner)
    elif args.test == 80 or args.test == 81 or args.test == 82 or args.test == 83:
        world.add_measurement(imo8timeToMove)

    figure = world.plot()
    figure.savefig("tmp/img" + str(args.number) + "/0.png",
                   bbox_inches='tight',
                   pad_inches=0.1)
    figure.clear()
    plt.close(figure)

    for step in range(args.steps):
        if not world.step():
            break
        world.update()
        if step % (args.steps / args.images) == (args.steps / args.images) - 1:
            figure = world.plot()
            figure.savefig("tmp/img" + str(args.number) + "/" + str(
                (step + 1) / (args.steps / args.images)) + ".png",
                           bbox_inches='tight',
                           pad_inches=0.1)
            figure.clear()
            plt.close(figure)

    if args.test == 1 or args.test == 4 or args.test == 80:
        np.savetxt("tmp/measurements" + str(args.number) + "/measurements.txt",
                   np.array(timeLeft).reshape(1, ),
                   fmt="%1.4f")
    elif args.test == 6:
        np.savetxt("tmp/measurements" + str(args.number) + "/measurements.txt",
                   np.array(perpetrated).reshape(1, ),
                   fmt="%d")
    elif args.test == 81 or args.test == 82 or args.test == 83:
        f = open("tmp/measurements" + str(args.number) + "/measurements.txt",
                 'ab')
        np.savetxt(f, np.array(timeLeft).reshape(1, ), fmt="%1.4f")
        f.close()
Пример #3
0
def main(args):

    barrier_start = 50.0
    barrier_points = [[50.0, 1.0], [50.0, 4.0]]
    barrier_time = args.barriertime

    mean, theta, sigma = 0.0, 0.05, 0.005

    measurements = []

    for r in range(args.repetitions):
        barrier_state = 0

        if os.path.exists("hddm/{}_pedestrians_{}.csv".format(args.outfile,
                                                              r)):
            print "Already done, continue..."
            continue

        with open("hddm/{}_pedestrians_{}.csv".format(args.outfile, r),
                  "w") as ped_outfile:
            ped_writer = csv.writer(ped_outfile)
            ped_writer.writerow([
                'p', 'mass', 'radius', 'desired_velocity', 'maximum_velocity'
            ])

        with open("hddm/{}_measurements_{}.csv".format(args.outfile, r),
                  "w") as csv_outfile:
            csv_writer = csv.writer(csv_outfile)
            csv_writer.writerow([
                't', 'p', 'pos_x', 'pos_y', 'vel_x', 'vel_y', 'speed',
                'local_density', 'local_velocity_variance'
            ])

        all_pedestrians = set()

        if not os.path.exists("img"):
            os.makedirs("img")
        if not os.path.exists("img/" + args.outfile):
            os.makedirs("img/" + args.outfile)
        if not os.path.exists("measurements"):
            os.makedirs("measurements")

        measurements.append({
            't': [],
            'count_near': [],
            'count_far': [],
            'speed_near': [],
            'speed_far': []
        })

        loader = sfm.ParameterLoader(args.file)
        world = loader.world

        if args.pedestrian_file != '':
            with open(args.pedestrian_file) as infile:
                import pickle
                data = pickle.load(infile)
                # exit()
                for p in data:
                    ped = sfm.Pedestrian(
                        group=world.groups[0],
                        radius=p['radius'],
                        mass=p['mass'],
                        desired_velocity=p['desired_velocity'],
                        maximum_velocity=p['maximum_velocity'],
                        relaxation_time=p['relaxation_time'],
                        target_path=p['target_path'],
                        start=p['position'])
                    ped.velocity = p['velocity']
                    ped.next_velocity = p['velocity']
                    ped.speed = p['speed']
                    ped.next_speed = p['speed']
                    world.groups[0].add_pedestrian(ped)

            print "Imported {} pedestrians".format(
                len(world.groups[0].get_pedestrians()))

        world.update()
        world.groups[0].spawn_max = args.max_pedestrians
        # world.groups[0].set_ornstein_uhlenbeck_process(self, 0, 0.05, 1.0):

        for group in world.groups:
            group.set_ornstein_uhlenbeck_process(mean, theta, sigma)

        bar = progressbar.ProgressBar()
        for step in bar(range(args.steps)):

            if not world.step():
                break

            world.update()

            for group in world.groups:
                for p in group.get_pedestrians():
                    all_pedestrians.add(p)

            # if step % 5 == 0:

            #     figure = world.plot()
            #     figure.savefig("img/" + args.outfile + "/" + str((step + 1) // 5).zfill(4) + ".png",
            #                    bbox_inches = 'tight',
            #                    pad_inches = 0.1)
            #     figure.clear()
            #     plt.close(figure)

            # if step % 5 == 0:

            #     near = sensor_near(world)
            #     far = sensor_far(world)

            #     measurements[r]['t'].append(world.time)
            #     measurements[r]['count_near'].append(near['count'])
            #     measurements[r]['count_far'].append(far['count'])
            #     measurements[r]['speed_near'].append(near['average_speed'])
            #     measurements[r]['speed_far'].append(far['average_speed'])

            #     print len(all_pedestrians)

            # Cleanup to avoid high memory usage.
            if step % 200 == 0:

                # tr.print_diff()
                # process = psutil.Process(os.getpid())
                # print "Before:", process.memory_info().rss
                # print len(all_pedestrians)

                # Get all pedestrians no longer in simulation.
                current_pedestrians = set()
                for group in world.groups:
                    current_pedestrians = current_pedestrians.union(
                        group.get_pedestrians())
                retired_pedestrians = all_pedestrians - current_pedestrians

                # Write all pedestrian data to file.
                with open("hddm/{}_pedestrians_{}.csv".format(args.outfile, r),
                          "a") as ped_outfile:
                    with open(
                            "hddm/{}_measurements_{}.csv".format(
                                args.outfile, r), "a") as csv_outfile:
                        ped_writer = csv.writer(ped_outfile)
                        csv_writer = csv.writer(csv_outfile)

                        for p in retired_pedestrians:
                            m = p.measurements
                            row = [
                                p.id,
                                "%.4f" % p.mass,
                                "%.4f" % p.radius,
                                "%.4f" % p.desired_velocity,
                                "%.4f" % p.maximum_velocity
                            ]
                            ped_writer.writerow(row)

                        for p in all_pedestrians:
                            m = p.measurements
                            for arr in m:
                                s = arr['self']
                                row = [
                                    "%.2f" % s['time'], p.id,
                                    "%.4f" % s['position'][0],
                                    "%.4f" % s['position'][1],
                                    "%.4f" % s['velocity'][0],
                                    "%.4f" % s['velocity'][1],
                                    "%.4f" % s['speed'],
                                    "%.4f" % arr['forces']['local_density'],
                                    "%.4f" %
                                    arr['forces']['local_velocity_variance']
                                ]
                                csv_writer.writerow(row)
                            # Empty all data.
                            p.measurements = []

                # Remove pedestrians from local variables.
                all_pedestrians = current_pedestrians

                # process = psutil.Process(os.getpid())
                # print "After:", process.memory_info().rss

            if barrier_state == 0 and barrier_time != 0 and world.time > barrier_start:
                barrier_state = 1
                world.add_obstacle(sfm.Obstacle(barrier_points))
            elif barrier_state == 1 and world.time > barrier_start + barrier_time:
                barrier_state = 2
                del world.obstacles[-1]

        histogram = None

        # Write all pedestrian data to file.
        with open("hddm/{}_pedestrians_{}.csv".format(args.outfile, r),
                  "a") as ped_outfile:
            with open("hddm/{}_measurements_{}.csv".format(args.outfile, r),
                      "a") as csv_outfile:
                ped_writer = csv.writer(ped_outfile)
                csv_writer = csv.writer(csv_outfile)

                for p in all_pedestrians:
                    if p.id == 0:
                        histogram = [
                            m['self']['random'] for m in p.measurements
                        ]

                    m = p.measurements
                    row = [
                        p.id,
                        "%.4f" % p.mass,
                        "%.4f" % p.radius,
                        "%.4f" % p.desired_velocity,
                        "%.4f" % p.maximum_velocity
                    ]
                    ped_writer.writerow(row)

                    m = p.measurements
                    for arr in m:
                        s = arr['self']
                        row = [
                            "%.2f" % s['time'], p.id,
                            "%.4f" % s['position'][0],
                            "%.4f" % s['position'][1],
                            "%.4f" % s['velocity'][0],
                            "%.4f" % s['velocity'][1],
                            "%.4f" % s['speed'],
                            "%.4f" % arr['forces']['local_density'],
                            "%.4f" % arr['forces']['local_velocity_variance']
                        ]
                        csv_writer.writerow(row)
Пример #4
0
def main(args):

    mean, theta, sigma = 1.3, 0.15, 0.01

    measurements = []

    for r in range(args.repetitions):

        if not os.path.exists("img"):
            os.makedirs("img")
        if not os.path.exists("measurements"):
            os.makedirs("measurements")

        measurements.append({
            't': [],
            'count_near': [],
            'count_far': [],
            'speed_near': [],
            'speed_far': []
        })

        loader = sfm.ParameterLoader(args.file)
        world = loader.world
        world.update()
        barrier_state = 0

        for group in world.groups:
            group.set_ornstein_uhlenbeck_process(mean, theta, sigma)

        bar = progressbar.ProgressBar()
        for step in bar(range(args.steps)):

            if not world.step():
                break

            world.update()
            if step % 5 == 0:
                figure = world.plot()
                figure.savefig("img/" + str((step + 1) // 5) + ".png",
                               bbox_inches='tight',
                               pad_inches=0.1)
                figure.clear()
                plt.close(figure)

            if step % 5 == 0:

                near = sensor_near(world)
                far = sensor_far(world)

                measurements[r]['t'].append(world.time)
                measurements[r]['count_near'].append(near['count'])
                measurements[r]['count_far'].append(far['count'])
                measurements[r]['speed_near'].append(near['average_speed'])
                measurements[r]['speed_far'].append(far['average_speed'])

    types = ['count_near', 'count_far', 'speed_near', 'speed_far']
    m = measurements

    for i in range(4):
        with open("measurements/{}_{}.csv".format(args.outfile, types[i]),
                  "w") as outfile:
            import csv
            writer = csv.writer(outfile)
            writer.writerow(['t'] + [str(r) for r in range(args.repetitions)])

            for j in range(len(m[r]['t'])):
                row = [m[r]['t'][j]] + [
                    m[r][types[i]][j] for r in range(args.repetitions)
                ]
                writer.writerow(row)
Пример #5
0
    def build(self):
        """Run the simulation."""
        angle_ou = (0.0, 0.05, 0.005)
        velocity_ou = (0.0, 0.05, 0.04)

        if not os.path.exists(self.storage_folder):
            if self.debug:
                print("Creating directory {}".format(self.storage_folder))
            os.makedirs(self.storage_folder)

        if self.debug:
            print("Starting new simulation.")
            print("")

        if self.debug:
            print("Writing pedestrians to {}".format(self.pedestrian_file))
            print("Writing measurements to {}".format(self.measurement_file))

        if not os.path.exists(self.image_target):
            os.makedirs(self.image_target)

        # Build the simulation
        with open(self.parameter_file) as file:
            yaml_data = load(file, Loader=Loader)

        if self.spawn_mode == 3 and self.max_pedestrians:
            for g in range(len(yaml_data['groups'])):
                yaml_data['groups'][g]['num_pedestrians'] = int(
                    self.max_pedestrians / len(yaml_data['groups']))

        if self.labda:
            yaml_data['turbulence_lambda'] = self.labda

        loader = sfm.ParameterLoader(data=yaml_data)
        self.world = loader.world
        starting_time = 0.0

        if self.pedestrian_load_file != '':
            with open(self.pedestrian_load_file) as infile:
                import pickle
                data = pickle.load(infile)
                for p in data:
                    ped = sfm.Pedestrian(
                        group=self.world.groups[0],
                        radius=p['radius'],
                        mass=p['mass'],
                        desired_velocity=p['desired_velocity'],
                        maximum_velocity=p['maximum_velocity'],
                        relaxation_time=p['relaxation_time'],
                        target_path=p['target_path'],
                        start=p['position'])
                    ped.velocity = p['velocity']
                    ped.next_velocity = p['velocity']
                    ped.speed = p['speed']
                    ped.next_speed = p['speed']
                    self.world.groups[0].add_pedestrian(ped)

            print("Imported {} pedestrians".format(
                len(self.world.groups[0].get_pedestrians())))

        if os.path.exists(
                self.pedestrian_file) and not self.resume and not self.force:
            print(
                "Output file {} already exists. Either delete the file, or add the -R (resume) or -F (force) flag."
                .format(self.pedestrian_file))
            return False

        # If resume flag is enabled, load the data from file.
        # Important: not all stats are restored (such as angle variance)
        # causing measurements to show outliers.
        if self.resume:

            self.world.clear()

            pedestrians = {}
            with open(self.pedestrian_file) as infile:
                reader = csv.reader(infile)
                header = next(reader)
                for row in reader:
                    pedestrians[row[0]] = row
                    pedestrians[row[0]].append(None)

            with open(self.measurement_file) as infile:
                reader = csv.reader(infile)
                header = next(reader)

                for row in reader:
                    t = float(row[0])
                    if t > starting_time:
                        starting_time = t
                    pedestrians[row[1]][-1] = row

            for id_ in pedestrians:
                pedestrian = pedestrians[id_]
                last = pedestrian[-1]
                if last is None:
                    continue
                group_id = int(pedestrian[-2])
                ped = self.world.groups[group_id].spawn_pedestrian()

                ped.position = np.array([float(last[2]), float(last[3])])
                ped.velocity = np.array([float(last[4]), float(last[5])])
                ped.speed = float(last[6])
                ped.next_velocity = ped.velocity
                ped.next_position = ped.position
                ped.next_speed = ped.speed

                ped.mass = float(pedestrian[1])
                ped.radius = float(pedestrian[2])
                ped.desired_velocity = float(pedestrian[3])
                ped.maximum_velocity = float(pedestrian[4])
                ped.id = id_
                self.processed_pedestrians.add(id_)

            self.world.time = starting_time + self.world.step_size
        else:
            with open(self.pedestrian_file, "w") as ped_outfile:
                ped_writer = csv.writer(ped_outfile)
                ped_writer.writerow([
                    'p', 'mass', 'radius', 'desired_velocity',
                    'maximum_velocity', 'group'
                ])

            with open(self.measurement_file, "w") as csv_outfile:
                csv_writer = csv.writer(csv_outfile)
                csv_writer.writerow([
                    't', 'p', 'pos_x', 'pos_y', 'vel_x', 'vel_y', 'speed',
                    'attractive', 'ped_repulsive', 'repulsive', 'pushing',
                    'local_density', 'local_velocity_variance', 'force_angle',
                    'velocity_angle'
                ])

        self.world.update()

        # Set angular variance
        for group in self.world.groups:
            group.set_ornstein_uhlenbeck_process(*angle_ou, process='angle')

        # Spawn pedestrians in a diamond-like structure.
        if self.spawn_mode == 1:

            if not self.max_pedestrians:
                print("Please set -m")
                exit()

            spawn_area = self.world.groups[0].spawn_area
            min_x = spawn_area.start[0]
            max_x = spawn_area.end[0]
            diff_x = max_x - min_x
            min_y = spawn_area.start[1]
            max_y = spawn_area.end[1]
            diff_y = max_y - min_y

            startpos = np.array([min_x, min_y])
            third = np.pi / 3

            difference = 5 * self.world.groups[0].default_radius
            coordinates = []
            translation = [2, 1, -1]

            while len(
                    coordinates) < self.max_pedestrians and difference > 0.15:

                q = Queue()
                q.put(startpos)

                coordinates = []
                coordinates.append(startpos)

                cx, cy = min_x, min_y
                i = 0
                while True:
                    radial = (1 + (i % 2)) * third
                    position = np.array([cx, cy]) + difference * np.array(
                        [np.cos(radial), np.sin(radial)])
                    if not min_x <= position[
                            0] <= max_x or not min_y <= position[1] <= max_y:
                        break

                    q.put(position)
                    coordinates.append(position)
                    cx, cy = position
                    i += 1

                while len(
                        coordinates) < self.max_pedestrians and not q.empty():
                    cx, cy = q.get()
                    position = np.array([cx + difference, cy])

                    if not min_x <= position[
                            0] <= max_x or not min_y <= position[1] <= max_y:
                        continue

                    q.put(position)
                    coordinates.append(position)

                difference -= 0.01

            # # Add pedestrians to simulation
            group = self.world.groups[0]
            for i, position in enumerate(coordinates):
                p = self.world.groups[0].spawn_pedestrian()
                p.position = position
                p.initialize()
                p.quad.remove(p)
                self.world.quadtree.add(p)

        # Spawn pedestrians randomly at start time.
        elif self.spawn_mode == 2:
            for _ in range(self.max_pedestrians):
                self.world.groups[0].spawn_pedestrian()

        return True