Example #1
0
 def _loadFile(self, source):
     if not os.path.isfile(source):
         raise ShapeException('Source image not found')
     try:
         return mpimg.imread(source)
     except Exception as e:
         raise ShapeException(e)
Example #2
0
 def __init__(self, *args, **kwargs):
     try:
         if not self.__constructWithPoints(args[0], args[1]):
             if not self.__constructWithCoords(args[0], args[1], args[2],
                                               args[3]):
                 raise ShapeException("Line Construction Failed")
     except IndexError:  # If no construction method works, raise an exception
         raise ShapeException("Invalid arguments for line construction")
Example #3
0
 def validateSource(source):
     """Validate a source for an image"""
     if not os.path.isfile(source):
         raise ShapeException('Source image not found')
     try:
         if imghdr.what(source) not in VALID_IMAGES:
             raise ShapeException('Source is not a valid image.')
     except TypeError:
         raise ShapeException('Source is not a valid image.')
Example #4
0
 def __init__(self, *args, **kwargs):
     try:
         if not self.__constructWithPoints(args[0], args[1], args[2]):
             if not self.__constructWithLines(args[0], args[1], args[2]):
                 if not self.__constructWithCoords(
                         args[0], args[1], args[2], args[3], args[4],
                         args[5]):
                     raise ShapeException("Triangle construction failed")
     except IndexError:
         raise ShapeException("Invalid arguments for triangle construction")
Example #5
0
 def __init__(self, *args, **kwargs):
     """Expects arguments as center, focus1, focus2, edge1, edge2"""
     try:
         if not self.__constructWithPoints(args[0], args[1], args[2],
                                           args[3], args[4]):
             if not self.__constructWithCoords(
                     args[0], args[1], args[2], args[3], args[4], args[5],
                     args[6], args[7], args[8], args[9]):
                 raise ShapeException("Ellipse construction failed")
     except IndexError:
         raise ShapeException("Invalid arguments for ellipse construction")
Example #6
0
 def __init__(self, *args, **kwargs):
     try:  # Construct with x1, y1, x2, y2, x3, y3, x4, y4
         if not self.__constructWithPoints(args[0], args[1], args[2],
                                           args[3]):
             if not self.__constructWithLines(args[0], args[1], args[2],
                                              args[3]):
                 if not self.__constructWithCoords(
                         args[0], args[1], args[2], args[3], args[4],
                         args[5], args[6], args[7]):
                     raise ShapeException("Rectangle construction failed")
     except IndexError:
         raise ShapeException("Invalid arguments for shape construction")
Example #7
0
    def validateEllipse(value, errorMessage):
        if not isinstance(value, Ellipse):
            raise ShapeException(errorMessage)

        Line.validateLine(value.axis1, "Axis1 is not a valid line")
        Line.validateLine(value.axis2, "Axis2 is not a valid line")

        if value.computeArea() <= 0:
            raise ShapeException(errorMessage)

        Validator.validateLinesFormRightAngles([value.axis1, value.axis2],
                                               "Axis are not perpendicular")
Example #8
0
 def validateLinesFormRightAngles(lines, errorMessage):
     for i in range(len(lines)):
         m1 = lines[i].computeSlope()
         m2 = lines[(i+1)%len(lines)].computeSlope()
         if isInfinite(m1) or m1 == 0 or \
            isInfinite(m2) or m2 == 0:
             if isInfinite(m1) and m2 == 0 or \
                isInfinite(m2) and m1 == 0:
                 pass
             else:
                 raise ShapeException(errorMessage)
         else:
             if round(m1, 2) != round(-1/m2, 2):
                 raise ShapeException(errorMessage)
Example #9
0
    def validateComposite(value, errorMessage):
        if not isinstance(value, Composite):
            raise ShapeException(errorMessage)

        value.center.validate()
        for shape in value.shapes:
            shape.validate()
Example #10
0
 def validateLinesAreSameLength(lines, errorMessage):
     last_length = lines[0].computeLength()
     for line in lines:
         length = line.computeLength()
         if length != last_length:
             raise ShapeException(errorMessage)
         last_length = length
Example #11
0
    def validateDouble(value, errorMessage):
        """
        Method that validates that value is a double

        :raises: ShapeException: If value is not a valid double
        """
        if not isinstance(value, numbers.Real) or isInfinite(value):
            raise ShapeException(errorMessage)
Example #12
0
    def validateEllipse(value, errorMessage):
        from shapes.ellipse import Ellipse
        if not isinstance(value, Ellipse):
            raise ShapeException(errorMessage)

        Validator.validatePoint(value.center, "Center is not a valid point.")
        Validator.validatePoint(value.focus1, "Focus1 is not a valid point.")
        Validator.validatePoint(value.focus2, "Focus2 is not a valid point.")
        Validator.validateLine(value.axis1, "Axis1 is not a valid line")
        Validator.validateLine(value.axis2, "Axis2 is not a valid line")

        if value.computeArea() <= 0:
            raise ShapeException(errorMessage)

        Validator.__validateLinesFormRightAngles([value.axis1, value.axis2],
                                                 "Axis are not perpendicular")
        Validator.__validateFociAreAligned(value, "Foci are not aligned")
Example #13
0
    def build(type, *args, **kwargs):
        try:
            shape_class = SHAPE_FACTORY_MAP[type]
        except KeyError:
            raise ShapeException(
                'Error: Invalid type for shape factory construction')

        return shape_class(*args, **kwargs)
Example #14
0
 def loadShape(self, string=None, file=None):
     if string is None and file is None:
         raise ShapeException(
             "Expected either a string or file for loadShape")
     if file:
         with open(file, "r") as myfile:
             string = myfile.readlines()
     return self._parse(string)
