Exemple #1
0
                plants.append(s['geometry']['coordinates'])
            elif s['geometry']['type'] == 'MultiPoint':
                plants.append(s['geometry']['coordinates'][0])

heights = np.zeros((len(plants), len(paths)))
for i in range(len(plants)):
    heights[i, :] = np.array([
        plane.getMaxValueAt(plants[i][1], plants[i][0], k_size=15)
        for plane in planes
    ])

beds_points = dib.divide(plants)
beds = [util.get_convex_hull(np.array(bed)) for bed in beds_points]

spindex = Index(bbox=(np.amin(np.array(plants)[:, 0]),
                      np.amin(np.array(plants)[:, 1]),
                      np.amax(np.array(plants)[:, 0]),
                      np.amax(np.array(plants)[:, 1])))
for i, plant in enumerate(plants):
    spindex.insert({
        'obj': plant,
        'index': i
    },
                   bbox=(plant[0], plant[1], plant[0], plant[1]))
dates_str = [p.split("_DEM")[0].split("-")[-1] for p in paths]
dates = [
    datetime.datetime(int(d[:4]), int(d[4:6]), int(d[6:8]), int(d[8:10]),
                      int(d[10:12])) for d in dates_str
]
time_diffs = [(dates[i] - dates[0]).total_seconds() / (60 * 60 * 24)
              for i in range(len(dates))]
plt.plot(time_diffs, [np.median(heights[:, i]) for i in range(len(planes))])
Exemple #2
0
def divide(plants,
           plot=False,
           orientation='East-West',
           a=1,
           b=4,
           c=4,
           heighest_in_group=True):
    if orientation == 'North-South':
        plants = np.array(
            sorted(sorted(plants, key=lambda a: a[1]), key=lambda a: a[0]))
    else:
        plants = np.array(
            sorted(sorted(plants, key=lambda a: a[0]), key=lambda a: a[1]))

    spindex = Index(bbox=(np.amin(plants[:, 0]), np.amin(plants[:, 1]),
                          np.amax(plants[:, 0]), np.amax(plants[:, 1])))
    for plant in plants:
        spindex.insert(plant, bbox=(plant[0], plant[1], plant[0], plant[1]))

    convex_hulls = []

    n = 5000
    overlap = 500
    for i in range(int(np.ceil(len(plants) / n))):
        offset = n if (i + 1) * n < len(plants) else len(plants) - i * n
        offset = offset + overlap if i * n + offset + overlap < len(
            plants) else offset
        convex_hulls.append(
            util.get_convex_hull(plants[i * n:i * n + offset, :]))

    convex_hull = convex_hulls[0]
    for i in range(1, len(convex_hulls)):
        convex_hull = convex_hull.union(convex_hulls[i])
    if isinstance(convex_hull, MultiPolygon):
        convex_hull = sorted(convex_hull, key=lambda a: a.area,
                             reverse=True)[0]
    convex_hull_o = util.get_convex_hull(plants)

    ds = convex_hull.length / 5000
    dy = (np.max(plants[:, 1]) - np.min(plants[:, 1])) / 2000
    dx = (np.max(plants[:, 0]) - np.min(plants[:, 0])) / 2000

    x, y = convex_hull.exterior.xy

    dist = []
    for i in range(len(x) - 1):
        line = LineString([(x[i], y[i]), (x[i + 1], y[i + 1])])
        lc = line.coords
        n = int(line.length / ds + 0.5) - 1
        points = fill_points_in_line(lc[0], lc[1], n) + [[x[i], y[i]]]
        for p in points:
            j = 1
            while j < 200 and not spindex.intersect(
                (p[0] - j * dx, p[1] - j * dy, p[0] + j * dx, p[1] + j * dy)):
                j += 1
            dist.append({'coord': p, 'dist': j})

    lone_points = []
    dists = []
    indices = []
    for i in range(len(dist)):
        if dist[i]['dist'] > c:
            if plot:
                plt.plot(dist[i]['coord'][0], dist[i]['coord'][1], '*')
                plt.text(dist[i]['coord'][0], dist[i]['coord'][1],
                         dist[i]['dist'])
            lone_points.append(dist[i]['coord'])
            indices.append(i)

    for i in range(len(lone_points) - 1):
        dists.append(
            LineString([(lone_points[i][0], lone_points[i][1]),
                        (lone_points[i + 1][0], lone_points[i + 1][1])
                        ]).length)

    groups = []
    groups.append([{'coord': lone_points[0], 'index': indices[0]}])
    for i in range(1, len(lone_points)):
        if indices[i] - indices[i - 1] < 4:
            for j in range(len(groups)):
                if {
                        'coord': lone_points[i - 1],
                        'index': indices[i - 1]
                } in groups[j]:
                    groups[j].append({
                        'coord': lone_points[i],
                        'index': indices[i]
                    })
        else:
            groups.append([{'coord': lone_points[i], 'index': indices[i]}])

    for i in range(len(groups) - 1, -1, -1):
        if len(groups[i]) < b:
            del groups[i]

    max_points = []
    for i in range(len(groups)):
        if heighest_in_group:
            max_index = groups[i][0]['index']
            max_dist = dist[max_index]['dist']
            for j in range(1, len(groups[i])):
                if dist[groups[i][j]['index']]['dist'] > max_dist:
                    max_index = groups[i][j]['index']
                    max_dist = dist[max_index]['dist']

            max_points.append(dist[max_index]['coord'])
        else:
            max_points.append(groups[i][int(len(groups[i]) / 2)]['coord'])

    likeliness = []
    for i in range(len(max_points)):
        for j in range(i, len(max_points)):
            p = max_points[i]
            q = max_points[j]
            if p != q:
                l = LineString([(p[0], p[1]), (q[0], q[1])])
                lc = l.coords
                if convex_hull.exterior.distance(
                        Point((p[0] + q[0]) / 2,
                              (p[1] + q[1]) / 2)) > ds and LineString(
                                  [p, q]).length > convex_hull_o.length / 4:
                    points = fill_points_in_line(lc[0], lc[1],
                                                 int(l.length / ds + 0.5) - 1)
                    n = 0
                    for point in points:
                        if spindex.intersect(
                            (point[0] - a * dx, point[1] - a * dy,
                             point[0] + a * dx, point[1] + a * dy)):
                            n += 1
                    likeliness.append({
                        'line': (i, j),
                        'likeliness': 1 - n / len(points)
                    })
                else:
                    likeliness.append({'line': (i, j), 'likeliness': 0})

    splitting_lines = []
    for l in likeliness:
        if l['likeliness'] > 0.95:
            splitting_lines.append(
                [max_points[l['line'][0]], max_points[l['line'][1]]])
            if plot:
                plt.plot(
                    [max_points[l['line'][0]][0], max_points[l['line'][1]][0]],
                    [max_points[l['line'][0]][1], max_points[l['line'][1]][1]])

    if plot:
        for p in max_points:
            plt.plot(p[0], p[1], 'o')
        plt.plot(x, y)
        plt.show()

    beds = [plants]

    pbar = tqdm(desc="dividing into beds", total=len(splitting_lines))
    for l in splitting_lines:
        newbeds = []
        for bed in beds:
            p1 = []
            p2 = []
            for plant in bed:
                if LinearRing([(l[0][0], l[0][1]), (l[1][0], l[1][1]),
                               (plant[0], plant[1])]).is_ccw:
                    p1.append(plant)
                else:
                    p2.append(plant)
            if p1:
                newbeds.append(p1)
            if p2:
                newbeds.append(p2)
        beds = newbeds
        pbar.update(1)
    pbar.close()

    if plot:
        for bed in beds:
            plt.scatter(np.array(bed)[:, 0], np.array(bed)[:, 1])
        plt.show()

    return beds
