Exemplo n.º 1
0
Arquivo: point.py Projeto: cklb/sympy
    def distance(self, other):
        """The Euclidean distance between self and another GeometricEntity.

        Returns
        =======

        distance : number or symbolic expression.

        Raises
        ======
        AttributeError : if other is a GeometricEntity for which
                         distance is not defined.
        TypeError : if other is not recognized as a GeometricEntity.

        See Also
        ========

        sympy.geometry.line.Segment.length
        sympy.geometry.point.Point.taxicab_distance

        Examples
        ========

        >>> from sympy.geometry import Point, Line
        >>> p1, p2 = Point(1, 1), Point(4, 5)
        >>> l = Line((3, 1), (2, 2))
        >>> p1.distance(p2)
        5
        >>> p1.distance(l)
        sqrt(2)

        The computed distance may be symbolic, too:

        >>> from sympy.abc import x, y
        >>> p3 = Point(x, y)
        >>> p3.distance((0, 0))
        sqrt(x**2 + y**2)

        """
        if not isinstance(other , GeometryEntity) :
            try :
                other = Point(other, dim=self.ambient_dimension)
            except TypeError :
                raise TypeError("not recognized as a GeometricEntity: %s" % type(other))
        if isinstance(other , Point) :
            s, p = Point._normalize_dimension(self, Point(other))
            return sqrt(Add(*((a - b)**2 for a, b in zip(s, p))))
        try :
            return other.distance(self)
        except AttributeError :
            raise AttributeError("distance between Point and %s is not defined" % type(other))
