def line(pos=(0,0), np=2, rotate=0.0, scale=1.0, xscale=1.0, yscale=1.0, thickness=None, start=(0,0), end=(0,1), path=False): v = vis.vector((end[0]-start[0]), (end[1]-start[1])) if thickness is None: thickness = 0.01*vis.mag(v) dv = thickness*vis.norm(vis.vector(0,0,1).cross(v)) dx = dv.x dy = dv.y cp = [] # outer line cpi = [] # inner line vline = (vis.vector(end)-vis.vector(start)).norm() mline = vis.mag(vis.vector(end)-vis.vector(start)) for i in range(np): x = start[0] + (vline*i)[0]/float(np-1)*mline y = start[1] + (vline*i)[1]/float(np-1)*mline cp.append( (x+pos[0],y+pos[1]) ) cpi.append( (x+pos[0]+dx,y+pos[1]+dy) ) if not path: cpi.reverse() for p in cpi: cp.append(p) cp.append(cp[0]) if rotate != 0.0: cp = rotatecp(cp, pos, rotate) if scale != 1.0: xscale = yscale = scale pp = Polygon(cp) if xscale != 1.0 or yscale != 1.0: pp.scale(xscale,yscale) if not path: return pp else: return [cp]
def nframe(pos=(0,0), length=1.0, np=3, thickness=None, rotate=0.0, roundness=0.0, invert=False, scale=1.0, xscale=1.0, yscale=1.0): if thickness == Default or thickness == None: thickness = length*0.2 else: thickness = length*thickness*2 fsqr = ngon(pos=pos, np=np, length=length) nga = (np-2)*pi/np angle = (pi/2 - nga) length2=length-thickness*cos(angle) csa = cos(angle) sqr1 = ngon(pos=pos, np=np, length=length-thickness/csa*2-thickness*tan(angle)*2) pp = fsqr - sqr1 if rotate != 0.0: pp.rotate(rotate) if xscale != 1.0 or yscale != 1.0: pp.scale(xscale,yscale) if roundness > 0: cp0 = pp.contour(0) cp0.append(cp0[0]) cp0 = roundc(cp0, roundness=roundness, invert=invert) cp1 = pp.contour(1) cp1.append(cp1[0]) cp1 = roundc(cp1, roundness=roundness, invert=invert) p1 = Polygon(cp0) p2 = Polygon(cp1) pp = p2-p1 return pp else: return pp
def trframe(pos=(0,0), width=2.0, height=1.0, top=None, thickness=None, rotate=0.0, roundness=0.0, invert=False, scale=1.0, xscale=1.0, yscale=1.0): if top == None: top = width/2.0 if thickness == Default or thickness == None: thickness = min(height,top)*0.2 else: thickness = min(height,top)*thickness*2 fsqr = trapezoid(pos=pos, width=width, height=height, top=top) angle = atan((width-top)/2.0/height) db = (thickness)/cos(angle) sqr1 = trapezoid(pos=pos, width=(width-db-thickness*tan(angle)), height=height-thickness, top=top-(db-thickness*tan(angle))) pp = fsqr - sqr1 if rotate != 0.0: pp.rotate(rotate) if xscale != 1.0 or yscale != 1.0: pp.scale(xscale,yscale) if roundness > 0: cp0 = pp.contour(0) cp0.append(cp0[0]) cp0 = roundc(cp0, roundness=roundness, invert=invert) cp1 = pp.contour(1) cp1.append(cp1[0]) cp1 = roundc(cp1, roundness=roundness, invert=invert) p1 = Polygon(cp0) p2 = Polygon(cp1) pp = p2-p1 return pp else: return pp
def rectangle(pos=(0,0), width=1.0, height=None, rotate=0.0, thickness=0, roundness=0.0, invert=False, scale=1.0, xscale=1.0, yscale=1.0): if height is None: height = width if thickness == 0: p0 = (pos[0]+width/2.0, pos[1]-height/2.0) p1 = (pos[0]+width/2.0, pos[1]+height/2.0) p2 = (pos[0]-width/2.0, pos[1]+height/2.0) p3 = (pos[0]-width/2.0, pos[1]-height/2.0) p4 = (pos[0]+width/2.0, pos[1]-height/2.0) cp = [p0, p1, p2, p3, p4] if rotate != 0.0: cp = rotatecp(cp, pos, rotate) if scale != 1.0: xscale = yscale = scale pp = Polygon(cp) if xscale != 1.0 or yscale != 1.0: pp.scale(xscale,yscale) if roundness > 0: cp = roundc(pp.contour(0), roundness=roundness, invert=invert) return Polygon(cp) else: return pp else: pp = rframe(pos=pos, width=width, height=height, thickness=thickness, rotate=rotate, roundness=roundness, invert=invert, scale=scale, xscale=xscale, yscale=yscale) return pp
def pointlist(pos=[], rotate=0.0, roundness=0.0, invert=False, scale=1.0, xscale=1.0, yscale=1.0, path=False): # pos may be either a list of points or a Polygon object try: points = pos.contour(0) if len(pos) > 1: raise AttributeError("pointlist can deal with only a single contour.") except: points = pos[:] closed = (points[-1] == points[0]) if not closed: points.append(points[0]) pp = Polygon(points) if len(pp) and rotate != 0.0: pp.rotate(rotate) if scale != 1.0: xscale = yscale = scale if xscale != 1.0 or yscale != 1.0: pp.scale(xscale,yscale) if roundness > 0: cp = roundc(pp.contour(0), roundness=roundness, invert=invert) pp = Polygon(cp) if path: if closed: return list(pp) else: return list(pp)[:-1] else: return pp
def get_pyramid_polygons(): polygons = [] # front face = get_triangle_points() transform = get_shift_matrix(0, 0, 1).dot(get_rot_x_matrix(-math.pi / 4)) face = face.dot(transform) face = face.dot(get_shift_matrix(0, 0, 1)) polygons.append(Polygon(face)) # back face = get_triangle_points() face = face.dot(get_rot_x_matrix(math.pi / 4)) face = face.dot(get_shift_matrix(0, 0, -1)) polygons.append(Polygon(face)) # left face = get_triangle_points() face = face.dot(get_rot_x_matrix(-math.pi / 4)) face = face.dot(get_rot_y_matrix(-math.pi / 2)) face = face.dot(get_shift_matrix(1, 0, 0)) polygons.append(Polygon(face)) # right face = get_triangle_points() face = face.dot(get_rot_x_matrix(-math.pi / 4)) face = face.dot(get_rot_y_matrix(math.pi / 2)) face = face.dot(get_shift_matrix(-1, 0, 0)) polygons.append(face) return polygons
def ngon(pos=(0,0), np=3, length=None, radius=1.0, rotate=0.0, thickness=0, roundness=0.0, invert=False, scale=1.0, xscale=1.0, yscale=1.0): cp = [] if np < 3: raise AttributeError("number of sides can not be less than 3") return None angle = 2*pi/np if length != None: radius = (length/2.0)/(sin(angle/2)) else: length = radius*(sin(angle/2))*2 if thickness == 0: seg = 2.0*pi/np angle = rotate for i in range(np): x = radius*cos(angle) + pos[0] y = radius*sin(angle) + pos[1] cp.append((x,y)) angle += seg cp.append(cp[0]) if scale != 1.0: xscale = yscale = scale pp = Polygon(cp) if xscale != 1.0 or yscale != 1.0: pp.scale(xscale,yscale) if roundness > 0: cp = roundc(pp.contour(0), roundness=roundness, invert=invert) return Polygon(cp) else: return pp else: pp = nframe(pos=pos, length=length, thickness=thickness, roundness=roundness, invert=invert, rotate=rotate, np=np) return pp
def reset_everything(self): self.canvas.delete('all') self.operation_flag = 0 self.reset_last_coord() self.reset_first_coord() self.main_polygon = Polygon() self.clipping_polygon = Polygon() self.vertex_list = None self.clipping = None
def common_area(x0, y0, x1, y1): nb, _ = x0.shape cost = empty((nb)) for i in range(nb): x0_, x1_ = x0[i], x1[i] if abs(x0_[0] - x1_[0]) > 180: x1_ = (x1[i] - (x0_[0] - 180)) % 360 + x0_[0] - 180 p0 = Polygon(create_vertice(x0_, y0[i])) p1 = Polygon(create_vertice(x1_, y1[i])) cost[i] = (p0 & p1).area() / (p0 + p1).area() return cost
def overlaps_segment(self, other): """ Determines whether the query segment overlaps with this :py:class:`TriSegment` :param other: query :py:class:`TriSegment` :return: ``True`` iff the query segment overlaps with this segment """ p_self = Polygon(np.dot(self.xyz_points, self.projection_plane.T)) p_other = Polygon(np.dot(other.xyz_points, self.projection_plane.T)) return ((p_self & p_other).area() > 0)
def test_circle_overlaps_poly(circle_center, circle_radius, poly_points): # Start with a cheap points-in-circle test circle_radius2 = circle_radius * circle_radius for i in range(len(poly_points)): xdiff = poly_points[i][0] - circle_center[0] ydiff = poly_points[i][1] - circle_center[1] if (xdiff*xdiff + ydiff*ydiff) <= circle_radius2: return True # Now try a bounding-rectangle test min_x = min(poly_points, key=lambda p: p[0])[0] max_x = max(poly_points, key=lambda p: p[0])[0] min_y = min(poly_points, key=lambda p: p[1])[1] max_y = max(poly_points, key=lambda p: p[1])[1] rect_pos = [min_x, min_y] rect_size = np.subtract((max_x, max_y), rect_pos) if not test_circle_overlaps_rect(circle_center, circle_radius, rect_pos, rect_size): return False # Brute-force all the possible line collsions for i in range(len(poly_points)-1): line = [poly_points[i], poly_points[i+1]]; inters = circle_line_intersection(circle_center, circle_radius, line); if inters is not None and 0 < len(inters): return True # The only other way to collide is if the circle is completely inside # the polygon polyob = Polygon(poly_points) return polyob.contains_point(circle_center)
def support( p ): # false if not satisfies some the next conditions on the parameter spaces [x, spline, alpha, elast] = p if elast > 60: return False if len(spline) == 0: return False if (alpha <= 0): return False x_sp = spline if (x_sp > 0.78).any() | (x_sp < 0.0).any(): return False Q = Polygon(x_sp) if Q.is_valid_polygon() == False: return False area_convex = ConvexHull(x.T).volume if (Q.area() / area_convex) < 0.8: return False return is_valid_spline_JA(x_sp, h)
def test_7_distance(self): """Test distance after various operations""" polygon = Polygon() # Test initial distance polygon.insert((0, 0), 0) self.assertTrue(polygon[0].distance_to_next == 0) # Test distance after adding after polygon.insert((3, 4), 1) self.assertTrue(polygon[0].distance_to_next == 5) self.assertTrue(polygon[1].distance_to_next == 5) # Test distance after adding before polygon.insert((3, -4), 1) self.assertTrue(polygon[0].distance_to_next == 5) self.assertTrue(polygon[1].distance_to_next == 8) # Test distance after []= polygon[1] = (1, 1) self.assertTrue(polygon[0].distance_to_next == math.sqrt(2)) self.assertTrue(polygon[1].distance_to_next == math.sqrt(13)) # Test distance after remove polygon.remove(1) self.assertTrue(polygon[0].distance_to_next == 5)
def show_history(self, space): material = self.region.target.material i3D, count = self.region.target.vertices() v = self while v: v3D = i3D i3D = v.region.window.intersections_3D(v.region.origin, v3D, count) for i2 in range(1, count): i1 = i2 - 1 plane = space.plane_from_points(v.region.origin, v3D[i1,:], v3D[i2,:]) poly = Polygon(plane, 4, material) poly.verts[0,:], z_0 = plane.project(v3D[i1,:]) poly.verts[1,:], z_1 = plane.project(v3D[i2,:]) poly.verts[2,:], z_2 = plane.project(i3D[i2,:]) poly.verts[3,:], z_3 = plane.project(i3D[i1,:]) poly.ill_only = [0,0,0] space.add_poly(poly) v = v.parent
def __init__(self, vertices, color=(255, 255, 255), velocity=(0, 0), angular_velocity=0, colors=None): if isinstance(vertices, Polygon): self.poly = vertices else: self.poly = Polygon(vertices) self.colors = colors self._color = 'primary' if colors: self.color = color else: self.colors = {'primary': color} self.velocity = np.asarray(velocity) self.angular_velocity = angular_velocity # Construct vertex_list. self._vertex_list = self._get_vertex_list() self.enabled = True
def arc(pos=(0,0), radius=0.5, np=32, rotate=0.0, scale=1.0, xscale=1.0, yscale=1.0, thickness=None, angle1=0.0, angle2=pi, path=False): if thickness is None: thickness = 0.01*radius cp = [] # outer arc cpi = [] # inner arc seg = 2.0*pi/np nseg = int(abs((angle2-angle1))/seg)+1 seg = (angle2-angle1)/nseg for i in range(nseg+1): x = cos(angle1+i*seg) y = sin(angle1+i*seg) cp.append( (radius*x+pos[0],radius*y+pos[1]) ) cpi.append( ((radius-thickness)*x+pos[0],(radius-thickness)*y+pos[1]) ) if not path: cpi.reverse() for p in cpi: cp.append(p) cp.append(cp[0]) if rotate != 0.0: cp = rotatecp(cp, pos, rotate) if scale != 1.0: xscale = yscale = scale pp = Polygon(cp) if xscale != 1.0 or yscale != 1.0: pp.scale(xscale,yscale) if not path: return pp else: return [cp]
def gear(pos=(0,0), n=20, radius=5, phi=20, addendum=0.4, dedendum=0.5, fradius=0.1, rotate=0, scale=1.0, internal=False, res=1, bevel=0): tooth = ToothOutline(n, res, phi, radius, addendum, dedendum, fradius, bevel=0.0) if internal: itooth = [] for p in tooth: px = p[0] py = p[1] driro = sqrt(px*px +py*py) - radius ir = radius - driro ro = radius + driro ix = (ir/ro)*px iy = (ir/ro)*py itooth.append((ix,iy)) tooth = itooth gear = [] for i in range(0, n): rotan = -i*2*pi/n rtooth = [] for (x, y) in tooth: rx = x*cos(rotan) - y*sin(rotan) + pos[0] ry = x*sin(rotan) + y*cos(rotan) + pos[1] rtooth.append((rx,ry)) gear.extend(rtooth) #gear.append(gear[0]) pp = Polygon(gear) if rotate != 0.0: pp.rotate(rotate) if scale != 1.0 : pp.scale(scale,scale) return pp
def __init__(self, score, time): "Initialises resources and start level" self.background = pygame.image.load("sprites/sky.jpg") self.background.convert() #for blitting more faster self.screen = Constants.SCREEN self.score = score self.display_items = pygame.sprite.Group() self.timeclock = GameTime((0.05, 0.05), time) self.display_items.add(self.timeclock, self.score) self.time_speed = pygame.time.Clock() self.time = 0.0 self.quit = False self.pause = False self.start = False self.completed = False self.gameover = False self.message = None self.polygon = Polygon(self) self.event_manager = EventManager(self) self.on_enter()
def __init__(self, filename): with open(filename, 'r') as input_file: parsed_file = json.loads(input_file.read()) self.start = Point(**parsed_file['start']) self.finish = Point(**parsed_file['finish']) self.polygons = [Polygon(**x) for x in parsed_file['polygons']]
def _create_map_1(env): #obs_movement = MovementPattern.StaticMovement((0,0)) #obs = DynamicObstacle(obs_movement) #obs.fillcolor = (0x55, 0x55, 0x55) #obs.shape = 4 #obs.polygon = Polygon([ # (640, 80), # (640, 480), # (445, 450), # (408, 300), # (408, 165), # (460, 108), # (490, 104), # (490, 91), # (640, 80), #]); with open('obs2.json') as f: obslist = json.load(f) for obs in obslist: obs_movement = MovementPattern.StaticMovement((0, 0)) if obs['type'] == 'circle': obs_movement = MovementPattern.StaticMovement(obs['center']) obs2 = DynamicObstacle(obs_movement) obs2.shape = 1 obs2.radius = obs['radius'] obs2.fillcolor = (0x55, 0x55, 0x55) env.static_obstacles.append(obs2) continue polygon = Polygon(np.array(obs['points'])) obs2 = DynamicObstacle(obs_movement) obs2.shape = 4 obs2.polygon = polygon obs2.fillcolor = (0x55, 0x55, 0x55) env.static_obstacles.append(obs2)
def seg_from_json(fname, gt_flag): with open(fname) as data_file: data = json.load(data_file) annotations = {} if gt_flag: annotations = data[0]["annotations"] else: annotations = data["annotations"] # print annotations[0].items() # TODO: make sure to address the box type (article/image/title) assignment problem (i.e. # at box or polygon level) polygon_dict = {} # polygon_dict has key = id, value = list of boxes for segment in annotations: if segment['id'] not in polygon_dict: polygon_dict[segment['id']] = [] coord0 = [segment['y'], segment['x']] coord1 = [coord0[0] + segment['height'], coord0[1] + segment['width']] polygon_dict[segment['id']].append(Box(coor0=coord0, coor1=coord1)) # convert polygons dict to Segmentation object #seg = Segmentation() polygons = [Polygon(boxes=boxList) for boxList in polygon_dict.values()] return Segmentation(segments=polygons)
def rackGear(pos=(0,0), n=30, radius=5., phi=20., addendum=0.4, dedendum=0.5, fradius=0.1, rotate=0, scale=1.0, length=10*pi, res=1, bevel=0.05, depth=(0.4+0.6+0.1)): tooth = RackOutline(n, res, phi, radius, addendum, dedendum, fradius, bevel) toothl = tooth[0][1] - tooth[-1][1] ntooth = int(length/toothl) flength = ntooth * toothl gear = [] for i in range(0, ntooth): ntooth = [] for (x, y) in tooth: nx = x + pos[0] ny = -i*toothl + y + pos[1] ntooth.append((nx,ny)) gear.extend(ntooth) gear.append((gear[-1][0]-depth,gear[-1][1])) gear.append((gear[0][0]-depth,gear[0][1])) gear.append(gear[0]) pp = Polygon(gear) pp.shift(-pp.center()[0],-pp.center()[1]) if rotate != 0.0: pp.rotate(rotate) if scale != 1.0 : pp.scale(scale,scale) return pp
def merge(x, y): """ Merge all polygon of the list :param array x: 2D array for a list of polygon :param array y: 2D array for a list of polygon :return: Polygons which enclosed all :rtype: array, array """ nb = x.shape[0] p = None for i in range(nb): p_ = Polygon(create_vertice(x[i], y[i])) if p is None: p = p_ else: p += p_ x, y = list(), list() for p_ in p: p_ = array(p_).T x.append((nan, )) y.append((nan, )) x.append(p_[0]) y.append(p_[1]) return concatenate(x), concatenate(y)
def set_tracks(self, x, y, ids, window): """ Will split one group in tracks :param array x: coordinates of group :param array y: coordinates of group :param ndarray ids: several fields like time, group, ... :param int windows: number of days where observations could missed """ time_index = build_index(ids["time"]) nb = x.shape[0] used = zeros(nb, dtype="bool") track_id = 1 # build all polygon (need to check if wrap is needed) polygons = [ Polygon(create_vertice_from_2darray(x, y, i)) for i in range(nb) ] for i in range(nb): # If observation already in one track, we go to the next one if used[i]: continue self.follow_obs(i, track_id, used, ids, polygons, *time_index, window) track_id += 1
def buildSection(fields): fieldname = fields[0].lower() if fieldname == '[cities]': field = Cities(fields, 'Cities') field.initAttributes() return field if fieldname == '[countries]': field = Countries(fields, 'Countries') field.initAttributes() return field if fieldname == '[highways]': field = Highways(fields, 'Highways') field.initAttributes() return field if fieldname == '[img id]': field = ImgId(fields, 'IMG ID') field.initAttributes() return field if fieldname == '[regions]': field = Regions(fields, 'Regions') field.initAttributes() return field if fieldname == '[poi]': field = Poi(fields, 'POI') field.initAttributes() return field if fieldname == '[polyline]': field = PolyLine(fields, 'POLYLINE') field.initAttributes() return field if fieldname == '[polygon]': field = Polygon(fields, 'POLYGON') field.initAttributes() return field
def __init__(self, world, chunk_pos): self.world = world self.pos = (chunk_pos[0] * 51.2, chunk_pos[1] * 51.2) self.chunk_pos = (chunk_pos[0] % 32, chunk_pos[1]) self.texture = None self.polygon = None self.body = None self.entities = [] self.things_to_blit = [] texture_filename = "data/world/%i_%i.tga" % self.chunk_pos if os.path.exists(texture_filename): self.texture = pygame.image.load(texture_filename) self.texture.set_colorkey((255, 0, 255)) elif chunk_pos[1] <= 1: self.texture = Chunk.underground_texture data_filename = "data/world/%i_%i.dat" % self.chunk_pos if os.path.exists(data_filename): with open(data_filename) as fin: self.polygon, self.entities = pickle.load(fin) elif chunk_pos[1] <= 1: self.polygon = Polygon( ((-25.6, -25.6), (-25.6, 25.6), (25.6, 25.6), (25.6, -25.6))) self.load_body()
def box_from_json(fname): with open(fname) as data_file: data = json.load(data_file) annotations = data[0]["annotations"] polygon_dict = {} # polygon_dict has key = id, value = list of boxes id = 0 for segment in annotations: id_str = str(id) if id_str not in polygon_dict: polygon_dict[id_str] = [] id += 1 coord0 = [segment['y'], segment['x']] coord1 = [coord0[0] + segment['height'], coord0[1] + segment['width']] polygon_dict[id_str].append( Box(coor0=coord0, coor1=coord1, label=segment['class'])) # convert polygons dict to Segmentation object polygons = [Polygon(boxes=boxList) for boxList in polygon_dict.values()] #img_name = fname[:fname.rfind('/') + 1] + data[0]['filename'] # newsimage = NewsImage(img_name[:img_name.rfind('.')]) # print img_name[:img_name.rfind('.')] #for p in polygons: # p.weight_image = newsimage #Polygon.weight_image = newsimage return Segmentation(segments=polygons)
def ellipse(pos=(0,0), width=1.0, height=None, np=32, rotate=0.0, thickness=None, scale=1.0, xscale=1.0, yscale=1.0): if height == None: height = 0.5*width if thickness == 0 or thickness == None: cp = [] seg = 2.0*pi/np angle = 0 radius=0.5 lf = width/2.0 hf = height/2.0 for i in range(np): x = cos(angle)*lf + pos[0] y = sin(angle)*hf + pos[1] cp.append((x,y)) angle += seg cp.append(cp[0]) if rotate != 0.0: cp = rotatecp(cp, pos, rotate) if scale != 1.0: xscale = yscale = scale pp = Polygon(cp) if xscale != 1.0 or yscale != 1.0: pp.scale(xscale,yscale) return pp else: pp = ering(pos=pos, width=width, height=height, np=np, rotate=rotate, thickness=thickness) return pp
def build_polygons(cell_indices, A0): polys = [] for i,indices in enumerate(cell_indices): theta = rand_angle() poly = Polygon(i, indices, A0, theta) polys.append(poly) return polys
class Playground(): Circle=Circle(6) Polygon=Polygon(3) Square=Square(5,2) Triangle=Triangle(1,4,2) Shape=Shape() # Implement __init__() for this class def __init__(self): print("The instances you created") # Call Method find_area of each class print(f"{Circle} and area = {Circle.find_area()}") print(f"{Square} and area = {Square.find_area()}") print(f"{Triangle} and area = {Triangle.find_area()}") #find_circumference #find_perimeter # Call Methods find_circumference and find_perimeter of each class print(f"{Circle} and circumference = {Circle.find_circumference()}") print(f"{Square} and perimeter = {Square.find_perimeter()}") print(f"{Triangle} and perimeter = {Triangle.find_perimeter()}") def __str__(self): print("Playground...Shapes")