Exemple #3
0
def main():
    seed = random.randrange(sys.maxsize)
    rng = random.Random(seed)
    print("Using seed: ", seed)

    # Load mask and colored image
    mask = Image(Point(0, 0), "res/ok_mask.png")
    W = mask.getWidth()
    H = mask.getHeight()
    mask = Image(Point(W / 2, H / 2), "res/ok_mask.png")
    image = Image(Point(W / 2, H / 2), "res/ok_color.png")

    win = GraphWin('CPack', W, H)
    win.setCoords(0, 0, W, H)

    # Initialize quadtree
    spindex = Index(bbox=(0, 0, W, H))

    # Clear screen
    clear_screen(win, W, H)
    # mask.draw(win)

    max_radius = W / 2
    min_radius = 2

    for ii in range(10000):
        # Select random point in screen
        center = Point(random.randint(1, W - 1), random.randint(1, H - 1))
        radius = 1
        # Make sure initial center is valid
        matches = spindex.intersect(get_bbox(center, radius))
        while point_in_any_circle(center,
                                  matches) or not point_in_mask(center, mask):
            center = Point(random.randint(0, W - 1), random.randint(0, H - 1))
            matches = spindex.intersect(get_bbox(center, radius))
        # Get circles in the direct vicinity
        matches = spindex.intersect(get_bbox(center, radius + 1))
        # Grow circle till it collides with screen or another circle
        # NOTE(ndx): I tried binary search here but found that on average it resulted in more collision queries
        while not collide_circle_any(center, radius + 1, matches, W,
                                     H) and collide_circle_mask(
                                         center, radius + 1, mask):
            radius += 1
            matches = spindex.intersect(get_bbox(center, radius))
            if radius >= max_radius:
                break

        # Get rid of circle if too small
        if radius <= min_radius:
            continue

        circle = Circle(center, radius)
        color = image.getPixel(int(center.x), int(H - center.y))
        circle.setFill(color_rgb(color[0], color[1], color[2]))
        circle.draw(win)
        # Add circle to quadtree
        spindex.insert(circle, get_bbox(center, radius))

    print('Done.')
    win.getMouse()
    win.close()
