Exemplo n.º 1
0
    def __add__(self, other):
        """Add other to self by incrementing self's coordinates by those of other.

        See Also
        ========

        sympy.geometry.entity.translate

        """

        if isinstance(other, Point):
            if len(other.args) == len(self.args):
                return Point(
                    *[simplify(a + b) for a, b in zip(self.args, other.args)])
            else:
                raise TypeError(
                    "Points must have the same number of dimensions")
        else:
            raise ValueError('Cannot add non-Point, %s, to a Point' % other)
Exemplo n.º 2
0
Arquivo: point.py Projeto: xrmx/sympy
    def affine_rank(*args):
        """The affine rank of a set of points is the dimension
        of the smallest affine space containing all the points.
        For example, if the points lie on a line (and are not all
        the same) their affine rank is 1.  If the points lie on a plane
        but not a line, their affine rank is 2.  By convention, the empty
        set has affine rank -1."""

        if len(args) == 0:
            return -1
        # make sure we're genuinely points
        # and translate every point to the origin
        points = Point._normalize_dimension(*[Point(i) for i in args])
        origin = points[0]
        points = [i - origin for i in points[1:]]

        m = Matrix([i.args for i in points])
        # XXX fragile -- what is a better way?
        return m.rank(iszerofunc=lambda x: abs(x.n(2)) < 1e-12
                      if x.is_number else x.is_zero)
Exemplo n.º 3
0
    def transform(self, matrix):
        """Return the point after applying the transformation described
        by the 3x3 Matrix, ``matrix``.

        See Also
        ========
        geometry.entity.rotate
        geometry.entity.scale
        geometry.entity.translate
        """
        try:
            col, row = matrix.shape
            valid_matrix = matrix.is_square and col == 3
        except AttributeError:
            # We hit this block if matrix argument is not actually a Matrix.
            valid_matrix = False
        if not valid_matrix:
            raise ValueError("The argument to the transform function must be " \
            + "a 3x3 matrix")
        x, y = self.args
        return Point(*(Matrix(1, 3, [x, y, 1])*matrix).tolist()[0][:2])
Exemplo n.º 4
0
    def intersection(self, other):
        """The intersection between this point and another GeometryEntity.

        Parameters
        ==========

        other : Point

        Returns
        =======

        intersection : list of Points

        Notes
        =====

        The return value will either be an empty list if there is no
        intersection, otherwise it will contain this point.

        Examples
        ========

        >>> from sympy import Point
        >>> p1, p2, p3 = Point(0, 0), Point(1, 1), Point(0, 0)
        >>> p1.intersection(p2)
        []
        >>> p1.intersection(p3)
        [Point2D(0, 0)]

        """
        if not isinstance(other, GeometryEntity):
            other = Point(other)
        if isinstance(other, Point):
            if self == other:
                return [self]
            p1, p2 = Point._normalize_dimension(self, other)
            if p1 == self and p1 == p2:
                return [self]
            return []
        return other.intersection(self)
Exemplo n.º 5
0
def Tangent_lines(circle_C, point_P):
    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))
    radian_half = np.arccos(cos)

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

    tangent_angle2 = circle_point_angle - radian_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))]
Exemplo n.º 6
0
    def translate(self, x=0, y=0):
        """Shift the Point by adding x and y to the coordinates of the Point.

        See Also
        ========

        rotate, scale

        Examples
        ========

        >>> from sympy import Point
        >>> t = Point(0, 1)
        >>> t.translate(2)
        Point(2, 1)
        >>> t.translate(2, 2)
        Point(2, 3)
        >>> t + Point(2, 2)
        Point(2, 3)

        """
        return Point(self.x + x, self.y + y)
Exemplo n.º 7
0
    def rotate(self, angle, pt=None):
        """Rotate the object about pt by the given angle (in radians).

        The default pt is the origin, Point(0, 0)

        XXX geometry needs a modify_points method which operates
        on only the points of the object

        >>> from sympy import Point, RegularPolygon, Polygon, pi
        >>> t = Polygon(*RegularPolygon(Point(0, 0), 1, 3).vertices)
        >>> t # vertex on x axis
        Triangle(Point(1, 0), Point(-1/2, sqrt(3)/2), Point(-1/2, -sqrt(3)/2))
        >>> t.rotate(pi/2) # vertex on y axis now
        Triangle(Point(0, 1), Point(-sqrt(3)/2, -1/2), Point(sqrt(3)/2, -1/2))

        """
        from sympy import cos, sin, Point

        c = cos(angle)
        s = sin(angle)

        if isinstance(self, Point):
            rv = self
            if pt is not None:
                rv -= pt
            x, y = rv
            rv = Point(c * x - s * y, s * x + c * y)
            if pt is not None:
                rv += pt
            return rv

        newargs = []
        for a in self.args:
            if isinstance(a, GeometryEntity):
                newargs.append(a.rotate(angle, pt))
            else:
                newargs.append(a)
        return type(self)(*newargs)
