def compute_lane_from_candidates(line_candidates, img_shape):
    """
    Compute lines that approximate the position of both road lanes.
    :param line_candidates: lines from hough transform
    :param img_shape: shape of image to which hough transform was applied
    :return: lines that approximate left and right lane position
    """

    # separate candidate lines according to their slope
    pos_lines = [l for l in line_candidates if l.slope > 0]
    neg_lines = [l for l in line_candidates if l.slope < 0]

    # interpolate biases and slopes to compute equation of line that approximates left lane
    # median is employed to filter outliers
    neg_bias = np.median([l.bias for l in neg_lines]).astype(int)
    neg_slope = np.median([l.slope for l in neg_lines])
    x1, y1 = 0, neg_bias
    x2, y2 = -np.int32(np.round(neg_bias / neg_slope)), 0
    left_lane = Line(x1, y1, x2, y2)

    # interpolate biases and slopes to compute equation of line that approximates right lane
    # median is employed to filter outliers
    lane_right_bias = np.median([l.bias for l in pos_lines]).astype(int)
    lane_right_slope = np.median([l.slope for l in pos_lines])
    x1, y1 = 0, lane_right_bias
    x2, y2 = np.int32(
        np.round(
            (img_shape[0] - lane_right_bias) / lane_right_slope)), img_shape[0]
    right_lane = Line(x1, y1, x2, y2)

    return left_lane, right_lane
Ejemplo n.º 2
0
def createLinevertical():
    length = int(w.lenlineEntry.get())
    function = w.functionEntry.get()
    line_type = w.linetypeEntry.get()
    rotate_type = w.rotatetypeEntry.get()
    degree_rote = w.degreeroteEntry.get()
    speed_max = w.speedmaxEntry.get()
    wait_time = w.waittimeEntry.get()
    f = Frame(w.mapFrame,
              height=length * LineVertical['height'],
              width=LineVertical['width'],
              bg="black")
    labelsLine.append(
        Line(f, length, function, line_type, rotate_type, degree_rote,
             speed_max, wait_time))
    labelsLinevertical.append(
        Line(f, length, function, line_type, rotate_type, degree_rote,
             speed_max, wait_time))
    f.pack_propagate(0)  # don't shrink
    f.place(x=0, y=0)
    f.bind("<Button-1>", drag_start)
    f.bind("<B1-Motion>", drag_motion)
    f.bind("<ButtonRelease-1>", drop_motionVertical)
    f.bind("<Button-3>", popup)
    f.bind("<Enter>", information)
Ejemplo n.º 3
0
def render(SceneLoaded, Scale, Light, CamDist, Fdist):
    Scene = SceneLoaded
    Screen = []
    projection_plane = Plane(Vector(0, CamDist, 0), Vector(1, 0, 0),
                             Vector(0, 0, 1))
    focalPoint = Vector(0, CamDist + Fdist, 0)
    #Sort by Y value all triangles (oclusion)
    Scene.sort(key=lambda tri: tri.centre.y)
    for triangle in Scene:
        triangle.shade(Light)
        triangle.v1 = triangle.v1 * Scale
        triangle.v2 = triangle.v2 * Scale
        triangle.v3 = triangle.v3 * Scale
    for triangle in Scene:
        try:
            V1 = Line(triangle.v1, focalPoint - triangle.v1).plane_intersect(
                projection_plane)  # Three lines from the vertices to the plane
            V2 = Line(triangle.v2, focalPoint - triangle.v2).plane_intersect(
                projection_plane)  #
            V3 = Line(triangle.v3, focalPoint - triangle.v3).plane_intersect(
                projection_plane)  #
            Screen.append(Triangle(V1, V2, V3, color=triangle.color))
        except:
            pass
    draw(Screen)
Ejemplo n.º 4
0
    def intersect(self, polyline):
        interPoints = []
        for j in range(len(polyline.points)-1):
            for i in range(len(self.points)-1):
                ls1 = Line(self.points[i].x, self.points[i].y, self.points[i+1].x, self.points[i+1].y)
                ls2 = Line(polyline.points[j].x, polyline.points[j].y, polyline.points[j+1].x, polyline.points[j+1].y)
                interp = ls1.intersect(ls2)
                if interp:
                    interPoints.append(Point(int(interp.x), int(interp.y)))
                # if self.points[i].x > self.points[i+1].x:
                #     minx = self.points[i+1].x
                #     maxx = self.points[i].x
                # else:
                #     minx = self.points[i].x
                #     maxx = self.points[i+1].x
                #
                # if self.points[i].y > self.points[i+1].y:
                #     miny = self.points[i+1].y
                #     maxy = self.points[i].y
                # else:
                #     miny = self.points[i].y
                #     maxy = self.points[i+1].y
                #
                # if (polyline.points[j].x>=minx and polyline.points[j].x<=maxx) or (polyline.points[j].y>=miny and polyline.points[j].y<=maxy):
                #     ls1 = LineSeg(self.points[i].x, self.points[i].y, self.points[i+1].x, self.points[i+1].y)
                #     ls2 = LineSeg(polyline.points[j].x, polyline.points[j].y, polyline.points[j+1].x, polyline.points[j+1].y)
                #     interp = ls1.intersect(ls2)
                #     if interp:
                #         interPoints.append(Point(int(interp.x), int(interp.y)))

        return interPoints
Ejemplo n.º 5
0
 def draw(self):
     for x in range(self.gridSize, self.width, self.gridSize):
         Line(self.x1 + x, self.y1, self.x1 + x, self.y1 + self.height,
              [0, 1, 0], 0.0).draw()
     for y in range(self.gridSize, self.height, self.gridSize):
         Line(self.x1, self.y1 + y, self.x1 + self.width, self.y1 + y,
              [0, 1, 0], 0.0).draw()