Exemple #4
0
def algorithm(input, grid_size, d_max, k_min):
    d_max = d_max / grid_size
    # insert the dot_list into a quadtree
    file = open(input, "r")
    nr_data_point = int(next(file))
    quad_tree = create_quadtree(file)
    output_quadtree = Index(bbox=(0, 0, 1, 1))

    #determine k
    counter = 0
    for y in range(grid_size):
        for x in range(grid_size):
            current_cell = (x / grid_size, y / grid_size, (x + 1) / grid_size,
                            (y + 1) / grid_size)
            intersection = quad_tree.intersect(current_cell)
            if len(intersection) >= k_min * int(nr_data_point /
                                                (grid_size * grid_size)):
                counter += 1
    k = int((nr_data_point / counter) * 0.9)

    # loop through the grid
    for y in range(grid_size):
        for x in range(grid_size):
            # make the rectangle to find dots in
            current_cell = (max(x / grid_size - d_max,
                                0), max(y / grid_size - d_max, 0),
                            min((x + 1) / grid_size + d_max,
                                1), min((y + 1) / grid_size + d_max, 1))
            # intersect on this rectangle
            intersection = quad_tree.intersect(current_cell)

            # count the number of each label in the intersection
            label_count = {}
            for dot in intersection:
                if dot.label in label_count:
                    label_count[dot.label] += 1
                else:
                    label_count[dot.label] = 1

            # find the lowest frequency label that can be made into a new dot
            while len(label_count) > 0:
                min_label = min(label_count, key=label_count.get)
                # if we can make it into a new dot we remove the labels and enter a new one
                if label_count[min_label] >= k_min * k:
                    cell_center = Dot(
                        min_label,
                        bbox=((x / grid_size + (x + 1) / grid_size) / 2,
                              (y / grid_size + (y + 1) / grid_size) / 2,
                              (x / grid_size + (x + 1) / grid_size) / 2,
                              (y / grid_size + (y + 1) / grid_size) / 2))
                    output_quadtree.insert(cell_center, cell_center.bbox)
                    # now remove the dots that it intersected with going by minimum distance up to k
                    if label_count[min_label] >= k:
                        sorted_distance_list = sorted_distance(
                            intersection, cell_center, k, min_label)
                        for dot in sorted_distance_list:
                            quad_tree.remove(dot, dot.bbox)
                    else:
                        for dot in intersection:
                            if (dot.label == min_label):
                                quad_tree.remove(dot, dot.bbox)
                    break
                else:
                    # if there werent enough labels of a color remove them from the dict.
                    del label_count[min_label]

    # write the output to file
    create_output(output_quadtree, k, grid_size)
Exemple #5
0
import csv
from pyqtree import Index
from pcpoint import PostCodePoint

pcFile = "postcodes.csv"

# Latitudes: 54.596553 to 54.603728
# Longitudes: -5.937032 to -5.922495
pcBounds = (54.596552, -5.937033, 54.603729, -5.922494)

pcIndex = Index(bbox=pcBounds)

with open(pcFile) as csvfile:
    pcReader = csv.DictReader(csvfile)

    print "populating qtree"

    for row in pcReader:
        postcode = PostCodePoint(row['Postcode'])
        lat = row['Latitude']
        lon = row['Longitude']

        pcIndex.insert(postcode, (lat, lon, lat, lon))

    print "qtree populated"
    print "attempt delaunay?"
Exemple #6
0
 def __init__(self):
     self.index = Index(bbox=self.bbox, max_items=40, max_depth=15)
class Item(Player):
    state: int = -1  # -1 intangible, 0 container unopened, 1 container opened
    sound: str = 'default_sound'
    contains: str = 'default_nothing'


class Resource:
    full_path: str = ''
    stream: None
    data: None


zone_map = {}
for i in zone_names:
    zone_map[i] = Zone(Index(bbox=(-1024, -1024, 1024, 1024)))
    zone_map[i].name = i

player = Player('Steve')
# static center of player square
player.center_x = 4 * 64
player.center_y = 4 * 64
# center of all the squares aka 0,0
player.x = zone_width // 2
player.y = zone_height // 2
player.width = sprite_width
player.height = sprite_height
# handlers for player movement
player.x_vel = 0
player.y_vel = 0
Exemple #8
0
 def __init__(self):
     self.trips = {}
     self.stops = {}
     self.maxFreq = 0
     self.stops_by_name = {}
     self.spindex = Index(bbox=(331792, 4317252, 586592, 4540683))