Exemplo n.º 8
0
    def scale(self, x=1, y=1):
        """Scale the object by multiplying the x,y-coordinates by x and y.

        >>> from sympy import RegularPolygon, Point, Polygon
        >>> t = Polygon(*RegularPolygon(Point(0, 0), 1, 3).vertices)
        >>> t
        Triangle(Point(1, 0), Point(-1/2, sqrt(3)/2), Point(-1/2, -sqrt(3)/2))
        >>> t.scale(2)
        Triangle(Point(2, 0), Point(-1, sqrt(3)/2), Point(-1, -sqrt(3)/2))
        >>> t.scale(2,2)
        Triangle(Point(2, 0), Point(-1, sqrt(3)), Point(-1, -sqrt(3)))

        """
        from sympy import Point
        if isinstance(self, Point):
            return Point(self[0] * x, self[1] * y)
        newargs = []
        for a in self.args:
            if isinstance(a, GeometryEntity):
                newargs.append(a.scale(x, y))
            else:
                newargs.append(a)
        return type(self)(*newargs)
Exemplo n.º 9
0
    def _collect_shapes(self, d, materials):
        """
        Collect and instantiate the dictionary stored in the shapes attribute
        given a dictionary describing the shapes in the layer
        """

        shapes = OrderedDict()
        sorted_d = OrderedDict(
            sorted(d.items(), key=lambda tup: tup[1]['order']))
        for name, data in sorted_d.items():
            shape = data['type'].lower()
            if shape == 'circle':
                center = Point(data['center']['x'], data['center']['y'])
                radius = data['radius']
                material = data['material']
                if material not in self.materials:
                    self.materials[material] = materials[material]
                shape_obj = Circle(center, radius)
            else:
                raise NotImplementedError('Can only handle circles right now')
            shapes[name] = (shape_obj, material)
        self.shapes = shapes
        return shapes
Exemplo n.º 10
0
    def is_collinear(self, *args):
        """Returns `True` if there exists a line
        that contains `self` and `points`.  Returns `False` otherwise.
        A trivially True value is returned if no points are given.

        Parameters
        ==========

        args : sequence of Points

        Returns
        =======

        is_collinear : boolean

        See Also
        ========

        sympy.geometry.line.Line

        Examples
        ========

        >>> from sympy import Point
        >>> from sympy.abc import x
        >>> p1, p2 = Point(0, 0), Point(1, 1)
        >>> p3, p4, p5 = Point(2, 2), Point(x, x), Point(1, 2)
        >>> Point.is_collinear(p1, p2, p3, p4)
        True
        >>> Point.is_collinear(p1, p2, p3, p5)
        False

        """
        points = (self,) + args
        points = Point._normalize_dimension(*[Point(i) for i in points])
        points = list(uniq(points))
        return Point.affine_rank(*points) <= 1
Exemplo n.º 11
0
    def intersection(self, other):
        """The intersection between this point and another GeometryEntity.

        Parameters
        ==========

        other : GeometryEntity or sequence of coordinates

        Returns
        =======

        intersection : list of Points

        Notes
        =====

        The return value will either be an empty list if there is no
        intersection, otherwise it will contain this point.

        Examples
        ========

        >>> from sympy import Point3D
        >>> p1, p2, p3 = Point3D(0, 0, 0), Point3D(1, 1, 1), Point3D(0, 0, 0)
        >>> p1.intersection(p2)
        []
        >>> p1.intersection(p3)
        [Point3D(0, 0, 0)]

        """
        if not isinstance(other, GeometryEntity):
            other = Point(other, dim=3)
        if isinstance(other, Point3D):
            if self == other:
                return [self]
            return []
        return other.intersection(self)
Exemplo n.º 12
0
def enclosing_circle(P: [Point]):
    C_min = Circle(Point(250, 250), 10000)
    
    # Two points
    for a in P:
        for b in P:
            if b == a:
                continue
            C = get_circle(a, b)
            for d in P:
                if d == b or d == a:
                    continue
                if not C.encloses_point(d):
                    break
            else:
                if C.radius < C_min.radius:
                    C_min = C
    
    # Three points
    for a in P:
        for b in P:
            if b == a:
                continue
            for c in P:
                if c == a or c == b:
                    continue
                C = Circle(a, b, c)
                for d in P:
                    if d == a or d == b or d == c:
                        continue
                    if not C.encloses_point(d):
                        break
                else:
                    if C.radius < C_min.radius:
                        C_min = C
    
    return C_min
Exemplo n.º 13
0
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 + 5)

        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
Exemplo n.º 14
0
 def __mul__(self, factor):
     """Multiply point's coordinates by a factor."""
     factor = sympify(factor)
     return Point([x * factor for x in self.args])
Exemplo n.º 15
0
 def dot(self, p2):
     """Return dot product of self with another Point."""
     p2 = Point(p2)
     x1, y1 = self.args
     x2, y2 = p2.args
     return x1 * x2 + y1 * y2
