Example #1
0
    def reflect(self, line):
        from sympy import atan, Line, Point, Dummy, oo

        g = self
        l = line
        o = Point(0, 0)
        if l == Line(o, slope=0):
            return g.scale(y=-1)
        elif l == Line(o, slope=oo):
            return g.scale(-1)
        if not hasattr(g, 'reflect') and not all(
                isinstance(arg, Point) for arg in g.args):
            raise NotImplementedError
        a = atan(l.slope)
        c = l.coefficients
        d = -c[-1] / c[1]  # y-intercept
        # apply the transform to a single point
        x, y = Dummy(), Dummy()
        xf = Point(x, y)
        xf = xf.translate(y=-d).rotate(-a,
                                       o).scale(y=-1).rotate(a,
                                                             o).translate(y=d)
        # replace every point using that transform
        reps = [(p, xf.xreplace({x: p.x, y: p.y})) for p in g.atoms(Point)]
        return g.xreplace(dict(reps))
def get_intersection_points2D_with_img(intersection_points: list,
                                       plane_range: np.ndarray) -> tuple:
    x, y = intersection_points
    p1 = Point(x[0], y[0])
    p2 = Point(x[1], y[1])
    intersection_line = Line(p1, p2)

    points1 = Point(plane_range[0, 1],
                    plane_range[0, 0]), Point(plane_range[0, 1],
                                              plane_range[1, 0])
    points2 = Point(plane_range[0, 1],
                    plane_range[1, 0]), Point(plane_range[1, 1],
                                              plane_range[1, 0])
    points3 = Point(plane_range[1, 1],
                    plane_range[1, 0]), Point(plane_range[1, 1],
                                              plane_range[0, 0])
    points4 = Point(plane_range[1, 1],
                    plane_range[0, 0]), Point(plane_range[0, 1],
                                              plane_range[0, 0])

    line1 = Segment(*points1)
    line2 = Segment(*points2)
    line3 = Segment(*points3)
    line4 = Segment(*points4)

    result = tuple(
        filter(
            lambda x: x != [],
            intersection_line.intersection(line1) +
            intersection_line.intersection(line2) +
            intersection_line.intersection(line3) +
            intersection_line.intersection(line4)))

    return (float(result[0].x), float(result[0].y)), (float(result[1].x),
                                                      float(result[1].y))
Example #3
0
def find_valid_corners(mat_size, corners):
    popped = False
    top_edge_line = Line(Point(0, 0), Point(100, 0))
    while corners and corners[0][1] < 0:
        pt = corners.popleft()
        left_line = Line(pt, corners[0])
        temp_pt = left_line.intersection(top_edge_line)
        popped = True
    if popped:
        first_pt = corners[0]
        if first_pt[1] != temp_pt[0].y:
            new_point = (int(temp_pt[0].x), int(temp_pt[0].y))
            if new_point[0] != corners[0][0] and new_point[1] != corners[0[1]]:
                corners.appendleft(new_point)

    popped = False
    bottom_edge_line = Line(Point(0, mat_size[1] - 1), Point(100, mat_size[1] - 1))
    while corners[-1][1] >= mat_size[1] and len(corners) > 0:
        pt = corners.pop()
        left_line = Line(pt, corners[-1])
        temp_pt = left_line.intersection(bottom_edge_line)
        popped = True
    if popped:
        first_pt = corners[0]
        if first_pt[1] != temp_pt[0].y:
            new_point = (int(temp_pt[0].x), int(temp_pt[0].y))
            if new_point[0] != corners[-1][0] and new_point[1] != corners[-1][1]:
                corners.append(new_point)
    return corners
Example #4
0
class wire:
    def __init__(self, left0, left1, right0, right1, planeNo, wireNo,
                 trueWireNo):
        self.leftBound = Line(left0, left1)
        self.rightBound = Line(right0, right1)
        self.planeNo = planeNo
        self.wireNo = wireNo
        self.trueWireNo = trueWireNo

    def rotate(self, angle):
        self.leftBound = self.leftBound.rotate(angle)
        self.rightBound = self.rightBound.rotate(angle)

    def translate(self, x, y):
        self.leftBound = self.leftBound.translate(x, y)
        self.rightBound = self.rightBound.translate(x, y)

    def doesIntersect(self, wire):
        ll = intersect(self.leftBound.points[0], self.leftBound.points[1],
                       wire.leftBound.points[0], wire.leftBound.points[1])
        lr = intersect(self.leftBound.points[0], self.leftBound.points[1],
                       wire.rightBound.points[0], wire.rightBound.points[1])
        rl = intersect(self.rightBound.points[0], self.rightBound.points[1],
                       wire.leftBound.points[0], wire.leftBound.points[1])
        rr = intersect(self.rightBound.points[0], self.rightBound.points[1],
                       wire.rightBound.points[0], wire.rightBound.points[1])
        # print(ll,lr,rl,rr)
        return ll and lr and rl and rr

    def __repr__(self):
        # return str([self.planeNo,self.wireNo,self.trueWireNo])
        return str([self.leftBound, self.rightBound])