Exemplo n.º 2
0
    def are_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
        =======

        are_collinear : boolean

        See Also
        ========

        sympy.geometry.line.Line3D

        Examples
        ========

        >>> from sympy import Point3D, Matrix
        >>> from sympy.abc import x
        >>> p1, p2 = Point3D(0, 0, 0), Point3D(1, 1, 1)
        >>> p3, p4, p5 = Point3D(2, 2, 2), Point3D(x, x, x), Point3D(1, 2, 6)
        >>> Point3D.are_collinear(p1, p2, p3, p4)
        True
        >>> Point3D.are_collinear(p1, p2, p3, p5)
        False
        """
        return Point.is_collinear(*points)
Exemplo n.º 3
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.º 4
0
    def project(a, b):
        """Project the point `a` onto the line between the origin
        and point `b` along the normal direction.

        Parameters
        ==========

        a : Point
        b : Point

        Returns
        =======

        p : Point

        See Also
        ========

        sympy.geometry.line.LinearEntity.projection

        Examples
        ========

        >>> from sympy.geometry import Line, Point
        >>> a = Point(1, 2)
        >>> b = Point(2, 5)
        >>> z = a.origin
        >>> p = Point.project(a, b)
        >>> Line(p, a).is_perpendicular(Line(p, b))
        True
        >>> Point.is_collinear(z, p, b)
        True
        """
        a, b = Point._normalize_dimension(Point(a), Point(b))
        if b.is_zero:
            raise ValueError("Cannot project to the zero vector.")
        return b * (a.dot(b) / b.dot(b))
Exemplo n.º 5
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.º 6
0
def drawExWall(xSmallExWall, xBigExWall, ySmallExWall, yBigExWall, msp):
    '''
	Draw external wall lines. 
	uppose that buildings are ractangle.
	Args:
		xSmallExWall,
		xBigExWall,
		ySmallExWall,
		yBigExWall,
		msp, en ezdxf.modelspace() object used to create a new dxf file.
	'''
    recognizeObject = recognize.Recognize()
    xMax, xMin, yMax, yMin = recognizeObject.getExtremePointInLines(
        xSmallExWall)
    msp.add_line((xMin, yMin, 0), (xMin, yMax, 0))  # add a LINE entity
    '''xMax,xMin,yMax,yMin = recognizeObject.getExtremePointInLines(xBigExWall)
	msp.add_line((xMax,yMin,0),(xMax,yMax,0))  # add a LINE entity
	xMax,xMin,yMax,yMin = recognizeObject.getExtremePointInLines(ySmallExWall)
	msp.add_line((xMin,yMin,0),(xMax,yMin,0))  # add a LINE entity
	xMax,xMin,yMax,yMin = recognizeObject.getExtremePointInLines(yBigExWall)
	msp.add_line((xMin,yMax,0),(xMax,yMax,0))  # add a LINE entity
	'''
    del recognizeObject
    return Point(xMin, yMin), Point(xMin, yMax)
Exemplo n.º 7
0
def paralline(nl=2, x0=0, y0=100, x1=33, y1=66):
    
    p1, p2 = Point(x0, y0), Point(x1, y1)
    s1 = Segment(p1, p2)
    
    # Create a new Line perpendicular to this linear entity which passes through the point p1.
    l1 = s1.perpendicular_line(p1)
    l2 = s1.perpendicular_line(p2)
    
    p1 in l1
    p2 in l2
    s1.is_perpendicular(l2)
    s1.is_perpendicular(l1)
    
    #p11 = subs_point(l1, s1.length)
    # find coords of parallel nl segments from each side of the transect
    x11, y11 = zeros(2*nl+1), zeros(2*nl+1)
    x22, y22 = zeros(2*nl+1), zeros(2*nl+1)
    j=0
    for i in range(-nl,nl+1):
        p11 = subs_point(l1, 1*i/s1.length) # divide unit segment on its length
        x111, y111 = p11.args
        x11[j], y11[j] = float64(x111), float64(y111)
        p22 = subs_point(l2, 1*i/s1.length) # divide unit segment on its length
        x222, y222 = p22.args
        x22[j], y22[j] = float64(x222), float64(y222)
        j+=1
    
#    # Checking that segments are parallel and same length
#    s2 = Segment(p11,p22)
#    s2.is_parallel(s1)
#    s1.length - s2.length
#    plt.plot([x0, x1], [y0, y1])
#    plt.plot([x11, x22],[y11, y22], 'k')

    return x11, y11, x22, y22
Exemplo n.º 8
0
    def orthogonal_direction(self):
        """Returns a non-zero point that is orthogonal to the
        line containing `self` and the origin.

        Examples
        ========

        >>> from sympy.geometry import Line, Point
        >>> a = Point(1, 2, 3)
        >>> a.orthogonal_direction
        Point3D(-2, 1, 0)
        >>> b = _
        >>> Line(b, b.origin).is_perpendicular(Line(a, a.origin))
        True
        """
        dim = self.ambient_dimension
        # if a coordinate is zero, we can put a 1 there and zeros elsewhere
        if self[0] == S.Zero:
            return Point([1] + (dim - 1)*[0])
        if self[1] == S.Zero:
            return Point([0,1] + (dim - 2)*[0])
        # if the first two coordinates aren't zero, we can create a non-zero
        # orthogonal vector by swapping them, negating one, and padding with zeros
        return Point([-self[1], self[0]] + (dim - 2)*[0])
Exemplo n.º 9
0
    def sphere_impact_points(self):
        impact_points = getattr(self, '_impact_points', None)

        print round(self.semi_major_axis, 2)
        if impact_points:
            # TODO should include semi minor too
            """Invalid ellipse on change of semi major axis"""
            if round(self.semi_major_axis, 2) != round(self._impact_sma, 2):
                impact_points = None
                print 'invalid!'

        if impact_points is None:
            print 'create!'
            self._impact_sma = self.semi_major_axis

            r = self.equatorial_radius
            a = self.semi_major_axis
            b = self.semi_minor_axis
            c = math.sqrt(a ** 2 - b ** 2)  # linear eccentricity

            elp = Ellipse(Point(c, 0), a, b)
            crc = Circle(Point(0, 0), r)
            self._impact_points = sorted(list(set([(float(point.x), float(point.y)) for point in elp.intersection(crc)])))
        return self._impact_points
Exemplo n.º 10
0
def separaArestas(p1, p2, p3, p4=None):
    """."""
    arestas_separadas = []
    if p1 != p2:
        arestas_separadas.append(Segment(Point(p1.x, p1.y), Point(p2.x, p2.y)))
    if p2 != p3:
        arestas_separadas.append(Segment(Point(p2.x, p2.y), Point(p3.x, p3.y)))
    if p3 != p4 and not (p4 is None):
        arestas_separadas.append(Segment(Point(p3.x, p3.y), Point(p4.x, p4.y)))
    return arestas_separadas
Exemplo n.º 11
0
    def transform(self, matrix):
        """Return the point after applying the transformation described
        by the 3x3 Matrix, ``matrix``.

        See Also
        ========
        sympy.geometry.point.Point2D.rotate
        sympy.geometry.point.Point2D.scale
        sympy.geometry.point.Point2D.translate
        """
        if not (matrix.is_Matrix and matrix.shape == (3, 3)):
            raise ValueError("matrix must be a 3x3 matrix")

        col, row = matrix.shape
        x, y = self.args
        return Point(*(Matrix(1, 3, [x, y, 1]) * matrix).tolist()[0][:2])
Exemplo n.º 12
0
    def handle_position_request(self, req):
        x, y = req.current_pose.pose.position.x, req.current_pose.pose.position.y
        rospy.loginfo(
            "Received request for topological pose: x={0:.3f}, y={1:.3f} (frame: {2})"
            .format(x, y, req.current_pose.header.frame_id))
        robot_pose = Point(x, y)  # Inspection test pose
        for room in self.rooms:
            if not self.rooms[room].encloses_point(robot_pose):
                continue
            rospy.loginfo('robot is in room: ' + room)
            return TopologicalPositionResponse(room)

        position = 'hallway'
        rospy.logwarn("Failed to find room, using default location: %s" %
                      position)
        return TopologicalPositionResponse(position)
Exemplo n.º 13
0
def print_display(screen):
    lowest_x = sorted(screen, key=lambda point: point.x)
    lowest_y = sorted(screen, key=lambda point: point.y)
    highest_x = sorted(screen, key=lambda point: point.x, reverse=True)
    highest_y = sorted(screen, key=lambda point: point.y, reverse=True)
    print("Part2")

    for y in range(lowest_y[0].y, highest_y[0].y + 1):
        row = ""
        for x in range(lowest_x[0].x, highest_x[0].x):
            current = Point(x, y)
            if current not in screen:
                row += "0"
            else:
                row += str(screen[current])
        print(row)
Exemplo n.º 14
0
 def _normalize_dimension(cls, *points, **kwargs):
     """Ensure that points have the same dimension.
     By default `on_morph='warn'` is passed to the
     `Point` constructor."""
     # if we have a built-in ambient dimension, use it
     dim = getattr(cls, '_ambient_dimension', None)
     # override if we specified it
     dim = kwargs.get('dim', dim)
     # if no dim was given, use the highest dimensional point
     if dim is None:
         dim = max(i.ambient_dimension for i in points)
     if all(i.ambient_dimension == dim for i in points):
         return list(points)
     kwargs['dim'] = dim
     kwargs['on_morph'] = kwargs.get('on_morph', 'warn')
     return [Point(i, **kwargs) for i in points]
Exemplo n.º 15
0
def create_segments(line):
    segs = []
    pos = Point(0, 0)
    steps = 0
    for movement in line:
        match = re.match(dir_re, movement)
        direction = match.group(1)
        amount = int(match.group(2))

        new_pos = pos + maps[direction] * amount
        segs.append((Segment(pos, new_pos), steps))

        steps = steps + amount
        pos = new_pos

    return segs
Exemplo n.º 16
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
        """
        if not (matrix.is_Matrix and matrix.shape == (3, 3)):
            raise ValueError("matrix must be a 3x3 matrix")

        col, row = matrix.shape
        valid_matrix = matrix.is_square and col == 3
        x, y = self.args
        return Point(*(Matrix(1, 3, [x, y, 1]) * matrix).tolist()[0][:2])