Exemplo n.º 16
0
    def is_concyclic(*points):
        """Is a sequence of points concyclic?

        Test whether or not a sequence of points are concyclic (i.e., they lie
        on a circle).

        Parameters
        ==========

        points : sequence of Points

        Returns
        =======

        is_concyclic : boolean
            True if points are concyclic, False otherwise.

        See Also
        ========

        sympy.geometry.ellipse.Circle

        Notes
        =====

        No points are not considered to be concyclic. One or two points
        are definitely concyclic and three points are conyclic iff they
        are not collinear.

        For more than three points, create a circle from the first three
        points. If the circle cannot be created (i.e., they are collinear)
        then all of the points cannot be concyclic. If the circle is created
        successfully then simply check the remaining points for containment
        in the circle.

        Examples
        ========

        >>> from sympy.geometry import Point
        >>> p1, p2 = Point(-1, 0), Point(1, 0)
        >>> p3, p4 = Point(0, 1), Point(-1, 2)
        >>> Point.is_concyclic(p1, p2, p3)
        True
        >>> Point.is_concyclic(p1, p2, p3, p4)
        False

        """
        if len(points) == 0:
            return False
        if len(points) <= 2:
            return True
        points = [Point(p) for p in points]
        if len(points) == 3:
            return (not Point.is_collinear(*points))

        try:
            from .ellipse import Circle
            c = Circle(points[0], points[1], points[2])
            for point in points[3:]:
                if point not in c:
                    return False
            return True
        except GeometryError:
            # Circle could not be created, because of collinearity of the
            # three points passed in, hence they are not concyclic.
            return False
Exemplo n.º 17
0
    def is_collinear(*points):
        """Is a sequence of points collinear?

        Test whether or not a set of points are collinear. Returns True if
        the set of points are collinear, or False otherwise.

        Parameters
        ==========

        points : sequence of Point

        Returns
        =======

        is_collinear : boolean

        Notes
        =====

        Slope is preserved everywhere on a line, so the slope between
        any two points on the line should be the same. Take the first
        two points, p1 and p2, and create a translated point v1
        with p1 as the origin. Now for every other point we create
        a translated point, vi with p1 also as the origin. Note that
        these translations preserve slope since everything is
        consistently translated to a new origin of p1. Since slope
        is preserved then we have the following equality:

              * v1_slope = vi_slope
              * v1.y/v1.x = vi.y/vi.x (due to translation)
              * v1.y*vi.x = vi.y*v1.x
              * v1.y*vi.x - vi.y*v1.x = 0           (*)

        Hence, if we have a vi such that the equality in (*) is False
        then the points are not collinear. We do this test for every
        point in the list, and if all pass then they are collinear.

        See Also
        ========

        sympy.geometry.line.Line

        Examples
        ========

        >>> from sympy import Point
        >>> from sympy.abc import x
        >>> p1, p2 = Point(0, 0), Point(1, 1)
        >>> p3, p4, p5 = Point(2, 2), Point(x, x), Point(1, 2)
        >>> Point.is_collinear(p1, p2, p3, p4)
        True
        >>> Point.is_collinear(p1, p2, p3, p5)
        False

        """
        # Coincident points are irrelevant and can confuse this algorithm.
        # Use only unique points.
        points = list(set(points))
        if not all(isinstance(p, Point) for p in points):
            raise TypeError('Must pass only Point objects')

        if len(points) == 0:
            return False
        if len(points) <= 2:
            return True  # two points always form a line
        points = [Point(a) for a in points]

        # XXX Cross product is used now, but that only extends to three
        #     dimensions. If the concept needs to extend to greater
        #     dimensions then another method would have to be used
        p1 = points[0]
        p2 = points[1]
        v1 = p2 - p1
        x1, y1 = v1.args
        rv = True
        for p3 in points[2:]:
            x2, y2 = (p3 - p1).args
            test = simplify(x1 * y2 - y1 * x2).equals(0)
            if test is False:
                return False
            if rv and not test:
                rv = test
        return rv
Exemplo n.º 18
0
def intersects_ellipse(ob, major, minor, tip, tip_r, tip_r2):
    """
    Calculates the intersection of an ellipse and two circles
    (representing the tip) with different radii
    Args:
        major: major axis of the ellipse
        minor: minor axis of the ellipse
        tip: position of the circles (one for both)
        tip_r: first radius
        tip_r2: second (bigger) radius
    """
    # check if there is any chance of contact
    if tip[0] + tip_r2 < - major:
        # the tip's maximum x is below the object's minimum x
        return [np.zeros((2, 1), dtype=np.float32),
                np.zeros((2, 1), dtype=np.float32)]
    elif tip[0] - tip_r2 > major:
        # the tip's minimum x is above the object's maximum x
        return [np.zeros((2, 1), dtype=np.float32),
                np.zeros((2, 1), dtype=np.float32)]
    elif tip[1] + tip_r2 < - minor:
        # the tip's maximum y is below the object's minimum y
        return [np.zeros((2, 1), dtype=np.float32),
                np.zeros((2, 1), dtype=np.float32)]
    elif tip[1] - tip_r2 > minor:
        # the tip's minimum y is above the object's maximum y
        return [np.zeros((2, 1), dtype=np.float32),
                np.zeros((2, 1), dtype=np.float32)]

    # try with the bigger probe
    tp = Circle(Point(tip[0], tip[1]), tip_r2)
    if '1' in ob:
        cps = ellip1.intersection(tp)
    elif '2' in ob:
        cps = ellip2.intersection(tp)
    elif '3' in ob:
        cps = ellip3.intersection(tp)
    count = 0.
    avg = np.zeros((2, 1), dtype=np.float32)
    for cp in cps:
        c = np.zeros((2, 1), dtype=np.float32)
        c[0] = cp.x
        c[1] = cp.y
        count += 1
        avg += c

    if count != 0:
        contact2 = avg / count
    else:
        contact2 = avg

    # only check the smaller one if the bigger radius had a contact
    if np.linalg.norm(contact2) > 0:
        tp = Circle(Point(tip[0], tip[1]), tip_r)
        if '1' in ob:
            cps = ellip1.intersection(tp)
        elif '2' in ob:
            cps = ellip2.intersection(tp)
        elif '3' in ob:
            cps = ellip3.intersection(tp)
        count = 0.
        avg = np.zeros((2, 1), dtype=np.float32)
        for cp in cps:
            c = np.zeros((2, 1), dtype=np.float32)
            c[0] = cp.x
            c[1] = cp.y
            count += 1
            avg += c

        if count != 0:
            contact1 = avg / count
        else:
            contact1 = avg
    else:
        contact1 = np.zeros((2, 1), dtype=np.float32)

    return [contact1, contact2]