Example #5
0
def Dubins_msg(UAV, target, R0):
    v = UAV.v 
    phi0 = UAV.phi
    UAV_p = Point(UAV.site)
    target_p = Point(target[0:2])

    c1 = Point(UAV_p.x + R0 * np.sin(phi0), UAV_p.y - R0 * np.cos(phi0))
    c2 = Point(UAV_p.x - R0 * np.sin(phi0), UAV_p.y + R0 * np.cos(phi0))
    len1 = c1.distance(target_p)
    len2 = c2.distance(target_p)
    center = c1

    if len2 > len1:
        center = c2

    center = Point(round(center.x.evalf(), 4), round(center.y.evalf(), 4))
    circle = Circle(center, R0)
    tangent_lines = Tangent_lines(circle, target_p)
    tangent_line1 = tangent_lines[0]  
    tangent_line1 = Line(tangent_line1.p2, tangent_line1.p1)
    tangent_point1 = tangent_line1.p1
    y = float((target_p.y - tangent_point1.y).evalf())
    x = float((target_p.x - tangent_point1.x).evalf())
    tangent_angle1 = np.arctan2(y, x)

    tangent_line2 = tangent_lines[1]
    tangent_line2 = Line(tangent_line2.p2, tangent_line2.p1)
    tangent_point2 = tangent_line2.p1
    y = float((target_p.y - tangent_point2.y).evalf())
    x = float((target_p.x - tangent_point2.x).evalf())
    tangent_angle2 = np.arctan2(y, x)

    vec1 = [UAV_p.x - center.x, UAV_p.y - center.y]
    vec2 = [np.cos(phi0), np.sin(phi0)]
    direction = np.sign(vec1[0] * vec2[1] - vec1[1] * vec2[0])
    sin1 = float(tangent_point1.distance(UAV_p).evalf()) / (2 * R0)
    angle1 = 2 * np.arcsin(sin1)
    sin2 = float(tangent_point2.distance(UAV_p).evalf()) / (2 * R0)
    angle2 = 2 * np.arcsin(sin2)

    tangent_point = []
    radian = 0

    if abs(modf(abs(direction * angle1 + phi0 - tangent_angle1) / (2 * np.pi))[0] - 0.5) > 0.5 - deviation:
        tangent_point = tangent_point1
        radian = angle1
    elif abs(modf(abs(direction * (2 * np.pi - angle1) + phi0 - tangent_angle1) / (2 * np.pi))[
                 0] - 0.5) > 0.5 - deviation:
        tangent_point = tangent_point1
        radian = 2 * np.pi - angle1
    elif abs(modf(abs(direction * angle2 + phi0 - tangent_angle2) / (2 * np.pi))[0] - 0.5) > 0.5 - deviation:
        tangent_point = tangent_point2
        radian = angle2
    elif abs(modf(abs(direction * (2 * np.pi - angle2) + phi0 - tangent_angle2) / (2 * np.pi))[
                 0] - 0.5) > 0.5 - deviation:
        tangent_point = tangent_point2
        radian = 2 * np.pi - angle2

    return direction, radian, (float(tangent_point.x.evalf()), float(tangent_point.y.evalf())), (
        float(center.x.evalf()), float(center.y.evalf()))
Example #6
0
 def __init__(self, left0, left1, right0, right1, planeNo, wireNo,
              trueWireNo):
     self.leftBound = Line(left0, left1)
     self.rightBound = Line(right0, right1)
     self.planeNo = planeNo
     self.wireNo = wireNo
     self.trueWireNo = trueWireNo
Example #7
0
def Tangent_lines(circle_C, point_P):
    # 圆外一点到圆的切线,
    # 返回从point到切点的line
    R = float(circle_C.radius.evalf())
    circle = [
        float(circle_C.center.x.evalf()),
        float(circle_C.center.y.evalf())
    ]
    point = [float(point_P.x.evalf()), float(point_P.y.evalf())]

    circle_point_angle = np.arctan2(point[1] - circle[1], point[0] - circle[0])
    cos = R / np.sqrt(np.sum((np.array(circle) - np.array(point))**2))
    hudu_half = np.arccos(cos)

    tangent_angle1 = circle_point_angle + hudu_half
    tangent_point1 = Point(circle[0] + R * np.cos(tangent_angle1),
                           circle[1] + R * np.sin(tangent_angle1))

    tangent_angle2 = circle_point_angle - hudu_half
    tangent_point2 = Point(circle[0] + R * np.cos(tangent_angle2),
                           circle[1] + R * np.sin(tangent_angle2))

    return [
        Line(Point(point), Point(tangent_point1)),
        Line(Point(point), Point(tangent_point2))
    ]
Example #8
0
def test(f, col=30, n=200):
    for i in range(0, n):
        points = []
        while True:
            points = generate_test(col)
            if points[0] is points[1] or points[0][0] is points[0][
                    1] or points[1][0] is points[1][1]:
                continue
            l = Line(P(points[0][0], points[0][1]),
                     P(points[1][0], points[1][1]))
            if len(l.intersection(P(points[2][0], points[2][1]))) != 0:
                continue
            break

        if i % 50 == 0 and i != 0:
            print('passed {} tests'.format(i))
        for j in range(0, 2 * len(points)):
            point = np.random.randint(0, 25, size=(2))
            answer = check(points, point)
            for k in range(0, len(points) - 1):
                points.insert(len(points), points[0])
                points.remove(points[0])
                result = f(points, point)
                if result is answer:
                    continue
                print("Test â„–{} failed".format(i + 1))
                print("Expected {}, result {}".format(answer, result))
                print("points={}".format(points))
                print("point={}".format(point))
                draw(points, point)
                return
    print("All tests passed")
Example #9
0
def compute_distances_between_two_points_set(points1, points2, check = None) :
    index = 0
    distances = []
    i = 0
    li = []
    while i < len(points1):
        p1 = points1[i]
        if index >= len(points2) - 1: break

        if check:
            if i < len(points1) - 1:
                if check(points2[index], points2[index+1], points1[i], points1[i+1]):
                    logging.warn("crossing~")

        line = Line(points2[index], points2[index + 1])
        pro = line.projection(p1)


        if is_projection_between_two_points(pro, points2[index], points2[index + 1]):
            distances.append(p1.distance(pro))
            li.append([p1, pro])
            index += 1
        else:
            if pro.distance(points2[index + 1]) < pro.distance(points2[index]):
                i -= 1
                index += 1
        i += 1
    return distances, li
