def __init__(self, start, p2, end, color=(0, 1, 0, .3), num_points=50): plane = Plane(start, p2, end) pr1 = plane.project(start) pr2 = plane.project(p2) pr3 = plane.project(end) circle = Circle(pr1, pr2, pr3) radian_len = circle.chord_angle(pr1.distance(pr3)) increment = radian_len / num_points diff = pr1 - circle.center offset = np.arctan(diff.y / diff.x) # the range of arcsin is from -90 to 90 so (or radians but that's harder to type) if diff.x < 0: offset += np.pi / 2 else: offset -= np.pi / 2 points3d = [] for p in range(num_points): radian = increment * p - offset point = circle.center + Vector( np.sin(radian) * circle.radius, np.cos(radian) * circle.radius) points3d.append(plane.unproject(point)) points3d.append(end) super(Arc, self).__init__(pos=np.array(points3d), color=color, width=2, antialias=True, mode='line_strip')
def __init__(self, circles=None): self.circles = circles if circles: self.value = self.StraightWay.build(circles, Path.CurveWay(Circle(0.0, 0.0, 1e-10)), Path.CurveWay(Circle(1.0, 1.0, 1e-10))) else: self.value = None
def __init__(self, type, pos, radius, rotation, density): Circle.__init__(self, pos, radius) self.id = None # will be set later self.type = type self.pos = self.center self.rotation = rotation self.density = density self.mass = density * np.pi * np.power(radius, 3) * 4 / 3 self.poleOrbit = self.orbit(0, 0)
def test_circle(self): # Define instance of Circle wheel = Circle(1) # Test __str__ self.assertEqual(wheel.__str__(), "Circle of radius 1.") # Test area self.assertEqual(wheel.area(), math.pi) # Test circumference self.assertEqual(wheel.circumference(), 2 * math.pi)
def build(_json: str): parsed_json = json.loads(_json) circles = [] for circle in parsed_json["circles"]: circles.append(Circle(circle["X"], circle["Y"], circle["R"])) return parsed_json["name"], circles, parsed_json["dt"], parsed_json[ "Fmax"]
def __init__(self, body, color, uni2canvas, scale): self.id = None # filled later self.rotID = None # filled later self.u2c = uni2canvas self.scale = scale self.circle = Circle(self.u2c(body.pos, Point(0, 0)), body.radius*scale) self.body = body self.col = color
def input_circle() -> Circle: """Reads a Circle from the standard input. Reads the center position on one line, then the radius on the next. """ center = input_position("Enter the circle's center: ") radius = float(input("Enter the circle's radius: ")) return Circle(center, radius)
def find_circles(image, count_): image = 255 - image image[np.where(image > 170)] = 255. image = np.array(image, dtype='float64') prev_proc = sum(sum(image)) / (image.shape[0] * image.shape[1]) / 255. # 0.17, 0.031 are constants based on example 'many_circles.bmp' if count_ == -1: bord1 = 0.17 * prev_proc bord2 = 0.031 * prev_proc else: bord1 = -10000 bord2 = -10000 final_list_of_circles = [] max_amount_of_circles = 18 if count_ != -1: max_amount_of_circles = int(count_) for indd in range(max_amount_of_circles): edges = canny(image, sigma=3, low_threshold=10, high_threshold=50) minim_radii = int(min(image.shape[0], image.shape[1]) / 20) maxim_radii = int(min(image.shape[0], image.shape[1]) / 2) # Adapt step in Hough transform if picture is too big stepp = 1 if (maxim_radii - minim_radii) > 200: stepp = 2 if (maxim_radii - minim_radii) > 400: stepp = 4 hough_radii = np.arange(minim_radii, maxim_radii, stepp) hough_res = hough_circle(edges, hough_radii) accums, cx, cy, radii = hough_circle_peaks(hough_res, hough_radii, total_num_peaks=1) fig, ax = plt.subplots(ncols=1, nrows=1, figsize=(10, 4)) image1 = np.zeros((image.shape[0], image.shape[1])) for center_y, center_x, radius in zip(cy, cx, radii): circy, circx = circle_perimeter(center_y, center_x, radius) for ccy, ccx in zip(circy, circx): if 0 < ccy < image.shape[0] and 0 < ccx < image.shape[1]: image1[ccy][ccx] = 255 # Thick segments before subtracting selem = disk(5) thickimage1 = binary_dilation(image1, selem) thickimage1 = np.uint8(thickimage1) * 255 image = subtract_skimage(image, thickimage1) white_proc = sum(sum(image)) / (image.shape[0] * image.shape[1]) / 255 # if prev iteration is very similar to new iteration, stop if abs(white_proc - prev_proc) < 0.3 * bord2 + 0.7 * 0.0009: break for center_y, center_x, radius in zip(cy, cx, radii): final_list_of_circles.append( Circle(Point(center_y, center_x), radius)) prev_proc = white_proc # if procent of white pixels is too small, stop if white_proc < 0.3 * bord1 + 0.7 * 0.005: break #ax.imshow(image, cmap=plt.cm.gray) #plt.show() return final_list_of_circles
def processPlanCircle(self): if self.step == 0: self.preview = Circle(self.mx, self.my) self.step = 1 elif self.step == 1: self.preview.finalize() self.editor.level.plans.add(self.preview) self.editor.level.planTree.insert(self.preview) self.preview = None self.step = 0
def _find_right_center_and_radius(self, gray_image: np.ndarray, circle: Circle): count_non_zero_now = circle.count_intersections(gray_image, self.speed_rate) moves = ((1, 1), (-1, 1), (-1, -1), (1, -1), (1, 0), (0, 1), (-1, 0), (0, -1), (1, 0), (0, 1), (-1, 0), (0, -1)) for move in moves: for _ in range(0, self.max_thickness): circle.center.x_coord = circle.center.x_coord + move[0] circle.center.y_coord = circle.center.y_coord + move[1] count_non_zero_move = circle.count_intersections(gray_image, self.speed_rate) if count_non_zero_move > self.is_circle * 2 * np.pi * circle.radius: count_non_zero_now = count_non_zero_move else: circle.center.x_coord = circle.center.x_coord - move[0] circle.center.y_coord = circle.center.y_coord - move[1] break if count_non_zero_now > self.is_circle * 2 * np.pi * circle.radius and \ circle.radius > self.min_radius: circle.radius = circle.radius - 1 count_non_zero_new = circle.count_intersections(gray_image, self.speed_rate) if count_non_zero_new > self.is_circle * 2 * np.pi * circle.radius: count_non_zero_now = count_non_zero_new else: circle.radius = circle.radius + 1
def detect_centers_of_circles(self, gray_image: np.ndarray) -> List[Circle]: centers: list = cv2.HoughCircles(gray_image, cv2.HOUGH_GRADIENT, 1, minDist=0.0001, param1=50, param2=self.threshold_center, minRadius=self.min_radius, maxRadius=self.max_radius) if centers is not None: circles: list = [] if centers is not None: for center in centers[0, :]: x_center, y_center, radius = map(int, center) circles.append(Circle(Point(x_center, y_center), radius, 1)) return circles return []
def load_figure_list(filepath): f = open(filepath, "r") res = [] for s in f.readlines(): words = s.split() nums = list(map(float, words[1:])) t = words[0] if t == 'segment': res.append( Segment(Point(nums[0], nums[1]), Point(nums[2], nums[3]))) elif t == 'circle': res.append(Circle(Point(nums[1], nums[2]), nums[0])) else: raise RuntimeError("Can't load figure named {}".format(t)) f.close() return res
def parse(geom_str): """Parse a string into a shape object (Point, Circle, or Rectangle) Formats that can be given: p <px> <py> c <cx> <cy> <r> r <llx> <lly> <urx> <ury> Returns - Point, Circle, or Rectangle """ if geom_str.startswith('p'): _, x, y, *_ = geom_str.split(' ') return Point(float(x), float(y)) elif geom_str.startswith('c'): _, cx, cy, r, *_ = geom_str.split(' ') return Circle(Point(float(cx), float(cy)), float(r)) elif geom_str.startswith('r'): _, llx, lly, urx, ury, *_ = geom_str.split(' ') return Rectangle(Point(float(llx), float(lly)), Point(float(urx), float(ury)))
def parse(geom_str): """Parse a string into a shape object (Point, Circle, or Rectangle) Formats that can be given: p <px> <py> c <cx> <cy> <r> r <llx> <lly> <urx> <ury> Returns - Point, Circle, or Rectangle """ geom_str = geom_str.split(" ") if geom_str[0] == 'p': geom_str.pop(0) p_list = [] for l in geom_str: l = float(l) p_list.append(l) pt = Point(p_list[0], p_list[1]) return pt elif geom_str[0] == 'c': geom_str.pop(0) c_list = [] for l in geom_str: l = float(l) c_list.append(l) crcl = Circle(Point(c_list[0], c_list[1]), c_list[2]) return crcl elif geom_str[0] == 'r': geom_str.pop(0) r_list = [] for l in geom_str: l = float(l) r_list.append(l) rctgl = Rectangle(Point(r_list[0], r_list[1]), Point(r_list[2], r_list[3])) return rctgl
def generator_images(random_seed, circles, lines, max_thickness, size) -> list: # ->ListOfLinesAndCircles random.seed(random_seed) figures = [] for _ in range(circles): x_center = random.randint(1, size) y_center = random.randint(1, size) radius = random.randint( 1, min(x_center, size - x_center, y_center, size - y_center)) line_width = random.randint(1, max_thickness) figures.append(Circle(Point(x_center, y_center), radius, line_width)) for _ in range(lines): x_first = random.randint(1, size) y_first = random.randint(1, size) x_second = random.randint(1, size) y_second = random.randint(1, size) line_width = random.randint(1, max_thickness) figures.append( Line(Point(x_first, y_first), Point(x_second, y_second), line_width)) return figures
def parse(geom_str): """Parse a string into a shape object (Point, Circle, or Rectangle) Formats that can be given: p <px> <py> c <cx> <cy> <r> r <llx> <lly> <urx> <ury> Returns - Point, Circle, or Rectangle """ geom = geom_str.split() #POINT if geom_str.startswith('p'): return Point(float(geom[1]), float(geom[2])) #CIRCLE elif geom_str.startswith('c'): centerofcircle = Point(float(geom[1]), float(geom[2])) return Circle(centerofcircle, float(geom[3])) #RECTANGLE elif geom_str.startswith('r'): lowleft = Point(float(geom[1]), float(geom[2])) upperright = Point(float(geom[3]), float(geom[4])) return Rectangle(lowleft, upperright)
def test_area_zero_radius(self): circ = Circle(8) area = circ.area self.assertEqual(0, area)
def test_create_circle_neg_radius(self): circ = Circle(-3.7) circ_string = str(circ) self.assertGreater(circ_string.find("3.7"), -1)
def get_circle(self, im): x = self._im_to_x(im) res = self.get_circle_model.predict(x) return Circle.construct_from_y(res[0], self.image_size)
def circle_from_dict(dikt): return Circle(vec2_from_dict(dikt['center']), dikt['radius'])
def generate_circle(plot_side): radius = uniform(plot_side / 10, plot_side / 2) x = uniform(radius, plot_side - radius) y = uniform(radius, plot_side - radius) center = Point(x, y) return Circle(center, radius)
from geometry import Circle print("Partial Testing for CSS340 Lab1") c1 = Circle(3, 3, 7) c2 = Circle() print("First Circle Perimeter: " + str(c1.getPerimeter())) print("First Circle Area: " + str(c1.getArea())) c2.setX(3) c2.setY(3) c2.setRadius(2) if c2.isPointWithinCircle(4, 3.7): print("(4, 3.7) is within circle two") else: print("(4, 3.7) is not within circle two") print("Moving second Circle") c2.setX(3 + c2.getX()) if c2.isPointWithinCircle(4, 3.7): print("(7, 3.7) is within circle two") else: print("(7, 3.7) is not within circle two")
def test_create_circle(self): circ = Circle(5.2) circ_string = str(circ) self.assertGreater(circ_string.find("5.2"), False)
class Editor: def __init__(self, main): #Current editing process self.process = None self.step = 0 self.preview = None #Interaction modes self.snapModes = ['grid', 'subdivision', 'projection'] self.snapSet = [Line, Circle] self.selectSet = [Line, Circle] #Subjects of interaction. self.snapX = 0.0 self.snapY = 0.0 self.snapped = None #a Plan self.hovered = None #a Block self.selection = [] #a Block #Event handling #main.bind('event', callback) def getHoveredPlan(self): hits = list(block for block \ in self.level.quadTree.hit(pygame.Rect(pos[0]-2, pos[1]-2, 4, 4)) \ if (type(block) in self.selectSet)) if hits: candidate = hits[0] if candidate.hit(*pos): #mousepos self.hovered = candidate else: self.hovered = None else: self.hovered = None def processPlanLine(self): if self.step == 0: self.preview = Line(self.mx, self.my, self.mx, self.my) self.step = 1 elif self.step == 1: self.preview.finalize() self.editor.level.plans.add(self.preview) self.editor.level.planTree.insert(self.preview) self.preview = None self.step = 0 def processPlanCircle(self): if self.step == 0: self.preview = Circle(self.mx, self.my) self.step = 1 elif self.step == 1: self.preview.finalize() self.editor.level.plans.add(self.preview) self.editor.level.planTree.insert(self.preview) self.preview = None self.step = 0 def edit(self, mx, my): if self.preview: if self.mode == PLAN_TYPE_LINE: self.preview.x1 = mx self.preview.y1 = my elif self.mode == PLAN_TYPE_CIRCLE: self.preview.direction = getDirection(self.preview.x, self.preview.y, mx, my) self.preview.refresh() def remove(self, mx, my): if self.step == 0: hits = self.editor.level.planTree.hit(pygame.Rect(mx-1, my-1, 2, 2)) for plan in hits: if plan.hit(mx, my): self.editor.level.plans.remove(plan) self.editor.level.planTree.remove(plan) break else: self.preview = None self.step = 0 def onMouseMotion(self, mx, my): self.mx = mx self.my = my def onMouseButtonDown(self, pos, button): if button == 1: self.place() elif button == 2: pass elif button == 3: self.deleteSelection() elif button == 4: pass elif button == 5: pass def processPlaceRect(self): #UNWORKING if self.editor.hoveredPlanTouched: s = self.selection x, y = self.mx, self.my cx, cy = self.editor.hoveredPlan.center direction = self.editor.hoveredPlan.direction s.append(self.editor.hoveredPlanTouched) if len(self.selection) == 2: if self.mode == PLACE_TYPE_RECTANGLE: block = blocks.Rectangle() elif self.mode == PLACE_TYPE_CIRCLE: pass elif self.mode == PLACE_TYPE_ARC: pass def deleteSelection(self): if self.selection: self.level.blocks.remove(self.selection) self.level.quadTree.remove(self.selection)
def test_new_rectangle_from_circle(self): circ = Circle(1 , 5, 3) circ_new_rectangle = circ.circle_new_circle_to_rectangle() self.assertTrue(circ_new_rectangle.x, circ.circle_max_x_position()) self.assertTrue(circ_new_rectangle.y, circ.circle_max_y_position())
def test_max_x_coordinates_for_a_Circle(self): circ = Circle(2, 3 ,8) self.assertEquals(18, circ.circle_max_x_position())
from geometry import Vector, Circle, Tangent from variable import Variable, registry import math c1 = Circle('circle1') c1.radius > c1.area c1.radius > 0 c1.area < 5 c1.origin == Vector((0, 0)) c2 = Circle('circle2') c2.origin > Vector((-10, -10)) c2.origin < Vector((10, 10)) Tangent(c1, c2) with open('/tmp/test.mzn', 'w+') as test_file: test_file.write(registry.Dump()) print(registry.Dump()) print("Wrote registry to", test_file.name)
def test_area(self): circ = Circle(1)
def test_circumference(self): circ = Circle(1) self.assertEqual(math.pi, circ.circumference())
def plot_navigation_surface(self, x: np.ndarray, y: np.ndarray): xx, yy = np.meshgrid(x, y) zz_nav = self._evaluate_potential_on_grid(xx, yy) fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.plot_surface(xx, yy, zz_nav) ax.set_xlabel('X') ax.set_ylabel('Y') ax.set_zlabel('Z') ax.view_init(elev=45., azim=45.) if __name__ == '__main__': obstacles_ = [ Circle(np.array([0, 5]), 2), Circle(np.array([0, -5]), 2), Circle(np.array([5, 0]), 2), Circle(np.array([-5, 0]), 2) ] workspace = Circle(np.array([0., 0.]), 12) goal = np.array([10., 0.]) navigation_function = NavigationFunction2D(np.array(goal), workspace, obstacles_, 5) # navigation_function.plot_path_on_contour(np.array([[1, 2], [2, 1], [3, 3.1]]), epsilon=1) navigation_function.plot_path_on_contour(np.array([[-9, .1], [-8, -5], [0, .1], [.1, -9]]), epsilon=1, scale_magnitude=.1) # navigation_function.plot_path_on_contour(np.array([-9, 0.1]), epsilon=1, scale_magnitude=.1)
def test_max_size_for_a_Circle(self): circ = Circle(0 , 0 ,4) self.assertEquals(8, circ.circle_size())
def turbo_independent(self): """Returns a maximal independent set (maximal means that no other independent set cantains it, doesn't mean that it has the most vertices)""" #Return 'None' if there are no vertices if self.ver_len() == 0: return None #Let 'v' be a vertice closest to (0, 0) v = self[0] dist_v = dist(v, (0, 0)) for w in self.vertices: d = dist(w, (0, 0)) if d < dist_v: v = w dist_v = d """'close_circle' is now a circle with a center in 'v' and radius of length 1, this means that no vertice contained in 'close_circle' is connected with 'v'""" close_circle = Circle(v, 1) """Let 'close_vertices' be a list containing vertices that lay in 'close_circle'""" close_vertices = [] for w in self.vertices: if w in close_circle: close_vertices.append(w) """'the_circle' will be a closed circle that will contain vertices chosen as elements of returned set, it has to have diameter of length 1 so that no two vertices that lay in it are connected and it has to contain 'v' 'max_card' will be the number of those vertices""" max_card = 0 the_circle = ClosedCircle(v, 0.5) #Count vertices in 'the_circle' for vertex in close_vertices: if vertex in the_circle: max_card += 1 #We want 'the_circle' to contain the most vertices possible for w in close_vertices: if w == v: continue """'circ_1' and 'circ_1' are closed circles with diameter of length 1, such that 'v' and 'w' lay on edges of 'circ_1' and 'circ_1'""" circles = find_circles(v, w, 0.5, type='closed') circ_1 = circles[0] circ_2 = circles[1] #'card_1' will be the number of vertices that lay in 'circ_1' card_1 = 0 #Count vertices in 'circ_1' for vertex in close_vertices: if vertex in circ_1: card_1 += 1 """If 'circ_1' contains more vertices than 'the_ circle' swap them with one another""" if card_1 > max_card: the_circle = circ_1 max_card = card_1 #'card_2' will be the number of vertices that lay in 'circ_2' card_2 = 0 #Count vertices in 'circ_2' for vertex in close_vertices: if vertex in circ_2: card_2 += 1 """If 'circ_2' contains more vertices than 'the_ circle' swap them with one another""" if card_2 > max_card: the_circle = circ_2 max_card = card_2 #'chosen_vertices' will be a list of all vertices from 'the_circle' chosen_vertices = [] for w in close_vertices: if w in the_circle: chosen_vertices.append(w) """'big_circle' is a circle that contains vertices that can be connected with vertices from 'the_circle'""" big_circle = Circle(the_circle.center, 2.5) #'rejested' will be a list of vertices from 'big_cirle' rejected = [] for w in self.vertices: if w in big_circle: rejected.append(w) """remove vertices from 'rejected' because it contains alredy chosen vertices as well as their potential neighbors""" new_graph = self - rejected #Repeat the action for what remained ind = new_graph.turbo_independent() if ind is None: return chosen_vertices else: return ind + chosen_vertices
def test_max_y_coordinates_for_a_Circle(self): circ = Circle(1, 5, 4) self.assertEquals(13, circ.circle_max_y_position())
def test_something(self): circ = Circle(5.2) circ_string = str(circ) self.assertGreater(circ_string.find("5.2"), 0)
def test_area(self): circ = Circle(1) self.assertEqual(math.pi, circ.area())
from geometry import Triangle, Circle, Point, Square if __name__ == '__main__': figure_list = [ Triangle(Point(0, 0), Point(0, 2), Point(3, 4)), Circle(2, Point(0, 0)), Square(Point(0, 0), Point(2, 2)) ] for figure in figure_list: figure.figure_square() figure.figure_perimeter() print(f'{figure.square},{figure.perimeter}')