Exemplo n.º 19
0
from sympy import Point, Circle, Line, var
import matplotlib.pyplot as plt

var('t')

c1 = Circle(Point(0, 0), 2)
c2 = Circle(Point(4, 4), 3)
l1 = Line(c1.center, c2.center)
p1 = l1.arbitrary_point(t).subs({t: -c1.radius / (c2.radius - c1.radius)})
p2 = l1.arbitrary_point(t).subs({t:  c1.radius / (c1.radius + c2.radius)})
t1 = c1.tangent_lines(p1)
t2 = c1.tangent_lines(p2)
ta = t1 + t2

fig = plt.gcf()
ax = fig.gca()
ax.set_xlim((-10, 10))
ax.set_ylim((-10, 10))
ax.set_aspect(1)

cp1 = plt.Circle((c1.center.x, c1.center.y), c1.radius, fill = False)
cp2 = plt.Circle((c2.center.x, c2.center.y), c2.radius, fill = False)
tp = [0 for i in range(4)]
for i in range(4):
    start = ta[i].arbitrary_point(t).subs({t:-10})
    end = ta[i].arbitrary_point(t).subs({t:10})
    tp[i] = plt.Line2D([start.x, end.x], [start.y, end.y], lw = 2)

ax.add_artist(cp1)
ax.add_artist(cp2)
Exemplo n.º 20
0
def test_parabola_intersection():
    l1 = Line(Point(1, -2), Point(-1,-2))
    l2 = Line(Point(1, 2), Point(-1,2))
    l3 = Line(Point(1, 0), Point(-1,0))

    p1 = Point(0,0)
    p2 = Point(0, -2)
    p3 = Point(120, -12)
    parabola1 = Parabola(p1, l1)

    # parabola with parabola
    assert parabola1.intersection(parabola1) == [parabola1]
    assert parabola1.intersection(Parabola(p1, l2)) == [Point2D(-2, 0), Point2D(2, 0)]
    assert parabola1.intersection(Parabola(p2, l3)) == [Point2D(0, -1)]
    assert parabola1.intersection(Parabola(Point(16, 0), l1)) == [Point2D(8, 15)]
    assert parabola1.intersection(Parabola(Point(0, 16), l1)) == [Point2D(-6, 8), Point2D(6, 8)]
    assert parabola1.intersection(Parabola(p3, l3)) == []
    # parabola with point
    assert parabola1.intersection(p1) == []
    assert parabola1.intersection(Point2D(0, -1)) == [Point2D(0, -1)]
    assert parabola1.intersection(Point2D(4, 3)) == [Point2D(4, 3)]
    # parabola with line
    assert parabola1.intersection(Line(Point2D(-7, 3), Point(12, 3))) == [Point2D(-4, 3), Point2D(4, 3)]
    assert parabola1.intersection(Line(Point(-4, -1), Point(4, -1))) == [Point(0, -1)]
    assert parabola1.intersection(Line(Point(2, 0), Point(0, -2))) == [Point2D(2, 0)]
    # parabola with segment
    assert parabola1.intersection(Segment2D((-4, -5), (4, 3))) == [Point2D(0, -1), Point2D(4, 3)]
    assert parabola1.intersection(Segment2D((0, -5), (0, 6))) == [Point2D(0, -1)]
    assert parabola1.intersection(Segment2D((-12, -65), (14, -68))) == []
    # parabola with ray
    assert parabola1.intersection(Ray2D((-4, -5), (4, 3))) == [Point2D(0, -1), Point2D(4, 3)]
    assert parabola1.intersection(Ray2D((0, 7), (1, 14))) == [Point2D(14 + 2*sqrt(57), 105 + 14*sqrt(57))]
    assert parabola1.intersection(Ray2D((0, 7), (0, 14))) == []
    # parabola with ellipse/circle
    assert parabola1.intersection(Circle(p1, 2)) == [Point2D(-2, 0), Point2D(2, 0)]
    assert parabola1.intersection(Circle(p2, 1)) == [Point2D(0, -1), Point2D(0, -1)]
    assert parabola1.intersection(Ellipse(p2, 2, 1)) == [Point2D(0, -1), Point2D(0, -1)]
    assert parabola1.intersection(Ellipse(Point(0, 19), 5, 7)) == []
    assert parabola1.intersection(Ellipse((0, 3), 12, 4)) == \
           [Point2D(0, -1), Point2D(0, -1), Point2D(-4*sqrt(17)/3, 59/9), Point2D(4*sqrt(17)/3, 59/9)]