Example #10
0
def slice_file(image_position_patient_array,
               image_orientation_patient,
               output_path=None,
               input_path=None):
    print("Status: Loading File.")

    model = STLModel(input_path)
    stats = model.stats()

    print(stats)

    print("Status: Calculating Slices")

    v1 = Point3D(image_orientation_patient[0][0],
                 image_orientation_patient[0][1],
                 image_orientation_patient[0][2])
    v2 = Point3D(image_orientation_patient[1][0],
                 image_orientation_patient[1][1],
                 image_orientation_patient[1][2])
    org = Point3D(0, 0, 0)

    for i, slice_loc in enumerate(image_position_patient_array):
        slice_loc = Point3D(slice_loc[0], slice_loc[1], slice_loc[2])

        dwg = Drawing(output_path + str(i) + '.svg', profile='tiny')
        plane = Plane(v1 + slice_loc, v2 + slice_loc, org + slice_loc)
        x_axis = Line(org + slice_loc, v1 + slice_loc)
        y_axis = Line(org + slice_loc, v2 + slice_loc)
        pairs = model.slice_at_plane(plane, x_axis, y_axis)
        for pair in pairs:
            dwg.add(dwg.line(pair[0], pair[1], stroke=rgb(0, 0, 0, "%")))
        dwg.save()

    print("Status: Finished Outputting Slices")
Example #11
0
def locate_puzzle(img, debug=False):
    # Blurr image to reduce noise in edges
    thresh = cv.GaussianBlur(img, (3,3), cv.BORDER_REFLECT)

    param1, param2 = 15, 20 
    while True:
        # Canny edge detection
        edges = cv.Canny(thresh, param1, param2, None, 3)
        # Dilate and erode edges (from https://stackoverflow.com/questions/48954246/find-sudoku-grid-using-opencv-and-python)
        edges = cv.dilate(edges, np.ones((3,3),np.uint8), iterations=1)
        edges = cv.erode(edges, np.ones((5,5),np.uint8), iterations=1)

        lines = cv.HoughLines(edges, 1, np.pi / 180, 150, None, 0, 0)
        param1, param2 = param1+5, param2+30
        if lines is None: continue
        if len(lines) <= 35: break
        
    # Copy edges to the images that will display the results in BGR
    cdst = cv.cvtColor(edges, cv.COLOR_GRAY2BGR)

    # Find four corners of sudoku board
    poss_corners = []
    for i in range(len(lines)):
        rho = lines[i][0][0]
        theta = lines[i][0][1]
        pt1, pt2 = polar_to_points(rho, theta)
        cv.line(cdst, pt1, pt2, (0,0,255), 3, cv.LINE_AA)
        p1, p2 = Point(pt1), Point(pt2)
        l1 = Line(p1, p2)
        for j in range(len(lines)):
            if i == j: continue
            rho = lines[j][0][0]
            theta = lines[j][0][1]
            p3, p4 = polar_to_points(rho, theta, return_class=True)
            l2 = Line(p3, p4)
            p = l1.intersection(l2)
            if len(p) == 0: continue
            p = np.array([int(p[0][1]), int(p[0][0])])
            if 0 <= p[0] < len(img) and 0 <= p[1] < len(img[1]):
                poss_corners.append(p)
    
    tl = poss_corners[np.argmin(np.array(list(map(euclidean, poss_corners, [[0,0]]*len(poss_corners)))))]
    tr = poss_corners[np.argmin(np.array(list(map(euclidean, poss_corners, [[0,len(img[0])]]*len(poss_corners)))))]
    bl = poss_corners[np.argmin(np.array(list(map(euclidean, poss_corners, [[len(img),0]]*len(poss_corners)))))]
    br = poss_corners[np.argmin(np.array(list(map(euclidean, poss_corners, [[len(img),len(img[0])]]*len(poss_corners)))))]

    # Idea for warping using imutils: https://www.pyimagesearch.com/2020/08/10/opencv-sudoku-solver-and-ocr/
    img = four_point_transform(img, np.array([
        [tl[1],tl[0]],
        [tr[1],tr[0]],
        [bl[1],bl[0]],
        [br[1],br[0]]]))

    if debug: 
        cv.imshow("Lines", cdst)
        cv.imshow("Cropped", img)
        cv.waitKey()
    
    return img
Example #12
0
	def on_track(self, line):
		"""Are we still on track (that is, is our distance to the given line
		small enough? If not, better re-navigate"""
		if line is None:
			return False
		else:
			line = Line(*line)
			return line.distance(self.tracker.getPosition()) < THRESHOLD
Example #13
0
 def __init__(self, p0, p1, center):
     self.p0 = p0
     self.p1 = p1
     self.center = center
     self.radius = self.center.distance(self.p0)
     line1 = Line(self.center, self.p1)
     line2 = Line(self.center, self.p0)
     self.central_angle = line1.angle_between(line2)
Example #14
0
 def eval_end_pt_tang(self, first):
     trgt_pt = self.p0 if first else self.p1
     res_norm = Line(self.center, trgt_pt).direction.unit
     res_tang = res_norm.rotate(np.pi / 2.)
     halfpl = get_halfplane(self.p0, self.p1, self.center)
     if -1 == halfpl:
         res_tang = -res_tang
     return res_tang
Example #15
0
def extendExWall(P0, P1, l1, msp):
    l0 = Line(p0, p1)
    intersectedPoint = l0.intersection(l1)
    xE, yE = intersectedPoint
    xS, yS = p1
    msp.add_line(((xS, yS, 0), (xE, yE, 0)))
    l0 = Line(p1, intersectedPoint)
    return l0