Ejemplo n.º 6
0
    def findKeyRanges(self, key, requireSymbol=None):
        """ Return the ndex of start and end lines matching the key given, if any.
 Used to find well-formed embedded blocks. As there may be more than one embedded, 
 result is a list. Illformed embedded blocks will cause an early exit, warnings,
 status, {index1, index2, ...} = findKeyRanges... 
 status == 0 --> ok; status != 0 --> result is error string instead of list.
"""
# state is 0 if outside keyblock and 1 if inside
        state=0
        index = 0
        result = []
        for s in self.data:
            if Line.keyBegins(key,s) and (not requireSymbol or Line.symbolOf(s) == requireSymbol):
                if not state:
                    result.append(index)
                    state = 1
                else:
                    return (1, "begin encountered twice without end for key " + key + " at line " + str(index))
            if Line.keyEnds(key,s) and (not requireSymbol or Line.symbolOf(s) == requireSymbol):
                if state:
                    result.append(index)
                    state = 0
                else:
                    return (1, "end encountered without begin for key " + 
                            key + " at line " + str(index))
            index += 1
        return( 0, result )
Ejemplo n.º 7
0
def order(plane1, plane2):
        '''returns True if plane1 should be in front of plane2'''
        front = True
        pointList1 = plane1.getPointPositionsOnScreen()
        pointList2 = plane2.getPointPositionsOnScreen()
        rawPointList = plane1.getPoints()
        pointList = []
        planeCoordinates = plane1.getCoordinates()
        for i in range(0, len(rawPointList)):
                pointList.append([])
                for j in range(0, 3):
                        pointList[i].append(rawPointList[i].getPosition()[j] + planeCoordinates[j])
        lineList = []
        #creating lines between the points of plane2
        for i in range(0, len(pointList2)):
                if i == len(pointList2) - 1:
                        lineList.append(Line.Line(pointList2[i], pointList2[0]))
                else:
                        lineList.append(Line.Line(pointList2[i], pointList2[i + 1]))
        #cycling through all of plane1 points, seeing if any are behind plane2
        for i in range(0, len(pointList1)):
                count = 0
                ray = Line.Line([0, pointList1[i][1]], pointList1[i])
                vectorToEye = Line.Vector([center[0], 0, center[1]], [pointList[i][0] - center[0], pointList[i][1], pointList[i][2] - center[1]])
                for j in range(0, len(lineList)):
                        if Line.intersect(ray, lineList[j]):
                                count += 1

                

                if count % 2 == 1 and plane1.getDepth(i) > getIntersection(plane2, vectorToEye)[1]: 
                        front = False
                        break
        return front
Ejemplo n.º 8
0
def main():
    """
    all the test of the class Line
    """
    #Header
    print("*******************")
    print(" Line module test")
    print("*******************")
    #creation of 5 stations
    A = Station("A", [1., 0.])
    B = Station("B", [2., 0.])
    C = Station("C", [3., 0.])
    D = Station("D", [4., 0.])
    E = Station("E", [5., 0.])
    Line_1 = Line([A, B, C, D, E], "underground", "Line_1")
    ############################################################################
    #                           Declaration TEST                               #
    ############################################################################
    assert Line_1.station == [A, B, C, D, E]
    print("self.station    OK")
    assert Line_1.mode == "underground"
    print("self.mode       OK")
    assert Line_1.name == "Line_1"
    print("self.name       OK")
    ############################################################################
    #                               Message end                                #
    ############################################################################
    print("Line is         OK")
    print("*******************")
    print(Line_1._repr_())
Ejemplo n.º 9
0
 def __generateChildren(self):
     self.__population = self.__population[0:20]
     parents = list(self.__population)
     while len(parents) > 0:
         father = random.choice(parents)
         parents.remove(father)
         father = father.combinaison
         mother = random.choice(parents)
         parents.remove(mother)
         mother = mother.combinaison
         splitid = random.choice(range(self.nbcolor))
         children1 = Line.Line()
         children2 = Line.Line()
         for id in range(self.nbcolor):
             if id < splitid:
                 children1.addcolor(father.getcolor(id))
                 children2.addcolor(mother.getcolor(-id))
             else:
                 children1.addcolor(mother.getcolor(id))
                 children2.addcolor(father.getcolor(-id))
         result1 = children1.compareto(self.__answer)
         essai1 = Essai(result1.getCorrect(), result1.getRigthColor(), 10*result1.getCorrect()+result1.getRigthColor(), children1)
         result2 = children2.compareto(self.__answer)
         essai2 = Essai(result2.getCorrect(), result2.getRigthColor(), 10*result2.getCorrect()+result2.getRigthColor(), children2)
         if self.__population.count(essai1) == 0:
             self.__population.append(essai1)
         if self.__population.count(essai2) == 0:
             self.__population.append(essai2)
     self.__population.sort(key=lambda x: x.score, reverse=True)
Ejemplo n.º 10
0
 def __init__(self, filename):
     self.filename = filename
     self.file = [[]]
     self.longest = 0
     try:
         f = open(filename)
     except FileNotFoundError:
         print("File cannot be opened.")
         sys.exit(1)
     in_function = False
     i = 1
     for line in f:
         if line.startswith("import"):
             pass
         elif line.startswith("from"):
             pass
         elif line.strip().startswith("#"):
             pass
         elif line == '\n':
             if in_function:
                 in_function = False
             self.file[-1].append(Line.Line(line, "#", i))
         elif line.strip().startswith("def"):
             in_function = True
             self.file.append([Line.Line(line, "#", i)])
         else:
             self.file[-1].append(Line.Line(line, "#", i))
         i += 1
     f.close()