Exemplo n.º 21
0
 def __abs__(self):
     """Returns the distance between this point and the origin."""
     origin = Point([0] * len(self.args))
     return Point.distance(origin, self)
Exemplo n.º 22
0
 def __div__(self, divisor):
     """Divide point's coordinates by a factor."""
     divisor = sympify(divisor)
     return Point([x / divisor for x in self.args])
Exemplo n.º 23
0
 def __neg__(self):
     """Negate the point."""
     return Point([-x for x in self.args])
def createallwaypoint(rboundary, inputwidth):
    bounds = rboundary.bounds
    cutnum = float(
        math.ceil(
            round((round(bounds[2], 6) - round(bounds[0], 6)) / inputwidth,
                  6)))
    width = (round(bounds[2], 6) - round(bounds[0], 6)) / cutnum
    cutpos = np.arange(bounds[0] + width, bounds[2] + width, width)
    pointpos = np.arange(bounds[0] + width / 2, bounds[2] + width / 2, width)
    cutlines = formperpenicularlines(cutpos)
    #form sub-polygons cut by cutlines
    subpolygons = []
    remain = rboundary
    for line in cutlines:
        subpolygon, remain = splitpolygon(remain, line)
        subpolygons.append(subpolygon)
        if not (remain):
            break
    #design waypoints in subpolygons
    i = 0
    waypoints = []
    for polygon in subpolygons:
        sides = polygon.sides
        vertices = polygon.vertices
        lines = []
        lineindex = []
        j = 0
        for side in sides:
            if (side.is_parallel(yaxis)):
                lineindex.append(j)
                lines.append(side)
            j = j + 1
        waypoint = []
        if (len(lines) == 2):  #formed by 2 cuts
            #seprate vertices into upper part and lower part
            if (lines[0].p1.x < lines[1].p1.x):
                leftupindex = lineindex[0]
                leftdownindex = (lineindex[0] + 1) % len(vertices)
                rightupindex = (lineindex[1] + 1) % len(vertices)
                rightdownindex = lineindex[1]
            else:
                rightdownindex = lineindex[0]
                rightupindex = (lineindex[0] + 1) % len(vertices)
                leftdownindex = (lineindex[1] + 1) % len(vertices)
                leftupindex = lineindex[1]
            if (rightupindex < leftupindex):
                uppoints = list(vertices[rightupindex:leftupindex + 1])
            else:
                uppoints = list(vertices[rightupindex:len(vertices)])
                uppoints.extend(vertices[0:leftupindex + 1])
            if (leftdownindex < rightdownindex):
                downpoints = list(vertices[leftdownindex:rightdownindex + 1])
            else:
                downpoints = list(vertices[leftdownindex:len(vertices)])
                downpoints.extend(vertices[0:leftupindex + 1])
            upindex = findbound(uppoints)
            downindex = findbound(downpoints)
            upmin = uppoints[upindex[1]].y  #ymin
            upmax = uppoints[upindex[3]].y  #ymax
            downmin = downpoints[downindex[1]].y
            downmax = downpoints[downindex[3]].y
            if (upmax - downmin <= width):
                waypoint.append(Point(pointpos[i], (upmax + downmin) / 2))
            else:
                if (upmax - upmin <= width / 2):
                    waypoint.append(Point(pointpos[i], upmax - width / 2))
                else:
                    cutpt = Point(pointpos[i], upmax - width / 2)
                    cut = yaxis.perpendicular_line(cutpt)
                    crosspoint = polygon.intersection(cut)
                    if (crosspoint[0].x < crosspoint[1].x):
                        leftcross = crosspoint[0]
                        rightcross = crosspoint[1]
                    else:
                        leftcross = crosspoint[1]
                        rightcross = crosspoint[0]
                    if (leftcross.x <= pointpos[i]
                            and rightcross.x >= pointpos[i]):
                        waypoint.append(Point(pointpos[i], upmax - width / 2))
                    elif (leftcross.x > pointpos[i]):
                        waypoint.append(leftcross)
                        if (upmin - downmax <= width):
                            waypoint.append(
                                Point(pointpos[i], (upmin + downmax) / 2))
                        else:
                            waypoint.append(
                                Point(pointpos[i], upmin - width / 2))
                    else:
                        waypoint.append(rightcross)
                        if (upmin - downmax <= width):
                            waypoint.append(
                                Point(pointpos[i], (upmin + downmax) / 2))
                        else:
                            waypoint.append(
                                Point(pointpos[i], upmin - width / 2))
                if (downmax - downmin <= width / 2):
                    waypoint.append(Point(pointpos[i], downmin + width / 2))
                else:
                    cutpt = Point(pointpos[i], downmin + width / 2)
                    cut = yaxis.perpendicular_line(cutpt)
                    crosspoint = polygon.intersection(cut)
                    if (crosspoint[0].x < crosspoint[1].x):
                        leftcross = crosspoint[0]
                        rightcross = crosspoint[1]
                    else:
                        leftcross = crosspoint[1]
                        rightcross = crosspoint[0]
                    if (leftcross.x <= pointpos[i]
                            and rightcross.x >= pointpos[i]):
                        waypoint.append(Point(pointpos[i],
                                              downmin + width / 2))
                    elif (leftcross.x > pointpos[i]):
                        if (upmin - downmax <= width):
                            waypoint.append(
                                Point(pointpos[i], (upmin + downmax) / 2))
                        else:
                            waypoint.append(
                                Point(pointpos[i], downmax + width / 2))
                        waypoint.append(leftcross)
                    else:
                        if (upmin - downmax <= width):
                            waypoint.append(
                                Point(pointpos[i], (upmin + downmax) / 2))
                        else:
                            waypoint.append(
                                Point(pointpos[i], downmax + width / 2))
                        waypoint.append(rightcross)
        elif (len(lines) == 1):
            index = findbound(vertices)
            leftindex = index[0]
            line = lines[0]
            ymax = vertices[index[3]].y
            ymin = vertices[index[1]].y
            xmin = vertices[index[0]].x
            xmax = vertices[index[2]].x
            if (line.contains(vertices[leftindex])):  #cut line at left
                if (ymax - ymin <= width):
                    waypoint.append(Point(xmax - width / 2, (ymin + ymax) / 2))
                else:
                    upcutpt = Point(pointpos[i], ymax - width / 2)
                    upcut = yaxis.perpendicular_line(upcutpt)
                    downcutpt = Point(pointpos[i], ymin + width / 2)
                    downcut = yaxis.perpendicular_line(downcutpt)
                    rightcutpt = Point(xmax - width / 2, 0)
                    rightcut = xaxis.perpendicular_line(rightcutpt)
                    upcrosspoint = rightcut.intersection(upcut)
                    if (polygon.encloses_point(upcrosspoint[0])):
                        waypoint.append(upcrosspoint[0])
                    else:
                        crosspoint = polygon.intersection(upcut)
                        if (crosspoint[0].x < crosspoint[1].x):
                            waypoint.append(crosspoint[0])
                        else:
                            waypoint.append(crosspoint[1])
                        crosspoint = polygon.intersection(rightcut)
                        if (crosspoint[0].y > crosspoint[1].y):
                            uppt = crosspoint[0]
                            downpt = crosspoint[1]
                        else:
                            uppt = crosspoint[1]
                            downpt = crosspoint[0]
                        if ((uppt.y - downpt.y) <= width):
                            waypoint.append(Segment(uppt, downpt).midpoint)
                        else:
                            waypoint.append(Point(uppt.x, uppt.y - width / 2))
                    downcrosspoint = rightcut.intersection(downcut)
                    if (polygon.encloses_point(downcrosspoint[0])):
                        waypoint.append(downcrosspoint[0])
                    else:
                        crosspoint = polygon.intersection(rightcut)
                        if (crosspoint[0].y > crosspoint[1].y):
                            uppt = crosspoint[0]
                            downpt = crosspoint[1]
                        else:
                            uppt = crosspoint[1]
                            downpt = crosspoint[0]
                        if ((uppt.y - downpt.y) <= width):
                            waypoint.append(Segment(uppt, downpt).midpoint)
                        else:
                            waypoint.append(
                                Point(downpt.x, downpt.y + width / 2))
                        crosspoint = polygon.intersection(downcut)
                        if (crosspoint[0].x < crosspoint[1].x):
                            waypoint.append(crosspoint[0])
                        else:
                            waypoint.append(crosspoint[1])
            else:  #cut line at right
                if (ymax - ymin <= width):
                    waypoint = [Point(xmin + width / 2, (ymin + ymax) / 2)]
                else:
                    upcutpt = Point(pointpos[i], ymax - width / 2)
                    upcut = yaxis.perpendicular_line(upcutpt)
                    downcutpt = Point(pointpos[i], ymin + width / 2)
                    downcut = yaxis.perpendicular_line(downcutpt)
                    leftcutpt = Point(xmin + width / 2, 0)
                    leftcut = xaxis.perpendicular_line(leftcutpt)
                    upcrosspoint = leftcut.intersection(upcut)
                    if (polygon.encloses_point(upcrosspoint[0])):
                        waypoint.append(upcrosspoint[0])
                    else:
                        crosspoint = polygon.intersection(upcut)
                        if (crosspoint[0].x > crosspoint[1].x):
                            waypoint.append(crosspoint[0])
                        else:
                            waypoint.append(crosspoint[1])
                        crosspoint = polygon.intersection(leftcut)
                        if (crosspoint[0].y > crosspoint[1].y):
                            uppt = crosspoint[0]
                            downpt = crosspoint[1]
                        else:
                            uppt = crosspoint[1]
                            downpt = crosspoint[0]
                        if ((uppt.y - downpt.y) <= width):
                            waypoint.append(Segment(uppt, downpt).midpoint)
                        else:
                            waypoint.append(Point(uppt.x, uppt.y - width / 2))
                    downcrosspoint = leftcut.intersection(downcut)
                    if (polygon.encloses_point(downcrosspoint[0])):
                        waypoint.append(downcrosspoint[0])
                    else:
                        crosspoint = polygon.intersection(leftcut)
                        if (crosspoint[0].y > crosspoint[1].y):
                            uppt = crosspoint[0]
                            downpt = crosspoint[1]
                        else:
                            uppt = crosspoint[1]
                            downpt = crosspoint[0]
                        if ((uppt.y - downpt.y) <= width):
                            waypoint.append(Segment(uppt, downpt).midpoint)
                        else:
                            waypoint.append(
                                Point(downpt.x, downpt.y + width / 2))
                        crosspoint = polygon.intersection(downcut)
                        if (crosspoint[0].x > crosspoint[1].x):
                            waypoint.append(crosspoint[0])
                        else:
                            waypoint.append(crosspoint[1])
        else:  #width of the area less than sensor width
            bound = polygon.bounds
            if (bound[3] - bound[1] < width):
                waypoint = [Point(pointpos[i], (bound[1] + bound[3]) / 2)]
            else:
                ypos = np.array(bound[3] - width / 2, bound[1] + width / 2,
                                width)
                ypos = ypos.reshape(len(ypos), 1)
                waypoint = ypos.insert(0, pointpos[i], axis=1)
        i = i + 1
        if (i % 2 == 1):
            waypoint.reverse()
        waypoints.extend(waypoint)
    return waypoints