Example #16
0
def crossing(p1: Point, p2: Point, p3: Point, p4: Point):
    line1, seg1 = Line(p1, p2), Segment(p1, p2)
    line2, seg2 = Line(p3, p4), Segment(p3, p4)
    intersect = line1.intersection(line2)
    if intersect:
        seg1 = Segment(p1, p2)
        seg2 = Segment(p3, p4)
        pi = intersect[0]
        return seg1.contains(pi) and seg2.contains(pi)
Example #17
0
def calculateFaceTilt(leftEye, rightEye):
    zeroLine = Line(Point(1, 0), Point(0, 0))
    eyeMiddlePoint = Point((leftEye + rightEye) / 2)
    eyeLine = Line(leftEye, rightEye)
    angle = mpmath.degrees(eyeLine.angle_between(zeroLine))
    if (leftEye.y > rightEye.y):
        return int(angle) - 180
    else:
        return 180 - int(angle)
Example #18
0
    def __compute_1st_vanishing_points(self):
        road_l1 = Line(Point(self.p1), Point(self.p2))
        road_l2 = Line(Point(self.p3), Point(self.p4))

        road_intersection = intersection(road_l1, road_l2)
        u0 = float(road_intersection[0][0])
        v0 = float(road_intersection[0][1])

        return u0, v0
def path_of_white_ball(p1, p2, r):
    pathBallW[:] = []
    middle_ray = Line(p1, p2)
    cue_circle = Circle(p1, r)
    normal_line = middle_ray.perpendicular_line(p1)
    points = intersection(cue_circle, normal_line)
    pathBallW.append(middle_ray.parallel_line(points[0]))
    pathBallW.append(middle_ray)
    pathBallW.append(middle_ray.parallel_line(points[1]))
Example #20
0
    def projection(self, eye1, eye2):
        target = self.estimate(eye1, eye2)

        horizontal, = Line(target, self.abscissa_hinge).intersection(abscissa)
        vertical, = Line(target, self.ordinate_hinge).intersection(ordinate)

        x = self.to_width(horizontal.x)
        y = self.to_height(vertical.y)

        return float(x), float(y)
Example #21
0
    def _calculate_angle(line: Line) -> float:
        angle = line.angle_between(Line((0, 0), (1, 0))).evalf()
        if line.p2.x <= line.p1.x:
            if line.p2.y <= line.p1.y:
                angle = math.pi - angle + math.pi
        else:
            if line.p2.y <= line.p1.y:
                angle = 2 * math.pi - angle

        return angle
Example #22
0
    def __compute_2nd_vanishing_points(self):
        # perp_l1 = Line(Point(self.p2), Point(self.p3))
        perp_l1 = Line(Point(self.p1), Point(self.p4))
        # horizon_l = Line(Point(0, self.v0), (1, self.v0))
        horizon_l = Line(Point(self.p2), Point(self.p3))

        perp_intersection = intersection(perp_l1, horizon_l)
        u1 = float(perp_intersection[0][0])

        return u1
Example #23
0
def formperpenicularlines(xpos):
    xpos = xpos.reshape(len(cutpos), 1)
    xpts = np.insert(xpos, 1, [0], axis=1)
    xpts = map(Point, xpts)
    xaxis = Line((0, 0), (1, 0))
    cutlines = []
    for pt in xpts:
        cutline = xaxis.perpendicular_line(pt)
        cutlines.append(cutline)
    return cutlines
def calculateFaceTilt(faceEyesIrisPoints, regionOfInterestColorObjects):
    zeroLine = Line (Point (1,0), Point (0,0));
    leftEye = Point (faceEyesIrisPoints.pop());
    rightEye =  Point (faceEyesIrisPoints.pop());
    eyeMiddlePoint = Point ((leftEye + rightEye)/2);       
    eyeLine = Line (leftEye, rightEye);
    faceSymmetryLine = eyeLine.perpendicular_line(eyeMiddlePoint);
    angle = mpmath.degrees(eyeLine.angle_between(zeroLine));
    if (int(angle) > 90):    
        return {'angle':int(angle) - 180, 'tiltline':faceSymmetryLine};
    else:
        return {'angle':int(angle), 'tiltline':faceSymmetryLine};
Example #25
0
def get_polygon(left, right, top, bottom):
    # convert rays to lines
    left = Line(left.p1, left.p2)
    right = Line(right.p1, right.p2)
    top = Line(top.p1, top.p2)
    bottom = Line(bottom.p1, bottom.p2)

    top_left = left.intersection(top)[0]
    top_right = right.intersection(top)[0]
    bottom_left = left.intersection(bottom)[0]
    bottom_right = right.intersection(bottom)[0]
    return Polygon(top_left, top_right, bottom_right, bottom_left)
Example #26
0
def get_osculating_center(pt, tang, radius, jnc_cntr):
    init_line = Line(pt, pt + tang)
    tang_perp = init_line.perpendicular_line(pt).direction.unit
    cand_cntr1 = pt + tang_perp * radius
    cand_cntr2 = pt - tang_perp * radius
    dist_cand1 = jnc_cntr.distance(cand_cntr1)
    dist_cand2 = jnc_cntr.distance(cand_cntr2)
    if (dist_cand1 < dist_cand2):
        res_cntr = cand_cntr1
    else:
        res_cntr = cand_cntr2
    return res_cntr
