Пример #1
0
 def setDirection(self, hero, point):
     tile = hero.getTile()
     cones = []
     for x in range(len(tile.points)):
         if x == 6:
             break
         else:
             cones.append((line.Line(tile.points[x], tile.getCenter()),
                           line.Line(tile.points[x + 1], tile.getCenter())))
     for cone in range(len(cones)):
         if cone == 0:
             if cones[cone][0].isPointGreaterThan(
                     point) and cones[cone][1].isPointLessThan(point):
                 hero.setDirection(1)
         if cone == 1:
             if cones[cone][0].isPointGreaterThan(
                     point) and cones[cone][1].isPointGreaterThan(point):
                 hero.setDirection(2)
         if cone == 2:
             if cones[cone][0].isPointLessThan(
                     point) and cones[cone][1].isPointGreaterThan(point):
                 hero.setDirection(3)
         if cone == 3:
             if cones[cone][0].isPointLessThan(
                     point) and cones[cone][1].isPointGreaterThan(point):
                 hero.setDirection(4)
         if cone == 4:
             if cones[cone][0].isPointLessThan(
                     point) and cones[cone][1].isPointLessThan(point):
                 hero.setDirection(5)
         if cone == 5:
             if cones[cone][0].isPointGreaterThan(
                     point) and cones[cone][1].isPointLessThan(point):
                 hero.setDirection(6)
Пример #2
0
def findWalls(cloud, startAngle, endAngle):
    wStart, wEnd = startAngle, endAngle
    walls = []
    while wEnd < 360:
        start, end = probableWall(cloud, wStart, wEnd, 15, 95)  # look for wall
        if start:  # found a wall..
            XY = splitXY(cloud, start, end)
            m, b = leastSquare(XY)  # calculate gradient/intersection of wall

            farAway = 10000000
            pt1 = (-farAway, (-farAway * m) + b)
            pt2 = (farAway, farAway * m + b)
            longLine = line.Line(pt1, pt2)  # long line best fit to data

            pt1, pt2 = bounds(XY)
            if m < 0.0:  # gradient is reversed # gradient of line between corners of the bound rectangle is always positive
                myPt1 = longLine.closestPoint(pt2[0], pt1[1])
                myPt2 = longLine.closestPoint(pt1[0], pt2[1])
            else:
                myPt1 = longLine.closestPoint(pt1[0], pt1[1])
                myPt2 = longLine.closestPoint(pt2[0], pt2[1])
            myLine = line.Line(myPt1, myPt2)
            walls.append(myLine)

            wStart = start
            wEnd = end
        wStart = wEnd
        wStart = wStart + (wEnd - wStart) / 2
        wEnd = wStart + 5
    return walls
 def testCoverAreaNumericalIntegration(self):
     """
     Test the excess area computation.
     """
     p1 = [20, 30]
     p2 = [50, 60]
     line_segment = Line(p1, p2)
     lines = [line_segment]
     ccle = circle.Circle(center=[40, 40], radius=15)
     b, l, c = ccle.collides(line_segment)
     self.assertTrue(b)
     self.assertTrue(len(l) == 2)
     self.assertTrue(c is not None)
     l1 = line.Line(ccle.get_center(), c.get_p1())
     l2 = line.Line(ccle.get_center(), c.get_p2())
     angle = math.pi - l1.angle(l2)
     # The angle that is outside the wedge.
     remaining_angle = 2 * math.pi - angle
     # The portion of the circle that is outside the wedge
     portion_outside = remaining_angle / (2 * math.pi) * ccle.area()
     # The triangle area
     triangleArea = areaOfTriangle(c, l1, l2)
     # The following is the exact computation of the excess area.
     segmentArea = ccle.area() - (triangleArea + portion_outside)
     # Now compare it with the numerical integration result.
     segmentArea1, totalarea = circlecover.compute_excess_area([ccle],
                                                               lines)
     print "segmentArea ", segmentArea, " segmentArea1 ", segmentArea1
     self.assertTrue(np.allclose(segmentArea, segmentArea1, rtol=.01))
     self.assertTrue(np.allclose(ccle.area(), totalarea, rtol=.01))
Пример #4
0
    def __init__(self, viewport, gw, gh, paint):
        Object.__init__(self, viewport)
        utils.copy_object(paint, self)

        # draw
        num_lines = int(viewport.w / gw) - 1
        x = viewport.x + gw
        for l in range(0, num_lines):
            v = line.Line()
            v.x1 = x
            v.y1 = viewport.y
            v.x2 = x
            v.y2 = v.y1 + viewport.h

            x += gw
            self.append(v)

        num_lines = int(viewport.h / gh) - 1
        y = viewport.y + gh
        for l in range(0, num_lines):
            h = line.Line()
            h.x1 = viewport.x
            h.y1 = y
            h.x2 = h.x1 + viewport.w
            h.y2 = y

            y += gh
            self.append(h)