Exemplo n.º 17
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

        See Also
        ========

        scale, translate

        Examples
        ========

        >>> 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.º 18
0
    def canberra_distance(self, p):
        """The Canberra Distance from self to point p.

        Returns the weighted sum of horizontal and vertical distances to
        point p.

        Parameters
        ==========

        p : Point

        Returns
        =======

        canberra_distance : The weighted sum of horizontal and vertical
        distances to point p. The weight used is the sum of absolute values
        of the coordinates.

        Examples
        ========

        >>> from sympy.geometry import Point
        >>> p1, p2 = Point(1, 1), Point(3, 3)
        >>> p1.canberra_distance(p2)
        1
        >>> p1, p2 = Point(0, 0), Point(3, 3)
        >>> p1.canberra_distance(p2)
        2

        Raises
        ======

        ValueError when both vectors are zero.

        See Also
        ========

        sympy.geometry.point.Point.distance

        """

        s, p = Point._normalize_dimension(self, Point(p))
        if self.is_zero and p.is_zero:
            raise ValueError("Cannot project to the zero vector.")
        return Add(*((abs(a - b) / (abs(a) + abs(b))) for a, b in zip(s, p)))
    def testFindIntersection1(self):
        buyerPoints = [Point(2, 3), Point(3, 3), Point(3, 2), Point(5, 2)]
        sellerPoints = [Point(1, 1), Point(4, 1), Point(4, 4)]

        buyerIntersectPoint, sellerIntersectPoint = findIntersection(
            buyerPoints, sellerPoints)

        self.assertEqual(buyerIntersectPoint[0].x.evalf(), 3)
        self.assertEqual(buyerIntersectPoint[0].y.evalf(), 2)
        self.assertEqual(buyerIntersectPoint[1].x.evalf(), 5)
        self.assertEqual(buyerIntersectPoint[1].y.evalf(), 2)

        self.assertEqual(sellerIntersectPoint[0].x.evalf(), 4)
        self.assertEqual(sellerIntersectPoint[0].y.evalf(), 1)
        self.assertEqual(sellerIntersectPoint[1].x.evalf(), 4)
        self.assertEqual(sellerIntersectPoint[1].y.evalf(), 4)