Example #27
0
def find_circle(circle,A,C,D,i):
    AD = Line(A,D)
    svg.append(AD,"AD",i)
    K = intersection(circle, AD)[0]
    svg.append(K,"K",i)
    tangentK = Line(A,D).perpendicular_line(K)
    svg.append(tangentK,"tangK",i)
    P1 = intersection(tangentK, Line(A,C))[0]
    svg.append(P1,"P1",i)
    P2 = intersection(tangentK, xaxis)[0]
    svg.append(P2,"P2",i)
    T = Triangle(P1,A,P2)
    svg.append(T,"T",i)
    return T.incircle
    def test_project_on_line_parallel(self):
        """
        Simple test, building line and points near it, which can form parallel line.
        """

        line = Line(Point2D(0, 0), Point2D(4, 4))

        not_line_points = set()

        start_point = Point2D(0, -2)

        points_reference = []

        not_line_point = start_point
        for i in range(0, 5):
            not_line_points.add(Point2D(not_line_point.x, not_line_point.y))

            projected_point = SegmentsInLineFinder.ProjectedPoint(not_line_point, Point2D(not_line_point.x - 1,
                                                                                          not_line_point.y + 1),
                                                                  (i - 1) * sqrt(2))

            points_reference.append(projected_point)
            not_line_point = Point2D(not_line_point.x + 1, not_line_point.y + 1)

        points_test = SegmentsInLineFinder.project_on_line(line, not_line_points)

        self.assertListEqual(points_test, points_reference)
Example #29
0
def calc_prompt_perpendicular_line(p_1: QPointF, p_2: QPointF,
                                   p_mouse: QPointF):
    if p_1 == p_2:
        return None, None
    mouse = Point(p_mouse.x(), p_mouse.y())
    p_1 = Point(p_1.x(), p_1.y())
    p_2 = Point(p_2.x(), p_2.y())
    line = Line(p_1, p_2)
    para_line = line.parallel_line(mouse)
    perp_line_1 = line.perpendicular_line(p_1)
    perp_line_2 = line.perpendicular_line(p_2)
    conj_p1 = para_line.intersection(perp_line_1)
    conj_p2 = para_line.intersection(perp_line_2)
    qp1 = QPointF(conj_p1[0].x, conj_p1[0].y)
    qp2 = QPointF(conj_p2[0].x, conj_p2[0].y)
    return qp1, qp2
def plotline(ax, rwaypoints, width):
    pointx, pointy = pointtolist(rwaypoints)
    ax.plot(pointx, pointy)
    for i in range(len(rwaypoints) - 1):
        x = []
        y = []
        if (rwaypoints[i].x == rwaypoints[i + 1].x
                and rwaypoints[i].y == rwaypoints[i + 1].y):
            continue
        else:
            line = Line(rwaypoints[i], rwaypoints[i + 1])
            diracp = line.direction.unit
            diracn = diracp.rotate(math.pi / 2)
            rectpt1 = rwaypoints[i].translate(
                (diracn.x - diracp.x) * width / 2,
                (diracn.y - diracp.y) * width / 2)
            rectpt2 = rwaypoints[i + 1].translate(
                (diracn.x + diracp.x) * width / 2,
                (diracn.y + diracp.y) * width / 2)
            rectpt3 = rwaypoints[i + 1].translate(
                (diracp.x - diracn.x) * width / 2,
                (diracp.y - diracn.y) * width / 2)
            rectpt4 = rwaypoints[i].translate(
                (-diracp.x - diracn.x) * width / 2,
                (-diracp.y - diracn.y) * width / 2)
            x.extend([rectpt1.x, rectpt2.x, rectpt3.x, rectpt4.x])
            y.extend([rectpt1.y, rectpt2.y, rectpt3.y, rectpt4.y])
            ax.fill(x, y, 'b', alpha=0.2)
def during_collision(cue_point, radius, stick_point, ball_coord):
    future_point = cue_point
    collision_ball_info = cue_point
    min_distance = 1e9

    temp_ray = Ray(cue_point, stick_point)
    temp_Line = Line(cue_point, stick_point)
    temp_circle = Circle(cue_point, radius)
    temp_collision_points = intersection(temp_Line, temp_circle)

    if temp_ray.contains(temp_collision_points[0]):
        white_ray = Ray(cue_point, temp_collision_points[1])
    else:
        white_ray = Ray(cue_point, temp_collision_points[0])

    for coord in ball_coord:
        enlarged_ball = Circle(Point(coord[0], coord[1]), coord[2] + radius)

        intersect_point = intersection(white_ray, enlarged_ball)

        if len(intersect_point) == 2 and cue_point.distance(
                intersect_point[0]) >= cue_point.distance(intersect_point[1]):
            temp_point = intersect_point[1]
        elif len(intersect_point) == 2 or len(intersect_point) == 1:
            temp_point = intersect_point[0]
        else:
            continue

        dist = cue_point.distance(temp_point)
        if min_distance > dist:
            min_distance = dist
            future_point = temp_point
            collision_ball_info = coord

    return future_point, collision_ball_info
Example #32
0
    def find_direction_split(self, template, x, nn, pre_nn):
        samples = polytope.sample(10000, template, np.array(x))
        preprocessed = pre_nn(torch.tensor(samples).float())
        preprocessed_np = preprocessed.detach().numpy()
        samples_ontput = torch.softmax(nn(preprocessed), 1)
        predicted_label = samples_ontput.detach().numpy()[:, 0]
        y = np.clip(predicted_label, 1e-7, 1 - 1e-7)
        inv_sig_y = np.log(y / (1 - y))  # transform to log-odds-ratio space
        from sklearn.linear_model import LinearRegression
        lr = LinearRegression()
        lr.fit(samples, inv_sig_y)
        template_2d: np.ndarray = np.array([Experiment.e(3, 2), Experiment.e(3, 0) - Experiment.e(3, 1)])

        def sigmoid(x):
            ex = np.exp(x)
            return ex / (1 + ex)

        preds = sigmoid(lr.predict(samples))
        plot_points_and_prediction(samples @ template_2d.T, preds)
        plot_points_and_prediction(samples @ template_2d.T, predicted_label)
        coeff = lr.coef_
        intercept = lr.intercept_
        a = sympy.symbols('x')
        b = sympy.symbols('y')
        classif_line1 = Line(coeff[0].item() * a + coeff[1].item() * b + intercept)
        new_coeff = -coeff[0].item() / coeff[1].item()