Exemplo n.º 25
0
def Dubins_msg(UAV, target, R0):
    # 单架无人机到达目标点所需时间
    #  这里的UAV和target是无人机和目标对象
    v = UAV.v  # 飞机速度
    phi0 = UAV.phi  # 转化为弧度,[0,2pi]

    UAV_p = Point(UAV.site)
    target_p = Point(target[0:2])

    # 以上为所有已知信息

    # 1. 求两个圆心,判断出采用哪一个圆
    # 2. 求切线
    # 3. 确定用那一段弧长

    # 1.求两个圆心,判断出采用哪一个圆
    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

    # 2. 求切线
    center = Point(round(center.x.evalf(), 4), round(center.y.evalf(), 4))
    circle = Circle(center, R0)
    # start=time.time()
    # tangent_lines = circle.tangent_lines(target_p)
    tangent_lines = Tangent_lines(circle, target_p)
    # end=time.time()
    # print(end-start)
    tangent_line1 = tangent_lines[0]  # 注意这里的切线方向是从target-> 切点
    tangent_line1 = Line(tangent_line1.p2, tangent_line1.p1)  # 改为从切点->target
    tangent_point1 = tangent_line1.p1  # 切点1
    y = float((target_p.y - tangent_point1.y).evalf())
    x = float((target_p.x - tangent_point1.x).evalf())
    tangent_angle1 = np.arctan2(y, x)  # arctan2(y,x) 向量(x,y)的角度[-pi,pi]

    tangent_line2 = tangent_lines[1]
    tangent_line2 = Line(tangent_line2.p2, tangent_line2.p1)  # 改为从切点->target
    tangent_point2 = tangent_line2.p1  # 切点2
    y = float((target_p.y - tangent_point2.y).evalf())
    x = float((target_p.x - tangent_point2.x).evalf())
    tangent_angle2 = np.arctan2(y, x)  # arctan2(y,x) 向量(x,y)的角度[-pi,pi]

    # 3. 确定用哪一段弧长
    # a. 确定用顺时针还是逆时针
    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])  # 1 表示逆时针 -1 表示顺时针
    # b. 判断是哪一个切点,哪一段弧
    sin1 = float(tangent_point1.distance(UAV_p).evalf()) / (2 * R0)
    angle1 = 2 * np.arcsin(sin1)  # 无人机位置与切点之间的弧度[0,pi] 小弧
    sin2 = float(tangent_point2.distance(UAV_p).evalf()) / (2 * R0)
    angle2 = 2 * np.arcsin(sin2)

    tangent_point = []
    hudu = 0

    # 判断式的意思  角度要在误差范围内相隔2kpi,使用modf(abs 把值控制在0-1之内,误差范围内靠近1,靠近0 都ok  用于0.5之间的距离来判断
    if abs(modf(abs(direction * angle1 + phi0 - tangent_angle1) / (2 * np.pi))[0] - 0.5) > 0.5 - deviation:
        tangent_point = tangent_point1
        hudu = angle1
    # modf 返回浮点数的小数部分和整数部分modf(1.23) return [0.23,1]
    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
        hudu = 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
        hudu = 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
        hudu = 2 * np.pi - angle2

    # 返回 旋转方向 弧度 切点坐标 圆心坐标
    return direction, hudu, (float(tangent_point.x.evalf()), float(tangent_point.y.evalf())), (
        float(center.x.evalf()), float(center.y.evalf()))
