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 vertice_overlap(x0, y0, x1, y1, minimal_area=False, p1_area=False): r""" Return percent of overlap for each item. :param array x0: x for polygon list 0 :param array y0: y for polygon list 0 :param array x1: x for polygon list 1 :param array y1: y for polygon list 1 :param bool minimal_area: If True, function will compute intersection/little polygon, else intersection/union :param bool p1_area: If True, function will compute intersection/p1 polygon, else intersection/union :return: Result of cost function :rtype: array By default .. math:: Score = \frac{Intersection(P_0,P_1)_{area}}{Union(P_0,P_1)_{area}} If minimal area: .. math:: Score = \frac{Intersection(P_0,P_1)_{area}}{min(P_{0 area},P_{1 area})} If P1 area: .. math:: Score = \frac{Intersection(P_0,P_1)_{area}}{P_{1 area}} """ nb = x0.shape[0] cost = empty(nb) for i in range(nb): # Get wrapped vertice for index i v0, v1 = get_wrap_vertice(x0, y0, x1, y1, i) p0 = Polygon(v0) p1 = Polygon(v1) # Area of intersection intersection = (p0 & p1).area() # we divide intersection with the little one result from 0 to 1 if minimal_area: cost[i] = intersection / min(p0.area(), p1.area()) # we divide intersection with p1 elif p1_area: cost[i] = intersection / p1.area() # we divide intersection with polygon merging result from 0 to 1 else: cost[i] = intersection / (p0 + p1).area() return cost
def common_area(x0, y0, x1, y1, minimal_area=False): nb, _ = x0.shape cost = empty((nb)) for i in range(nb): # Get wrapped vertice for index i v0, v1 = get_wrap_vertice(x0, y0, x1, y1, i) p0 = Polygon(v0) p1 = Polygon(v1) # Area of intersection intersection = (p0 & p1).area() # we divide intersection with the little one result from 0 to 1 if minimal_area: p0_area = p0.area() p1_area = p1.area() cost[i] = intersection / min(p0_area, p1_area) # we divide intersection with polygon merging result from 0 to 1 else: union = (p0 + p1).area() cost[i] = intersection / union return cost
def cost_function_common_area(xy_in, xy_out, distance, intern=False): """ How does it work on x bound ? Args: xy_in: xy_out: distance: intern: Returns: """ x_name, y_name = ( ("contour_lon_s", "contour_lat_s") if intern else ("contour_lon_e", "contour_lat_e") ) r_name = "radius_s" if intern else "radius_e" nb_records = xy_in.shape[0] x_in, y_in = xy_in[x_name], xy_in[y_name] x_out, y_out = xy_out[x_name], xy_out[y_name] x_in_min, y_in_min = x_in.min(axis=1), y_in.min(axis=1) x_in_max, y_in_max = x_in.max(axis=1), y_in.max(axis=1) x_out_min, y_out_min = x_out.min(axis=1), y_out.min(axis=1) x_out_max, y_out_max = x_out.max(axis=1), y_out.max(axis=1) costs = ma.empty(nb_records, dtype="f4") for i in range(nb_records): if x_in_max[i] < x_out_min[i] or x_in_min[i] > x_out_max[i]: costs[i] = 1 continue if y_in_max[i] < y_out_min[i] or y_in_min[i] > y_out_max[i]: costs[i] = 1 continue x_in_, x_out_ = x_in[i], x_out[i] p_in = Polygon(custom_concat(x_in_, y_in[i])) if abs(x_in_[0] - x_out_[0]) > 180: x_out_ = (x_out[i] - (x_in_[0] - 180)) % 360 + x_in_[0] - 180 p_out = Polygon(custom_concat(x_out_, y_out[i])) costs[i] = 1 - (p_in & p_out).area() / min(p_in.area(), p_out.area()) costs.mask = costs == 1 return costs
def _maxeffpolygon(c): max_ratio = 0 radius = 5 for i in range(3, c + 1): pol = Polygon(i, radius) #print(pol.area()) r = pol.area() / pol.perimeter() #print(r) if r > max_ratio: max_ratio = r side_len = i return f'Polygon having max efficiency is having side:{side_len} and the ratio is:{max_ratio:0.3f}\n'
def fetch_grid((i, j)): """on demand generation of empty grid squares.""" (i, j) = unwrap((i, j)) if (i, j) not in grid: xloc = i * grid_spacing yloc = j * grid_spacing r = Polygon( [ (xloc, yloc), (xloc + grid_spacing, yloc), (xloc + grid_spacing, yloc + grid_spacing), (xloc, yloc + grid_spacing), ] ) p = sample.sample(r) t = random.expovariate(r.area()) grid[i, j] = (p, t, r) return grid[(i, j)]
def draw_result(shift_data, polygons, bin_polygon, bin_bounds): """ 从结果中得到平移旋转的数据,把原始图像移到到目标地方,然后保存结果 :param shift_data: 平移旋转数据 :param polygons: 原始图形数据 :param bin_polygon: :param bin_bounds: :return: """ # 生产多边形类 shapes = list() for polygon in polygons: contour = [[p['x'], p['y']] for p in polygon['points']] shapes.append(Polygon(contour)) bin_shape = Polygon([[p['x'], p['y']] for p in bin_polygon['points']]) #print(bin_shape) shape_area = bin_shape.area(0) solution = list() rates = list() for s_data in shift_data: # 一个循环代表一个容器的排版 tmp_bin = list() total_area = 0.0 for move_step in s_data: if move_step['rotation'] != 0: # 坐标原点旋转 shapes[int(move_step['p_id'])].rotate( math.pi / 180 * move_step['rotation'], 0, 0) # 平移 shapes[int(move_step['p_id'])].shift(move_step['x'], move_step['y']) tmp_bin.append(shapes[int(move_step['p_id'])]) total_area += shapes[int(move_step['p_id'])].area(0) # 当前排版的利用率 rates.append(total_area / shape_area) solution.append(tmp_bin) # 显示结果 draw_polygon(solution, rates, bin_bounds, bin_shape)
def draw_result(shift_data, polygons, bin_polygon, bin_bounds): """ 从结果中得到平移旋转的数据,把原始图像移到到目标地方,然后保存结果 Nhận dữ liệu dịch và xoay từ kết quả, di chuyển hình ảnh gốc đến vị trí đích, sau đó lưu kết quả :param shift_data: Translation and rotation data :param polygons: Raw graphics data :param bin_polygon: :param bin_bounds: :return: """ # Đa giác sản xuất shapes = list() for polygon in polygons: contour = [[p['x'], p['y']] for p in polygon['points']] shapes.append(Polygon(contour)) bin_shape = Polygon([[p['x'], p['y']] for p in bin_polygon['points']]) shape_area = bin_shape.area(0) solution = list() rates = list() for s_data in shift_data: # Một chu trình biểu thị bố cục của vùng chứa tmp_bin = list() total_area = 0.0 for move_step in s_data: if move_step['rotation'] != 0: # Xoay gốc tọa độ shapes[int(move_step['p_id'])].rotate( math.pi / 180 * move_step['rotation'], 0, 0) # Pan shapes[int(move_step['p_id'])].shift(move_step['x'], move_step['y']) tmp_bin.append(shapes[int(move_step['p_id'])]) total_area += shapes[int(move_step['p_id'])].area(0) # Sử dụng sắp chữ hiện tại rates.append(total_area / shape_area) solution.append(tmp_bin) # kết quả cho thấy draw_polygon(solution, rates, bin_bounds, bin_shape)
class MPolygon: """ this class will eventually stop the mess with Polygon classes """ def __init__(self, id, points, mode='tuple', data=None): from Polygon import Polygon as Poly self.poly = Poly() def __str__(self): return '<M;Polygon ('+str(len(self.points))+' points)>' def svgPathString(self, useInt=True): """ returns the path string representation of this polygon """ ps = '' pts = self.points[:] if self.closed: pts.append(pts[0]) for pt in pts: if pt.deleted: continue #ignore deleted points if ps == '': ps = 'M' else: ps += 'L' if useInt: ps += '%d,%d' % (round(pt.x), round(pt.y)) else: ps += '%.3f,%.3f' % (pt.x, pt.y) if self.closed: ps += 'Z' # close path return ps def area(self): return self.poly.area()
print("the four vertices of the myrectangle are ...") print(myrectangle) print("the length of myrectangle is ... ") print(myrectangle.length) print("the width of myrectangle is ... ") print(myrectangle.width) print("the perimeter of myrectangle is ... ") print(myrectangle.perimeter()) print("the area of myrectangle is ... ") print(myrectangle.area()) else: vertices = int(line[i].split()[1]) i = i + 1 list = [] for j in range(vertices): point = Point(float(line[i].split()[0]), float(line[i].split()[1])) list.append(point) i = i + 1 mypolygon = Polygon(list) print("the four vertices of the mypolygon are ...") print(mypolygon) print("the perimeter of mypolygon is ... ") print(mypolygon.perimeter()) print("the area of mypolygon is ... ") print(mypolygon.area())
def draw_result(shift_data, polygons, polygons_str, bin_polygon, bin_bounds, file_path, file_id): """从结果中得到平移旋转的数据,把原始图像移到到目标地方,然后保存结果 """ def myrotate_polygon(contour, angle): rotated = [] #angle = angle * math.pi / 180 if angle == 0: cosangle = 1 sinangle = 0 elif angle == 90: cosangle = 0 sinangle = 1 elif angle == 180: cosangle = -1 sinangle = 0 elif angle == 270: cosangle = 0 sinangle = -1 for x, y in contour: rotated.append( [x * cosangle - y * sinangle, x * sinangle + y * cosangle]) return Polygon(rotated) # 生产多边形类 #print(polygons) shapes = list() for polygon in polygons: contour = [[p['x'], p['y']] for p in polygon['points']] shapes.append(Polygon(contour)) bin_shape = Polygon([[p['x'], p['y']] for p in bin_polygon['points']]) shape_area = bin_shape.area(0) solution = list() rates = list() #loops=1 #print(shift_data) shapes_before = copy.deepcopy(shapes) for s_data in shift_data: #print(loops) #loops=loops+1 # 一个循环代表一个容器的排版 tmp_bin = list() total_area = 0.0 for move_step in s_data: if move_step['rotation'] > 0: #改为大于0 # 坐标原点旋转 #print("before",[p for p in shapes[int(move_step['p_id'])].contour(0)]) #shapes[int(move_step['p_id'])].rotate(math.pi / 180 * move_step['rotation'], 0, 0) shapes[int(move_step['p_id'])] = myrotate_polygon( shapes[int(move_step['p_id'])].contour(0), move_step['rotation']) #print("after",[p for p in shapes[int(move_step['p_id'])].contour(0)]) #shapes[int(move_step['p_id'])]= shapes[int(move_step['p_id'])] # 平移 shapes[int(move_step['p_id'])].shift(move_step['x'], move_step['y']) tmp_bin.append(shapes[int(move_step['p_id'])]) total_area += shapes[int(move_step['p_id'])].area(0) #print("total_area",total_area) # 当前排版总面积 rates.append(total_area) solution.append(tmp_bin) # 显示结果 idx = 0 myresult = "" max_x = 0 max_y = 0 while (idx < len(shapes)): inpolygon = polygons_str[idx] # inpolygon="" # for x,y in shapes_before[idx].contour(0): # inpolygon=inpolygon+"({x},{y})".format(x=x/SCALE,y=y/SCALE) outpolygon = "" for x, y in shapes[idx].contour(0): if x > max_x: max_x = x if y > max_y: max_y = y outpolygon = outpolygon + "({x},{y})".format(x=x / settings.SCALE, y=y / settings.SCALE) text=\ """In Polygon: {inpolygon} Out Polygon: {outpolygon}\n""".format(inpolygon=inpolygon,outpolygon=outpolygon) myresult = myresult + text idx = idx + 1 myresult = myresult.rstrip("\n") result_file = file_path + "/result_" + file_id + ".txt" # import os # if os.path.exists(file_path+"/result.txt"): # i=1 # flag=1 # while flag: # if os.path.exists(file_path+"/result_"+str(i)+".txt"): # i=i+1 # continue # result_file=file_path+"/result_"+str(i)+".txt" # flag=0 with open(result_file, "w") as file_hand: file_hand.write(myresult) if settings.DEBUG: print("polygon total area:", rates[-1] / (settings.SCALE * settings.SCALE)) print("bin:", max_x / 10, max_y / 10) print("occupation:", rates[-1] / (max_x * max_y)) if settings.DRAWPIC: draw_polygon(solution, rates, bin_bounds, bin_shape, max_x, max_y, rates[-1] / (max_x * max_y))
fp = open("project01data.txt") line = fp.readline() while line != "": polygonheader = line.split() # this is the line with the identifier polytype = polygonheader[0] polynum = int(polygonheader[1]) # It is assumed that the polygons are either "polygon" or "rectangle" # print("Reading vertices for a %s with %d vertices..." # % ("polygon" if polytype == "P" else "rectangle", polynum)) # Construct a list of points to be used in constructing the polygon points = [] for i in range(polynum): vertices = fp.readline().split() points.append([float(vertices[0]), float(vertices[1])]) # print("Vertex %d has coordinates at (%.2f, %.2f)" # % (i, float(vertices[0]), float(vertices[1]))) # Construct a polygon/rect and return its vertices, perimeter, and area if polytype == "P": someshape = Polygon(points) else: someshape = Rectangle(points) print(someshape) print("Perimeter:", someshape.perimeter()) print("Area:", someshape.area()) print('--------------------------') line = fp.readline()
def plg_get_union(pD:plg.Polygon,pG:plg.Polygon): areaA = pD.area() areaB = pG.area() return areaA + areaB - plg_get_intersection(pD, pG)