Пример #5
0
 def UP(self, node):
     """Repairs what DOWN did."""
     while node != None:
         #print "hola"
         if node.__class__ == self.Line_Node:
             node = node.parent
         elif node.right == None:
             node.local_env = node.left.local_env
             node.bridge_left = None
             node.bridge_right = None
             node.left.local_env = None
             node = node.parent
         else:
             (lleft, lright) = Envelope_Mantainer.point_of_intersection(
                 node.left.local_env, node.right.local_env)
             (Env_left, n,
              node.left.local_env) = node.left.local_env.split(lleft.key)
             Env_left.insert_node(n)
             (node.right.local_env, n,
              Env_right) = node.right.local_env.split(lright.key)
             Env_right.insert_node(n)
             node.local_env = Env_left.join(Env_right)
             if self.lower:
                 nlleft = line.Line()
                 nlleft.m = lleft.obj.m
                 nlleft.b = -lleft.obj.b
                 nlright = line.Line()
                 nlright.m = lright.obj.m
                 nlright.b = -lright.obj.b
             else:
                 nlleft = lleft.obj
                 nlright = lright.obj
             node.bridge_left = nlleft
             node.bridge_right = nlright
             node = node.parent
Пример #6
0
def tests():

    pt0 = (0, 0)
    pt1 = (0, 1)
    pt2 = (1, 1)
    pt3 = (1, 0)
    pt4 = (0, 2)
    pt5 = (2, 2)
    pt6 = (2, 0)

    l0 = line.Line(pt0, pt3)
    l1 = line.Line(pt1, pt2)
    l2 = line.Line(pt4, pt5)
    l3 = line.Line(pt0, pt2)

    t0 = Trap(l1, l0, pt0, pt3)
    t1 = Trap(l2, l0, pt0, pt5)
    t2 = Trap(l0, l1, pt3, pt0)
    t3 = Trap(l3, l0, pt0, pt3)

    # Check comparators
    assert t0 != t1
    assert t0 == t2
    assert len(t0.corners) == 4
    assert len(t3.corners) == 3
Пример #7
0
def TestSimpleLines():
    print("###################################################")
    l1 = line.Line([0, 2], 10)
    l2 = line.Line([0, 16], 80)
    orientation, intersect = l1.GetIntersection(l2)
    PrintResult_Task7(orientation, intersect)

    l1 = line.Line([0, 2], 10)
    l2 = line.Line([0, 15], 80)
    orientation, intersect = l1.GetIntersection(l2)
    PrintResult_Task7(orientation, intersect)

    l1 = line.Line([2, 0], 10)
    l2 = line.Line([16, 0], 80)
    orientation, intersect = l1.GetIntersection(l2)
    PrintResult_Task7(orientation, intersect)

    l1 = line.Line([2, 0], 10)
    l2 = line.Line([15, 0], 80)
    orientation, intersect = l1.GetIntersection(l2)
    PrintResult_Task7(orientation, intersect)

    l1 = line.Line([2, 0], 10)
    l2 = line.Line([0, 16], 80)
    orientation, intersect = l1.GetIntersection(l2)
    PrintResult_Task7(orientation, intersect)
Пример #8
0
 def __init__(self,ul,lr):
     p = point.Point
     self.rect = [ 
              line.Line(ul,p(lr.x,ul.y)),
              line.Line(p(lr.x,ul.y),p(lr.x,lr.y)),
              line.Line(p(lr.x,lr.y),p(ul.x,lr.y)),
              line.Line(p(ul.x,lr.y),p(ul.x,ul.y)), ]
Пример #9
0
def main():
    rect = [
        line.Line(point.Point(1, 6), point.Point(6, 6)),
        line.Line(point.Point(5, 6), point.Point(5, 1)),
        line.Line(point.Point(6, 1), point.Point(1, 1)),
        line.Line(point.Point(1, 1), point.Point(1, 6))
    ]
    print(rect)
Пример #10
0
 def crossesEdge(self, node1, node2):
     newLine = line.Line(node1, node2)
     for source, targets in self.edges.iteritems():
         for target in targets:
             altLine = line.Line(source, target)
             collision = newLine.lineLineIntersect(altLine)
             if collision == line.LINE_INTERSECT:
                 return True
     return False