Example #33
0
def get_anchor_pt(p0, p1, t0, t1, r0, r1):
    jnc_cntr, jnc_radius = get_junction_circle(p0, p1, t0, t1)
    if -1 == jnc_radius:
        # Straight line - "infinite" circle
        anchor_pt = (p0 + p1) / 2.
    else:
        aux_start = get_auxiliary_pt(p0, t0, r0, jnc_cntr, jnc_radius, p1)
        aux_end = get_auxiliary_pt(p1, t1, r1, jnc_cntr, jnc_radius, p0)
        aux_mid_pt = (aux_start + aux_end) / 2.
        if aux_mid_pt.distance(jnc_cntr) < 0.0001:
            # half a circle. Give the preference to p0
            assert abs(aux_mid_pt.distance(aux_start) - jnc_radius) < 0.0001
            diameter_line = Line(aux_start, aux_end)
            bisec_radius_vec = diameter_line.perpendicular_line(
                jnc_cntr).direction.unit
            anch_pt_1 = jnc_cntr + bisec_radius_vec * jnc_radius
            anch_pt_2 = jnc_cntr - bisec_radius_vec * jnc_radius
            test_pt = p0 + t0
            closest_cand = get_closest_pt(anch_pt_1, anch_pt_2, test_pt)
            if closest_cand == anch_pt_2:
                bisec_radius_vec = -bisec_radius_vec
        else:
            bisec_radius_vec = Line(jnc_cntr, aux_mid_pt).direction.unit
        anchor_pt = jnc_cntr + bisec_radius_vec * jnc_radius

        DEBUG = 'IN_DEBUG' in globals()
        if DEBUG and IN_DEBUG:
            crc = mpt.Circle(
                [float(aux_start.x), float(aux_start.y)],
                radius=float(0.1),
                color="#D4AC0D",
                fill=True)
            plt.gca().add_patch(crc)
            crc = mpt.Circle(
                [float(aux_end.x), float(aux_end.y)],
                radius=float(0.1),
                color="#D4AC0D",
                fill=True)
            plt.gca().add_patch(crc)
            crc = mpt.Circle(
                [float(anchor_pt.x), float(anchor_pt.y)],
                radius=float(0.1),
                color="#85929E",
                fill=True)
            plt.gca().add_patch(crc)

    return anchor_pt
Example #34
0
    def _select_optimal_threshold(self, thresholds: np.ndarray,
                                  spot_counts: List[int]) -> float:

        # calculate the gradient of the number of spots
        grad = np.gradient(spot_counts)
        self._grad = grad
        optimal_threshold_index = np.argmin(grad)

        # only consider thresholds > than optimal threshold
        thresholds = thresholds[optimal_threshold_index:]
        grad = grad[optimal_threshold_index:]

        # if all else fails, return 0.
        selected_thr = 0

        if len(thresholds) > 1:

            distances = []

            # create a line whose end points are the threshold and and corresponding gradient value
            # for spot_counts corresponding to the threshold
            start_point = Point(thresholds[0], grad[0])
            end_point = Point(thresholds[-1], grad[-1])
            line = Line(start_point, end_point)

            # calculate the distance between all points and the line
            for k in range(len(thresholds)):
                p = Point(thresholds[k], grad[k])
                dst = line.distance(p)
                distances.append(dst.evalf())

            # remove the end points
            thresholds = thresholds[1:-1]
            distances = distances[1:-1]

            # select the threshold that has the maximum distance from the line
            # if stringency is passed, select a threshold that is n steps higher, where n is the
            # value of stringency
            if distances:
                thr_idx = np.argmax(np.array(distances))

                if thr_idx + self.stringency < len(thresholds):
                    selected_thr = thresholds[thr_idx + self.stringency]
                else:
                    selected_thr = thresholds[thr_idx]

        return selected_thr
Example #35
0
def compute_distances_between_two_points_set(points1, points2) :
    index = 0
    distances = []
    i = 0
    li = []
    while i < len(points1):
        p1 = points1[i]
        if index >= len(points2) - 1: break
        line = Line(points2[index], points2[index + 1])
        pro = line.projection(p1)
        if is_projection_between_two_points(pro, points2[index], points2[index + 1]):
            distances.append(p1.distance(pro))
            li.append([p1, pro])
            index += 1
        else:
            if pro.distance(points2[index + 1]) < pro.distance(points2[index]):
                i -= 1
                index += 1
        i += 1
    return distances, li
Example #36
0
def demonstrate_circle_power(circle):
    """Demonstrate power-of-a-point theorem."""

    A, B, C, D = (circle.random_point() for i in range(4))
    P = Line.intersection(Line(A, B), Line(C, D))
    assert len(P) == 1
    P = P[0]

    PAPB = P.distance(A) * P.distance(B)
    PCPD = P.distance(C) * P.distance(D)

    print("PA * PB =", PAPB.evalf())
    print("PC * PD =", PCPD.evalf())