Exemplo n.º 20
0
    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])
        return m.rank()
Exemplo n.º 21
0
    def is_scalar_multiple(self, p):
        """Returns whether each coordinate of `self` is a scalar
        multiple of the corresponding coordinate in point p.
        """
        s, o = Point._normalize_dimension(self, Point(p))
        # 2d points happen a lot, so optimize this function call
        if s.ambient_dimension == 2:
            (x1, y1), (x2, y2) = s.args, o.args
            rv = (x1*y2 - x2*y1).equals(0)
            if rv is None:
                raise Undecidable(filldedent(
                    '''can't determine if %s is a scalar multiple of
                    %s''' % (s, o)))

        # if the vectors p1 and p2 are linearly dependent, then they must
        # be scalar multiples of each other
        m = Matrix([s.args, o.args])
        return m.rank() < 2
Exemplo n.º 22
0
    def are_coplanar(cls, *points):
        """Return True if there exists a plane in which all the points
        lie.  A trivial True value is returned if `len(points) < 3` or
        all Points are 2-dimensional.

        Parameters
        ==========

        A set of points

        Raises
        ======

        ValueError : if less than 3 unique points are given

        Returns
        =======

        boolean

        Examples
        ========

        >>> from sympy import Point3D
        >>> p1 = Point3D(1, 2, 2)
        >>> p2 = Point3D(2, 7, 2)
        >>> p3 = Point3D(0, 0, 2)
        >>> p4 = Point3D(1, 1, 2)
        >>> Point3D.are_coplanar(p1, p2, p3, p4)
        True
        >>> p5 = Point3D(0, 1, 3)
        >>> Point3D.are_coplanar(p1, p2, p3, p5)
        False

        """
        if len(points) <= 1:
            return True

        points = cls._normalize_dimension(*[Point(i) for i in points])
        # quick exit if we are in 2D
        if points[0].ambient_dimension == 2:
            return True
        points = list(uniq(points))
        return Point.affine_rank(*points) <= 2
