def _write_boat_area(pier, stg_manager, coords_transform: co.Transformation): if len(pier.nodes) < 3: return # Guess a possible position for realistic boat placement linear_ring = shg.LinearRing(pier.nodes) centroid = linear_ring.centroid # Simplify ring = linear_ring.convex_hull.buffer( 40, cap_style=CAP_STYLE.square, join_style=JOIN_STYLE.bevel).simplify(20) for p in ring.exterior.coords: line_coords = [[centroid.x, centroid.y], p] target_vector = shg.LineString(line_coords) coords = linear_ring.coords for i in range(len(coords) - 1): segment = LineString(coords[i:i + 2]) if segment.length > 20 and segment.intersects(target_vector): direction = math.degrees( math.atan2(segment.coords[0][0] - segment.coords[1][0], segment.coords[0][1] - segment.coords[1][1])) parallel = segment.parallel_offset(10, 'right') boat_position = parallel.interpolate(segment.length / 2) try: pos_global = coords_transform.to_global( (boat_position.x, boat_position.y)) _write_model(segment.length, stg_manager, pos_global, direction, pier.elevation) except AttributeError as reason: logging.error(reason)
def split_way_1d_vertex(self, ways_1d, way, v): coord_idx = way.vertex_index(v) if coord_idx is None: logger.debug("Coordinates: %s", list(way.geom.coords)) raise ValueError("Coordinate not found (%s) to split a path (%s) by coordinates." % (v, way)) if coord_idx == 0 or coord_idx >= len(way.geom.coords) - 1: # raise ValueError("Cannot split a path (%s) by the first or last index (%s)." % (way, coord_idx)) return None, None # logger.debug("Splitting %s at %d (%s)", way, coord_idx, v) part1 = way.copy() part1.geom = LineString(way.geom.coords[:coord_idx + 1]) part1.extra['ddd:connections'] = [] part2 = way.copy() part2.geom = LineString(way.geom.coords[coord_idx:]) part2.extra['ddd:connections'] = [] ''' part1 = DDDObject2(name=way.name + "/1", geom=LineString(way.geom.coords[:coord_idx + 1]), extra=copy.deepcopy(way.extra)) part1.extra['ddd:connections'] = [] part2 = DDDObject2(name=way.name + "/2", geom=LineString(way.geom.coords[coord_idx:]), extra=copy.deepcopy(way.extra)) part2.extra['ddd:connections'] = [] ''' ways_1d.children.remove(way) ways_1d.children.extend([part1, part2]) return part1, part2
def findCrossingGroups(tickArray, bugStatus): ''' Identify crossing groups within the direct paths Args: tickArray: array with the starting and ending points Returns: crossingBugs: np.ndarray Collection of pairs of crossing bugs. ''' activeFilter = bugStatus != bugStatusDict[ 'NOT_PRESENT'] #NU EDITED ----->> TURNING OFF ACTIVE FILTER crossingBugs = [] for thisBugIdx, thisBug in zip( np.arange(tickArray.shape[0])[activeFilter], tickArray[activeFilter]): path1 = LineString(thisBug) for otherBugIdx, otherBug in zip( np.arange(tickArray.shape[0])[activeFilter], tickArray[activeFilter]): if thisBugIdx > otherBugIdx: path2 = LineString(otherBug) dist = path1.distance(path2) if dist < 2 * const.CORRIDOR_HALF_WIDTH: crossingBugs.append([thisBugIdx, otherBugIdx]) crossingBugs = np.array(crossingBugs) return crossingBugs
def testIsCcw(self): self.assertTrue(geom_util.IsCcw(LineString([ [0, 0], [1, 0], [0, 1]]))) self.assertFalse(geom_util.IsCcw(LineString([ [0, 0], [0, 1], [1, 0]])))
def CreatePath(start_config, engine, obstacles, max_walk, ideal=True): current_path = [] current_config = start_config walk_limit = max_walk if ideal: sample_func = engine.grid.GetDestinationLocationAndOrientation else: sample_func = engine.grid.SampleMovement while (walk_limit and not markov.CloseToGoalConst( current_config, engine.goal_config, engine.grid) and not obstacles.contains( Point(current_config[0][0], current_config[0][1])) and not markov.OutsideBoundaries(current_config)): walk_limit -= 1 steering_angle = engine.GetSteeringAngle(current_config) x, y, o = sample_func(current_config[0][0], current_config[0][1], current_config[1], steering_angle, engine.average_path_length) if geom_util.AngleAlmostEqual(steering_angle % ANGLE_MOD, 0.0): current_path.append(LineString([current_config[0], (x, y)])) ls = LineString([current_config[0], (x, y)]) if ls.crosses(obstacles): break else: radius = engine.vehicle_length / math.sin(steering_angle) antirangle = (math.pi / 2.0 - current_config[1]) % ANGLE_MOD dx = math.cos(antirangle) * radius dy = math.sin(antirangle) * radius circumrad = engine.average_path_length / abs(radius) if steering_angle > 0.0: direction = COUNTER_CLOCKWISE begin_radian = (current_config[1] - math.pi / 2.0) % ANGLE_MOD end_radian = (begin_radian + circumrad) % ANGLE_MOD else: direction = CLOCKWISE begin_radian = (current_config[1] + math.pi / 2.0) % ANGLE_MOD end_radian = (begin_radian - circumrad) % ANGLE_MOD current_path.append( Arc( (current_config[0][0] - dx, current_config[0][1] + dy), abs(radius), begin_radian, end_radian, direction, )) end_pos = current_path[-1].AngleToPoint(end_radian) current_path.append(LineString([end_pos, (x, y)])) current_config = ((x, y), o) state = SUCCESS if not markov.CloseToGoalConst(current_config, engine.goal_config, engine.grid): state = ICED if not walk_limit: state = TLE return current_path, state
def step_to(pt, node, screen): longls = LineString([(node.x, node.y),(pt.x, pt.y)]) ipt = longls.interpolate(30) ls = LineString([(ipt.x, ipt.y),(node.x, node.y)]) if collide_ln(ls) == False and lines_cross(ls,ipt,node,screen) == False and ls.length > 20: circle(screen, YELLOW, [int(ipt.x), int(ipt.y)], 3, 0) return ls, ipt, True else: return ls, ipt, False
def step_to(pt, node): longls = LineString([(node.x, node.y), (pt.x, pt.y)]) ipt = longls.interpolate(30) ls = LineString([(ipt.x, ipt.y), (node.x, node.y)]) if collide_ln(ls) == False and lines_cross( ls, ipt, node) == False and ls.length > 20: return ls, ipt, True else: return ls, ipt, False
def linestrings(draw, min_value=None, max_value=None, exclude_zero=None, num_verts=2, closed=False): """Strategy that generates shapely linestrings""" assert num_verts >= 2 elements = reals(min_value, max_value, exclude_zero, shape=(num_verts, 2)) array = draw(elements) if closed: return LineString(np.concatenate((array, array[0].reshape((1, 2))))) else: return LineString(array)
def CreatePath(start_config, engine, obstacles, max_walk, ideal=True): current_path = [] current_config = start_config walk_limit = max_walk if ideal: sample_func = engine.grid.GetDestinationLocationAndOrientation else: sample_func = engine.grid.SampleMovement while (walk_limit and not markov.CloseToGoalConst(current_config, engine.goal_config, engine.grid) and not obstacles.contains(Point(current_config[0][0], current_config[0][1])) and not markov.OutsideBoundaries(current_config)): walk_limit -= 1 steering_angle = engine.GetSteeringAngle(current_config) x, y, o = sample_func(current_config[0][0], current_config[0][1], current_config[1], steering_angle, engine.average_path_length) if geom_util.AngleAlmostEqual(steering_angle % ANGLE_MOD, 0.0): current_path.append(LineString([current_config[0], (x, y)])) ls = LineString([current_config[0], (x, y)]) if ls.crosses(obstacles): break else: radius = engine.vehicle_length / math.sin(steering_angle) antirangle = (math.pi / 2.0 - current_config[1]) % ANGLE_MOD dx = math.cos(antirangle) * radius dy = math.sin(antirangle) * radius circumrad = engine.average_path_length / abs(radius) if steering_angle > 0.0: direction = COUNTER_CLOCKWISE begin_radian = (current_config[1] - math.pi / 2.0) % ANGLE_MOD end_radian = (begin_radian + circumrad) % ANGLE_MOD else: direction = CLOCKWISE begin_radian = (current_config[1] + math.pi / 2.0) % ANGLE_MOD end_radian = (begin_radian - circumrad) % ANGLE_MOD current_path.append(Arc((current_config[0][0] - dx, current_config[0][1] + dy), abs(radius), begin_radian, end_radian, direction,)) end_pos = current_path[-1].AngleToPoint(end_radian) current_path.append(LineString([end_pos, (x, y)])) current_config = ((x, y), o) state = SUCCESS if not markov.CloseToGoalConst(current_config, engine.goal_config, engine.grid): state = ICED if not walk_limit: state = TLE return current_path, state
def shift_points(points, distance=1, side='left', resolution=16, join_style=3, mitre_limit=5.0): """Takes array of points, create linestring, shift the linestring and return shifted""" line = LineString(points) shift_line = line.parallel_offset(distance, side) print('shift_line=\n', shift_line) return shift_line
def __init__(self, XYs): LineString.__init__(self, XYs) self.Xs = XYs[0][0] self.Xe = XYs[1][0] self.dx = self.Xe - self.Xs self.Ys = XYs[0][1] self.Ye = XYs[1][1] self.dy = self.Ye - self.Ys
def random_point_within(poly, n=40): min_x, min_y, max_x, max_y = poly.bounds X = [] Y = [] for i in range(n): x = random.uniform(min_x, max_x) X.append(x) x_line = LineString([(x, min_y), (x, max_y)]) x_line_intercept_min, x_line_intercept_max = x_line.intersection( poly).xy[1].tolist() y = random.uniform(x_line_intercept_min, x_line_intercept_max) Y.append(y) return ([X, Y])
def test_partition_mls_simple_overlapping(self): from shapely.geometry import LineString, MultiLineString from vectordatasource.transform import \ _linestring_nonoverlapping_partition ls1 = LineString([[-1, 0], [1, 0]]) ls2 = LineString([[0, -1], [0, 1]]) # these are overlapping, so should be split mls = MultiLineString([ls1, ls2]) shapes = _linestring_nonoverlapping_partition(mls) self.assertEquals(shapes, [ls1, ls2])
def test_partition_mls_nonoverlapping(self): from shapely.geometry import LineString, MultiLineString from vectordatasource.transform import \ _linestring_nonoverlapping_partition # these are already non-overlapping, so should not be split mls = MultiLineString([ LineString([[0, 0], [1, 0]]), LineString([[0, 1], [1, 1]]), ]) shapes = _linestring_nonoverlapping_partition(mls) self.assertEquals(shapes, [mls])
def test_simple_merge(self): from shapely.geometry import LineString, MultiLineString from vectordatasource.transform import \ _merge_junctions_in_multilinestring angle_tolerance = 15.0 mls = MultiLineString([ LineString([[0, 0], [1, 0]]), LineString([[-1, 0], [0, 0]]), ]) shape = _merge_junctions_in_multilinestring(mls, angle_tolerance) expected = LineString([[-1, 0], [0, 0], [1, 0]]) self.assertEquals(shape, expected)
def GetTwoCirclesConfig(self, circle, target_circle, origin_dir, target_dir, obstacle_manager, direction): key = (circle.pk, target_circle.pk, origin_dir, target_dir, direction) if key in self.circle_pair_to_config: return self.circle_pair_to_config[key] angle1, angle2 = geom_util.GetTangentLine(circle, origin_dir, target_circle, target_dir) if not obstacle_manager.CanLineStringGo(LineString([ circle.AngleToPoint(angle1), target_circle.AngleToPoint(angle2)])): self.circle_pair_to_config[key] = None return None config = Configuration(len(self.configurations), target_circle, angle2, direction,) self.configurations.append(config) self.circle_pair_to_config[key] = (config, angle1) return config, angle1
def test_split_intersection(): a_split, b_split = split_intersection(intersecting_line_a, intersecting_line_b) assert len(a_split) == 2 assert len(b_split) == 2 assert a_split[0] == LineString(([1, 0], [1, 1]))
def make_line(x, y): print("in x of lenght:{} :{}".format(len(x), x), "\nin y of length {}:{}".format(len(y), y)) line = LineString(zip(x, y)) for point in line.coords: print(point) return line
def _check(self, coords, angle): from shapely.geometry import LineString from vectordatasource.transform import _angle_at ls = LineString(coords) self.assertEqual(_angle_at(ls, ls.coords[0]), angle) self.assertEqual(_angle_at(ls, ls.coords[-1]), angle)
def _GenerateCirclesAndBasicConfig(start_config, goal_config, obstacles, turning_radius, manager, level): circles = [] # First generate two circles adjacent to the start and goal configs. begins = _AdjCircles(start_config, turning_radius, level) ends = _AdjCircles(goal_config, turning_radius, level) for i in range(2): manager.CreateInitConfig(begins[i], start_config[0], 1 - i) manager.CreateEndConfig(ends[i], goal_config[0], 1 - i) circles.extend(begins) circles.extend(ends) if level == 0: fracts = [0.5] else: delta = 1.0 / (2**level) fracts = [delta] while fracts[-1] + delta < 1.0 - EPS: fracts.append(fracts[-1] + delta) fracts = [0.0] + fracts + [1.0] # Now generate midpoint circle on each vertex. for polygon in obstacles.geoms: for coords in list(map(lambda interior: interior.coords, polygon.interiors)) + [polygon.exterior.coords]: # Not a bug, the center is really only n-1 elements. This is since polygon's boundary repeats the last vertex. for p3, p2, p1 in zip(coords, coords[1:], coords[2:-1] + coords[:2]): if p2[0] < BOUNDARIES[0] or p2[0] > BOUNDARIES[1] or p2[1] < BOUNDARIES[0] or p2[1] > BOUNDARIES[1]: continue if geom_util.CrossProd(p3, p2, p1) > -EPS: continue for fractions in fracts: circles.append(_GenerateCircle( LineString([p1, p2, p3]), angle_fraction=fractions, radius=turning_radius)) circles.append(_GenerateCircle( LineString([p1, p2, p3]), angle_fraction=fractions, radius=turning_radius, mirror=True)) # TODO(irvan): generate random circles return circles
def Heuristic(self, circle, point): if circle.pk in self.circle_cache: blockeds = self.circle_cache[circle.pk] else: to_tries = [] for polygon in self.obstacles.geoms: for coords in list(map(lambda interior: interior.coords, polygon.interiors)) + [polygon.exterior.coords]: for p1, p2 in zip(coords, coords[1:]): if geom_util.CircleLineSegmentIntersections(circle, LineString([p1, p2])): continue to_tries.append([p1, p2]) center = circle.center blockeds = [] for p in self.points: blocked = False if circle.radius**2 + EPS < (p[0] - center[0])**2 + (p[1] - center[1])**2: # not inside circle # Get the two tangent lines angle1 = geom_util.GetTangentLinePoint(circle, is_circle1_ccw=True, point=p) angle2 = geom_util.GetTangentLinePoint(circle, is_circle1_ccw=True, point=p) line1 = [p, circle.AngleToPoint(angle1)] line2 = [p, circle.AngleToPoint(angle2)] for p1, p2 in to_tries: if (geom_util.LineSegmentIntersectStrict(line1, [p1, p2]) and geom_util.LineSegmentIntersectStrict(line2, [p1, p2])): blocked = True break blockeds.append(blocked) self.circle_cache[circle.pk] = blockeds best = None for p, dist, blocked in zip(self.points, self.distances, blockeds): if blocked: continue if dist is not None: if best is None or dist < best: euc = math.sqrt((p[0] - point[0])**2 + (p[1] - point[1])**2) if best is None or best > dist + euc: if self.obstacle_manager.CanLineStringGo(LineString([p, point])): best = dist + euc if best is None: return 10**9 return best
def canonicalize_line(line): """Ensures a consistent order of a line's coordinates.""" coord1 = LatLon(line.coords[0][1], line.coords[0][0]) coord2 = LatLon(line.coords[1][1], line.coords[1][0]) if bearing_to(coord1, coord2) > 180: return LineString(reversed(line.coords)) else: return line
def test_boundary_difference_exception(self): from vectordatasource.transform import admin_boundaries from tilequeue.process import Context from shapely.geometry.linestring import LineString from shapely.geometry import box from collections import namedtuple shape = LineString([[0, 0], [1, 1]]) props1 = {'id': 1, 'kind': 'foo', 'maritime_boundary': False} props2 = {'id': 2, 'kind': 'foo', 'maritime_boundary': False} fid = None bounds = (0, 0, 1, 1) # it turns out to be difficult to make a simple, canned example of # geometries which will cause a TopologicalError. instead, this fake # geometry class will cause Shapely to throw AttributeError whenever # it's used in a geometric operation, as it doesn't have the _geom # attribute used to store a pointer to GEOS' native object. class FakeGeom(namedtuple("FakeGeom", "geom_type envelope")): def difference(self, other_shape): from shapely.geometry import GeometryCollection return GeometryCollection([]) fake_geom = FakeGeom("LineString", box(*bounds)) feature_layers = [ dict( layer_datum=dict( is_clipped=True, area_threshold=0, simplify_before_intersect=True, simplify_start=0, name='foo', ), padded_bounds={'line': bounds}, features=[ (shape, props1, fid), # the fake geometry here causes an exception to be thrown, as # if the operation failed. (fake_geom, props2, fid), ], ) ] nominal_zoom = 0 unpadded_bounds = bounds params = dict( simplify_before=16, base_layer='foo', ) resources = None ctx = Context(feature_layers, nominal_zoom, unpadded_bounds, params, resources) # the test is simply that an exception isn't thrown. admin_boundaries(ctx)
def __init__(self, coordinates=None): """ Parameters ---------- coordinates : sequence A sequence of (x, y [,z]) numeric coordinate pairs or triples or an object that provides the numpy array interface, including another instance of LineString. Example ------- Create a line with two segments >>> a = Polyline([[0, 0], [1, 0], [1, 1]]) >>> a.length 2.0 """ LineString.__init__(self, coordinates)
def find_near_neighbor(rand): nn = NODES[0] for p in NODES: if dist([p.x,p.y],[rand.x,rand.y]) < dist([nn.x,nn.y],[rand.x,rand.y]) and \ dist([p.x,p.y],[rand.x,rand.y]) > EPSILON: line = LineString([(p.x,p.y), (rand.x,rand.y)]) if collides(line) == False: nn = p return nn
def get_point_at_percent(self, linestring: LineString, pct_along: float, offset_side: Sides = None, offset_distance: Distance = None): """ Get the point on a linestring at a given distance (expressed as a percentage of the total distance) from the start of the line. :param linestring: the linestring :type linestring: :py:class:`ogr.Geometry` :param pct_along: How far along the linestring is the point you want? :type pct_along: ``float`` :param offset_side: If you want a point on the left- or right-hand side, specify the side. :type offset_side: :py:class:`Sides` :param offset_distance: If you want a point offset from the centerline, how far away should it be? :type offset_distance: :py:class:`Distance` :return: the point at the specified offset :rtype: :py:class:`ogr.Geometry` """ # Perform a sanity check: We need the geometry to be a linestring. if linestring.GetGeometryType() != ogr.wkbLineString: raise GeometryException('The input geometry must be a LineString.') # If we haven't been supplied enough information to find an offset, we can just carry on with the original # geometry; otherwise we need to find the line parallel on the requested side at the specified distance. _linestring = (linestring if offset_side is None or offset_distance is None else self.get_parallel_offset(linestring=linestring, side=offset_side, distance=offset_distance)) # Convert the OGR geometry to a shapely geometry so we can perform some calculations. shapely_linestring: LineString = self.ogr_to_shapely(_linestring) # Let's get the point at the given percent. # (See http://toblerity.org/shapely/manual.html#object.interpolate) shapely_point_at_pct: Point = shapely_linestring.interpolate( pct_along, normalized=True) # Now we need to convert the geometry back to OGR. (For the spatial reference, we just use the one from the # original geometry.) ogr_point: ogr.Geometry = self.shapely_to_ogr( shapely_geometry=shapely_point_at_pct, srs=linestring.GetSpatialReference()) # Good to go! return ogr_point
def find_near_neighbor(pt): #print "finding near neighbor" nearest = NODES[0] ls = LineString([(0, 0), (0, 0)]) valid = False for n in NODES: #print "dist:", dist(n,pt) if dist(n, pt) < dist(nearest, pt): nearest = n return nearest
def CirclePolygonIntersections(circle, polygon): '''Returns all points of intersections between circle and polygon''' intersections = [] for coords in list(map(lambda interior: interior.coords, polygon.interiors)) + [polygon.exterior.coords]: for p1, p2 in zip(coords, coords[1:]): intersections.extend( CircleLineSegmentIntersections(circle, LineString((p1, p2)))) return intersections
def calculate_over_fluxgate(start, vdata, surfdata, bdot, dhdt, beddata, end=None, offset=100, gamma=0.9, plotfig=None): startgate = LineString(start) # just to make sure... startpt = startgate.coords[0] flowLine1 = get_flowline(startpt, vdata, end=end) fluxDist = 0 gates = [] flowcellnumber = [] bed = np.empty(0) while (startgate.length - fluxDist) > offset: startpt = startgate.interpolate(fluxDist + offset).coords[0] flowLine2 = get_flowline(startpt, vdata, end=end) if plotfig is not None: plt.plot(flowLine1.x, flowLine1.y, 'b') plt.plot(flowLine2.x, flowLine2.y, 'b') thesegates, thisbed = calculate_bed_elevs(flowLine1, flowLine2, vdata, surfdata, bdot, dhdt, beddata, gamma, offset, plotfig) for j, x in enumerate(thesegates[0]): gates.append(Point(x, thesegates[1][j])) flowcellnumber.append(j) bed = np.append(bed, thisbed) flowLine1 = flowLine2 fluxDist += offset return gates, bed, flowcellnumber
def test_create_line_from_points(self): geo_point_1 = Point(0.0, 0.0) geo_point_2 = Point(1.0, 1.0) expected_line = LineString([ [0.0, 0.0], [1.0, 1.0], ]) geo_line = geo_fields.GeoLine.from_points(self.env.cr, geo_point_1, geo_point_2) self.assertEqual(geo_line, expected_line)
def convert_pix_lstring_to_geo(wkt_lstring, im_file, utm_zone=None, utm_letter=None, verbose=False): '''Convert linestring in pixel coords to geo coords If zone or letter changes inthe middle of line, it's all screwed up, so force zone and letter based on first point (latitude, longitude, force_zone_number=None, force_zone_letter=None) Or just force utm zone and letter explicitly ''' shape = wkt_lstring #shapely.wkt.loads(lstring) x_pixs, y_pixs = shape.coords.xy coords_latlon = [] coords_utm = [] for i, (x, y) in enumerate(zip(x_pixs, y_pixs)): targetSR = osr.SpatialReference() targetSR.ImportFromEPSG(4326) lon, lat = pixelToGeoCoord(x, y, im_file, targetSR=targetSR) if utm_zone and utm_letter: [utm_east, utm_north, _, _] = utm.from_latlon(lat, lon, force_zone_number=utm_zone, force_zone_letter=utm_letter) else: [utm_east, utm_north, utm_zone, utm_letter] = utm.from_latlon(lat, lon) if verbose: print("lat lon, utm_east, utm_north, utm_zone, utm_letter]", [lat, lon, utm_east, utm_north, utm_zone, utm_letter]) coords_utm.append([utm_east, utm_north]) coords_latlon.append([lon, lat]) lstring_latlon = LineString([Point(z) for z in coords_latlon]) lstring_utm = LineString([Point(z) for z in coords_utm]) return lstring_latlon, lstring_utm, utm_zone, utm_letter
def segment_to_polyline(segment): points = [(p.latitude, p.longitude) for p in segment.points] ls = LineString(points) ls = ls.simplify(0.0001) return ls.coords