Example #37
0
    def triangulate(self, vertex):
        others = [0, 1, 2, 0, 1]
        others = others[(vertex + 1):(vertex + 3)]
        segment = Segment(self.triangle[others[0]], self.triangle[others[1]])
        vertex_str = 'h' + str(vertex)
        segment_heights_str = ['h' + str(other) for other in others]

        new_points = []
        counter = 2

        for line in self.polygon_lines:
            perp = line.perpendicular_line(Point2D(self.triangle[vertex][0],
                                                   self.triangle[vertex][1]))
            intersections = perp.intersection(segment)

            if len(intersections) > 0:
                counter = counter + 1
                new_points.append(Point3D(intersections[0].x,
                                          intersections[0].y,
                                          'h' + str(counter)))

        no_vars = counter + 1
        all_side_points = [Point3D(segment.points[0][0],
                                   segment.points[0][1],
                                   segment_heights_str[0])] + new_points + \
                          [Point3D(segment.points[1][0],
                                   segment.points[1][1],
                                   segment_heights_str[1])]
        all_pairs = zip(all_side_points, all_side_points[1:])

        h_coefs = matrix(0.0, (len(all_pairs) * len(self.polygon), no_vars))
        rhs_coefs = []

        for (idx1, pair) in enumerate(all_pairs):
            # Compute gradient for each triangulation.
            gradient = compute_plane_gradient(
                Point3D(self.triangle[vertex][0], self.triangle[vertex][1], vertex_str),
                        pair[0],
                        pair[1])

            heights_str = [str(pair[0][2]), str(pair[1][2])]
            hs = [int(heights_str[0][1:]), int(heights_str[1][1:])]

            # Ensure that each gradient is with the convex polygon.
            for (idx2, (prev_point, curr_point, next_point)) in enumerate(self.adj_polygon_points):
                line = Line(Point2D(next_point), Point2D(curr_point))
                line_equation_poly = poly(str(line.equation()), gens=sp.symbols(['x', 'y']))
                # Flip equation if necessary.
                if line_equation_poly.eval(prev_point) > 0:
                    line_equation_poly = -line_equation_poly

                gradient_poly = poly(str(line_equation_poly.eval(gradient)),
                                     gens=sp.symbols([vertex_str, heights_str[0], heights_str[1]]))

                row = idx1 * len(self.polygon) + idx2
                h_coefs[row, 0] = float(gradient_poly.diff(vertex_str).eval((0, 0, 0)))
                h_coefs[row, hs[0]] = float(gradient_poly.diff(heights_str[0]).eval((0, 0, 0)))
                h_coefs[row, hs[1]] = float(gradient_poly.diff(heights_str[1]).eval((0, 0, 0)))
                rhs_coefs.append(-float(gradient_poly.eval((0, 0, 0))))

        ones = [1.0] * no_vars

        # Final LP Problem.
        # Objective function.
        objective_function_vector = matrix(ones)

        # Coefficient matrix.
        ones_matrix = spmatrix(ones, range(no_vars), range(no_vars))
        heights_coef_matrix = h_coefs
        bounds_coef_matrix = matrix([ones_matrix, -ones_matrix])
        coef_matrix = sparse([heights_coef_matrix, bounds_coef_matrix])

        # Column vector of right hand sides.
        column_vector = matrix(rhs_coefs + \
                               [self.bounds[1]] * no_vars + [-self.bounds[0]] * no_vars)

        min_sol = solvers.lp(objective_function_vector, coef_matrix, column_vector)
        is_consistent = min_sol['x'] is not None

        if is_consistent:
            self.min_heights = np.array(min_sol['x'])
            print np.around(self.min_heights, decimals=2)

            max_sol = solvers.lp(-objective_function_vector, coef_matrix, column_vector)
            self.max_heights = np.array(max_sol['x'])
            print np.around(self.max_heights, decimals=2)

        return is_consistent
Example #38
0
    def solveLP(self):
        # Check simple case when gradient of plane is contained within the convex polygon.
        gradient = compute_plane_gradient(Point3D(self.triangle[0][0], self.triangle[0][1], 'h0'),
                                          Point3D(self.triangle[1][0], self.triangle[1][1], 'h1'),
                                          Point3D(self.triangle[2][0], self.triangle[2][1], 'h2'))

        # Get all adjacent pairs of points that make up all sides of the polygon.
        self.adj_polygon_points = zip(*[[self.polygon[-1]] + self.polygon[:-1],
                                              self.polygon,
                                              self.polygon[1:] + [self.polygon[0]]])

        # Vectors of coefficients.
        (h1_coefs, h2_coefs, h3_coefs, rhs_coefs) = ([], [], [], [])

        for (prev_point, curr_point, next_point) in self.adj_polygon_points:
            # Choose clockwise order when constructing line of eq. a x + b y + c = 0 from 2 given
            # points. Then the semi-plane containing the convex polygon will be given by:
            # a x + b y + c <= 0.
            line = Line(Point2D(next_point), Point2D(curr_point))
            self.polygon_lines.append(line)

            line_equation_poly = poly(str(line.equation()), gens=sp.symbols(['x', 'y']))

            # Check if a x + b y + c <= 0 holds; if not, flip the line equation -- critical step!
            if line_equation_poly.eval(prev_point) > 0:
                line_equation_poly = -line_equation_poly

            gradient_poly = poly(str(line_equation_poly.eval(gradient)),
                                 gens=sp.symbols(['h0', 'h1', 'h2']))

            h1_coefs.append(float(gradient_poly.diff('h0').eval((0, 0, 0))))
            h2_coefs.append(float(gradient_poly.diff('h1').eval((0, 0, 0))))
            h3_coefs.append(float(gradient_poly.diff('h2').eval((0, 0, 0))))
            rhs_coefs.append(-float(gradient_poly.eval((0, 0, 0))))

        # Construct LP problem.
        # Objective function: Minimise/Maximise h1 + h2 + h3
        objective_function_vector = matrix([1.0, 1.0, 1.0])

        # Coefficient matrix.
        ones_matrix = spmatrix([1.0, 1.0, 1.0], range(3), range(3))
        heights_coef_matrix = matrix([h1_coefs, h2_coefs, h3_coefs])
        bounds_coef_matrix = matrix([ones_matrix, -ones_matrix])
        coef_matrix = sparse([heights_coef_matrix, bounds_coef_matrix])

        # Column vector of right hand sides.
        column_vector = matrix(rhs_coefs + [self.bounds[1]] * 3 + [-self.bounds[0]] * 3)

        min_sol = solvers.lp(objective_function_vector, coef_matrix, column_vector)
        is_consistent = min_sol['x'] is not None

        if is_consistent:
            self.min_heights = np.array(min_sol['x'])
            print np.around(self.min_heights, decimals=2)

            max_sol = solvers.lp(-objective_function_vector, coef_matrix, column_vector)
            self.max_heights = np.array(max_sol['x'])
            print np.around(self.max_heights, decimals=2)
        else:
            # Try to determine triangulation of the given triangle.
            print "Triangulating..."

            # Perform triangulation w.r.t to a fixed vertex.
            return self.triangulate(0) or self.triangulate(1) or self.triangulate(2)
