def __check_collisions(self):
        """Update proximity sensors and detect collisions between objects"""

        collisions = []
        checked_robots = []

        if self.__qtree is None:
            self.__qtree = QuadTree(self.__obstacles)

        if len(self.__robots) > 1:
            rqtree = QuadTree(self.__robots)
        else:
            rqtree = None

        # check each robot
        for robot in self.__robots:

            # update proximity sensors
            for sensor in robot.get_external_sensors():
                sensor.get_world_envelope(True)
                rect = Rect(sensor.get_bounding_rect())
                sensor.update_distance()
                # distance to obstacles
                for obstacle in self.__qtree.find_items(rect):
                    sensor.update_distance(obstacle)
                # distance to other robots
                if rqtree is None: continue
                for other in rqtree.find_items(rect):
                    if other is not robot:
                        sensor.update_distance(other)

            rect = Rect(robot.get_bounding_rect())

            # against nearest obstacles
            for obstacle in self.__qtree.find_items(rect):
                if robot.has_collision(obstacle):
                    collisions.append((robot, obstacle))

            # against other robots
            if rqtree is not None:
                for other in rqtree.find_items(rect):
                    if other is robot: continue
                    if other in checked_robots: continue
                    if robot.has_collision(other):
                        collisions.append((robot, other))

            checked_robots.append(robot)

        if len(collisions) > 0:
            # Test code - print out collisions
            for (robot, obstacle) in collisions:
                self.log("Collision with {}".format(obstacle),
                         obj=robot,
                         color=robot.get_color())
            # end of test code
            return True

        return False
示例#2
0
def reflect_rect(rect):
    """Conditionally reflects the rectangle about the following lines:
    * RA 0 <-> 360 boundary"""

    x_min = rect.x_min
    x_max = rect.x_max
    y_min = rect.y_min
    y_max = rect.y_max

    # rectangles on the 0 <-> 360 line
    if x_min < 0:
        x_min += 360.0
        x_max += 360.0

    return Rect(x_min, x_max, y_min, y_max)
    def __init__(self, MI, NI, granulometry, matrixLabel):

        self.MI = MI
        self.NI = NI
        self.granulometry = granulometry
        self.matrixLabel = matrixLabel

        xv = np.linspace(0, self.MI - 1, self.MI,
                         endpoint=True).astype(np.int32)
        yv = np.linspace(0, self.NI - 1, self.NI,
                         endpoint=True).astype(np.int32)
        X, Y = np.int32(np.meshgrid(xv, yv))

        self.coords = {(x, y) for x, y in zip(X.ravel(), Y.ravel())}

        depth = 4
        self.qtree = Quadtree(int(depth), Rect(0, 0, int(self.MI),
                                               int(self.NI)))
        (self.XX, self.YY) = np.meshgrid(range(0, self.NI), range(0, self.MI))
示例#4
0
文件: main.py 项目: annell/Survive
import numpy as np
import matplotlib.pyplot as plt
from quadtree import Point, Rect, QuadTree
from matplotlib import gridspec

DPI = 72
np.random.seed(13)

width, height = 600, 400

N = 5000
coords = np.random.randn(N, 2) * height / 3 + (width / 2, height / 2)
points = [Point(*coord) for coord in coords]

domain = Rect(width / 2, height / 2, width, height)
qtree = QuadTree(domain, 3)
for point in points:
    qtree.insert(point)

print('Number of points in the domain =', len(qtree))

fig = plt.figure(figsize=(700 / DPI, 500 / DPI), dpi=DPI)
ax = plt.subplot()
ax.set_xlim(0, width)
ax.set_ylim(0, height)
qtree.draw(ax)

ax.scatter([p.x for p in points], [p.y for p in points], s=4)
ax.set_xticks([])
ax.set_yticks([])
示例#5
0
def main():
    """Creates a coverage map which shows the number of observations in each
    node in each zone."""

    # the coverage map is (internally) represented as a (square) Numpy NDArray
    # whose dimensions are defined by the number of times the sphere is sudivided.

    max_obs = 10  # a threshold value

    parser = argparse.ArgumentParser(
        description='Produces a coverage map with data from all zones')
    parser.add_argument('save_dir',
                        type=str,
                        help="Directory in which results (dats) are saved.")
    args = parser.parse_args()

    # collect all of the dat files.
    filenames = glob.glob((args.save_dir + "/z*.dat"))
    filenames = sorted(filenames)
    if len(filenames) == 0:
        print("No DAT files found in %s" % (args.save_dir))

    # build a tree that summarizes the properties of stars in its node
    depth = 7
    bounds = Rect(0, 360, -90, 90)
    tree = QuadTreeNode(bounds, 0)
    tree.split_until(depth, leafClass=SummaryLeaf)

    # determine the size of the image we will generate
    width = 2**depth
    height = width

    # read in the datfile entries to the tree
    for filename in filenames:
        dat_data = dat.read_dat(filename)
        print("Read %s which has %i stars" % (filename, len(dat_data)))

        for datum in dat_data:
            x = datum['ra']
            y = datum['dec']
            tree.insert(x, y, datum)

    # Extract the data from the leaves
    leaves = tree.get_leaves()
    data = [leaf.get_data() for leaf in leaves]
    data = np.concatenate(data, axis=0)

    # create a distinct number of colors for plotting
    color_map = discrete_cmap(max_obs, 'gnuplot')

    filter_names = dat.apass_phot_names
    for filter_name in filter_names:

        # set up the image
        image = np.zeros((width, height), dtype=float)

        # determine the filter and star columns
        filter_col = 'num_obs_' + filter_name
        stars_col = 'num_stars_' + filter_name

        # extract the average number of observations for each pixel
        for datum in data:
            ra = datum['ra']
            dec = datum['dec']
            num_obs = datum[filter_col]
            num_stars = datum[stars_col]

            ave_obs = 0
            if (num_obs > 0):
                ave_obs = float(num_obs) / num_stars

            if ave_obs > 10:
                ave_obs = 10

            [x, y] = coords_to_pixel(ra, dec, width, height)

            image[y, x] = ave_obs

        # configure the plot
        fig = plt.figure(figsize=(18, 9))
        im = plt.imshow(image, extent=[0, 360, -90, 90])
        plt.colorbar(im)

        #axes.set_ylim([-90, 90])
        #axes.set_xlim([0, 360])

        plt.title("APASS %s coverage" % (filter_name))
        plt.savefig("apass_" + filter_name + ".png")