Ejemplo n.º 11
0
def load_image(image_name, camimgs, cam, invmask, hgback, hgmax, hgqual,
               hgmind, hgminf, scale, sigma):
    try:
        camimgs += image_name
        # Set up Homography object
        homog = Velocity.Homography(camimgs,
                                    cam,
                                    invmask,
                                    calibFlag=True,
                                    band='L',
                                    equal=True)
        # Calculate homography
        hg = homog.calcHomographyPairs(hgback, hgmax, hgqual, hgmind, hgminf)
        homogmatrix = [item[0] for item in hg]
        new_terminus = Line(camimgs, cam, homogmatrix)
        current_imgset = new_terminus._imageSet
        imn = new_terminus.getImageNames()

        cameraMatrix = cam.getCamMatrixCV2()
        distortP = cam.getDistortCoeffsCV2()

        # Create New Snake
        image = current_imgset[0].getImageCorr(cameraMatrix, distortP)
        processed_image = setup_image(image, scale, sigma)
        return processed_image
    except:
        return [[False]]
Ejemplo n.º 12
0
def crossroadLine():
    length = int(w.lenlineEntry.get())
    function = w.functionEntry.get()
    line_type = w.linetypeEntry.get()
    rotate_type = w.rotatetypeEntry.get()
    degree_rote = w.degreeroteEntry.get()
    speed_max = w.speedmaxEntry.get()
    wait_time = w.waittimeEntry.get()
    f = Frame(w.mapFrame,
              height=grid_size * 2,
              width=grid_size * 2,
              bg="#d9d9d9")
    k = Frame(f,
              height=LineVertical['height'],
              width=LineVertical['width'],
              bg="black")
    j = Frame(f,
              height=LineHorizal['height'],
              width=LineHorizal['width'],
              bg="black")
    k.place(x=grid_size / 2 + 4, y=0)
    j.place(y=grid_size / 2 + 4, x=0)
    f.pack_propagate(0)  # don't shrink
    f.place(x=0, y=0)
    labelsLine.append(
        Line(f, length, function, line_type, rotate_type, degree_rote,
             speed_max, wait_time))
    labelsLinecross.append(
        Line(f, length, function, line_type, rotate_type, degree_rote,
             speed_max, wait_time))
    f.bind("<Button-1>", drag_start)
    f.bind("<B1-Motion>", drag_motion)
    f.bind("<ButtonRelease-1>", drop_motion)
    f.bind("<Button-3>", popup)
    f.bind("<Enter>", information)
Ejemplo n.º 13
0
 def BinOpNode_compile(self, node: BinOpNode):
     if (node.op == ':='):
         self.__codeGen(node.arg2)
         self.lines.append(Line('STORE', node.arg1.name))
     else:
         self.__codeGen(node.arg1)
         self.__codeGen(node.arg2)
         self.lines.append(Line(op_cmd[node.op.value]))
Ejemplo n.º 14
0
    def minute(self):
        if self.minutes < MATCH_GLOBALS["TOTAL_TURNS"]:
            self.home.update_skill_tactic()
            self.away.update_skill_tactic()
            self.minutes += 1
            self.events = {"Home Possession": False, "Goal": False}
            home_tactic_inf = [(self.home.tactic[0] - self.away.tactic[2]) * MATCH_GLOBALS["TACTIC_INFLUENCE"],
                                (self.home.tactic[1] - self.away.tactic[1]) * MATCH_GLOBALS["TACTIC_INFLUENCE"],
                                (self.home.tactic[2] - self.away.tactic[0]) * MATCH_GLOBALS["TACTIC_INFLUENCE"]]

            home_concedes_rat   = (self.home.skill[0] - self.away.skill[2]) / float(PLAYER_GLOBALS["MAX_SKILL"]) + home_tactic_inf[0]
            home_possession_rat = (self.home.skill[1] - self.away.skill[1]) / float(PLAYER_GLOBALS["MAX_SKILL"]) + home_tactic_inf[1]
            home_scores_rat     = (self.home.skill[2] - self.away.skill[0]) / float(PLAYER_GLOBALS["MAX_SKILL"]) + home_tactic_inf[2]

            home_scores_prob     = Line.Line(((-1, MATCH_GLOBALS["MIN_GOAL_PER_POSS"]), (1, MATCH_GLOBALS["MAX_GOAL_PER_POSS"]))).solve_for_y(home_scores_rat)
            home_possession_prob = Line.Line(((-1, 1 - MATCH_GLOBALS["MAX_POSSESSION"]),(1, MATCH_GLOBALS["MAX_POSSESSION"]))).solve_for_y(home_possession_rat)
            home_concedes_prob   = Line.Line(((-1, MATCH_GLOBALS["MAX_GOAL_PER_POSS"]), (1, MATCH_GLOBALS["MIN_GOAL_PER_POSS"]))).solve_for_y(home_concedes_rat)

            poss_rand = random.uniform(0, 1)
            goal_rand = random.uniform(0, 1)

            #ANTI GOLEADAS:
            if self.result[0] >= 3 + self.result[1]:
                home_scores_prob = home_scores_prob * MATCH_GLOBALS["ANTI_GOLEADAS"]
            elif self.result[1] >= 3 + self.result[0]:
                home_concedes_prob = home_concedes_prob * MATCH_GLOBALS["ANTI_GOLEADAS"]

            #PROBABILIDADE HUMANA DE MARCAR NO FINAL
            min_norm = HelperMethods.normalize(self.minutes, 0, MATCH_GLOBALS["TOTAL_TURNS"])
            if min_norm <= 0.2:
                if self.away.manager.human:
                    home_scores_prob = home_scores_prob * MATCH_GLOBALS["GOAL_BEGINNING_END_MULTI"]
                if self.home.manager.human:
                    home_concedes_prob = home_concedes_prob * MATCH_GLOBALS["GOAL_BEGINNING_END_MULTI"]

            if min_norm >= 0.8:
                if self.home.manager.human:
                    home_scores_prob = home_scores_prob * MATCH_GLOBALS["GOAL_BEGINNING_END_MULTI"]
                if self.away.manager.human:
                    home_concedes_prob = home_concedes_prob * MATCH_GLOBALS["GOAL_BEGINNING_END_MULTI"]

            if poss_rand <= home_possession_prob:
                self.events["Home Possession"] = True
                self.possession[0] += 1
                if goal_rand <= home_scores_prob:
                    self.result[0] += 1
                    self.events["Goal"] = True
                    self.set_goalscorer(True)
            else:
                self.events["Home Possession"] = False
                self.possession[1] += 1
                if goal_rand <= home_concedes_prob:
                    self.result[1] += 1
                    self.events["Goal"] = True
                    self.set_goalscorer(False)
            return True
        else:
            return False