Example #39
0
from sympy import Point, Line, Segment
p1, p2, p3 = Point(0, 0), Point(1, 1), Point(1, 2)
l1 = Line(p1, p2)

print l1.contains(Point(-1,-1))
print l1.contains(Point(1,1))

print l1.contains(Point(0.1,0.1))
Example #40
0
def find_left_and_right_points_on_lines_from_corners(corners, mat_size):
    corners_tmp = deque(list(map(lambda x: list(map(lambda y: int(y), x)), corners)))
    assert (len(corners_tmp) == 4)
    left_top_c_id = 0
    for c_id, c in enumerate(corners_tmp):
        if c[1] < corners_tmp[left_top_c_id][1]:
            left_top_c_id = c_id
        elif c[1] == corners_tmp[left_top_c_id][1] and c[0] < corners[left_top_c_id][0]:
            left_top_c_id = c_id
    corners = deque([])
    for i in list(range(left_top_c_id, len(corners_tmp))) + list(range(0, left_top_c_id)):
        corners.append(corners_tmp[i])
    left_corners, right_corners = deque([]), deque([])
    if corners[0][1] == corners[1][1]:
        left_corners.append(corners[0])
        right_corners.append(corners[1])
    elif corners[0][1] < corners[1][1]:
        left_corners.append(corners[0])
        right_corners.append(corners[0])
        right_corners.append(corners[1])
    else:
        left_corners.append(corners[1])
        left_corners.append(corners[0])
        right_corners.append(corners[1])
    if corners[2][1] == corners[3][1]:
        right_corners.append(corners[2])
        left_corners.append(corners[3])
    elif corners[2][1] < corners[3][1]:
        left_corners.append(corners[3])
        right_corners.append(corners[2])
        right_corners.append(corners[3])
    else:
        left_corners.append(corners[3])
        left_corners.append(corners[2])
        right_corners.append(corners[2])

    left_corners = find_valid_corners(mat_size, left_corners)
    right_corners = find_valid_corners(mat_size, right_corners)

    if not (left_corners and right_corners):
        return []
    assert (left_corners[0][1] == right_corners[0][1])

    left1 = left_corners.popleft()
    left2 = left_corners.popleft()
    left_line = Line(left1, left2)

    right1 = right_corners.popleft()
    right2 = right_corners.popleft()
    right_line = Line(right1, right2)

    pts_on_lines = []  # y, left_x, right_x
    curr_y = left1[1]
    while True:
        if curr_y > left2[1]:
            if not left_corners:
                break
            else:
                left1 = left2
                left2 = left_corners.popleft()
                left_line = Line(left1, left2)
        if curr_y > right2[1]:
            if not right_corners:
                break
            else:
                right1 = right2
                right2 = right_corners.popleft()
                right_line = Line(right1, right2)
        hor_line_with_curr_y = Line(Point(0, curr_y), Point(100, curr_y))
        temp_pt = left_line.intersection(hor_line_with_curr_y)
        left_cross = temp_pt[0]
        left_x = 0 if left_cross.x < 0 else (left_cross.x if left_cross.x < mat_size[0] else (mat_size[0] - 1))
        temp_pt = right_line.intersection(hor_line_with_curr_y)
        right_cross = temp_pt[0]
        right_x = 0 if right_cross.x < 0 else (right_cross.x if right_cross.x < mat_size[0] else (mat_size[0] - 1))
        pts_on_lines.append((curr_y, int(left_x), int(right_x)))
        curr_y += 1
    return pts_on_lines
Example #41
0
from sympy import Line, Point
f=open('D:\UVA\Python\Q378.txt','r')
while f:
	a=f.readline().strip().split(' ')
	if a ==['']:
		break
	p1,p2,p3,p4=Point(int(a[0]),int(a[1])),Point(int(a[2]),int(a[3])),Point(int(a[4]),int(a[5])),Point(int(a[6]),int(a[7]))
	l1=Line(p1,p2)
	l2=Line(p3,p4)



	if l1.is_similar(l2):
		print("LINE")
	elif Line.is_parallel(l1,l2):
		print("NONE")
	elif Line.are_concurrent(l1,l2):
		smaepoint= l1.intersection(l2)
		print("POINT %.2f %.2f " %(smaepoint[0].x,smaepoint[0].y))
	
print("END OF OUTPUT")