def compute_intersection_demo(): """ calculating area of polygon inside region :return: """ print("compute_intersection_demo") # http://toblerity.org/shapely/manual.html a = Point(1, 1).buffer(1.5) b = Point(2, 1).buffer(1.5) c = a.intersection(b) print("intersect area (circles): ", c.area) # http://toblerity.org/shapely/manual.html#polygons a = Polygon([(0, 0), (1, 1), (1, 0)]) b = Polygon([(0.5, 0.5), (1.5, 1.5), (1.5, 0.5)]) c = a.intersection(b) print("intersect area (polygons): ", c.area) # poly = Polygon(list(zip(X[0], Y[0]))) # a = box(0, 0, 3, 3) # patch b = Polygon([(0, 0), (0, 2), (2, 2), (2, 0)]) # roi c = Polygon([(0.5, 0.5), (1.0, 1.0), (1.5, 0.5), (1.0, 0.0)]) # polygon d = c.intersection(b) print("poly area", c.area) print("intersect area (poly, roi): ", d.area) # WITHIN: # object's boundary and interior intersect only with the interior of the other # (not its boundary or exterior) print("poly within roi: ", c.within(b)) # CROSSES: # interior of the object intersects the interior of the other but does not contain it... print("poly crosses roi: ", c.crosses(b)) # DISJOINT: boundary and interior of the object do not intersect at all print("poly does not intersect roi: ", c.disjoint(b))
def calcRatio(p1, p2, p3): A1 = Point((p1['x'], p1['y'])).buffer(p1['r']) A2 = Point((p2['x'], p2['y'])).buffer(p2['r']) A3 = Point((p3['x'], p3['y'])).buffer(p3['r']) ratio = (A1.intersection(A2).area + A1.intersection(A3).area + A2.intersection(A3).area) / ( A1.intersection(A2).intersection(A3).area + 1) return ratio
def find_zero(): b = 1; a = 0.99; ra = sqrt(a/pi) rb = sqrt(b/pi) circleB = Point((0,0)).buffer(rb) circleA = Point((0,ra+rb)).buffer(rb) print(circleB.area) print(circleA.area) print("b-g(x,y)",circleB.area - circleB.intersection(circleA).area) print("area of a:",a) print("m: ",ceil(a/(circleB.intersection(circleA).area))) print("lowerbound: ",a/(a+b))
def testIntervalRange(): #the interval is [a, b] a = 100 b = 400 xarea = (a+b)/2 ra = sqrt(a/pi) rb = sqrt(b/pi) rx = sqrt(xarea/pi) #data collection delta = 0.1 tmax = int((rx+rb+2)/delta) dist = [i*delta for i in range(tmax)] L = [0 for i in range(tmax)] S = [0 for i in range(tmax)] M = [0 for i in range(tmax)] E = [0 for i in range(tmax)] E2 = [0 for i in range(tmax)] E3 = [0 for i in range(tmax)] for i in range(tmax): P = Point(0,0).buffer(rx) PMi = Point(dist[i],0).buffer(rx) PUp = Point(dist[i],0).buffer(rb) PLo = Point(dist[i],0).buffer(ra) """ L[i] = P.area - P.intersection(PUp).area S[i] = P.area - P.intersection(PLo).area M[i] = P.area - P.intersection(PMi).area """ L[i] = P.intersection(PUp).area S[i] = P.intersection(PLo).area M[i] = P.intersection(PMi).area E[i] =(3/5)*P.intersection(PUp).area E2[i] =3*P.intersection(PLo).area E3[i] = crappyg(dist[i],P.area,a,b) plt.plot(dist,L) plt.plot(dist,S) plt.plot(dist,M) plt.plot(dist,E3) plt.xlabel(r"$d(x_i,x_j)$") plt.ylabel(r"$f(x_i) - f(x_i|x_j)$") plt.legend([r'$f(x_i) - f(x_i|x_j)$ where $f(x_j) = b$',r'$f(x_i) - f(x_i|x_j)$ where $f(x_j) = a$',r'$f(x_i) - f(x_i|x_j)$ where $f(x_j) = f(x_i)$',r"Experimentally found $g$"]) plt.title(r"$f(x_i) - f(x_i|x_j)$ VS Distance") plt.show()
def exit_points_to_polys(exit_gates, boundary, buffer): """convert numpy array of gate centroids to list of circle polygons Parameters -------- exit_gates : array_like `exit_gates` numpy array containting the central point of each (semi-)circular exit gate. boundary : polygon `boundary` of the stationsim corridor. buffer : float `buffer` radius of the exit polygon circles. usually 1. Returns ------- exit_polys : list `exit_polys` list of polygons representings the the exit gates """ exit_polys = [] for i in range(exit_gates.shape[0]): exit_poly = Point(exit_gates[i, :]).buffer(buffer) exit_poly = exit_poly.intersection(boundary) exit_polys.append(exit_poly) return exit_polys
def add_edge(self, nodes, point, time_nodes): distances = [] time_node = [] for node in nodes: p1 = Point(node[0], node[1]) p2 = Point(point[0], point[1]) # if not self.close_obstacle(nodes[i], point) and self.is_timed_free(time_nodes[i], point): distances.append(p1.distance(p2)) # else: # distances.append(float("inf")) idx = np.argmin(distances) node = nodes[idx] t_node = time_nodes[idx] line = LineString([tuple(node), tuple(point)]) circle = Point(node[0], node[1]).buffer(self.step) inter = circle.intersection(line) if inter: inter = list(inter.coords) inter = list(inter[1]) inter[0] = round(inter[0], 1) inter[1] = round(inter[1], 1) else: inter = point p1 = Point(inter[0], inter[1]) p2 = Point(node[0], node[1]) dist = p1.distance(p2) edge = [inter, node] time_node.append(inter) time_node.append(round(dist / self.v + t_node[1], 2)) return edge, inter, time_node
def update_after_explosion(self, explosion_point, explosion_radius): left_ground = [] explosion_circle = Point(explosion_point).buffer( explosion_radius).boundary max_left = max(0, explosion_point[0] - explosion_radius) max_right = min(display_width, explosion_point[0] + explosion_radius) for i in range(max_left, max_right): ground_line = LineString([[i, display_height], self.points[i]]) intersection = explosion_circle.intersection(ground_line) if explosion_point[1] + explosion_radius > display_height: left_start = explosion_point[1] - explosion_radius if self.points[i][1] < left_start: left_ground.append([[i, left_start], [i, self.points[i][1]]]) self.points[i][1] = display_height else: self.points[i][1] = display_height elif isinstance(intersection, MultiPoint): first_point = intersection.geoms[0] second_point = intersection.geoms[1] fst_coordinate = i, min(int(first_point.coords[0][1]), int(second_point.coords[0][1])) snd_coordinate = i, max(int(first_point.coords[0][1]), int(second_point.coords[0][1])) left_length = fst_coordinate[1] - self.points[i][1] if left_length > 0: left_ground.append([[i, fst_coordinate[1]], [i, self.points[i][1]]]) self.points[i][1] = snd_coordinate[1] elif isinstance(intersection, Point): if not explosion_circle.contains(intersection): self.points[i][1] = int(intersection.coords[0][1]) return left_ground
def iou(params0, params1): row0, col0, rad0 = params0 row1, col1, rad1 = params1 shape0 = Point(row0, col0).buffer(rad0) shape1 = Point(row1, col1).buffer(rad1) return (shape0.intersection(shape1).area / shape0.union(shape1).area)
def get(self): radius = floatParser(request.args.get("radius", "")) x = floatParser(request.args.get("x", "")) y = floatParser(request.args.get("y", "")) res = True if radius <= 0: res = { "Error": "Invalid Input. Radius must be positive integer or float" }, 201 elif radius and x and y: circle = Point(x, y).buffer(radius) if circle.intersects(self.circle_default): intersection_area = circle.intersection( self.circle_default).area res = { "intersec": "yes", "ratio": intersection_area / (circle.area) } else: res = {"intersect": "no", "ratio": 0.0} else: res = { "Error": "Invalid Input. Make sure radius, x, y are integers or floats" }, 201 return res
def test_operations(self): point = Point(0.0, 0.0) # General geometry self.assertEqual(point.area, 0.0) self.assertEqual(point.length, 0.0) self.assertAlmostEqual(point.distance(Point(-1.0, -1.0)), 1.4142135623730951) # Topology operations # Envelope self.assertIsInstance(point.envelope, Point) # Intersection self.assertIsInstance(point.intersection(Point(-1, -1)), GeometryCollection) # Buffer self.assertIsInstance(point.buffer(10.0), Polygon) self.assertIsInstance(point.buffer(10.0, 32), Polygon) # Simplify p = loads('POLYGON ((120 120, 121 121, 122 122, 220 120, 180 199, ' '160 200, 140 199, 120 120))') expected = loads('POLYGON ((120 120, 140 199, 160 200, 180 199, ' '220 120, 120 120))') s = p.simplify(10.0, preserve_topology=False) self.assertTrue(s.equals_exact(expected, 0.001)) p = loads('POLYGON ((80 200, 240 200, 240 60, 80 60, 80 200),' '(120 120, 220 120, 180 199, 160 200, 140 199, 120 120))') expected = loads( 'POLYGON ((80 200, 240 200, 240 60, 80 60, 80 200),' '(120 120, 220 120, 180 199, 160 200, 140 199, 120 120))') s = p.simplify(10.0, preserve_topology=True) self.assertTrue(s.equals_exact(expected, 0.001)) # Convex Hull self.assertIsInstance(point.convex_hull, Point) # Differences self.assertIsInstance(point.difference(Point(-1, 1)), Point) self.assertIsInstance(point.symmetric_difference(Point(-1, 1)), MultiPoint) # Boundary self.assertIsInstance(point.boundary, GeometryCollection) # Union self.assertIsInstance(point.union(Point(-1, 1)), MultiPoint) self.assertIsInstance(point.representative_point(), Point) self.assertIsInstance(point.centroid, Point) # Relate self.assertEqual(point.relate(Point(-1, -1)), 'FF0FFF0F2')
def test_operations(self): point = Point(0.0, 0.0) # General geometry self.assertEqual(point.area, 0.0) self.assertEqual(point.length, 0.0) self.assertAlmostEqual(point.distance(Point(-1.0, -1.0)), 1.4142135623730951) # Topology operations # Envelope self.assertIsInstance(point.envelope, Point) # Intersection self.assertIsInstance(point.intersection(Point(-1, -1)), GeometryCollection) # Buffer self.assertIsInstance(point.buffer(10.0), Polygon) self.assertIsInstance(point.buffer(10.0, 32), Polygon) # Simplify p = loads('POLYGON ((120 120, 121 121, 122 122, 220 120, 180 199, ' '160 200, 140 199, 120 120))') expected = loads('POLYGON ((120 120, 140 199, 160 200, 180 199, ' '220 120, 120 120))') s = p.simplify(10.0, preserve_topology=False) self.assertTrue(s.equals_exact(expected, 0.001)) p = loads('POLYGON ((80 200, 240 200, 240 60, 80 60, 80 200),' '(120 120, 220 120, 180 199, 160 200, 140 199, 120 120))') expected = loads( 'POLYGON ((80 200, 240 200, 240 60, 80 60, 80 200),' '(120 120, 220 120, 180 199, 160 200, 140 199, 120 120))') s = p.simplify(10.0, preserve_topology=True) self.assertTrue(s.equals_exact(expected, 0.001)) # Convex Hull self.assertIsInstance(point.convex_hull, Point) # Differences self.assertIsInstance(point.difference(Point(-1, 1)), Point) self.assertIsInstance(point.symmetric_difference(Point(-1, 1)), MultiPoint) # Boundary self.assertIsInstance(point.boundary, GeometryCollection) # Union self.assertIsInstance(point.union(Point(-1, 1)), MultiPoint) self.assertIsInstance(point.representative_point(), Point) self.assertIsInstance(point.centroid, Point) # Relate self.assertEqual(point.relate(Point(-1, -1)), 'FF0FFF0F2')
def cl_int(c, l, f): circle = Point(c[0], c[1]).buffer(c[2]).boundary i = circle.intersection(LineString([(l[0][0], l[1][0]), (l[0][1], l[1][1])])) if i.geoms[0].coords[0][0] == f: res = list(i.geoms[1].coords[0]) else: res = list(i.geoms[0].coords[0]) if abs(res[0]) <= 0.01: res[0] = 0 if abs(res[1]) <= 0.01: res[1] = 0 return res
def is_free(self, coordinates): # check if in bounds if any(np.abs(coordinates) >= self.dimension_length): return False # check collision of robot with obstacles robot = Point(coordinates) if any([robot.intersection(obstacle) for obstacle in self.obstacles]): return False return True
def testLipshitz(): #sim = submodular_sim(None,dims=(100,100)) delta = 0.1 r1 = 1 r2 = 4 tmax = 50 dist = [i*delta for i in range(tmax)] data = [0 for i in range(tmax)] datalipshitzmax = [[0 for i in range(tmax)] for i in range(10)] datalipshitzmin = [[0 for i in range(tmax)] for i in range(10)] lower = [0 for i in range(tmax)] radii = lower = [0 for i in range(tmax)] for i in range(tmax): P1 = Point(0,0).buffer(r1) P2 = Point(dist[i],0).buffer(r1) data[i] = P1.area - P1.intersection(P2).area for j in range(2): rmax = sqrt(j*(dist[i])/pi + pow(r1,2)) -r1 rmin = sqrt(max([-j*(dist[i])/pi + pow(r1,2),0])) -r1 P3 = Point(dist[i],0).buffer(r1+rmax) P4 = Point(dist[i],0).buffer(r1+rmin) datalipshitzmax[j][i] = P1.area - P1.intersection(P3).area datalipshitzmin[j][i] = P1.area - P1.intersection(P4).area #lower[i] = P1.area - g2(dist[i])*P1.area #lower = [ g(delta*i) for i in reversed(range(100))] # upper = [h(delta*i) for i in reversed(range(100))] plt.plot(dist,data) #plt.plot(dist,lower) for i in range(10): plt.plot(dist,datalipshitzmax[i]) plt.plot(dist,datalipshitzmin[i]) plt.legend(['actual',"lipshitz"]) plt.xlabel(r"$d(x_i,x_j)$") plt.show()
def circleAndLineSegmentIntersection(pt1, pt2, center, radius): """ https://stackoverflow.com/a/30998492/750567 """ linePts = _getCoordinateList([pt1, pt2]) seg = SHLineString(linePts) cPt = convertToPoint(center) circle = SHPoint(cPt.x(), cPt.y()).buffer(radius).boundary SHintersection = circle.intersection(seg) if not isinstance(SHintersection, SHPoint): raise RuntimeError("Haven't debugged this yet") return Point(SHintersection.x, SHintersection.y)
def interm_point(self, sensor, relay): d_u, d_a = t_distances(sensor, relay) ox = LineString([(0, 0), (self.input.width, 0)]) oy = LineString([(0, 0), (self.input.height, 0)]) csx = Point(sensor.x, sensor.depth).buffer(d_u).boundary csy = Point(sensor.y, sensor.depth).buffer(d_u).boundary crx = Point(relay.x, relay.height).buffer(d_a).boundary cry = Point(relay.y, relay.height).buffer(d_a).boundary px = csx.intersection(ox) py = csy.intersection(oy) # print(px) try: tx = px.x except AttributeError: tx = px[0].x try: ty = py.x except AttributeError: ty = py[0].x return tx, ty
def c_int(c1, c2, f = False): circle_1 = Point(c1[0], c1[1]).buffer(c1[2]).boundary i = circle_1.intersection(Point(c2[0], c2[1]).buffer(c2[2]).boundary) if f: res = [list(i.geoms[0].coords[0]), list(i.geoms[1].coords[0])] if abs(res[0][0]) <= 0.01: res[0][0] = 0 if abs(res[0][1]) <= 0.01: res[0][1] = 0 if abs(res[1][0]) <= 0.01: res[1][0] = 0 if abs(res[1][1]) <= 0.01: res[1][1] = 0 return res if i.geoms[0].coords[0][0] <= i.geoms[1].coords[0][0]: res = list(i.geoms[0].coords[0]) else: res = list(i.geoms[1].coords[0]) if abs(res[0]) <= 0.01: res[0] = 0 if abs(res[1]) <= 0.01: res[1] = 0 return res
def identify_highest_point(location, radius): """ Identify the highest point inside the 5km buffer of given location. :param location: tuple(x, y) Location input by user, which is a xy coordinate pair in CRS of British National Grid :param radius: int or float The radius of buffer; use meter as unit :return x: float The x coordinate of the highest point in CRS of British National Grid. :return y: float The y coordinate of the highest point in CRS of British National Grid. :return local_elevation_array: shapely.geometry.polygon The elevation_array clipped by mask. :return out_transform: Information for mapping pixel coordinates in masked to another coordinate system. """ # Read elevation data and clip it with a 5km buffer whose central point is user's location elevation_data = rasterio.open(elevation_path) bf = Point(location).buffer(radius) elevation_bounds = elevation_data.bounds # Construct the polygon of the boundary of elevation map elevation_boundary = Polygon([(elevation_bounds[0], elevation_bounds[1]), (elevation_bounds[2], elevation_bounds[1]), (elevation_bounds[2], elevation_bounds[3]), (elevation_bounds[0], elevation_bounds[3])]) mask_polygon = bf.intersection( elevation_boundary) # Ensure the mask overlaps elevation map # Check if area of the mask exists', which means 5km buffer intersects with elevation map if mask_polygon.area != 0: local_elevation_array, out_transform = rasterio.mask.mask( dataset=elevation_data, shapes=[mask_polygon], crop=True, filled=False) # Find the max value and the location in elevation clipped by mask max_elevation = np.max(local_elevation_array) location = np.where(local_elevation_array == max_elevation) row_highest_point = location[1][0] col_highest_point = location[2][0] # Transform the row and col to xy coordinates in British National Grid x, y = rasterio.transform.xy(out_transform, row_highest_point, col_highest_point) return x, y, local_elevation_array, out_transform else: # If mask can't intersects elevation map, return none. return None
def broken_arc(w,h,ch,t): # (1-ca)r=w/2 # h=sa*r # ca= (1-t*t)/(1+t*t) # sa=2t/(2+t*t) # 2t*t/(1+t*t)h/2t*(1+t*t)=w/2 # th=w/2 # t=w/h/2 alpha=2*math.atan(w/h*0.5) r=h/math.sin(alpha) c1=Point(w/2-r,0).buffer(r) c2=Point(r-w/2,0).buffer(r) inter=c1.intersection(c2) cutrect=affine_transform(rectangle(2*w,2*h+ch),[1,0,0,1,0,-2*ch]) rect=affine_transform(rectangle(w,ch),[1,0,0,1,0,-ch*0.5]) arc=inter.union(rect) arc=arc.difference(cutrect) arc=arc.exterior.buffer(t) return arc
def close_obstacle(self, node, point): sm = Point(point[0], point[1]) goal = Point(self.goal[0], self.goal[1]) dis_sam = goal.distance(sm) if dis_sam > self.eps: return False line_p1_goal = LineString([tuple(node), tuple(point)]) circle = Point(node[0], node[1]).buffer(self.step) inter = circle.intersection(line_p1_goal) if inter: inter = list(inter.coords) inter = list(inter[1]) inter[0] = round(inter[0], 1) inter[1] = round(inter[1], 1) else: inter = point edge = [inter, node] if self.is_connectable(edge): return False return True
def g(dist, fx, U): P = Point(0, 0).buffer(sqrt(fx / pi)) Ph = Point(dist, 0).buffer(sqrt(U / pi)) return P.intersection(Ph).area
BLUE = '#6699cc' GRAY = '#999999' fig = pyplot.figure(1, figsize=SIZE, dpi=90) a = Point(1, 1).buffer(1.5) b = Point(2, 1).buffer(1.5) # 1 ax = fig.add_subplot(121) patch1 = PolygonPatch(a, fc=GRAY, ec=GRAY, alpha=0.2, zorder=1) ax.add_patch(patch1) patch2 = PolygonPatch(b, fc=GRAY, ec=GRAY, alpha=0.2, zorder=1) ax.add_patch(patch2) c = a.intersection(b) patchc = PolygonPatch(c, fc=BLUE, ec=BLUE, alpha=0.5, zorder=2) ax.add_patch(patchc) ax.set_title('a.intersection(b)') xrange = [-1, 4] yrange = [-1, 3] ax.set_xlim(*xrange) ax.set_xticks(range(*xrange) + [xrange[-1]]) ax.set_ylim(*yrange) ax.set_yticks(range(*yrange) + [yrange[-1]]) ax.set_aspect(1) #2 ax = fig.add_subplot(122)
# new ciclar partial cover, centered at fromNode of lastSeg temp_bf_shp = Point(lastSeg[-2]).buffer(v1_remain_dis) writeShp([temp_bf_shp], "buffer_v1.shp") # generate split line sl1 = SplitLine_mk2(lastSeg, lastSeg[0], coverage_distance, temp_bf_shp) # split line from prior split prior_radi = v1_sLines[-1].cuttingLine sl2 = SplitLine_mk2((lastSeg[0], list(prior_radi.coords)[1]), lastSeg[0], coverage_distance, temp_bf_shp) cutting_box_1, cutting_box_2 = cutting_box_mk2(sl1, sl2, temp_bf_shp) writeShp([cutting_box_1, cutting_box_2], "small_cuttingBox.shp") s_cutbox = [cutting_box_1, cutting_box_2] sector = temp_bf_shp.intersection(s_cutbox[0]) v1_remain_dis -= sl1.lineObj.length v1_esps.remove(v1_esps[0]) v1_sectors.append(sector) v1_sLines.append(sl1) # print "end of sub loop" # raw_input() if v1_remain_dis > 0: temp_bf_shp = Point(v1_overlap[0]).buffer(v1_remain_dis) sl1 = SplitLine_mk2(v1_overlap, v1_overlap[0], coverage_distance, temp_bf_shp) prior_radi = v1_sLines[-1].cuttingLine sl2 = SplitLine_mk2((v1_overlap[0], list(prior_radi.coords)[1]), v1_overlap[0], coverage_distance, temp_bf_shp) cutting_box_1, cutting_box_2 = cutting_box_mk2(sl1, sl2, temp_bf_shp) s_cutbox = [cutting_box_1, cutting_box_2] sector = temp_bf_shp.intersection(s_cutbox[0])
lines.boundary.boundary.is_empty ################################################################################ from shapely.geometry import LineString LineString([(0, 0), (1, 1)]).centroid.wkt ################################################################################ from shapely.geometry import Point a = Point(1, 1).buffer(1.5) b = Point(2, 1).buffer(1.5) a.difference(b).wkt ################################################################################ a = Point(1, 1).buffer(1.5) b = Point(2, 1).buffer(1.5) a.intersection(b).wkt ################################################################################ a = Point(1, 1).buffer(1.5) b = Point(2, 1).buffer(1.5) a.symmetric_difference(b).wkt ################################################################################ a = Point(1, 1).buffer(1.5) b = Point(2, 1).buffer(1.5) a.union(b).wkt ################################################################################ a.union(b).boundary.wkt a.boundary.union(b.boundary).wkt
def isAtGoalRegion(self, point): buffered_point = Point(point).buffer(self.obj_radius, self.resolution) intersection = buffered_point.intersection(self.goal_region) inGoal = intersection.area / buffered_point.area return inGoal >= 0.5
from shapely.geometry import LineString, MultiLineString, Point from pprint import pprint coords = [((0, 0), (1, 1)), ((-1, 0), (1, 0))] lines = MultiLineString(coords) lines.boundary lines.boundary.boundary lines.boundary.boundary.is_empty ############################################################################### LineString([(0, 0), (1, 1)]).centroid LineString([(0, 0), (1, 1)]).centroid.wkt ############################################################################### a = Point(1, 1).buffer(1.5) b = Point(2, 1).buffer(1.5) a.difference(b) ############################################################################### a = Point(1, 1).buffer(1.5) b = Point(2, 1).buffer(1.5) a.intersection(b) ############################################################################### a = Point(1, 1).buffer(1.5) b = Point(2, 1).buffer(1.5) a.symmetric_difference(b) ############################################################################### a = Point(1, 1).buffer(1.5) b = Point(2, 1).buffer(1.5) a.union(b) ############################################################################### a.union(b).boundary a.boundary.union(b.boundary)
def analyze_kicks(self): previous_owner = 0 for idx, row in self.cycles[self.cycles['Kick'].notnull()].iterrows(): try: self_pass = False kick = row['Kick'] for i in range(idx + 1, min(idx + 30, 5999)): next_kick = self.cycles.iloc[i]['Kick'] if type(next_kick) == dict: if next_kick['Side'] == kick['Side'] and next_kick[ 'Unum'] == kick['Unum']: logging.debug( 'Self pass detected at {}!'.format(idx)) self_pass = True break if not self_pass: logging.debug('Cycle {} {}'.format(idx + 1, kick)) current_owner = kick['Unum'] if kick['Side'] == 'Right': current_owner *= -1 next_owner = 0 target_cycle = 0 for i in range(idx + 1, min(idx + 150, 5999)): temp_owner = self.cycles.iloc[i]['Owner'] if temp_owner != 0 and temp_owner != current_owner: next_owner = temp_owner logging.debug( 'Change of possession at {} from {} to {}!'. format(i + 1, current_owner, next_owner)) target_cycle = i break if next_owner * current_owner < 0: # Checking for shoots goal_scored = False if current_owner > 0: # Left Player player_pos = (float(row['Left'][current_owner - 1]['PosX']), float(row['Left'][current_owner - 1]['PosY'])) logging.debug( 'Player left {} position is {}'.format( current_owner, player_pos)) ball_pos = ( float(self.cycles.iloc[idx]['Ball']['PosX']), float(self.cycles.iloc[idx]['Ball']['PosY'])) next_pos = ( ball_pos[0] + 16 * float( self.cycles.iloc[idx + 1]['Ball']['VelX']), ball_pos[1] + 16 * float( self.cycles.iloc[idx + 1]['Ball']['VelY'])) kick_projection = LineString([ball_pos, next_pos]) goal_line = LineString([(52.5, 7), (52.5, -7)]) inter = goal_line.intersection(kick_projection) if not inter.is_empty: logging.debug( 'Left correct shoot at: {}'.format(idx)) self.left_correct_shoot_count += 1 for goal in self.teams['Left']['Goals']: if goal['Cycle'] - idx < 30: goal_scored = True break if not goal_scored and math.fabs( next_owner ) == self.teams['Right']['Goalkeeper']: logging.debug( 'Right keeper save at:{}'.format(idx)) self.right_saves_count += 1 continue else: goal_line = LineString([(52.5, 11), (52.5, -11)]) inter = goal_line.intersection(kick_projection) if not inter.is_empty: logging.debug( 'Left wrong shoot at: {}'.format(idx)) self.left_wrong_shoot_count += 1 continue if type(row['Tackle']) == float: self.left_wrong_pass_count += 1 player_pos = (float(row['Left'][current_owner - 1]['PosX']), float(row['Left'][current_owner - 1]['PosY'])) target_pos = ( float(self.cycles.iloc[target_cycle] ['Right'][-next_owner - 1]['PosX']), float(self.cycles.iloc[target_cycle] ['Right'][-next_owner - 1]['PosY'])) self.left_wrong_pass_pos.append( (player_pos, target_pos)) logging.debug( 'Wrong left pass at {}'.format(idx)) continue else: # Right Player player_pos = (float(row['Right'][-current_owner - 1]['PosX']), float(row['Right'][-current_owner - 1]['PosY'])) logging.debug( 'Player right {} position is {}'.format( current_owner, player_pos)) ball_pos = ( float(self.cycles.iloc[idx]['Ball']['PosX']), float(self.cycles.iloc[idx]['Ball']['PosY'])) next_pos = ( ball_pos[0] + 16 * float( self.cycles.iloc[idx + 1]['Ball']['VelX']), ball_pos[1] + 16 * float( self.cycles.iloc[idx + 1]['Ball']['VelY'])) kick_projection = LineString([ball_pos, next_pos]) goal_line = LineString([(-52.5, 7), (-52.5, -7)]) inter = goal_line.intersection(kick_projection) if not inter.is_empty: logging.debug( 'Right correct shoot at: {}'.format(idx)) for goal in self.teams['Right']['Goals']: if goal['Cycle'] - idx < 30: goal_scored = True break if not goal_scored and math.fabs( next_owner ) == self.teams['Left']['Goalkeeper']: logging.debug( 'Left keeper save at:{}'.format(idx)) self.left_saves_count += 1 continue else: goal_line = LineString([(-52.5, 11), (-52.5, -11)]) inter = goal_line.intersection(kick_projection) if not inter.is_empty: logging.debug( 'Right wrong shoot at: {}'.format(idx)) self.right_wrong_shoot_count += 1 continue if type(row['Tackle']) == float: self.right_wrong_pass_count += 1 player_pos = (float( row['Right'][-current_owner - 1]['PosX']), float( row['Right'][-current_owner - 1]['PosY'])) target_pos = ( float(self.cycles.iloc[target_cycle] ['Left'][next_owner - 1]['PosX']), float(self.cycles.iloc[target_cycle] ['Left'][next_owner - 1]['PosY'])) self.right_wrong_pass_pos.append( (player_pos, target_pos)) logging.debug( 'Right wrong pass at {}'.format(idx)) continue elif next_owner * current_owner > 0: # Checking for passes if current_owner > 0: # Left Player player_pos = (float(row['Left'][current_owner - 1]['PosX']), float(row['Left'][current_owner - 1]['PosY'])) logging.debug( 'Player left {} position is {}'.format( current_owner, player_pos)) target_pos = (float(self.cycles.iloc[target_cycle] ['Left'][next_owner - 1]['PosX']), float(self.cycles.iloc[target_cycle] ['Left'][next_owner - 1]['PosY'])) logging.debug( 'Target position is {}.'.format(target_pos)) target_circle = Point(target_pos).buffer( 2.5).boundary ball_pos = ( float(self.cycles.iloc[idx]['Ball']['PosX']), float(self.cycles.iloc[idx]['Ball']['PosY'])) next_pos = ( ball_pos[0] + 12 * float( self.cycles.iloc[idx + 1]['Ball']['VelX']), ball_pos[1] + 12 * float( self.cycles.iloc[idx + 1]['Ball']['VelY'])) kick_projection = LineString([ball_pos, next_pos]) logging.debug("Next pos is {}".format(next_pos)) inter = target_circle.intersection(kick_projection) if not inter.is_empty: logging.debug( 'Left correct pass at: {}'.format(idx)) self.left_complete_pass_count += 1 self.left_correct_pass_pos.append( (player_pos, target_pos)) continue else: logging.debug('Anomaly at {}'.format(idx)) continue else: # Right Player player_pos = (float(row['Right'][-current_owner - 1]['PosX']), float(row['Right'][-current_owner - 1]['PosY'])) # print(kick_projection) logging.debug( 'Player right {} position is {}'.format( current_owner, player_pos)) target_pos = (float(self.cycles.iloc[target_cycle] ['Right'][-next_owner - 1]['PosX']), float(self.cycles.iloc[target_cycle] ['Right'][-next_owner - 1]['PosY'])) logging.debug( 'Target position is {}.'.format(target_pos)) target_circle = Point(target_pos).buffer( 2.5).boundary ball_pos = ( float(self.cycles.iloc[idx]['Ball']['PosX']), float(self.cycles.iloc[idx]['Ball']['PosY'])) next_pos = ( ball_pos[0] + 12 * float( self.cycles.iloc[idx + 1]['Ball']['VelX']), ball_pos[1] + 12 * float( self.cycles.iloc[idx + 1]['Ball']['VelY'])) kick_projection = LineString([ball_pos, next_pos]) logging.debug("Next pos is {}".format(next_pos)) inter = target_circle.intersection(kick_projection) if not inter.is_empty: logging.debug( 'Right correct pass at: {}'.format(idx)) self.right_complete_pass_count += 1 self.right_correct_pass_pos.append( (player_pos, target_pos)) continue else: logging.debug('Anomaly at {}'.format(idx)) continue except TypeError: continue logging.debug( 'Left complete passes count is {} and wrong passes count is {}'. format(self.left_complete_pass_count, self.left_wrong_pass_count)) logging.debug( 'Right complete passes count is {} and wrong passes count is {}'. format(self.right_complete_pass_count, self.right_wrong_pass_count)) logging.debug( 'Left correct shoot count is {} and wrong shoot count is {}'. format(self.left_correct_shoot_count, self.left_wrong_shoot_count)) logging.debug( 'Right correct shoot count is {} and wrong shoot count is {}'. format(self.right_correct_shoot_count, self.right_wrong_shoot_count)) logging.debug('Left saves are {} and right saves are {}'.format( self.left_saves_count, self.right_saves_count)) return
from numpy import sqrt from shapely.geometry import Point, LineString, LinearRing pt = Point(0,0) print 'pt', pt print 'pt type', pt.geom_type print 'pt coordinate:', pt.coords[:][0] #line = LineString([(0,1),(-1,0)]) line = LineString([(-1,-1),(1,1)]) print 'line', line print 'line type', line.geom_type print 'line coordinates:', line.coords[:] print 'line length:', line.length, '== sqrt(2)*2', line.length==sqrt(2)*2 print '' d = pt.distance(line) print 'distance:', d ipt = pt.intersection(line) print 'ipt type', ipt.geom_type print ipt print '' lr = LinearRing(line.coords[:]+pt.coords[:]) print 'is_ccw', lr.is_ccw
# -*- coding: utf-8 -*- import os from shapely.geometry import Point, LineString, LinearRing, Polygon, MultiLineString coords = [((0,0),(1,1)),((-1,0),(1,0))] lines = MultiLineString(coords) lines.boundary print(list(lines.boundary)) lines.boundary.boundary.is_empty LineString([(0,0),(1,1)]).centroid LineString([(0,0),(1,1)]).centroid.wkt a = Point(1,1).buffer(1.5) b = Point(2,1).buffer(1.5) a.difference(b) a.intersection(b) a.symmetric_difference(b) a.union(b) a.union(b).boundary a.boundary.union(b.boundary) def Test(): assert True
def Intersect(Rx, Ry, Rbuffer): xpoly = Point(Rx, Ry).buffer(Rbuffer) IntersectPoly = xpoly.intersection(po) return IntersectPoly
writeShp([temp_bf_shp], 'buffer_v1.shp') #generate split line sl1 = SplitLine_mk2(lastSeg, lastSeg[0], coverage_distance, temp_bf_shp) #split line from prior split prior_radi = v1_sLines[-1].cuttingLine sl2 = SplitLine_mk2((lastSeg[0], list(prior_radi.coords)[1]), lastSeg[0], coverage_distance, temp_bf_shp) cutting_box_1, cutting_box_2 = cutting_box_mk2(sl1, sl2, temp_bf_shp) writeShp([cutting_box_1, cutting_box_2], 'small_cuttingBox.shp') s_cutbox = [cutting_box_1, cutting_box_2] sector = temp_bf_shp.intersection(s_cutbox[0]) v1_remain_dis -= sl1.lineObj.length v1_esps.remove(v1_esps[0]) v1_sectors.append(sector) v1_sLines.append(sl1) #print "end of sub loop" #raw_input() if v1_remain_dis > 0: temp_bf_shp = Point(v1_overlap[0]).buffer(v1_remain_dis) sl1 = SplitLine_mk2(v1_overlap, v1_overlap[0], coverage_distance, temp_bf_shp) prior_radi = v1_sLines[-1].cuttingLine sl2 = SplitLine_mk2((v1_overlap[0], list(prior_radi.coords)[1]), v1_overlap[0], coverage_distance, temp_bf_shp) cutting_box_1, cutting_box_2 = cutting_box_mk2(sl1, sl2, temp_bf_shp)
def crappyg(dist, fx, a, b): P = Point(0, 0).buffer(sqrt(fx / pi)) d = (sqrt(fx / pi) + sqrt(a / pi)) * (dist / (1 + sqrt(fx / pi) + sqrt(b / pi))) Pg = Point(d, 0).buffer(sqrt(a / pi)) return (fx / a) * P.intersection(Pg).area
def read_bro(parameters): """Main function to read the BRO database. :param parameters: Dict of input `parameters` containing filename, location and radius. :type parameters: dict :return: Dict with multiple groupings of parsed CPTs as dicts :rtype: dict """ fn = parameters["BRO_data"] ifn = splitext(fn)[0] + ".idx" # index x, y = parameters["Source_x"], parameters["Source_y"] r = parameters["Radius"] out = {} if not exists(fn): print("Cannot open provided BRO data file: {}".format(fn)) sys.exit(2) # Check and use or create index # we use the size of the several GB xml file as a validity check # which we've saved in the index datasize = stat(fn).st_size if exists(ifn): with open(ifn, "rb") as f: (size, bro_index) = pickle.load(f) if size != datasize: logging.warning( "BRO datafile differs from index, recreating index.") bro_index = create_index(fn, ifn, datasize) else: bro_index = create_index(fn, ifn, datasize) # Polygon grouping method: # Find all geomorphological polygons intersecting the circle with midpoint # x, y and radius r, calculate percentage of overlap and retrieve all CPTs # inside those polygons. out["polygons"] = {} total_cpts = 0 file_idx = join(dirname(fn), 'geomorph') idx_fn = join(dirname(fn), 'geomorph.idx') if not exists(idx_fn): print( "Cannot open provided geomorphological data files (.dat & .idx): {}" .format(idx_fn)) sys.exit(2) gm_index = index.Index( file_idx) # created by auxiliary_code/gen_geomorph_idx.py geomorphs = list( gm_index.intersection((x - r, y - r, x + r, y + r), objects="raw")) circle = Point(x, y).buffer(r, resolution=32) for gm_code, polygon in geomorphs: indices = query_index_polygon(bro_index, polygon) poly = shape(polygon) if not poly.is_valid: poly = poly.buffer( 0.01 ) # buffering reconstructs the geometry, often fixing invalidity if circle.intersects(poly): total_cpts += len(indices) perc = circle.intersection(poly).area / circle.area cpts = read_bro_xml(fn, indices) if gm_code in out["polygons"]: out["polygons"][gm_code]["data"].extend(cpts) else: out["polygons"][gm_code] = {"data": cpts, "perc": perc} logging.warning( "Found {} CPTs in intersecting polygons.".format(total_cpts)) # Find CPT indexes in circle indices = query_index(bro_index, x, y, radius=r) logging.warning("Found {} CPTs in circle.".format(len(indices))) circle_cpts = read_bro_xml(fn, indices) out["circle"] = {"data": circle_cpts} return out
def h(dist, fx, l): P = Point(0, 0).buffer(sqrt(fx / pi)) Pg = Point(dist, 0).buffer(sqrt(l / pi)) return P.intersection(Pg).area