Пример #11
0
 def __init__(self, scene, pos, owning_civ):
     super().__init__(scene, pos, owning_civ)
     self.set_sprite_sheet("assets/warpship.png", 13)
     self.tethered_to, _ = get_nearest(
         self.pos, self.scene.get_civ_planets(owning_civ))
     self.line1 = line.Line(V2(0, 0), V2(0, 0), PICO_LIGHTGRAY)
     self.line2 = line.Line(V2(0, 0), V2(0, 0), PICO_RED)
     self.scene.game_group.add(self.line1)
     self.scene.game_group.add(self.line2)
     self.update_lines()
Пример #12
0
 def __init__(self):
     self.line_left = line.Line()
     self.line_right = line.Line()
     self.detected = False
     self.iteration = 0
     self.lane_widths = []  # save lane width for last 10 iteration
     self.lane_width = None
     self.algorithms = [
         proc.gradient_color, proc.yellow_white, proc.gradient_saturation
     ]
     self.current_option = 0
Пример #13
0
    def set_line_cluster(self):

        directions = [(-1, 0), (0, -1), (1, 0), (0, 1)]

        cluster = [line.Line(col_seq.Solid(WHITE))]

        i = self.width-1
        for dx, dy in directions:
            cluster.append(line.Line(col_seq.Flicker(BLUE, clear=False, finite=False), point=(dx*i, dy*i)))

        cluster.reverse()

        return cluster
Пример #14
0
    def isValid(self, sen, ref, newVars=None):
        '''
        Given a sentence and a set of reference lines, check that this proof proves 
        that the sentence is deductively follows from the reference lines

        @return - True iff the proof proves that given sentence 
        '''

        # Check that this proof is valid, if it is not then we canot check anything
        if self.verify() is not True:
            return False

        # put all of the reference sentences into a list
        refLines = []
        for r in ref:
            try:
                refLines.append(r())
            except ReferenceError:
                return False

        premises = self.getPremises()

        # Generalize the premises
        genPrem = set([])
        for prem in premises:
            genPrem.add(prem.generalize())

        # TODO: Use other symbols for subproof
        if sen.op() == '|-':
            # Add the subproof assumption to the reference list
            if str(sen.args()[0]) != '':
                assumption = line.Line(self)
                assumption.setSentence(sen.args()[0])
                refLines.append(assumption)

            # We are trying to prove the second part
            sen = sen.args()[1]

        ## If we have variables that we need to be new
        #if newVars is not None:
        #for s in refSenList:
        #for var in newVars:
        ## Check each sentence to see if it contains the "new" variable
        #if var in s:
        #return False

        prevSens = []
        metaSen = None
        for s in self:
            # Assume s is the conclusion
            curSen = s.getSentence().generalize()

            # Check if the current sentence can map into the conclusion
            for conclusionMap in curSen.mapInto(sen):
                # Try to map the assumptions to the refSenList
                mapping = self.makeMapping(conclusionMap, genPrem, refLines)
                if len(mapping) > 0:
                    # If there is a mapping then we are done
                    return True
        return False
Пример #15
0
 def __init__(self, obj=line.Line(), lower=False):
     Treap.Node.__init__(self, key=obj.m)
     #$Q_alpha$ in the "Mantainance of Configurations"
     self.local_env = Envelope_Mantainer.Treap_Line(lower=lower)
     #self.local_env.insert(obj)
     self.bridge_left = obj
     self.bridge_right = None
Пример #16
0
def check_entry(index_name, max_notify_count):
    csv = rikka_const.entry_csv
    df = pd.read_csv(csv, index_col=0)
    temp_df = df[df.index == index_name]
    stop_long_value = temp_df["stop_long"][0]
    stop_short_value = temp_df["stop_short"][0]
    notify_count = temp_df["notify_count"][0]
    close_time, close_price = get_closeprice(index_name)
    if close_price is None:
        return
    line_agent = line.Line(line_token.line_token)
    if notify_count >= max_notify_count:
        logger.debug(f"notify_count:[{notify_count}], max_notify_count:[{max_notify_count}]")
        return
    if stop_long_value != 0 and stop_long_value <= close_price:
        notify_count += 1
        msg = f"long trigger[{notify_count}]:" \
              f"index[{index_name}],stop_long_value[{stop_long_value:.2f}], close_price[{close_price:.2f}]"
        logger.info(msg)
        line_agent.send_message(msg)
        df.loc[index_name, "notify_count"] = notify_count
        df.to_csv(csv)
    elif stop_short_value != 0 and stop_short_value <= close_price:
        notify_count += 1
        msg = f"short trigger[{notify_count}]:index[{index_name}]" \
              f", stop_short_value[{stop_short_value:.2f}], close_price[{close_price:.2f}]"
        logger.info(msg)
        line_agent.send_message(msg)
        df.loc[index_name, "notify_count"] = notify_count
        df.to_csv(csv)
    else:
        logger.debug(f"None Order index[{index_name}], close_price:[{close_price}]"
                     f", stop_long_value:[{stop_long_value}], stop_short_value:[{stop_short_value}]")