Exemplo n.º 26
0
from sympy import Point, Line

p1, p2 = Point(1000, 0), Point(10, 20)
l1 = Line(p1, p2)
print(l1.length)

time = '8:30 9:30'
time1 = '8:00 8:30'
time2 = '8:15 8:45'
time3 = '8:45 9:00'
time4 = '8:30 9:00'
time5 = '9:00 9:30'
time6 = '9:10 9:20'


def convert_to_min(time_string):
    t = time.split()
    l = []
    l1 = []
    for s in t:
        t1 = s.split(':')
        l.append(t1)
    enter_in_minutes = int(l[0][0]) * 60 + int(l[0][1])
    exit_in_minutes = int(l[1][0]) * 60 + int(l[1][1])
    for minute in range(enter_in_minutes, exit_in_minutes):
        l1.append(minute)
    return (l1)


all_times = [time1, time2, time3, time4, time5, time6]
Exemplo n.º 27
0
def test_parabola_geom():
    p1 = Point(0, 0)
    p2 = Point(3, 7)
    p3 = Point(0, 4)
    p4 = Point(6, 0)
    d1 = Line(Point(4, 0), Point(4, 9))
    d2 = Line(Point(7, 6), Point(3, 6))
    d3 = Line(Point(4, 0), slope=oo)
    d4 = Line(Point(7, 6), slope=0)

    half = Rational(1, 2)

    pa1 = Parabola(None, d2)
    pa2 = Parabola(directrix=d1)
    pa3 = Parabola(p1, d1)
    pa4 = Parabola(p2, d2)
    pa5 = Parabola(p2, d4)
    pa6 = Parabola(p3, d2)
    pa7 = Parabola(p2, d1)
    pa8 = Parabola(p4, d1)
    pa9 = Parabola(p4, d3)

    raises(ValueError, lambda:
           Parabola(Point(7, 8, 9), Line(Point(6, 7), Point(7, 7))))
    raises(NotImplementedError, lambda:
           Parabola(Point(7, 8), Line(Point(3, 7), Point(2, 9))))
    raises(ValueError, lambda:
           Parabola(Point(0, 2), Line(Point(7, 2), Point(6, 2))))
    raises(ValueError, lambda: Parabola(Point(7, 8), Point(3, 8)))

    # Basic Stuff
    assert pa1.focus == Point(0, 0)
    assert pa2 == pa3
    assert pa4 != pa7
    assert pa6 != pa7
    assert pa6.focus == Point2D(0, 4)
    assert pa6.focal_length == 1
    assert pa6.p_parameter == -1
    assert pa6.vertex == Point2D(0, 5)
    assert pa6.eccentricity == 1
    assert pa7.focus == Point2D(3, 7)
    assert pa7.focal_length == half
    assert pa7.p_parameter == -half
    assert pa7.vertex == Point2D(7*half, 7)
    assert pa4.focal_length == half
    assert pa4.p_parameter == half
    assert pa4.vertex == Point2D(3, 13*half)
    assert pa8.focal_length == 1
    assert pa8.p_parameter == 1
    assert pa8.vertex == Point2D(5, 0)
    assert pa4.focal_length == pa5.focal_length
    assert pa4.p_parameter == pa5.p_parameter
    assert pa4.vertex == pa5.vertex
    assert pa4.equation() == pa5.equation()
    assert pa8.focal_length == pa9.focal_length
    assert pa8.p_parameter == pa9.p_parameter
    assert pa8.vertex == pa9.vertex
    assert pa8.equation() == pa9.equation()