def singlearearoute(cell, inputwidth, Entrance, Exit):
    mintime = float('inf')
    optimalangle = 0
    optimalpath = []
    isoptrf = False
    Entrance = Point(Entrance)
    Exit = Point(Exit)
    for angle in range(0, 180, 90):
        angle = float(angle)
        rcell = cell.rotate(angle / 180 * math.pi)
        rentrance = Entrance.rotate(angle / 180 * math.pi)
        rexit = Exit.rotate(angle / 180 * math.pi)
        rcell = roundpolygon(rcell)
        waypoint = createallwaypoint(rcell, inputwidth)
        time = timeconsume(waypoint, rentrance, rexit)
        if (time < mintime):
            mintime = time
            optimalangle = angle
            optimalpath = waypoint
            isoptrf = False
        rvwaypoint = waypoint[:]
        rvwaypoint.reverse()
        time = timeconsume(rvwaypoint, rentrance, rexit)
        if (time < mintime):
            mintime = time
            optimalangle = angle
            optimalpath = rvwaypoint
            isoptrf = False
        rfcell = reflectpolygon(rcell)
        rfentrance = rentrance.reflect(xaxis)
        rfexit = rexit.reflect(xaxis)
        waypoint = createallwaypoint(rfcell, inputwidth)
        time = timeconsume(waypoint, rfentrance, rfexit)
        if (time < mintime):
            mintime = time
            optimalangle = angle
            optimalpath = waypoint
            isoptrf = True
        rvwaypoint = waypoint[:]
        rvwaypoint.reverse()
        time = timeconsume(rvwaypoint, rfentrance, rfexit)
        if (time < mintime):
            mintime = time
            optimalangle = angle
            optimalpath = rvwaypoint
            isoptrf = True
    for i in range(len(optimalpath)):
        if (isoptrf):
            optimalpath[i] = optimalpath[i].reflect(xaxis)
        optimalpath[i] = optimalpath[i].rotate(-optimalangle / 180 * math.pi)
    return optimalpath
Exemplo n.º 24
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.º 25
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.º 26
0
def findPathOld(roada, lanea, roadb, laneb, width, maxRadius=10., midPoint=5):
    dxa, dya = getRoadUnitVector(roada)
    dxb, dyb = getRoadUnitVector(roadb)
    pxa, pya = getOutPoint(roada, width, lanea)
    pxb, pyb = getInPoint(roadb, width, laneb)

    pa = Point(pxa, pya)
    pb = Point(pxb, pyb)
    da = Point(dxa, dya)
    db = Point(dxb, dyb)

    la = Line(pa, pa + da)
    lb = Line(pb, pb + db)

    inter = la.intersection(lb)
    # print(roada, roadb)
    disa = inter.disntance(pa)
    disb = inter.disntance(pb)
    distance = np.min([disa, disb, maxRadius])
    ca = pa + da * (disa - distance)
    cb = pb - db * (disb - distance)

    o = (ca, ca + da.rotate(pi / 2)).intersection(cb, cb + db.rotate(pi / 2))
    oa = ca - o
    ob = cb - o
    angle = oa.dot(ob)
    dangle = angle / midPoint

    path = [pa]
    for i in range(midPoint + 1):
        path.append(o + oa.rotate(dangle * i))
    path.append(pb)

    # ix, iy = computeIntersection(pxa, pya, dxa, dya, pxb, pyb, dxb, dyb)
    # _width = (dxa * (pxb - pxa) + dya * (pyb - pya)) / 3
    # print(dxa, dya, (pxb - pxa), (pyb - pya), _width)
    # return getOutTurnPoints(roada, _width, lanea, width) + getInTurnPoints(roadb, _width, laneb, width)

    return list(map(pointToDict2, path))
Exemplo n.º 27
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])
    def Angle(self):
        yAxis = Line(Point(0, 1), Point(0, 0))
        point1 = Point(self.Box[1][0], self.Box[1][1])
        point2 = Point(self.Box[0][0], self.Box[0][1])
        point3 = Point(self.Box[2][0], self.Box[2][1])

        if point1.distance(point2) > point1.distance(point3):
            longerLine = Line(point1, point2)
        else:
            longerLine = Line(point1, point3)

        angle = int(math.degrees(yAxis.angle_between(longerLine)))

        if (int(angle) > 90):
            if angle - 180 + 80 >= 0:
                return angle - 180 + 80
            else:
                return 0
        else:
            if angle + 80 >= 0:
                return angle + 80
            else:
                return 0