Пример #17
0
 def insert(self, l):
     obj = l
     if self.lower:
         obj = line.Line()
         obj.m = l.m
         obj.b = -l.b
     Treap.insert(self, key=obj.m, obj=obj)
Пример #18
0
 def confirm_line(self):
     a = float(self.s.get())
     b = float(self.s2.get())
     self.top.destroy()
     self._nb_lines += 1
     l = line.Line(a, b, self.canv, self._nb_lines)
     self.LINES.append(l)
Пример #19
0
 def test_my_line(self):
     # Add code here.
     my_line = line.Line(1.1, 1.2, 1.3, 1.4)
     self.assertAlmostEqual(my_line.x1, 1.1)
     self.assertAlmostEqual(my_line.y1, 1.2)
     self.assertAlmostEqual(my_line.x2, 1.3)
     self.assertAlmostEqual(my_line.y2, 1.4)
Пример #20
0
 def __init__(self, obj=line.Line(), lower=False):
     Treap.Node.__init__(self, key=obj.m)
     self.local_env = Envelope_Mantainer.Treap_Line(lower=lower)
     self.local_env.insert(obj)
     self.lines = [obj]
     self.obj = obj
     self.empty = False
Пример #21
0
    def removeBadEdges(self):
        #        self.drawAll()
        newEdges = dict()
        for node, neighbors in self.edges.iteritems():
            newEdges[node] = set()
            for neighbor in neighbors:
                edge = line.Line(node, neighbor)
                edgeRect = edge.getBounds()
                edgeRect.left -= self.minDistanceEdgeToNode
                edgeRect.top -= self.minDistanceEdgeToNode
                edgeRect.width += 2 * self.minDistanceEdgeToNode
                edgeRect.height += 2 * self.minDistanceEdgeToNode
                isSafeEdge = True
                # No edges connecting different regions of the map.
                if node.terrain != neighbor.terrain:
                    isSafeEdge = False
                # No non-axis-aligned edges in axis-aligned parts of the map.
                elif (game.map.getRegionInfo(node.terrain, 'aligned')
                      and game.map.getRegionInfo(neighbor.terrain, 'aligned')
                      and abs(node.x - neighbor.x) > constants.EPSILON
                      and abs(node.y - neighbor.y) > constants.EPSILON):
                    isSafeEdge = False
                else:
                    for vecWrap in self.nodeTree.getObjectsIntersectingRect(
                            edgeRect):
                        nearNode = vecWrap.vector
                        if (nearNode not in [node, neighbor]
                                and edge.pointDistance(nearNode) <
                                self.minDistanceEdgeToNode):
                            isSafeEdge = False
                            break
                if isSafeEdge:
                    newEdges[node].add(neighbor)

        self.edges = self.addFixedEdges(newEdges)