Exemplo n.º 28
0
def pointInLine(qPointF, qLineF):
    from sympy import Point, Line, Segment, Rational
    p1 = Point(qPointF.x(), qPointF.y())
    l = Line(Point(qLineF.x1(), qLineF.y1()), Point(qLineF.x2(), qLineF.y2()))
    point2d = l.projection(p1)
    return QPointF(point2d[0], point2d[1])
Exemplo n.º 29
0
    localities = {}
    for coor in polygons:
        if coor.get('localidad') in localities.keys():
            localities[coor.get('localidad')].append((float(coor.get('latitud')), float(coor.get('longitud'))))
        else:
            coordinates = []
            coordinates.append((float(coor.get('latitud')), float(coor.get('longitud'))))
            localities[coor.get('localidad')] = coordinates

    polygons = pass_coordinates(localities)

    for point in points:
        for key, value in polygons.items():
            try:
                if value.encloses_point(Point(float(point.get('latitud')), float(point.get('longitud')))):
                    point['localidad'] = key
                    time_point = time()
                    print("{}: {}s locality: {}".format(point.get('id'), time_point-start, key))
                    pass
            except:
                print("invalid Coordinate", point.get('latitud'), point.get('longitud'))
    try:
        with open('points_locality.csv', 'w') as csvfile:
            fieldnames = ['id', 'latitud', 'longitud', 'localidad']
            writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
            writer.writeheader()
            writer.writerows(points)
    except:
        print("invalid field")
Exemplo n.º 30
0
# we use sympy to calculate the contact points. For line-circle intersections,
# we first solve the equations symbolically and then plug in the values when
# needed

# intersection line - circle
x, y, m, c, r = sp.symbols('x y m c r', real=True)
# solving for x
eq_line_circle_x = sp.Eq((m * x + c)**2, (r**2 - x**2))
expr_line_circle_x = sp.solve(eq_line_circle_x, x)
# solving for y
eq_line_circle_y = sp.Eq(((y - c) / m)**2, (r**2 - y**2))
expr_line_circle_y = sp.solve(eq_line_circle_y, y)

# Define the objects as sympy ellipses and circles
# Warning: this can lead to an error with sympy versions < 1.1.
ellip1 = Circle(Point(0., 0.), 0.0525)
ellip2 = Ellipse(Point(0., 0.), 0.0525, 0.065445)
ellip3 = Ellipse(Point(0., 0.), 0.0525, 0.0785)


def get_contact_annotation(source_dir, out_dir, num_jobs=10, debug=True,
                           criteria=['a=0']):
    if not os.path.exists(out_dir):
            os.mkdir(out_dir)

    mats = [f for f in os.listdir(source_dir)
            if os.path.isdir(os.path.join(source_dir, f)) if 'delrin' in f]
    for mat in mats:
        objects = [f for f in os.listdir(os.path.join(source_dir, mat))
                   if 'zip' not in f]
        if not os.path.exists(os.path.join(out_dir, mat)):