Ejemplo n.º 15
0
	def reset(self):
		self.left_fit = []
		self.right_fit = []
		ret,dist_coeffs,cam_matrix,rvecs,tvecs = calibrate_camera('camera_cal','calibration*.jpg',(9,6),(720,1280))
		self.c_matrix = cam_matrix
		self.dist_coeffs = dist_coeffs
		self.left_line = Line()
		self.right_line = Line()
		self.search_by_histogram = True
Ejemplo n.º 16
0
def drawEdges(screen, edgeMatrix, color):
    for i in range(0, len(edgeMatrix[0]) - 1, 2):
        Line.drawLine(
            screen,
            [int(round(edgeMatrix[0][i])),
             int(round(edgeMatrix[1][i]))], [
                 int(round(edgeMatrix[0][i + 1])),
                 int(round(edgeMatrix[1][i + 1]))
             ], color)
 def __init__(self, cameraCalibration, root_folder, output_folder):
     self.root_folder = root_folder
     self.output_folder = output_folder
     self.cameraCalibration = cameraCalibration
     self.frame_count = 0
     self.nframes_left_line = Line()
     self.nframes_right_line = Line()
     self.prev_left_fit = []
     self.prev_right_fit = []
Ejemplo n.º 18
0
    def pipeline(self):

        image = gradWarpPipeline.gradWarpPipeline()(self.image)

        # Histogram of the bottom half of the image
        histogram = np.sum(image[self.height // 2:, :], axis=0)

        # To find the peaks of the histogram. These peaks tell us where the lane edges are
        midpoint = np.int(histogram.shape[0] / 2)
        left_x = np.argmax(histogram[:midpoint])
        right_x = np.argmax(histogram[midpoint:]) + midpoint

        left_lane_indices = []
        right_lane_indices = []

        # Get nonzero pixels in the image. The nonzero() return a tuple of x, y points
        # that have nonzero value
        nonzero = image.nonzero()
        nonzeroy = nonzero[0]
        nonzerox = nonzero[1]

        # Stepping through the windows one by one

        for window in range(self.num_windows):
            # Identify window boundaries in x and y (and right and left)
            win_y_low = image.shape[0] - (window + 1) * self.window_height
            win_y_high = image.shape[0] - window * self.window_height

            left_window = laneTracker.window(left_x, win_y_low, win_y_high)
            right_window = laneTracker.window(right_x, win_y_low, win_y_high)

            # A list consisting of window objects
            self.left_lane_windows.append(left_window)
            self.right_lane_windows.append(right_window)

            # Get nonzero pixel indices within the window
            left_nonzero_indices = left_window.find_pixel_indices(nonzero)
            right_nonzero_indices = right_window.find_pixel_indices(nonzero)

            # Append the window nonzero pixel indices to the lists
            left_lane_indices.append(left_nonzero_indices)
            right_lane_indices.append(right_nonzero_indices)

            left_x = left_window.xMid
            right_x = right_window.xMid

        # Concatenate all the windows nonzero pixel indices
        left_lane_indices = np.concatenate(left_lane_indices)
        right_lane_indices = np.concatenate(right_lane_indices)

        self.left_lane = Line.Line(nonzerox[left_lane_indices],
                                   nonzeroy[left_lane_indices], self.height,
                                   self.width)

        self.right_lane = Line.Line(nonzerox[right_lane_indices],
                                    nonzeroy[right_lane_indices], self.height,
                                    self.width)
Ejemplo n.º 19
0
def test_toHTML():

    print("--- test_toHTML")

    filename = "../testData/monkeyAndThunder/AYA1_MonkeyandThunder.eaf"
    doc = etree.parse(filename)
    lineCount = len(doc.findall("TIER/ANNOTATION/ALIGNABLE_ANNOTATION"))
    line = Line(doc, 6)
    html = line.toHtml()
Ejemplo n.º 20
0
def dev():
    filename = "../testData/LOKONO_IJAL_2.eaf"
    doc = etree.parse(filename)
    line0 = Line(doc, 0)
    tbl = line0.getTable()

    childIDs = tbl.loc[tbl["ANNOTATION_REF"] == "a23",
                       "ANNOTATION_ID"].tolist()
    childText = tbl.loc[tbl["ANNOTATION_REF"] == "a23", "TEXT"].tolist()
    textLength = [len(t) for t in tbl["TEXT"].tolist()]
Ejemplo n.º 21
0
def callAll():
    fl = []
    with open('aist.csv', newline='') as f:
        reader = csv.reader(f, delimiter=',')
        for row in reader:
            fl.append(row)
    for row in fl:
        if (row[3] == 'manga') and checkConn():
            Ms.runn(row[0], row[1], int(row[2]))
        if (row[3] == 'webtoon') and checkConn():
            Line.runn(row[0], row[1], int(row[2]))
Ejemplo n.º 22
0
    def __init__(self, mtx, dist):
        self.mtx = mtx
        self.dist = dist
        self.sobelKernel = 3
        self.LeftLine = Line.Line()
        self.RightLine = Line.Line()
        self.confidence = 0

        #calculate perspective transformation matrix and inverse
        self.M = cv2.getPerspectiveTransform(src, dst)
        self.Minv = cv2.getPerspectiveTransform(dst, src)
Ejemplo n.º 23
0
class Borde:
    line = Line(0, 0, 0, 0)

    especularidad = False

    def __init__(self, x1, y1, x2, y2, _especularidad):
        self.line = Line(x1, y1, x2, y2)
        self.especularidad = _especularidad

    def draw(self, surface):
        self.line.draw(surface)
Ejemplo n.º 24
0
 def __init__(self):
     self.left_line = Line()
     self.right_line = Line()
     self.mtx = None
     self.dist = None
     self.sobel_kernel_size = 3
     self.x_grad_threshold = (30, 150)
     self.hls_s_channel_threshold = (125, 255)
     self.perspective_M = None
     self.perspective_Minv = None
     # Reset the line detection after too many bad curvature transform
     self.reset_lane_detect = True
Ejemplo n.º 25
0
def test_getTable_from_LOKONO():

    print("--- test_getTable_from_LOKONO")
    pd.set_option('display.width', 1000)
    filename = "../testData/LOKONO_IJAL_2.eaf"
    doc = etree.parse(filename)

    x3 = Line(doc, 3)
    tbl3 = x3.getTable()
    assert (x3.classifyTier(0) == "spokenText")
    assert (x3.classifyTier(1) == "nativeGlossOrFreeTranslation")
    assert (x3.classifyTier(2) == "nativeMorpheme")
def smoothen_over_time(lane_lines):
    """
    Smooth the lane line inference over a window of frames and returns the average lines.
    """

    avg_line_lt = np.zeros((len(lane_lines), 4))
    avg_line_rt = np.zeros((len(lane_lines), 4))
    for t in range(0, len(lane_lines)):
        avg_line_lt[t] += lane_lines[t][0].get_coords()
        avg_line_rt[t] += lane_lines[t][1].get_coords()

    return Line(*np.mean(avg_line_lt, axis=0)), Line(
        *np.mean(avg_line_rt, axis=0))
Ejemplo n.º 27
0
def test_recognizeDegenerateLine():

    """
      MonkeyAndThunder starts off with a few introductory lines in Spanish, with English translation.
      No words, no glosses, just a line with time slots, and one child
    """
    print("--- test_recognizeDegenerateLine")

    filename = "../testData/monkeyAndThunder/AYA1_MonkeyandThunder.eaf"
    xmlDoc = etree.parse(filename)
    x0 = Line(xmlDoc, 0)
    assert(x0.getTierCount() == 2)
    classifier = LineClassifier(x0.getTable())
    assert(classifier.run() == "DegenerateLine")
Ejemplo n.º 28
0
def test_LOKONO_allLinesRecognized():

    print("--- test_LOKONO_allLinesRecognized")

    filename = "../testData/LOKONO_IJAL_2.eaf"
    xmlDoc = etree.parse(filename)
    lineCount = len(xmlDoc.findall("TIER/ANNOTATION/ALIGNABLE_ANNOTATION"))
    assert(lineCount == 344)
    for i in range(lineCount):
       x = Line(xmlDoc, i)
       classifier = LineClassifier(x.getTable())
       classification = classifier.run()
       #print("%d: %s" % (i, classification))
       assert(classification in ["WordsAsElementsLine"])
Ejemplo n.º 29
0
def test_MonkeyAndThunder_allLinesRecognized():

    print("--- test_MonkeyAndThunder_allLinesRecognized")

    filename = "../testData/monkeyAndThunder/AYA1_MonkeyandThunder.eaf"
    xmlDoc = etree.parse(filename)
    lineCount = len(xmlDoc.findall("TIER/ANNOTATION/ALIGNABLE_ANNOTATION"))
    assert(lineCount == 41)
    for i in range(lineCount):
       x = Line(xmlDoc, i)
       classifier = LineClassifier(x.getTable())
       classification = classifier.run()
       #print("%d: %s" % (i, classification))
       assert(classification in ["DegenerateLine", "CanonicalLine"])
Ejemplo n.º 30
0
def test_recognizeCanonicalLine():

    """
      MonkeyAndThunder line 6 fits the canonical form:
        1) a time line
    """

    print("--- test_recognizeCanonicalLine")

    filename = "../testData/monkeyAndThunder/AYA1_MonkeyandThunder.eaf"
    xmlDoc = etree.parse(filename)
    x = Line(xmlDoc, 6)
    assert(x.getTierCount() == 4)
    classifier = LineClassifier(x.getTable())
    assert(classifier.run() == "CanonicalLine")
Ejemplo n.º 31
0
    def get_thread(self):
        """
        get thread
        """

        print(self.thread)
        print("=====body=====\n\n")
        seed = requests.get(self.thread)
        soup = BeautifulSoup(seed.content, "html.parser")
        # body = soup.find_all("span")
        body = soup.find_all("span", class_="cntd")
        print(body)
        # del body[0:4]
        # body.pop()
        # body.pop()
        # body.pop()
        print("-----after body -----\n\n")
        print(body)
        end = body[0].text
        end = end.replace(u"頃消えます", "")
        if len(end) > 5:
            end = end[(len(end) - 5):]
        gabage = '"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" %s'
        browser = webbrowser.get(gabage)
        browser.open(self.thread)
        noti = "'display notification " " with title \"Get Deresute Thread!!!\"'"
        os.system("osascript -e" + noti)
        Line(self.thread).notify_line()
        Output("g", end, "Get Thread!!!").call_result()
Ejemplo n.º 32
0
def test_recognizeWordsAsElementsLine():

    """
      LOKONO has the canonical spokenText tier, its translation, but each word in the
      spokenText is its own element, each with two children: morpheme and gloss
    """

    print("--- test_recognizeWordsAsElementsLine")

    filename = "../testData/LOKONO_IJAL_2.eaf"
    xmlDoc = etree.parse(filename)
    x = Line(xmlDoc, 1)
    # print(x.getTable())
    assert(x.getTierCount() == 20)
    classifier = LineClassifier(x.getTable())
    assert(classifier.run() == "WordsAsElementsLine")
Ejemplo n.º 33
0
 def updateAfterCount(self, opts, symbol):
     if not Line.matchedSymbolTail(symbol, opts.matchSyms):
         # here we assume the real symbol block comes last. works for uses in f90
         return 0
     if opts.language in ['cxx','python','f77','f90','java']:
         if (opts.linesAfter < 1):
             return 1
     if opts.language in ['c']:
         if (opts.linesAfter < 2):
             return 2
     return opts.linesAfter
Ejemplo n.º 34
0
    def writeString(self, outFileName, verbose=False, rejectSave=True, rejectFileName="", rejectLines =[]):
        """return string representation of file for other's to output. outFileName is used to write rejects if specified or to issue error messages.
@return (status, resultString) where if status is True, string will be valid and if false, the input
source was apparently empty."""
        fname = outFileName
        writeRejects = (rejectSave and rejectLines != None)
        if writeRejects:
            rname = fname + ".rej"
            if len(rejectFileName) > 0:
                rname = rejectFileName
        if self.nsplices < 1:
            if verbose:
                print "Nothing new to write to ", fname
            if self.num < 1:
                print "Nothing old to copy to ", fname
                print "Reading ", self.fin, " failed?" 
                return (False, "")
        if verbose:
            if writeRejects:
                print "Writing rejects to ", rname
            print "Writing to string for ", fname
        if True: 
            outlist = []
            if writeRejects:
                try:
                    rejfile = fileManager.open(rname,"w")
                except:
                    err('splicer could not open rejects file for writing: ' + rname)
            for i in self.sections:
                isProtected = False
                for s in self.protectedSymbols:
                    if i == self.getProtectedBlock(s):
                        isProtected = True
                        break
                if isProtected:
                    continue
                lines = i.getLines() 
                for p in lines:
                    outlist.append( p.strip("\n") )
            stringified = "\n".join(outlist)
            if writeRejects:
                date = Line.stringdate()
                print >> rejfile, "#FROM %s on %s" % (fname, date)
                for p in rejectLines:
                    print >> rejfile , p.strip("\n")
            if verbose:
                if writeRejects:
                    print " Finished ", rname
                print " Finished ", fname
            return (True, stringified)
        else:
            print "Error writing for "+ fname
            return (False, "")
Ejemplo n.º 35
0
 def endChunk(self, key, blockStart, lineList, line, inputfilename, subsymbols=[], protected=False):
     """ finish recording a chunk and save data.
         string key, int blockStart, reference linelist """
     symbol = "null"
     if key != "null":
         symbol = Line.symbolOf(line)
         if not protected and symbol in self.symbols:
             print "Warning: duplicate block for symbol ", symbol, " ignored at line ", str(blockStart)
             return
         elif protected and symbol in self.protectedSymbols:
             print "Warning: duplicate block for protected symbol ",symbol,"ignored at line ", str(blockStart)
             return
         if not protected:
             self.symbolIndex[symbol] = len(self.sections)
             self.symbols.append(symbol)
         else:
             self.protectedSymbolIndex[symbol] = len(self.sections)
             self.protectedSymbols.append(symbol)
     block = Block.Block()
     block.init(key, lineList, inputfilename, blockStart, subsymbols)
     self.sections.append(block)
Ejemplo n.º 36
0
    def loadList(self, input, key, lines, warn=True, preserveProtected=False):
        """Load a list of lines as a source. Either this or load may be called once per SourceFile object. 
        input is an identifier string, normally a filename, that might be useful in error messages. 
        key is the splicing generic prefix tag (not per-sidl-symbol), and lines is the data."""

        chunk = []
        protectedChunk = [] # protected blocks need a separate chunk
        subsymbols = [] # Symbols designating substitution blocks
        nokey = "null"
        protectedKey = "bocca.protected"
        message = "Block still unended at end of file."
        self.num = 0
        blockStart = 1
        protectedBlockStart = 0
        seek_begin = True # true while not in key'd block
        protected_block = False # true while in bocca.protected
        for line in lines:
            self.num += 1
            if seek_begin:
                if Line.keyEnds(key, line):
                    seek_begin = False
                    message = "Block end found before beginning."
                    break
                # outside a key block, start block, or append old.
                if Line.keyBegins(key, line):
                    seek_begin = False
                    self.endChunk( nokey, blockStart, chunk, line, input, protected=False) # save old if any
                    blockStart = self.num
                    self.beginChunk( chunk) # start new if any
                    chunk.append(line)
                else:
                    chunk.append(line)
            elif protected_block:
                # inside a protected block
                if Line.keyBegins(protectedKey, line) or Line.keyBegins(key, line):
                    message = "Block begin found inside bocca.protected"
                    break
                if Line.keyEnds(protectedKey, line):
                    protectedChunk.append(line)
                    chunk.append(line)
                    self.endChunk( protectedKey, protectedBlockStart, protectedChunk, line, input, protected=True)

                    subsymbols.append(Line.symbolOf(line))
                    protected_block = False;
                else:
                    # Chunk contains content of subblocks; will be replaced/stubbed if necessary when
                    # performing substitution
                    protectedChunk.append(line)
                    chunk.append(line)
            else:
                # inside  a key block
                if Line.keyBegins(key,line): # warn unended block
                    message = "Block begin found inside another."
                    break
                if Line.keyEnds(key,line):
                    seek_begin = True
                    chunk.append(line)
                    self.endChunk( key, blockStart, chunk, line, input, subsymbols, protected=False) # save key block
                    subsymbols = []
                    blockStart = self.num+1 # start new block
                    self.beginChunk( chunk)
                elif preserveProtected and Line.keyBegins(protectedKey, line):
                    # Begin the protected block
                    protectedBlockStart = self.num
                    self.beginChunk(protectedChunk)
                    protectedChunk.append(line)
                    chunk.append(line)
                    protected_block = True;
                else:
                    chunk.append(line)
            # end else
        # end for
        if not seek_begin:
            print "In ", input, ":", message, " at line ", self.num
            if len(chunk) > 0:
                print "Current block started at line ", blockStart, ":"
                print "\t", chunk[0]
            return (1, message)
        if len(chunk) > 0:
            self.endChunk( nokey, blockStart, chunk, line, input)
        if len(self.symbolIndex) < 1 and warn:
            print "Warning: no blocks in ", input, " for key ", key

        return (0, "ok")
Ejemplo n.º 37
0
    def writeBlock(self, before, fs, after, opts, append):
        """process a block with -B -A or --signature options.
# return 0 if ok, nonzero otherwise
# @param before the block ahead of this one or none if this is first.
# @param fs the current block to print.
# @param after the block after this one or none if this is last.
# @param opts handling flags for lines.
# @param append[0] an in-out integer array with one element. it tracks
# how many blocks have been written in the single file case.
"""
        lines = fs.getLines()
        pos = 0
        symbol = Line.symbolOf(lines[pos])
        if symbol == "null":
            return 1
        if not Line.matchedSymbol(symbol, opts.matchSyms):
            return 0
        # compute before lines
        pre = opts.linesBefore
        post = opts.linesAfter 
        if (opts.signatures or opts.method) and before != None:
            post = self.updateAfterCount(opts, symbol) 
            pre = before.computeSignature( symbol, opts.language, opts.sourceKey, opts.methodcomment)
        outlines = []
        if pre > 0 and before != None:
            blines = before.getLines()
            blen = len(blines)
            while blen > 0 and pre > 0:
                outlines.append(blines[blen-1])
                blen -= 1
                pre -= 1
            outlines.reverse()
        # copy main segment
        if opts.genLines:
            endtag=""
            if opts.method:
                endtag="/* This line not in actual source */"
            Line.addLineNumber(fs.start(), outlines, fs.source(), opts.language, endtag )
        while pos < len(lines):
            outlines.append(lines[pos])
            pos += 1
        pos = 0
        # compute after
        if post > 0 and after != None:
            alines = after.getLines()
            n = 0
            while n < len(alines) and post > 0:
                outlines.append(alines[n])
                n += 1
                post -= 1

        # write
        if len(outlines) < 1:
            return 1
        flags = "w"
        if opts.singleFile:
            if append[0]:
                flags= "a"
            if len(opts.outputFile):
                fname = os.path.join(opts.outputDir, opts.outputFile)
            else:
                fname = os.path.join(opts.outputDir, opts.inputFile)
                fname += ".splice"
        else:
            fname = os.path.join(opts.outputDir, opts.blockFilePrefix)
            # print "Writing block for ", symbol, fname
            fname = fname + symbol + opts.blockFileSuffix
            # print "Writing block for ", symbol, fname
        try:
            outfile = open(fname,flags)
            if opts.singleFile and append[0] and len(opts.spliceHeader) > 0 and (not opts.method):
                w = 0
                delta = len(opts.spliceHeader)
                while w < 72:
                    outfile.write("%s" % opts.spliceHeader)
                    w += delta
                outfile.write("\n")
            j = 0
            while j < len(outlines): 
                if opts.keepLines or opts.genLines or outlines[j][0:5] != "#line":
                    print >> outfile, outlines[j].strip("\n")
                j+= 1
            append[0] += 1
            return 0
        except:
            print "Error writing block for ", symbol
            return 1
Ejemplo n.º 38
0
    def computeSignature(self, symbol, language, sourcekey, withcomment=False):
        """return attempted guess at the number of lines at the end of the
block that constitute a babel impl method signature.
The block being checked is the block before the block with the symbol code body.
@param language one of python, java, c, cxx, f77, f90. 
@param sourceKey the key, not symbol, of interest.
@param withcomment try to include the comment block if any.
"""
        result = 0
        lines = self.getLines()
        p = len(lines)-1
        if p < 1:
            return 0
        line = lines[p]
        if language == "python":
            while p >= 0 and line[0:4] != "####" and line[0:6] != "  def " and \
                  not Line.keyEnds(sourcekey, line) and \
                  not Line.keyBegins(sourcekey,line):
                # break on 2 blank lines
                if len(line) == 0:
                    q = p -1
                    if q >= 0 and len(lines[q]) == 0:
                        break
                # else keep line, move on to next
                result += 1
                p -= 1
                line = lines[p]
            result += 1 ; # include '  def ' line.
            # python comment blocks are embedded, not extra.
        if language == "java":
            while p > 0 and len(line) != 0 and \
                line[0:6] != "import" and \
                line[0:8] != "  public" and \
                line[0:4] != "////" and \
                line[0:3] != "/**" and \
                line[0:5] != "   */" and \
                line[0:8] != "  static" and \
                not Line.keyEnds(sourcekey, line) and \
                not Line.keyBegins(sourcekey,line):
                result += 1
                p -= 1
                line = lines[p]
            result += 1 ; # include '  public' line.
            if withcomment:
                while p > 0 and len(line) != 0 and \
                    line[0:5] != "  /**" and \
                    not Line.keyEnds(sourcekey, line) and \
                    not Line.keyBegins(sourcekey,line):
                    result +=1
                    p -= 1
                    line = lines[p]

        if language == "c" or language == "cxx":
            while p > 0 and \
                not Line.cppDirective(line) and \
                line[0:15] != "// user defined" and \
                line[0:15] != "// static class"  and \
                line[0:3] != "/**"  and \
                line[0:3] != " */"  and \
                line[0:5] != "   */"  and \
                line[0:22] != "// special constructor"  and \
                line[0:22] != "// speical constructor" and \
                line[0:1] != "}"  and \
                line[0:8] != "////////"  and \
                line[0:8] != "/**//**/" and \
                not Line.keyEnds(sourcekey, line) and \
                not Line.keyBegins(sourcekey,line):

                # two blank lines, or 1 if _tail symbol
                if len(line) == 0:
                    mname = Line.methodName(symbol)
                    if mname[0] == "_":
                        break
                    q = p-1
                    if q >= 0 and len(lines[q]) == 0:
                        break
                # else keep line and move on
                result += 1
                p -= 1
                line = lines[p]
            if withcomment:
                while p > 0 and len(line) != 0 and \
                    line[0:5] != "  /**" and \
                    line[0:2] != "/*" and \
                    not Line.keyEnds(sourcekey, line) and \
                    not Line.keyBegins(sourcekey,line):
                    result +=1
                    p -= 1
                    line = lines[p]
                result += 1 ; # include '(  )/*(*)' line.

        if language == "f77" or language == "f77_31":
            while p > 0 and \
                line[0:19] != "        subroutine " and \
                line[0:4] != "CCCC" and \
                not Line.keyEnds(sourcekey, line) and \
                not Line.keyBegins(sourcekey,line):

                # break on 2 blank lines
                if len(line) == 0:
                    q = p -1
                    if q >= 0 and len(lines[q]) == 0:
                        break
                # else keep line and move on
                result += 1
                p -= 1
                line = lines[p]
            result += 1 ; # include subroutine
            if withcomment:
                while p > 0 and len(line) != 0 and \
                    line[0:15] != "C       Method:" and \
                    not Line.keyEnds(sourcekey, line) and \
                    not Line.keyBegins(sourcekey,line):
                    result +=1
                    p -= 1
                    line = lines[p]

        if language == "f90":
            while p > 0 and \
                line[0:21] != "recursive subroutine " and \
                line[0:5] != "!!!!" and \
                not Line.keyEnds(sourcekey, line) and \
                not Line.keyBegins(sourcekey,line):

                # break on 2 blank lines
                if len(line) == 0:
                    q = p -1
                    if q >= 0 and len(lines[q]) == 0:
                        break
                # else keep line and move on
                result += 1
                p -= 1
                line = lines[p]
            result += 1 ; # include subroutine
            if withcomment:
                while p > 0 and len(line) != 0 and \
                    line[0:9] != "! Method:" and \
                    not Line.keyEnds(sourcekey, line) and \
                    not Line.keyBegins(sourcekey,line):
                    result +=1
                    p -= 1
                    line = lines[p]

        return result
Ejemplo n.º 39
0
 def copy_line(self, line, x, y):
     new_line = Line(x, y)
     new_line.copy(line)
     self.model.add_line(new_line)
     self.drag_line(new_line, x, y)
Ejemplo n.º 40
0
	def add_line(self,ion,idx):
		lnow = Line(ion,idx,self.model_name,self.galaxy,self.radii)
		lnow.total_probability()
		self.lines = np.append(self.lines,lnow)
		self.nlines = self.nlines + 1
		return	
 def intersects(self, a,b,x,i):
   #if self.intersecting[a][b][x][i] == None:
     #self.intersecting[a][b][x][i]=Line.linesIntersect(self.cords[i],self.cords[x],self.cords[a],self.cords[b])
   #return self.intersecting[a][b][x][i]
   return Line.linesIntersect(self.cords[i],self.cords[x],self.cords[a],self.cords[b])
Ejemplo n.º 42
0
        if len(rejectLines) == 0:
            print "No rejection information to put into " + rejectFileName
            return False
        if dryrun:
            print "Dry run: Not writing to " + rejectFileName
            # For a dry run, don't do anything
            return True
        if verbose:
            print "Writing rejects to: " + rejectFileName
        outfile = None
        try:
            outfile = fileManager.open(rejectFileName,'w')
        except IOError, e:
            err('splicer could not open reject file %s for writing: %s' % (rejectFileName, str(e)))
        if len(originalFile) > 0:
            date = Line.stringdate()
            print >> outfile, "# Rejects FROM %s on %s" % (originalFile, date)
        for p in rejectLines:
                print >> outfile, p.strip("\n")
        if verbose:
            print "Finished writing rejects: " + rejectFileName
        return True
        
    # end writeRejects

    # private use
    def updateAfterCount(self, opts, symbol):
        if not Line.matchedSymbolTail(symbol, opts.matchSyms):
            # here we assume the real symbol block comes last. works for uses in f90
            return 0
        if opts.language in ['cxx','python','f77','f90','java']:
Ejemplo n.º 43
0
def isCommon(sym, commonSuppressions):
    """returns True if symbol matches commonSuppressions entry."""
    method = Line.methodName(sym)
    if method in commonSuppressions:
        return True
    return False