Пример #22
0
 def __init__(self,player,coords,wall):
     #######################################################################################
     # Programmer Name: Alec 
     # Date: 5/15/17
     # Purpose: initializes attributes of a block
     # Input: self, player, coords, wall
     # Output: attributes of the object
     #######################################################################################
     self.x=coords[0]        # top left coordinate
     self.y=coords[1]
     length=Block.LENGTH     # localized length of each side
     self.c=(self.x+length//2,self.y+length//2)
     # create each side in the side list
     self.sides=[line.Line([self.x+length,self.y],[self.x,self.y],wall),                  # north
                 line.Line([self.x,self.y+length],[self.x+length,self.y+length],wall),    # south
                 line.Line([self.x,self.y],[self.x,self.y+length],wall),                  # west
                 line.Line([self.x+length,self.y+length],[self.x+length,self.y],wall)]    # east
Пример #23
0
 def splitLineString(lineString):
     res = []
     coords = lineString.coords
     p0 = coords[0]
     for k in range(1, len(lineString.coords)):
         p1 = coords[k]
         res.append(line.Line(p0, p1))
         p0 = p1
     return res
Пример #24
0
    def __init__(self):
        group.Group.__init__(self)
        l = line.Line()
        l.x1 = 0
        l.y1 = -3
        l.x2 = 0
        l.y2 = 3

        self.append(l)
Пример #25
0
 def _merge_lines(cls, line_1, line_2):
     """Receives 2 mergeable lines, line_1.tail <= line_2.tail:
         [Line, Line]
     Returns the sum of the 2 lines:
         Line
     """
     new_tail = min(line_1.tail, line_2.tail)
     new_head = max(line_1.head, line_2.head)
     new_line = line.Line(new_tail, new_head)
     return new_line
 def testCoverAreaNumericalIntegration2(self):
     p1 = [99.0, 29.0]
     p2 = [100.0, 30.0]
     line_segment = line.Line(p1, p2)
     ccle = circle.Circle(center=[60, 20], radius=41.231)
     self.assertTrue(ccle.inside(p1) and ccle.inside(p2))
     segmentArea, totalArea = circlecover.compute_excess_area(
         [ccle], [line_segment], grid_divisions=200)
     print "segmentArea ", segmentArea
     self.assertTrue(segmentArea != 0)
Пример #27
0
 def get_line(self, line_pos, image_height):
     l = line.Line()
     l.allx, l.ally = zip(*line_pos)
     l.current_fit = np.polyfit(l.ally, l.allx, 2)
     ploty = np.linspace(0, image_height - 1, image_height)
     l.fitx = l.current_fit[0] * ploty**2 + l.current_fit[
         1] * ploty + l.current_fit[2]
     l.curverad = self.calculate_curvature(l, ploty)
     l.theta = self.theta(l.fitx)
     return l
Пример #28
0
    def __init__(self, text=None, part2=False):

        # 1. Set the initial values
        self.part2 = part2
        self.text = text
        self.lines = []

        # 2. Process text (if any)
        if text is not None and len(text) > 0:
            for text_line in self.text:
                self.lines.append(line.Line(text=text_line, part2=part2))
def find_lines(im, line_left=line.Line(), line_right=line.Line(), window_num=9):
    # 车道线图像的shape
    shape = im.shape

    # 扫描窗口的高度
    window_height = shape[0] / window_num

    # 计算图像下1/4部分的直方图(降低运算规模,并减少噪声干扰,因为一般情况噪声出现在图像的靠上部分)
    histogram = np.sum(im[int(shape[0] / 4 * 3):, :], axis=0)

    if line_left.detected:
        '''如果上一帧检测到了车道线'''

        pass
    else:
        '''如果上一帧未检测到车道线'''

        # 以直方图中最大值的x点为左边窗口检测起点
        start_left_X = np.argmax(histogram[:int(shape[1] / 2)])
        start_right_X = np.argmax(histogram[int(shape[1] / 2):]) + int(shape[1] / 2)
Пример #30
0
 def linesIntersectionResolution(self, startLineName, destLineName):
 #    print "funcLinesIntersectionResolution(sl: %s, dl: %s)" % (startLineName, destLineName)
     destLineIntersectionTaktNumber = 0 # start line enters dest line in this takt of dest line
     destLineEndTakt = 0
     startLineEndTakt = 0
     
     linesDict = ln.Line().lines()
     lineInfo = linesDict.get(startLineName, None)
     if lineInfo == None:
         print "funcLinesIntersectionResolution error"
         return None
     startLineEndTakt = lineInfo[1][1]
     lineInfo = linesDict.get(destLineName, None)
     if lineInfo == None:
         print "funcLinesIntersectionResolution error"
         return None
     # if the dest line is the res line, then we assign the res takt to the destLineEndTakt
     # otherwise the last takt of dest line will be assigned to destLineEndTakt
     if self.resolutionLine == destLineName:
         destLineEndTakt = self.resolutionTakt
     else:    
         destLineEndTakt = lineInfo[1][1]
     parallelLinesIntersectionDict = ln.Line().parallelLines()
     destLineInx = lineInfo[0]
     intersectionLines = parallelLinesIntersectionDict.get(startLineName, [])
     for line in intersectionLines:
         # line[0] = line index
         # line[1] = intersection takt
         if line[0] == destLineInx:
             destLineIntersectionTaktNumber = line[1]
     # if the start line is either Det line or Occ line, then return calculated
     # info for start line and dest line
     # otherwise, return the info for dest line    
     if self.occurranceLine == startLineName:
         return [[self.occurranceTakt, startLineEndTakt], [destLineIntersectionTaktNumber, destLineEndTakt]]
     elif self.occurranceLine == None and self.detectionLine == startLineName:
         return [[self.detectionTakt, startLineEndTakt], [destLineIntersectionTaktNumber, destLineEndTakt]]
     else:
         return [[destLineIntersectionTaktNumber, destLineEndTakt]]
     return None