Example #15
0
 def validateSlopesAreDifferent(lines, errorMessage):
     for line in lines:
         lineSlope = line.computeSlope()
         count = 0
         for other_line in lines:
             if lineSlope == other_line.computeSlope():
                 count += 1
         if count != 1:
             raise ShapeException(errorMessage)
Example #16
0
 def __init__(self, *args, **kwargs):
     points = list(args)
     if len(points) < 1:
         raise ShapeException(
             'No points provided during shape construction')
     self.center = points.pop(0)
     self.points = points
     self.lines = []
     Shape.validateShape(value=self, errorMessage="Invalid Shape")
Example #17
0
    def validatePositiveDouble(value, errorMessage):
        """
        Method that validates that value is a positive double

        :raises: ShapeException: If Values is not a valid positive double
        """
        Validator.validateDouble(value, errorMessage)
        if value < 0:
            raise ShapeException(errorMessage)
Example #18
0
 def _findEnd(self, list, index):
     begin_count = 1
     for i in range(index, len(list)):
         if list[i] == 'begin':
             begin_count += 1
         elif list[i] == 'end':
             begin_count -= 1
             if begin_count == 0: return i
     raise ShapeException(
         'No matching end found for list<{}> index<{}>'.format(list, index))
Example #19
0
    def validateShape(value, errorMessage):
        if not isinstance(value, Shape):
            raise ShapeException(errorMessage)

        Point.validatePoint(
            value.center,
            "Center <{}> is not a valid point.".format(value.center))
        for point in value.points:
            Point.validatePoint(
                point, "Point <{}> is not a valid point.".format(point))
Example #20
0
    def validatePoint(value, errorMessage):
        """
        Method that validates that value is a valid point

        :raises: ShapeException: If value is not a valid point
        """
        if not isinstance(value, Point):
            raise ShapeException(errorMessage)
        Validator.validateDouble(value.x, "Invalid x-location")
        Validator.validateDouble(value.y, "Invalid y-location")
Example #21
0
    def validateLine(value, errorMessage):
        """
        Method that validates that a line is valid.

        :raises: ShapeException: If the line is invalid
        """
        if not isinstance(value, Line):
            raise ShapeException(errorMessage)
        Point.validatePoint(value.point1, "Invalid point1")
        Point.validatePoint(value.point2, "Invalid point2")
        Validator.validateLineHasLength(
            value, "A Line must have a length greater than 0")
Example #22
0
    def validateRectangle(value, errorMessage):
        if not isinstance(value, Rectangle):
            raise ShapeException(errorMessage)

        Line.validateLine(value.line1, "Line 1 is not a valid line.")
        Line.validateLine(value.line2, "Line 2 is not a valid line.")
        Line.validateLine(value.line3, "Line 3 is not a valid line.")
        Line.validateLine(value.line4, "Line 4 is not a valid line.")

        Validator.validateLinesFormLoop([value.line1, value.line2, value.line3, value.line4], "Lines do not form an enclosed rectangle.")

        Validator.validateLinesFormRightAngles([value.line1, value.line2, value.line3, value.line4], "Lines do not form 90 degree angles.")
Example #23
0
    def validateTriangle(value, errorMessage):
        if not isinstance(value, Triangle):
            raise ShapeException(errorMessage)

        Line.validateLine(value.line1, "Line 1 has is not a valid line.")
        Line.validateLine(value.line2, "Line 2 has is not a valid line.")
        Line.validateLine(value.line3, "Line 3 has is not a valid line.")

        Validator.validateSlopesAreDifferent(
            [value.line1, value.line2, value.line3],
            "Angles of lines form an invalid triangle")

        Validator.validateLinesFormLoop(
            [value.line1, value.line2, value.line3],
            "Lines do not form an enclosed triangle")
Example #24
0
    def __validateFociAreAligned(ellipse, errorMessage):
        try:
            m1 = (ellipse.focus1.y - ellipse.center.y) / (ellipse.focus1.x -
                                                          ellipse.center.x)
        except ZeroDivisionError:
            if (ellipse.center.y - ellipse.focus1.y) > 0:
                m1 = float('inf')
            else:
                m1 = float('-inf')

        try:
            m2 = (ellipse.focus2.y - ellipse.center.y) / (ellipse.focus2.x -
                                                          ellipse.center.x)
        except ZeroDivisionError:
            if (ellipse.center.y - ellipse.focus2.y) > 0:
                m2 = float('-inf')
            else:
                m2 = float('inf')

        if m1 != ellipse.axis1.computeSlope() or \
           m2 != ellipse.axis2.computeSlope():
            raise ShapeException(errorMessage)
Example #25
0
    def validateCircle(value, errorMessage):
        Ellipse.validateEllipse(value, errorMessage)

        if value.axis1.computeLength() != value.axis2.computeLength():
            raise ShapeException(errorMessage)
Example #26
0
 def __init__(self, *args, **kwargs):
     try:
         self.__constructWithCoords(args[0], args[1])
     except IndexError:
         raise ShapeException("Invalid arguments for point construction")
Example #27
0
 def getShape(self, index):
     try:
         return self.shapes[index]
     except IndexError:
         raise ShapeException(
             'Index out of bounds for getShape({})'.format(index))
Example #28
0
 def removeShape(self, index):
     try:
         return self.shapes.pop(index)
     except IndexError:
         raise ShapeException(
             'Index out of bounds for removeShape({})'.format(index))
Example #29
0
 def validateLinesFormLoop(lines, errorMessage):
     for i in range(len(lines)):
         if lines[i].point2 != lines[(i + 1) % len(lines)].point1:
             raise ShapeException(errorMessage)
Example #30
0
 def validateLineHasLength(value, errorMessage):
     if value.computeLength() <= 0:
         raise ShapeException(errorMessage)