def test_direction_vector(): """Test getting the direction Vector of a Line""" line1 = Line(Vector([2, 3]), 6) direction_vector = line1.direction_vector() answer = Vector([3, -2]) assert direction_vector == answer
def trimJoin_Coro(self): """ Yields a list of lines that have their ends properly trimmed/joined after an offset. When the lines are offset their endpoints are just moved away the offset distance. If you offset a circle to the inside this would mean that all of the lines would overlap. If the circle was offset to the outside none of the lines would be touching. This function trims the overlapping ends and extends/joins the non touching ends. Yields ------ in - Lines out - one big List of lines at the end. """ offsetLines = [] moveEnd = yield moveStart = yield while not(moveStart is None): _, point = moveEnd.segmentsIntersect(moveStart, c.ALLOW_PROJECTION) moveEnd = Line(moveEnd.start, point, moveEnd) moveStart = Line(point, moveStart.end, moveStart) offsetLines.append(moveEnd) moveEnd = moveStart moveStart = yield _, point = moveEnd.segmentsIntersect(offsetLines[0], c.ALLOW_PROJECTION) moveEnd = Line(moveEnd.start, point, moveEnd) offsetLines.append(moveEnd) offsetLines[0] = Line(point, offsetLines[0].end, offsetLines[0]) yield offsetLines
def test_line_intersection(): """Test if two lines intersect""" line1 = Line(Vector([2, 5]), 10) line2 = Line(Vector([1, 1]), 5) assert line1.is_parallel(line2) is False assert line1.point_of_intersection(line2) == (Decimal(5), Decimal(0))
def test_intersect_edge(self): l1 = Line(Point([0,0]), Point([10, 0])) l2 = Line(Point([0, 0]), Point([5, 5])) p = l1.intersection(l2) self.assertEqual(p.vec, [0.0, 0.0, 1.0])
def roadWidthArr( roadPts ): "points are expected to be 4 already sorted by BLBRTRRL image order" assert len(roadPts) == 4, roadPts bl,br,tr,tl = roadPts lineL = Line(bl,tl) lineR = Line(br,tr) return abs(lineR.signedDistance(bl)),abs(lineL.signedDistance(br)),abs(lineL.signedDistance(tr)),abs(lineR.signedDistance(tl))
def add_date_lines(self, x_values, y_values, name='', has_dot=False, forced_selected_date=True, linestyle='-'\ ,linewidth=2, markersize=3, color='', alpha=1): line = Line(self) now_color = self.ax._get_lines.color_cycle.next() if color != '': now_color = color self.now_color = now_color self.alpha = float(alpha) y_values = self.change_missing_value(y_values, [np.nan, 'nan', 'Nan'], np.nan) output_line, = line.date_plotting(x_values, y_values, name, has_dot, forced_selected_date, linestyle, linewidth, markersize, now_color, float(alpha)) self._add_legends(output_line, name) if forced_selected_date: self.min_date = x_values[0] self.max_date = x_values[-1] self.set_xaxis_limit() valid_items = [i for i in y_values if i != 0] if len(valid_items) > 0: self.min_value.append(np.nanmin(valid_items)) self.max_value.append(np.nanmax(valid_items))
def test_intersect_parallel(self): l1 = Line(Point([0,0]), Point([10, 0])) l2 = Line(Point([0, 5]), Point([5, 5])) p = l1.intersection(l2) self.assertEqual(p, False)
def draw(self, *args, **kwargs): """ Draw both the Line and the Axis' label. Does not draw the Ticks. See Axis.drawTicks() for that. """ Line.draw(self, *args, **kwargs) self._label.draw(*args, **kwargs)
def getPolygon(self): leftLine = Line(self.p(0.0, 1.0), self.p(0.0, 0.0), self.weight(), shift="right", serif=3) topLine = Line(self.p(0.0, 1.0), self.p(1.0, 1.0), self.weight(), shift="down", serif=1) midHeight = self.p(0.0, 0.5, xHeight=True)[1] midLeft = leftLine.atY(midHeight) midLine = Line((midLeft, midHeight), (midLeft + self.width() / PHI, midHeight), self.weight()) return [leftLine, topLine, midLine]
def test_line_is_coincidence(): """Test if a line is a coincidece""" line1 = Line(Vector([2, 3]), 1) line2 = Line(Vector([2, 3]), 1) assert line1.is_parallel(line2) is True assert line1.is_coincidence(line2) is True line3 = Line(Vector([2, 3]), 6) assert line1.is_parallel(line3) is True assert line1.is_coincidence(line3) is False
def getPolygon(self): leftLine = Line(self.p(0.0, 1.0), self.p(0.0, 0.0), self.weight(), serif=4) rightLine = Line(self.p(1.0, 1.0), self.p(1.0, 0.0), self.weight(), serif=4) midHeight = self.p(0.0, 0.5, xHeight=True)[1] midLeft = leftLine.atY(midHeight) midRight = rightLine.atY(midHeight) midLine = Line((midLeft, midHeight), (midRight, midHeight), self.weight()) return [leftLine, rightLine, midLine]
def define (self, dwg): for element in range(0,1000): circle = Circle() line = Line() parabola = Parabola() splash = Splash() circle.define(dwg) line.define(dwg) parabola.define(dwg) splash.define(dwg)
def test_simpleLine(self): address = self.address() accept = self.serve(address) client=create_connection(address) try: data = b'sdafsf454534\n' line = Line(client) line.write(data) l = line.readline(timedelta(seconds=1), b'\n') self.assertEqual(data, l+b'\n') finally: client.close() accept.close()
def draw_shape(self,event,x,y,flag,parm): if event == cv2.EVENT_LBUTTONDOWN: if not self.lines or self.lines[-1].complete: newLine = Line(len(self.lines),x,y,0) self.lines.append(newLine) else: self.lines[-1].addSecondCoordinates(x,y) if event == cv2.EVENT_RBUTTONDOWN: if not self.lines or self.lines[-1].complete: newLine = Line(len(self.lines),x,y,1) self.lines.append(newLine) else: self.lines[-1].addSecondCoordinates(x,y)
def test_split_at_nomenclature(self): self.pp.append_ahead(Line('hamster')) self.pp.append_ahead( Line('≡ Polyporus mori (Pollini) Fr., Systema Mycologicum 1:')) self.pp.append_ahead(Line('344 (1821)')) self.pp.append_ahead(Line('gerbil')) result = self.pp.split_at_nomenclature() self.assertEqual(str(self.pp), 'hamster\n') self.assertEqual( str(result), '≡ Polyporus mori (Pollini) Fr., Systema Mycologicum 1:\n' '344 (1821)\n') self.assertEqual(result.next_line.line, 'gerbil')
def intersect(self, line: Line) -> float: point_a = self.__points[0] point_b = self.__points[1] point_c = self.__points[2] # degenerate line: 0x + 0y + 0 = 0, so it is point try: deviation_a = line.normalize().get_deviation(point_a[0], point_a[1]) deviation_b = line.normalize().get_deviation(point_b[0], point_b[1]) deviation_c = line.normalize().get_deviation(point_c[0], point_c[1]) except ZeroDivisionError: return 0 # line goes throw a vertex of triangle for point in self.__points: if line.contains_point(point[0], point[1]): other_points = list(set(self.__points) - {point}) intersection_point = line.intersect_with_line(Line(other_points[0][0], other_points[0][1], other_points[1][0], other_points[1][1])) return ((point[0] + intersection_point[0]) ** 2 + (point[1] + intersection_point[1]) ** 2) ** (1 / 2) # the line goes throw two sides of triangle new_points = [] if deviation_a * deviation_b < 0: proportionality_coefficient = abs(deviation_a / deviation_b) x = (point_a[0] + proportionality_coefficient * point_b[0]) / (1 + proportionality_coefficient) y = (point_a[1] + proportionality_coefficient * point_b[1]) / (1 + proportionality_coefficient) new_points.append((x, y)) if deviation_a * deviation_c < 0: proportionality_coefficient = abs(deviation_a / deviation_c) x = (point_a[0] + proportionality_coefficient * point_c[0]) / (1 + proportionality_coefficient) y = (point_a[1] + proportionality_coefficient * point_c[1]) / (1 + proportionality_coefficient) new_points.append((x, y)) if deviation_b * deviation_c < 0: proportionality_coefficient = abs(deviation_b / deviation_c) x = (point_b[0] + proportionality_coefficient * point_c[0]) / (1 + proportionality_coefficient) y = (point_b[1] + proportionality_coefficient * point_c[1]) / (1 + proportionality_coefficient) new_points.append((x, y)) # the line doesn't cross triangle if len(new_points) < 2: return 0 point1 = new_points[0] point2 = new_points[1] return ((point1[0] - point2[0]) ** 2 + (point1[1] - point2[1]) ** 2) ** (1 / 2)
def __init__(self, camera_calibrator=CameraCalibrator(), perspective_transformer=PerspectiveTransformer(), edges_detector=EdgesDetector(), picture_annotator=None): self.camera_calibrator = camera_calibrator self.perspective_transformer = perspective_transformer self.edges_detector = edges_detector if (picture_annotator is None): self.picture_annotator = PictureAnnotator(perspective_transformer) else: self.pictureAnnotator = picture_annotator self.left = Line() self.right = Line()
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))
def max_time_strategy(self, game): best_angle = -1 best_time = 0 best_vel = Vector2D(0, 0) best_p = None best_d = 0 for angle in np.linspace(0, math.pi * 2, NUM_RAYS): vel = Vector2D.from_angle(angle) line = Line(self.pos.x, self.pos.y, self.pos.x + vel.x * 1000, self.pos.y + vel.y * 1000) if game.draw: line.draw(game.screen) time = 0 for other_line in game.puck.path: p = line.intersection(other_line) if p: if game.draw: Circle(p.x, p.y, 5, pygame.Color('yellow')).draw(game.screen) t = other_line.find_t( p) * other_line.length() / game.puck.vel.mag() if game.draw: textsurface = myfont.render( str(round(time + t, 3)) + " frames", False, (0, 0, 0)) game.screen.blit(textsurface, (p.x, p.y)) if self.pos.distsq(p) < 5**2: self.vel = Vector2D(0, 0) if time + t >= best_time and p.y <= game.center_y: best_time = time + t best_p = p best_time = time + t best_angle = angle best_vel = copy(vel) best_d = math.sqrt(self.pos.distsq(p)) time += other_line.length() / game.puck.vel.mag() if best_p: if game.draw: Circle(best_p.x, best_p.y, 10, pygame.Color('purple')).draw(game.screen) self.vel = Vector2D.from_angle(best_angle).setmag( min(self.max_vel, best_d / best_time))
def generate_extremas(self, polygon, y): extremas = [] scan_line = Line(Point([self.canvas.xmin, y]), Point([self.canvas.xmax, y])) for edge in polygon.lines: if edge.horizontal(): continue if y == edge.highest(): continue if y >= edge.lowest() and y < edge.highest(): p = scan_line.intersection(edge) if p == False: continue # lines are parallel extremas.append(p) return extremas
def makeVCurveL(self): vCurvesHeight = self.vCurvesHeight vCurvesWidth = self.vCurvesWidth vCurvesDepth = self.vCurvesDepth v21 = Base.Vector(self.stopsWidth,0,self.botCurveHeight); v11 = v21 + Base.Vector(-(1-self.stopRatio)*self.stopsWidth,0,self.stopsHeight) v12 = v11+Base.Vector(vCurvesWidth,0,vCurvesHeight); l = Line().fromPoints((v11.x, v11.z), (v12.x, v12.z)) c11 = l.bissection().pointAtDist(-vCurvesDepth) cv11 = Base.Vector(c11[0],0,c11[1]) a1 = Part.Arc(v12,cv11,v11) return a1.toShape()
def test_lines(): n1 = Vector([4.046, 2.836]) c1 = 1.21 n2 = Vector([10.115, 7.09]) c2 = 3.025 l1 = Line(n1, c1) l2 = Line(n2,c2) #print "l1 is parallel to l2: ", l1.is_parallel_to(l2) print "l1 is same as l2: ", l1 ==l2 if l1.intersects(l2): intersection = l1.intersection_with(l2) print "intersection: ", intersection else: print "No intersection" print "-"*60 n1 = Vector([7.204, 3.182]) c1 = 8.68 n2 = Vector([8.172, 4.114]) c2 = 9.883 l1 = Line(n1, c1) l2 = Line(n2,c2) #print "l1 is parallel to l2: ", l1.is_parallel_to(l2) print "l1 is same as l2: ", l1 ==l2 if l1.intersects(l2): intersection = l1.intersection_with(l2) print "intersection: ", intersection else: print "No intersection" print "-"*60 n1 = Vector([1.182, 5.562]) c1 = 6.744 n2 = Vector([1.773, 8.343]) c2 = 9.525 l1 = Line(n1, c1) l2 = Line(n2,c2) #print "l1 is parallel to l2: ", l1.is_parallel_to(l2) print "l1 is same as l2: ", l1 ==l2 if l1.intersects(l2): intersection = l1.intersection_with(l2) print "intersection: ", intersection else: print "No intersection"
def __init__(self, id, points, algorithm, color): """store the basical information of a line object""" self.id = id self.points = points self.lines = [] for i in range(len(self.points)): if i == len(self.points) - 1: self.lines.append( Line(i, points[i], points[0], algorithm, color)) else: self.lines.append( Line(i, points[i], points[i + 1], algorithm, color)) self.algorithm = algorithm self.color = color
def read_line(self) -> Iterator['Line']: for l_str in self.contents(): l = Line(l_str, self) self._line_number += 1 # First line of first page does not have a form feed. if self._line_number == 1 and self._page_number == 1: self._set_empirical_page(l.line) if l.startswith(''): self._page_number += 1 self._line_number = 1 # Strip the form feed. self._set_empirical_page(l.line[1:]) l = Line(l_str, self) yield l
def main(writer): sim_time = 0 end_time = 60 * 60 # end_time = 1 n_wagon = 21 dt = 0.1 time = np.arange(0, end_time, dt) position = np.zeros((len(time), n_wagon)) line = Line('verte_full.json') stations = {name: dist for name, dist in zip(line.station_names, line.dist)} monitor = [400, 475] for v in line.speed_lim: print(v) print('min: ', min(line.speed_lim) * 3.6) print('max: ', max(line.speed_lim) * 3.6) print('moyenne: ', (sum(line.speed_lim) / len(line.speed_lim)) * 3.6) exit() try: for i, t in enumerate(time): line.update(t) # d = ['%06.1f' % t] now_p = np.zeros((n_wagon)) # n_wagon_now = len(line.wagons) for index, w in enumerate(reversed(line.wagons[-n_wagon:])): now_p[-index] = w.p_front # if monitor[0] < t and t < monitor[1]: # if w in line.wagons[-4:-1]: # d.append('%06.1f %s' % # (w.dp, w.state.__class__.__name__[:15])) # print(w.state) # print(w.p_front) # d.append('%02.3f' % w.dp) position[i, :] = now_p # if monitor[0] < t and t < monitor[1]: # print(', '.join(d)) except Exception as e: plot_positions(time, position, n_wagon, stations) raise e plot_positions(time, position, n_wagon, stations)
def roadWidthArr(roadPts): "points are expected to be 4 already sorted by BLBRTRRL image order" assert len(roadPts) == 4, roadPts bl, br, tr, tl = roadPts lineL = Line(bl, tl) lineR = Line(br, tr) return abs(lineR.signedDistance(bl)), abs(lineL.signedDistance(br)), abs( lineL.signedDistance(tr)), abs(lineR.signedDistance(tl))
def test_is_parallel_to(self): l = Line(Vector([2, 3]), 0) el = Line(Vector([-4, -6]), 9) self.assertTrue(l.is_parallel_to(el)) l = Line(Vector([1.182, 5.562]), 6.744) el = Line(Vector([1.773, 8.343]), 9.525) self.assertTrue(l.is_parallel_to(el))
def test_basic(self): A = Line(['4.046', '2.836'], '1.21') B = Line(['10.115', '7.09'], '3.025') assert A == B C, D = Line(['7.204', '3.182'], '8.68'), Line(['8.172', '4.114'], '9.883') x, y = C.intersection_with(D) assert (round(x, 3), round(y, 3)) == (Decimal('1.173'), Decimal('0.073')) E, F = Line(['1.182', '5.562'], '6.744'), Line(['1.773', '8.343'], '9.525') assert E.intersection_with(F) is None
def setup_all_lines(list_data): """ Make a list of instance store all line's instance. """ from line import Line ls_instance = [] for each in list_data: new_line = Line() new_line.name = each[0] new_line.stations = setup_value(each[0], each[1:]) new_line.conns = setup_value(each[0], each[1:], conn=True) ls_instance.append(new_line) return ls_instance
def __init__(self, c_space, shape): self.camera = Camera(shape) self.camera_pos = shape[1] / 2 self.color_space = c_space self.color_convert = self.COLOR_CONVERT[c_space] # sliding window variables self.nwindows = 9 self.margin = 100 self.minpix = 50 self.lane_width_threshold = 20 self.previous_difference = None self.previous_difference_threshold = 5 self.left_line = Line() self.right_line = Line()
def test_intersection_with(self): # return None for parallel lines l = Line(Vector([2, 3]), 0) el = Line(Vector([4, 6]), 1) self.assertIsNone(l.intersection_with(el)) l = Line(Vector([7.204, 3.182]), 8.68) el = Line(Vector([8.172, 4.114]), 9.883) self.assertEqual(l.intersection_with(el), Vector([1.173, 0.073])) # return line for same lines self.assertTrue(l.intersection_with(l) == l)
def intersect(self, line: Line) -> float: point_a = (self.x0 - self.a / 2, self.y0 - self.b / 2) point_b = (self.x0 - self.a / 2, self.y0 + self.b / 2) point_c = (self.x0 + self.a / 2, self.y0 + self.b / 2) point_d = (self.x0 + self.a / 2, self.y0 - self.b / 2) # degenerate line: 0x + 0y + 0 = 0, so it is point try: deviation_a = line.normalize().get_deviation(point_a[0], point_a[1]) deviation_b = line.normalize().get_deviation(point_b[0], point_b[1]) deviation_c = line.normalize().get_deviation(point_c[0], point_c[1]) deviation_d = line.normalize().get_deviation(point_d[0], point_d[1]) except ZeroDivisionError: return 0 new_points = [] if deviation_a * deviation_b < 0: proportionality_coefficient = abs(deviation_a / deviation_b) x = (point_a[0] + proportionality_coefficient * point_b[0]) / (1 + proportionality_coefficient) y = (point_a[1] + proportionality_coefficient * point_b[1]) / (1 + proportionality_coefficient) new_points.append((x, y)) if deviation_b * deviation_c < 0: proportionality_coefficient = abs(deviation_b / deviation_c) x = (point_b[0] + proportionality_coefficient * point_c[0]) / (1 + proportionality_coefficient) y = (point_b[1] + proportionality_coefficient * point_c[1]) / (1 + proportionality_coefficient) new_points.append((x, y)) if deviation_c * deviation_d < 0: proportionality_coefficient = abs(deviation_c / deviation_d) x = (point_c[0] + proportionality_coefficient * point_d[0]) / (1 + proportionality_coefficient) y = (point_c[1] + proportionality_coefficient * point_d[1]) / (1 + proportionality_coefficient) new_points.append((x, y)) if deviation_a * deviation_d < 0: proportionality_coefficient = abs(deviation_a / deviation_d) x = (point_a[0] + proportionality_coefficient * point_d[0]) / (1 + proportionality_coefficient) y = (point_a[1] + proportionality_coefficient * point_d[1]) / (1 + proportionality_coefficient) new_points.append((x, y)) # line doesn't cross the rectangle if len(new_points) < 2: return 0 point1 = new_points[0] point2 = new_points[1] return ((point1[0] - point2[0]) ** 2 + (point1[1] - point2[1]) ** 2) ** (1 / 2)
def executeFM(self, result_packet, rune): packet_lines = result_packet['data']['effects'] for line in packet_lines: try: if self.getLineByEffectId(line['actionId']) is not None: self.getLineByEffectId(line['actionId']).setValue( int(line['value'])) else: new_line = Line(line['actionId'], 0, 0) new_line.setValue(line['value']) self.exotic_lines.append(new_line) except Exception as e: print('e : ' + str(e)) ids_in_packet = [] for line in packet_lines: ids_in_packet.append(line['actionId']) for line in self.getLines(): if line.getEffectId() not in ids_in_packet: line.setValue(0) result_type = self.getResultType(result_packet) if result_type == 'SC': theorical_earned_weight = rune.getWeight() elif result_type in ['SN', 'EN']: theorical_earned_weight = 0 elif result_type == 'EC': theorical_earned_weight = -1 * rune.getWeight() real_earned_weight = 0 for line in self.getLines(): real_earned_weight += line.getLastModification( ) * line.getEffectWeight() print('Result : ' + result_type) print('Theorical earning : ' + str(theorical_earned_weight)) print('Real earning :' + str(real_earned_weight)) self.last_reliquat_modification = -1 * (real_earned_weight - theorical_earned_weight) self.reliquat += self.last_reliquat_modification self.clean_lines() self.listener.updateItem(self) return result_type
def generate(self): ''' Instantiate line ''' # On separe le text en ligne lines = self.splitText() # On instancie ses lignes et on les stocke for i in range(len(lines)): line = Line(lines[:][i]) self.Lines.append(line) self.Lines_images.append(line.image) # On calcule la taille des lignes totalHeight = getTotalHeigh(self.Lines_images) + 2 * 150 width = getMaxWidth(self.Lines_images) + 2 * 200 gap = 20 totalHeight += gap * len(self.Lines) #new_im = Image.new('RGB',(totalHeight,width)) new_im = Image.new('RGB', (2480 * 4, 3508 * 4)) # On créer la page en collant chaque image de ligne pos = 150 for i in range(len(self.Lines)): img = self.Lines[i].image #img.show() current_height = img.size[1] new_im.paste(img, (150, pos + gap + current_height)) pos += current_height + 270 #new_im.show() #time.sleep(30) self.image = new_im
def __init__(self, interactor, string, on_editing_end=None, highlight_color=None, highlight_opacity=None, **kwargs): super(Textbox, self).__init__(interactor, string, **kwargs) self.drag_interval = timedelta(0, .1) self.editing = False self.blank = False self.edit_indicator = None self.column = 0 self.row = 0 self.text = string self.on_editing_end = on_editing_end self.highlight_opacity = highlight_opacity self.highlight_color = highlight_color self.cursor = Line( (0, 0), (1, 1), renderer=self.widget.GetCurrentRenderer(), width=2) # Blink the cursor if we're editing. self.blink_timer = self.interactor.CreateRepeatingTimer(600) self.blink_observer = self.interactor.AddObserver( "TimerEvent", self.blink_cursor) # All timer events trigger all listeners, so we will only update when # the time elapsed is the expected period. self.last_blink = datetime.now() # Use the third argument (priority) to intercept key events before # anything else does self.keyboard_observer = self.interactor.AddObserver( "KeyPressEvent", self.typed, 1.0)
def __init__(self, screensize, speed, duration, line_seed): r.seed(line_seed) point1 = MovingPoint(screensize, speed, duration, r.random()) point2 = MovingPoint(screensize, speed, duration, r.random()) self.line_path = [] for i in range(duration): self.line_path.append(Line(point1[i], point2[i]))
def is_line_plausible(self, left, right): """ Determine if the detected pixels describing two lines are plausible lane lines based on curvature and distance. :param left: Tuple of arrays containing the coordinates of detected lane pixels :param right: Tuple of arrays containing the coordinates of detected lane pixels :return: """ # ignore lines that have less then 3 points if len(left[0]) < 3 or len(right[0]) < 3: return False # prepare some temporary line objects and test if they're plausible new_left = Line(y=left[0], x=left[1]) new_right = Line(y=right[0], x=right[1]) return are_lanes_plausible(new_left, new_right)
def add_comment(): error_message = "There was an error saving your comment!" data = request.get_json() print(data) time = datetime.now() line = data['line']['train'] token = data['token'] comment = data['comment'] line_record = Line.select_one(line) user = User.select_token(token) print(token) print(user.username) print(user.pk) # time = datetime.strptime(d, "%Y-%m-%d %H:%M:%S").strftime("%Y-%m-%d %I:%M:%S %p") new_comment = Comment(comment = comment, time = time, line_pk = line_record["pk"], user_pk = user.pk) new_comment.save() return jsonify({"comment": "made a comment!"})
def compute_lane_from_candidates(line_candidates, img_shape): pos_lines = [l for l in line_candidates if l.slope > 0] neg_lines = [l for l in line_candidates if l.slope < 0] 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) 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
def diff_multiple(self, seq): return [ Line( np.round((seq * nbr)[1:] - (seq * nbr)[:-1], 2), 'difference between term for the sequence times {}'.format( nbr), ['-']) for nbr in range(2, 6) ]
def intersection_with(self, p): if self == p: return self elif self.is_parallel_to(p): return None else: return Line()
def reset(self, pose=(0, 0, 0), offsetDeg=0): print "RESET ROW (%0.2f, %0.2f, %0.1f), offset=" % ( pose[0], pose[1], math.degrees(pose[2])), offsetDeg viewlog.dumpBeacon(pose[:2], color=(128, 128, 128)) self.preference = None self.center = None if self.rowHeading: self.directionAngle = normalizeAnglePIPI(self.rowHeading - pose[2]) if abs(self.directionAngle) > math.radians(90): self.directionAngle = normalizeAnglePIPI(self.rowHeading - pose[2] + math.radians(180)) if self.verbose: print "RESET_DIFF %.1f" % math.degrees(self.directionAngle) else: self.directionAngle = 0.0 # if you do not know, go ahead goal = combinedPose((pose[0], pose[1], pose[2] + self.directionAngle), (self.radius, 0, 0)) self.line = Line(pose, goal) # self.line = Line( (0.0, 0.0), (1.0, 0.0) ) self.newData = False self.endOfRow = False self.cornLeft = 10.0 # far self.cornRight = 10.0 self.collisionAhead = 10.0, 10.0, False # far (wide, narrow, override) self.lastLeft, self.lastRight = None, None self.prevLR = None self.poseHistory = []
def test_point_for_x(): """Test getting a point given an x Value""" line1 = Line(Vector([2, 3]), 6) x1_coord, y1_coord = line1.point_for_x(0) x2_coord, y2_coord = line1.point_for_x(3) x3_coord, y3_coord = line1.point_for_x(9) assert x1_coord == Decimal(0) assert y1_coord == Decimal(2) assert x2_coord == Decimal(3) assert y2_coord == Decimal(0) assert x3_coord == Decimal(9) assert y3_coord == Decimal(-4)
def analyze_intergenic(self): last_transcript_end = None last_transcript_neg = None for key in self.transcript_keys: transcript = self.transcripts[ key] #loop through certain chrom transcripts in order if last_transcript_end is None: last_transcript_end = transcript.end_pos last_transcript_neg = transcript.negative_dir else: sign = "-" if last_transcript_neg and transcript.negative_dir else "+" self.intergenic_lines.append( Line.creat_line_by_name_and_corr(transcript.chr, "Intergenic", last_transcript_end, transcript.start_pos, sign=sign)) last_transcript_end = transcript.end_pos last_transcript_neg = transcript.negative_dir self.analyze_interonics(transcript)
def __read_file(self, input, defines, input_name = None): from line import Line l = None block = self lineno = 0 if input_name is None: input_name = input.name for txt in input.readlines(): lineno = lineno + 1 l = Line.parse(txt, l) if l.is_complete(): info = l.expand(defines) try: block = block.parse(info[2], info[0]) except: print("%s:%u failed to parse '%s'" % (input_name, lineno, l), file = sys.stderr) raise if not block: raise Exception("failed to parse '%s'" % l) l = None while block and block != self: #print(block) block = block.parse(['@end'], True)
def test_angle(): p1 = (0, 0) p2 = (1, 1) l = Line(p1, p2=p2) assert l.angle == (math.pi / 4)
def angles(self): """ Returns a dictionary of {point: angle} entries containing the measure of all the internal angles of this polygon formed at each vertex. Examples: ====== >>> from sympy.geometry import * >>> p1,p2,p3,p4 = map(Point, [(0,0), (1,0), (5,1), (0,1)]) >>> poly = Polygon(p1, p2, p3, p4) >>> poly.angles[p1] pi/2 >>> poly.angles[p2] acos(-4*17**(1/2)/17) """ def tarea(a, b, c): return (b[0] - a[0])*(c[1] - a[1]) - (c[0] - a[0])*(b[1] - a[1]) def isright(a, b, c): return bool(tarea(a, b, c) <= 0) # Determine orientation of points cw = isright(self.vertices[-1], self.vertices[0], self.vertices[1]) ret = {} for i in xrange(0, len(self.vertices)): a,b,c = self.vertices[i-2], self.vertices[i-1], self.vertices[i] ang = Line.angle_between(Line(b, a), Line(b, c)) if cw ^ isright(a, b, c): ret[b] = 2*S.Pi - ang else: ret[b] = ang return ret
def __init__(self): self.calibration_values = pickle.load( open('calibration_values.p', 'rb')) self.mtx = self.calibration_values['mtx_distortion_correction'] self.dist_coeff = self.calibration_values['distortion_coefficient'] self.perspective_transform_matrix = None self.original_image = None self.image = None self.left_lane = Line() self.right_lane = Line() self.result_image = None self.image_hls = None self.empty_channel = None self.camera_offset = 0 self.radius_array = [] self.radius_of_curvature = 0
def __init__(self, irc, server, room, screen, theme): self.theme = theme self.screen = screen self.irc = irc self.server = server self.room = room self.height, self.width = self._limits(); self.topic = Line('topic', '', False) self.status = Line('status', '', False) self.input_line = Line('input', '', False) self.lines = [] curses.echo() curses.start_color() self.screen.clear() self.screen.timeout(0) self.screen.scrollok(True) self.screen.setscrreg(1, self.height-3) self._draw_chat() self.irc.add_global_handler("welcome", self.on_connect) self.irc.add_global_handler("motd", self.on_motd) self.irc.add_global_handler("pubmsg", self.on_pubmsg) self.irc.add_global_handler("currenttopic", self.on_currenttopic)
def tangent_line(self, p): """ If p is on the ellipse, returns the tangent line through point p. Otherwise, returns the tangent line(s) from p to the ellipse, or None if no tangent line is possible (e.g., p inside ellipse). Example: In [1]: e = Ellipse(Point(0,0), 3, 2) In [2]: t = e.tangent_line(e.random_point()) In [3]: p = Plot() In [4]: p[0] = e In [5]: p[1] = t The above will plot an ellipse together with a tangent line. """ if p in self: rise = (self.vradius**2) * (self.center[0] - p[0]) run = (self.hradius**2) * (p[1] - self.center[1]) p2 = Point(simplify(p[0] + run), simplify(p[1] + rise)) return Line(p, p2) else: # TODO If p is not on the ellipse, attempt to create the # tangent(s) from point p to the ellipse..? raise NotImplementedError( "Cannot find tangent lines when p is not on the ellipse")
def findBestLine( arr ): "find best fitting line in array of points (brute force)" bestCount = 0 bestLine = None for a in arr: for b in arr: if a != b: line = Line(a,b) count = 0 for c in arr: if math.fabs( line.signedDistance(c) ) < 0.05: count += 1 if count > bestCount: print count, (a, b) bestCount = count bestLine = line return bestLine
def poem_ex_nihilo(**kwargs): if 'format' in kwargs: poem = getattr(poemformat, kwargs['format'].capitalize())() #class else: poem = getattr(poemformat, sys.argv[1].capitalize())() #class if 'input_text' in kwargs: input_text = './SCALIA.txt' else: input_text = sys.argv[2] or "./SCALIA.txt" text = open(input_text).read() sent_detector = nltk.data.load('tokenizers/punkt/english.pickle') linetexts = sent_detector.tokenize(text) # lists_of_linetexts = map(lambda x: x.split(";"), open(input_text).read().split("\n")) # #lists_of_linetexts = map(lambda x: x.split(","), open(sys.argv[2]).read().split("\n")) # linetexts = [line for line_list in lists_of_linetexts for line in line_list] #linetexts = ["camping is in tents", "my tree table tries", "between those times I slept none"] # linetexts = ["many words in english rhyme with song", "one two three four five six", "a bee see dee word kicks", # "This is a line that is twenty long", "here are ten more ending in wrong", "Jeremy Bee Merrill plays ping pong", # ] if 'rhyme_checker' in kwargs: p = Poemifier(poem, rhyme_checker=kwargs['rhyme_checker']) else: p = Poemifier(poem) p.debug = True p.verbose = kwargs.get('verbose', False) p.allow_partial_lines = kwargs.get('allow_partial_lines', False) #this can't be a do... while, because we have to add all the lines, then do various processing steps. for linetext in linetexts: print linetext line = Line(linetext, p.rhyme_checker) if line.should_be_skipped(): continue #p.try_line(line) #too slow p.add_line(line) print "" complete_poem = p.create_poem(kwargs.get('be_random', True)) if complete_poem: print poem.format_poem( complete_poem ) #random? else: print "No Poem"
def scan_book(name, from_file, output=stdout): line_num = 0 book = Book(name) bookdb = BookDatabase(book) for line_string in from_file: line_string = line_string.strip() if line_string: line_num += 1 if line_num not in bookdb: line = Line(line_string, Source(book, line_num)) bookdb[line_num] = line print('%d. %s (%d scans)' % ( line_num, line.text_per_command_line(), len(line.scans) ), file=output) output.flush() return bookdb
def test_is_parallel(): n1 = Vector([1,1]) c1 = 1 l1 = Line(n1,c1) n2 = Vector([-3,-3]) c2 = -3 l2 = Line(n2,c2) #print l1, l2 assert l1.is_parallel_to(l2) # n = Vector([2,3]) # k = 6 # l1 = Line(n,k) # print "Line l1: ", l1
def populate_edges(self): edges = [] nv = len(self.vertices) for i in range(nv): for j in range(nv): if (i < j): distance = self.vertices[i].distance_to(self.vertices[j]) if distance < 0.073: # found an edge edge = Line(self.vertices[i], self.vertices[j]) moves = set() for k in range(len(self.cells)): cell = self.cells[k] if cell.distance_to(edge.center()) < 0.1306: moves.add(k) edge.add_moves(moves) edges.append(edge) return edges
def loop(self): if not self.connection.loop(): return False for line in self.connection.buffer: ln = Line.parse(line) self.state["last_line"] = ln self.parse_line(ln) self.hook_manager.run_irc_hooks(ln) return True
class LineTestCase(unittest.TestCase): '''Test creation and use of a Line.''' def setUp(self): self.line = Line(115, 85, 125, 85, media.black, 7) def tearDown(self): self.line = None def testString(self): assert str(self.line) == 'Line @ ( 115 , 85 ) to ( 125 , 85 )',\ 'mismatch in string version of line' def testGetPriority(self): assert self.line.get_priority() == 7, \ 'mismatch in initial priority value' def testSetGetPriority(self): self.line.set_priority(5) assert self.line.get_priority() == 5, \ 'mismatch in new priority value'
def raw(self, line): """ Send a raw IRC line to the server. @param line: The raw line to send, without a trailing carriage return or newline. """ logging.debug("[IRC] <- %s" % line) ln = Line.parse(line) force = True # Whether we bypass flood protection or not. if ln.command.lower() in self.flood_verbs: force = False self.connection.write_line(line, force)
def test_parallel(self): l1 = Line(Vector([3, -2]), 1) l2 = Line(Vector([-6, 4]), 0) self.assertTrue(l1.is_parallel_to(l2)) l1 = Line(Vector([3, -2]), 8) l2 = Line(Vector([-6, 4]), 10) self.assertTrue(l1.is_parallel_to(l2)) l1 = Line(Vector([1, 2]), 3) l2 = Line(Vector([1, -1]), 2) self.assertFalse(l1.is_parallel_to(l2)) l1 = Line(Vector([1, 2]), 13) l2 = Line(Vector([1, -1]), 12) self.assertFalse(l1.is_parallel_to(l2))