Exemplo n.º 29
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.º 30
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.º 31
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.º 32
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.º 33
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.º 34
0
    def sendFaceImages(self):
        self.statusLabel.set_text("Obrada uzoraka")
        detector = dlib.get_frontal_face_detector()
        predictor = dlib.shape_predictor("ldm.dat")

        for i in range(0, 7):
            gray = cv2.imread("Camera/Resources/" + str(i) + '.png', cv2.CV_8UC1)
            #gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

            rects = detector(gray, 1)

            # loop over the face detections
            for (j, rect) in enumerate(rects):
                shape = predictor(gray, rect)
                shape = face_utils.shape_to_np(shape)

                angle = self.calculateFaceTilt(Point(shape[39]), Point(shape[42]))

                gray = self.rotateImage(gray, angle, tuple(shape[33]))
                #gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
                rects = detector(gray, 1)

                # loop over the face detections
                for (k, rect) in enumerate(rects):

                    shape = predictor(gray, rect)
                    shape = face_utils.shape_to_np(shape)
                    eye = Point(shape[37])
                    eyebrow = Point(shape[19])
                    left = Point(min(shape, key=itemgetter(0)))
                    top = Point(min(shape, key=itemgetter(1)))
                    right = Point(max(shape, key=itemgetter(0)))
                    bottom = Point(max(shape, key=itemgetter(1)))

                    gray = gray[int(top.y - eye.distance(eyebrow) / 2):int(top.y + top.distance(bottom)),
                            int(left.x):int(left.x + left.distance(right))]

                    #ujednacavanje histograma
                    clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
                    gray = clahe.apply(gray)
                    #gray = cv2.bilateralFilter(gray, 9, 75, 75)

                    ratio = 300.0 / gray.shape[1]
                    dimensions = (300, int(gray.shape[0] * ratio))

                    gray = cv2.resize(gray, dimensions, interpolation=cv2.INTER_AREA)
                    cv2.imwrite("Camera/Resources/" + str(i) + '.png', gray)

        for i in range(0, 7):
            self.statusLabel.set_text("Slanje uzoraka")
            client.send("ftp:" + str(i))
            self.waitForResponse()
            imageFile = open("Camera/Resources/" + str(i) + '.png', "rb")
            offset = 0
            while True:
                sent = sendfile(client.fileno(), imageFile.fileno(), offset, 4096)
                if sent == 0:
                    client.send("EOF")
                    break  # EOF
                offset += sent
            self.statusLabel.set_text("Potvrdite PIN")
            self.btnConfirm.set_sensitive(True)
            self.waitForResponse()
Exemplo n.º 35
0
            for (j, rect) in enumerate(rects):
                shape = predictor(gray, rect)
                shape = face_utils.shape_to_np(shape)

                angle = calculateFaceTilt(Point(shape[39]), Point(shape[42]))

                gray = rotateImage(gray, angle, tuple(shape[33]))
                # gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
                rects = detector(gray, 1)

                # loop over the face detections
                for (k, rect) in enumerate(rects):
                    shape = predictor(gray, rect)
                    shape = face_utils.shape_to_np(shape)
                    eye = Point(shape[37])
                    eyebrow = Point(shape[19])
                    left = Point(min(shape, key=itemgetter(0)))
                    top = Point(min(shape, key=itemgetter(1)))
                    right = Point(max(shape, key=itemgetter(0)))
                    bottom = Point(max(shape, key=itemgetter(1)))

                    gray = gray[int(top.y - eye.distance(eyebrow) / 2):int(top.y + top.distance(bottom)),
                           int(left.x):int(left.x + left.distance(right))]

                    # ujednacavanje histograma
                    clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
                    gray = clahe.apply(gray)
                    # gray = cv2.bilateralFilter(gray, 9, 75, 75)

                    ratio = 300.0 / gray.shape[1]
Exemplo n.º 36
0
 def __abs__(self):
     """Returns the distance between this point and the origin."""
     origin = Point([0]*len(self.args))
     return Point.distance(origin, self)