本文整理汇总了Python中shapely.geometry.LineString.intersection方法的典型用法代码示例。如果您正苦于以下问题:Python LineString.intersection方法的具体用法?Python LineString.intersection怎么用?Python LineString.intersection使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类shapely.geometry.LineString
的用法示例。
在下文中一共展示了LineString.intersection方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: move_ball
# 需要导入模块: from shapely.geometry import LineString [as 别名]
# 或者: from shapely.geometry.LineString import intersection [as 别名]
def move_ball(self):
"""
Move the ball in game state
it calculates boundaries and it clips
the ball positioning when it is overlapping
with walls or paddles
return rewards when right player makes contact with the ball
and when ball leaves the game screen on the left side
"""
reward = 0.0
# get ball trajectory
prev_x, prev_y = self.ballx, self.bally
next_x, next_y = self.ballx + self.ball_speed_x, self.bally + self.ball_speed_y
ball_trajectory = LineString([(prev_x, prev_y), (next_x, next_y)])
# get possible collision lines
upper_wall = LineString([(0, 0),
(SCREEN_WIDTH, 0)])
bottom_wall = LineString([(0, SCREEN_HEIGHT - BALL_SIZE),
(SCREEN_WIDTH, SCREEN_HEIGHT - BALL_SIZE)])
left_paddle = LineString([(self.cpux + PADDLE_WIDTH, self.cpuy - BALL_SIZE),
(self.cpux + PADDLE_WIDTH, self.cpuy + PADDLE_HEIGHT)])
right_paddle = LineString([(self.playerx - BALL_SIZE, self.playery - BALL_SIZE),
(self.playerx - BALL_SIZE, self.playery + PADDLE_HEIGHT)])
# chop ball trajectory when colliding
if ball_trajectory.intersects(upper_wall):
self.ball_speed_y *= -1
upper = ball_trajectory.intersection(upper_wall)
self.ballx, self.bally = upper.x, upper.y + 1
elif ball_trajectory.intersects(bottom_wall):
self.ball_speed_y *= -1
bottom = ball_trajectory.intersection(bottom_wall)
self.ballx, self.bally = bottom.x, bottom.y - 1
elif ball_trajectory.intersects(left_paddle):
left = ball_trajectory.intersection(left_paddle)
contact_point = left.y - left_paddle.xy[1][0]
if contact_point < PADDLE_UPPER_SECTION or \
contact_point > PADDLE_BOTTOM_SECTION:
self.flip_and_spin_ball()
else:
self.flip_and_speed_ball()
self.ballx, self.bally = left.x + 1, left.y
elif ball_trajectory.intersects(right_paddle):
reward += 0.1
right = ball_trajectory.intersection(right_paddle)
contact_point = right.y - right_paddle.xy[1][0]
if contact_point < PADDLE_UPPER_SECTION or \
contact_point > PADDLE_BOTTOM_SECTION:
self.flip_and_spin_ball()
else:
self.flip_and_speed_ball()
self.ballx, self.bally = right.x - 1, right.y
else:
self.ballx += self.ball_speed_x
self.bally += self.ball_speed_y
return reward
示例2: removeCollisiononOnedCurves
# 需要导入模块: from shapely.geometry import LineString [as 别名]
# 或者: from shapely.geometry.LineString import intersection [as 别名]
def removeCollisiononOnedCurves(self, onedcurvedict, polygonxoncurvedict, collidingPolygondict):
"""
remove the nodes that collide with collidinPolygondict
:param onedcurvedict: the curve for collision test
:param polygonxoncurvedict: the curvedict to be updated
:param collidingPolygondict: the polygon for collision detection
:return: an updated oned curve dict
author: weiwei
date: 20170512
"""
newonedcurvedict = {}
newpolygonxoncurvedict = {}
maxkey = max(onedcurvedict.keys())
minkey = min(onedcurvedict.keys())
for key, point in onedcurvedict.iteritems():
newonedcurvedict[key] = [self.minusinf, self.minusinf, key]
newpolygonxoncurvedict[key] = None
polygonx = collidingPolygondict[key]
if not polygonx.contains(Point(point[0], point[1])):
newonedcurvedict[key] = point
newpolygonxoncurvedict[key] = polygonxoncurvedict[key]
elif polygonx.exterior.contains(Point(point[0], point[1])):
newonedcurvedict[key] = point
newpolygonxoncurvedict[key] = polygonxoncurvedict[key]
else:
# check jumps
pkey = key - self.steplength
nkey = key + self.steplength
if nkey <= maxkey:
npoint = onedcurvedict[nkey]
if npoint[0] > self.minusinf+1:
if not polygonx.contains(Point(npoint[0], npoint[1])):
pathseg = LineString([(point[0], point[1]), (npoint[0], npoint[1])])
cobsintersections = pathseg.intersection(polygonx.boundary)
if cobsintersections.geom_type == "Point":
newonedcurvedict[key] = [cobsintersections.x, cobsintersections.y, point[2]]
newpolygonxoncurvedict[key] = polygonxoncurvedict[key]
continue
if pkey >= minkey:
ppoint = onedcurvedict[pkey]
if ppoint[0] > self.minusinf+1:
if not polygonx.contains(Point(ppoint[0], ppoint[1])):
pathseg = LineString([(point[0], point[1]), (ppoint[0], ppoint[1])])
cobsintersections = pathseg.intersection(polygonx.boundary)
if cobsintersections.geom_type == "Point":
newonedcurvedict[key] = [cobsintersections.x, cobsintersections.y, point[2]]
newpolygonxoncurvedict[key] = polygonxoncurvedict[key]
continue
return [newonedcurvedict, newpolygonxoncurvedict]
示例3: test_line_line
# 需要导入模块: from shapely.geometry import LineString [as 别名]
# 或者: from shapely.geometry.LineString import intersection [as 别名]
def test_line_line():
'''
intersection between line and line
'''
#-------------------------------------------------
# intersection
#-------------------------------------------------
line1 = LineString([(0,0), (1,1)])
line2 = LineString([(1,0), (0,1)])
ist = line1.intersection(line2)
equal(ist.geom_type, 'Point')
a_equal([0.5,0.5], np.array(ist.coords)[0])
#-------------------------------------------------
# parallel
# line intersection
#-------------------------------------------------
line1 = LineString([(0,0), (1,1)])
line2 = LineString([(-1,-1), (0.5,0.5)])
ist = line1.intersection(line2)
equal(ist.geom_type, 'LineString')
a_equal([(0,0),(0.5,0.5)], np.array(ist.coords))
#-------------------------------------------------
# parallel
# not intersection
#-------------------------------------------------
line1 = LineString([(0,0), (1,1)])
line2 = LineString([(0,-1), (1,0)])
ist = line1.intersection(line2)
equal(True, ist.is_empty)
#-------------------------------------------------
# not intersection
#-------------------------------------------------
line1 = LineString([(0,0), (1,1)])
line2 = LineString([(3,0), (0,3)])
ist = line1.intersection(line2)
equal(True, ist.is_empty)
示例4: test_line_intersection
# 需要导入模块: from shapely.geometry import LineString [as 别名]
# 或者: from shapely.geometry.LineString import intersection [as 别名]
def test_line_intersection(self):
line1 = LineString([(0, 0, 0), (1, 1, 1)])
line2 = LineString([(0, 1, 1), (1, 0, 0)])
interxn = line1.intersection(line2)
self.failUnless(interxn.has_z)
self.failUnless(interxn._ndim == 3)
self.failUnless(0.0 <= interxn.z <= 1.0)
示例5: _add_crossroads
# 需要导入模块: from shapely.geometry import LineString [as 别名]
# 或者: from shapely.geometry.LineString import intersection [as 别名]
def _add_crossroads(new_edges, current_edges):
new_new_edges = set()
new_current_edges = set()
split_current_edge = [False] * len(current_edges)
for new_edge in new_edges:
found_crossroad = False
for current_edge_index, current_edge in enumerate(current_edges):
if State._different_starts_and_ends(new_edge, current_edge):
new_line_segment = LineString([(new_edge[0].x, new_edge[0].y), (new_edge[1].x, new_edge[1].y)])
current_line_segment = LineString(([(current_edge[0].x, current_edge[0].y),
(current_edge[1].x, current_edge[1].y)]))
intersection = new_line_segment.intersection(current_line_segment)
if type(intersection) is ShapelyPoint:
new_crossroad = Point(intersection.x, intersection.y, Point.TYPE_CROSSROAD)
new_current_edges.update(State._split_edge(current_edge, new_crossroad))
new_new_edges.update(State._split_edge(new_edge, new_crossroad))
split_current_edge[current_edge_index] = True
found_crossroad = True
break
if not found_crossroad:
new_new_edges.add(new_edge)
for current_edge_index, current_edge in enumerate(current_edges):
if not split_current_edge[current_edge_index]:
new_current_edges.add(current_edge)
if set(current_edges) == new_current_edges and set(new_edges) == new_new_edges:
return list(current_edges) + list(new_edges)
else:
return State._add_crossroads(list(new_new_edges), list(new_current_edges))
示例6: test_line_intersection
# 需要导入模块: from shapely.geometry import LineString [as 别名]
# 或者: from shapely.geometry.LineString import intersection [as 别名]
def test_line_intersection(self):
line1 = LineString([(0, 0, 0), (1, 1, 1)])
line2 = LineString([(0, 1, 1), (1, 0, 0)])
interxn = line1.intersection(line2)
self.assertTrue(interxn.has_z)
self.assertEqual(interxn._ndim, 3)
self.assertTrue(0.0 <= interxn.z <= 1.0)
示例7: lines_fusion
# 需要导入模块: from shapely.geometry import LineString [as 别名]
# 或者: from shapely.geometry.LineString import intersection [as 别名]
def lines_fusion(line1, line2):
"""
Validate each line segment for intersection. Intersection is checked as
http://en.wikipedia.org/wiki/Line_segment_intersection
:param line1: main line
:param line2: line to be fused
:return same line1 if there is no intersections with line2. else fused lines.
"""
# TODO use bounding boxes to speed up
# Cross validation for each line segment in polylines.
for i in range(len(line1) - 1, 0, -1):
p1 = line1[i]
p2 = line1[i - 1]
# line segment
l1 = LineString([p1, p2])
for j in range(len(line2) - 1, 0, -1):
p3 = line2[j]
p4 = line2[j - 1]
l2 = LineString([p3, p4])
# Check Line intersection
intersection = l1.intersection(l2)
# if intersected
if not intersection.is_empty:
# take the line 1 from first point until the intersection and line2
inter_p = (intersection.coords.xy[0][0], intersection.coords.xy[1][0])
new_line = line2[:j] + [inter_p] + line1[i:]
return new_line
# no fusion
return line1
示例8: intersection
# 需要导入模块: from shapely.geometry import LineString [as 别名]
# 或者: from shapely.geometry.LineString import intersection [as 别名]
def intersection(lineA, lineB):
line1 = LineString(lineA)
line2 = LineString(lineB)
if line1.intersects(line2):
i = line1.intersection(line2)
return i
return -1
示例9: lineIntersection
# 需要导入模块: from shapely.geometry import LineString [as 别名]
# 或者: from shapely.geometry.LineString import intersection [as 别名]
def lineIntersection(l1, l2):
(s1, e1) = l1
(s2, e2) = l2
ls1 = LineString([s1, e1])
ls2 = LineString([s2, e2])
ret = ls1.intersection(ls2)
print 'lineIntersection(%s, %s) -> %s' % (ls1, ls2, ret)
return (ret.x, ret.y)
示例10: raster
# 需要导入模块: from shapely.geometry import LineString [as 别名]
# 或者: from shapely.geometry.LineString import intersection [as 别名]
def raster(fig, w, deg=45, s=None):
"""Creates parallel lines to fill the figure"""
# Angle to radians
ang = deg * pi / 180.0
# Contour separation
if s is None:
s = w
# Bounding box, get limits
xmin, ymin, xmax, ymax = fig.bounds
# Correct path trajectory
fig = fig.buffer(-w / 2.0)
# Initial parameters
if 90 > deg > 0: # Start from left bottom
x = xmin - (ymax - ymin) / abs(tan(ang))
y = ymin
incx = abs(w / sin(ang))
incy = 0
elif -90 < deg < 0: # Start from left top
x = xmin - (ymax - ymin) / abs(tan(ang))
y = ymax
incx = abs(w / sin(ang))
incy = 0
elif deg == 0:
x = xmin
y = ymin
incx = 0
incy = w
elif abs(deg) == 90:
x = xmin
y = ymin
incx = w
incy = 0
else: # Raise Exception
raise "Exception: wrong degree value [-90, 90]."
# Obtain intersections
cuts = list()
while x < xmax:
line = LineString(
((x, y), (xmax, xmax * tan(ang) + y - x * tan(ang)))
) # Equacio linia: y = x*tan(deg) + (yo - xo*tan(deg))
lines = line.intersection(fig.buffer(-s))
if not lines.is_empty:
if lines.type == "LineString":
cuts.append(lines)
elif lines.type == "MultiLineString":
for line in list(lines):
cuts.append(line)
x += incx
y += incy
if ang == 0 and y > ymax:
x = xmax + 1
return cuts
示例11: intersect
# 需要导入模块: from shapely.geometry import LineString [as 别名]
# 或者: from shapely.geometry.LineString import intersection [as 别名]
def intersect(self, **kwargs):
"""
Intersect a Line or Point Collection and the Shoreline
Returns the point of intersection along the coastline
Should also return a linestring buffer around the interseciton point
so we can calculate the direction to bounce a particle.
"""
ls = None
if "linestring" in kwargs:
ls = kwargs.pop('linestring')
spoint = Point(ls.coords[0])
epoint = Point(ls.coords[-1])
elif "start_point" and "end_point" in kwargs:
spoint = kwargs.pop('start_point')
epoint = kwargs.pop('end_point')
ls = LineString(list(spoint.coords) + list(epoint.coords))
else:
raise TypeError( "must provide a LineString geometry object or (2) Point geometry objects" )
inter = False
# If the current point lies outside of our current shapefile index,
# re-query the shapefile in a buffer around this point
if self._spatial_query_object and not ls.within(self._spatial_query_object):
self.index(point=spoint)
for element in self._geoms:
prepped_element = prep(element)
# Test if starting on land
if prepped_element.contains(spoint):
raise Exception('Starting point on land')
inter = ls.intersection(element)
if inter:
# Return the first point in the linestring, and the linestring that it hit
if isinstance(inter, MultiLineString):
inter = inter.geoms[0]
inter = Point(inter.coords[0])
smaller_int = inter.buffer(self._spatialbuffer)
shorelines = element.exterior.intersection(smaller_int)
if isinstance(shorelines, LineString):
shorelines = [shorelines]
else:
shorelines = list(shorelines)
for shore_segment in shorelines:
# Once we find the linestring in the Polygon that was
# intersected, break out and return
if ls.touches(shore_segment):
break
return {'point': Point(inter.x, inter.y, 0), 'feature': shore_segment or None}
return None
示例12: ray_casting
# 需要导入模块: from shapely.geometry import LineString [as 别名]
# 或者: from shapely.geometry.LineString import intersection [as 别名]
def ray_casting(pose_dict, m, direction, grid_idx=None):
'''Return the hit point at the nearest occupied grid along the ray direction'''
resolution = 1
theta_add = {
'n': 0.0 / 180.0 * math.pi,
'nw': -45. / 180.0 * math.pi,
'w': -90 / 180.0 * math.pi,
'sw': -(90 + 45.0) / 180.0 * math.pi,
's': math.pi ,
'se': (90 + 45.0) / 180.0 * math.pi,
'e': 90. / 180.0 * math.pi,
'ne': 45. / 180.0 * math.pi
}
#print direction
#print theta_add[direction]
pose = (pose_dict['x'], pose_dict['y'], pose_dict['theta'] + theta_add[direction])
#
assert is_valid(pose, m), 'init pose is invalid: on the occupied grid'
# from the current pose, get the tip of the (trial) ray
tip = get_tip(pose, m)
# Construct the ray
ray = LineString([(pose[0], pose[1]), (tip[0], tip[1])])
# Construct the enclosing grid
if grid_idx==None:
grid_idx = get_grid_idx(pose[0], pose[1])
#print 'grid_idx=', grid_idx
xmin = float(grid_idx[0])
xmax = float(grid_idx[0]) + resolution
ymin = float(grid_idx[1])
ymax = float(grid_idx[1]) + resolution
grid = box(xmin, ymin, xmax, ymax)
# Obtain the intersection points
hit_raw = ray.intersection(grid)
#print 'list(hit_raw.coords)=', list(hit_raw.coords)
hit = hit_raw.coords[1]# the first element is the ray origin
#print 'hit=', hit
#
adj_grid_idx = get_adj_grid_idx(hit, grid_idx, grid)
#print 'adj_grid_idx=', adj_grid_idx
if m[adj_grid_idx[1]][adj_grid_idx[0]] != 'W':
new_pose = {'x': hit[0], 'y': hit[1], 'theta': pose_dict['theta']}
hit = ray_casting(new_pose, m, direction, grid_idx= adj_grid_idx)
return hit
示例13: getClosestNodeFromIntersection
# 需要导入模块: from shapely.geometry import LineString [as 别名]
# 或者: from shapely.geometry.LineString import intersection [as 别名]
def getClosestNodeFromIntersection(querynodes, nIDs, nodes):
nIDs_ = []
if nIDs is None:
for key in nodes:
nIDs_.append(key)
else:
nIDs_ = nIDs
# create nodestrings
nodestring = []
for nID in querynodes:
nodestring.append(querynodes[nID])
profile = []
for nID in nIDs_:
profile.append(nodes[nID][0:2])
# extend nodestring at first and last point
dxa = nodestring[0][0] - nodestring[1][0]
dya = nodestring[0][1] - nodestring[1][1]
nodestring[0] = [nodestring[0][0] + dxa * 100.0, nodestring[0][1] + dya * 100.0]
dxe = nodestring[-1][0] - nodestring[-2][0]
dye = nodestring[-1][1] - nodestring[-2][1]
nodestring[-1] = [nodestring[-1][0] + dxe * 100.0, nodestring[-1][1] + dye * 100.0]
# find intersection from nodestring with profile
ns1 = LineString(nodestring)
ns2 = LineString(profile)
querynode = [ns1.intersection(ns2).x, ns1.intersection(ns2).y]
# find nearest node to intersection
distance = []
for nID in nIDs_:
b = nodes[nID][0:2]
distance.append(np.linalg.norm(np.subtract(b, querynode)))
closestnode = distance.index(min(distance))
return closestnode
示例14: get_pos_intersection
# 需要导入模块: from shapely.geometry import LineString [as 别名]
# 或者: from shapely.geometry.LineString import intersection [as 别名]
def get_pos_intersection(self, e1, e2):
"""
DEPRECATED: Calculates the intersection between two entities.
:param: element 1
:param: element 2
:return: intersection point with positive y value
"""
# Hack: extend the line to make sure there is an intersection point
extended_point = Point(e1.coords[1][0] + (e1.coords[1][0] - e1.coords[0][0]) / e1.length * e1.length**2,
e1.coords[1][1] + (e1.coords[1][1] - e1.coords[0][1]) / e1.length * e1.length**2)
e1 = LineString([Point(e1.coords[0][0], e1.coords[0][1]), extended_point])
intersection_point = e1.intersection(e2)
return intersection_point
示例15: traversal_endpoints
# 需要导入模块: from shapely.geometry import LineString [as 别名]
# 或者: from shapely.geometry.LineString import intersection [as 别名]
def traversal_endpoints(polygon, x, miny, maxy):
line = LineString([(x, miny - 1), (x, maxy + 1)])
intersection = line.intersection(polygon)
if isinstance(intersection, Point):
return intersection, intersection
else:
# TODO: better error handling
assert isinstance(intersection, LineString)
endpoints = intersection.boundary
return (min(endpoints, key=lambda point: point.y),
max(endpoints, key=lambda point: point.y))