def _init_attack_zone(self): # TODO this to come up with another way x = self.x - self.abilities.attack_radius y = self.y - self.abilities.attack_radius w = self.width - 1 + 2 * self.abilities.attack_radius h = self.height - 1 + 2 * self.abilities.attack_radius return g.polygon.Polygon(g.Point(x, y), g.Point(x + w, y), g.Point(x + w, y + h), g.Point(x, y + h))
def align_rectangle_point(x1, y1, x2, y2, x3, y3) -> tuple: '''Re-aligns the third point among three points to form a rectangle''' line1 = SG.Line(SG.Point(x1,y1), SG.Point(x2,y2)) line2 = line1.perpendicular_line(SG.Point(x2,y2)) line3 = line2.perpendicular_line(SG.Point(x3,y3)) fixed_point = line2.intersection(line3)[0] return int(fixed_point.x), int(fixed_point.y)
def to_target(self): progress_x = 0 progress_y = 0 step_x = 0 step_y = 0 if self.x < self.target.x: step_x = 1 else: step_x = -1 if self.y < self.target.y: step_y = 1 else: step_y = -1 # while (abs(progress_x) + abs(progress_y)) < self.Speed: if abs(self.target.x - self.x) < abs(self.target.y - self.y): self.y += step_y progress_y += step_y self.collision_zone = g.Point(self.x, self.y) else: self.x += step_x progress_x += step_x self.collision_zone = g.Point(self.x, self.y) if abs(self.target.x - self.x) + abs(self.target.y - self.y) < self.target.width + self.target.height: self.check_for_collision()
def _init_polygon(self): x = self.x y = self.y w = self.width - 1 h = self.height - 1 return g.polygon.Polygon(g.Point(x, y), g.Point(x + w, y), g.Point(x + w, y + h), g.Point(x, y + h))
def _generate_base_region(n: int): # Generate the region where all bases can lie in the first quadrant. The region is a quarter circle. # Find all lattice points within the region min_x = 1 max_x = np.power(2, float(n + 2) / float(2)) close = np.isclose([abs(max_x - float(np.round(max_x)))], [0], atol=TOLERANCE) if close: max_x = max_x + 1 else: max_x = np.floor(max_x) min_y = 0 points = [] vectors = [] for x in np.arange(min_x, max_x, step=1): max_y = np.sqrt(np.power(max_x, 2) - np.power(x, 2)) std_max_y = np.floor(max_y) + 1 for y in np.arange(min_y, std_max_y, step=1): origin = g.Point(0, 0) p = g.Point(x, y) v = g.Segment(p1=origin, p2=p) points.append(p) vectors.append(v) return vectors
def cross(a, b): """ 線分の交点を返す """ line_a = sg.Line(sg.Point(a[0][0], a[0][1]), sg.Point(a[1][0], a[1][1])) line_b = sg.Line(sg.Point(b[0][0], b[0][1]), sg.Point(b[1][0], b[1][1])) result = line_a.intersection(line_b) return result
def align_rectangles_working(x1, y1, x2, y2, x3, y3): line1 = SG.Line(SG.Point(x1, y1), SG.Point(x2, y2)) line2 = line1.perpendicular_line(SG.Point(x2, y2)) line3 = line2.perpendicular_line(SG.Point(x3, y3)) # returns correct x3, y3 unlike the method above # please generate x4, y4 # Return type is that of sympy Point return line2.intersection(line3)
def intersection(self, s: "Segment2D") -> Vector2D: l1 = spg.Line( spg.Point(self.start.x, self.start.y), spg.Point(self.end.x, self.end.y) ) l2 = spg.Line(spg.Point(s.start.x, s.start.y), spg.Point(s.end.x, s.end.y)) intersections = l1.intersection(l2) if len(intersections) != 1: raise Exception("TODO") if not isinstance(intersections[0], spg.Point2D): raise Exception("TODO") return Vector2D(float(intersections[0].x), float(intersections[0].y))
def test_411(len, wid, win_pos_type, win_offset, win_len, door_pos_type): p0 = sge.Point(0, 0) p1 = sge.Point(p0.x, p0.y + len) p2 = sge.Point(p0.x + wid, p0.y + len) p3 = sge.Point(p0.x + wid, p0.y) brm = bd.Bedroom() brm.set_boundary(BaseClass.DY_boundary(p0, p1, p2, p3)) if win_pos_type == 0: # p0 向上偏移 win_p0 = sge.Point(p0.x, p0.y + win_offset) win_p1 = sge.Point(win_p0.x, win_p0.y + win_len) win = DY_Line.Window(win_p0, win_p1) brm.add_window(win) dr = CommonElement.Door() if door_pos_type == 1: # p1 向右 dr_p0 = sge.Point(p1.x + DOOR_OFF, p1.y) dr_p1 = sge.Point(dr_p0.x + DOOR_LEN, dr_p0.y) dr.set_pos(BaseClass.DY_segment(dr_p0, dr_p1), DOOR_LEN) brm.add_door(dr) hou = BaseClass.House() fp = BaseModual.FloorPlan() fp.set_boundary(BaseClass.DY_boundary(p0, p1, p2, p3)) fp.add_region(brm) hou.add_floorplan(fp) # brm.draw() helpers.save_house_to_xml(hou, r'E:/h.xml')
def refresh(self): if not self.parent_tower.in_checker_zone(self.target): self.alive = False if self.alive: self.collision_zone = g.Point(self.x, self.y) self.to_target()
def isInObsBkLinePair(self, pos): pPos = symgeo.Point(pos[0], pos[1]) for bkline in self.obsBkPairLines: if bkline.contains(pPos): return True return False
def generate_parallelogram(p1, p2, h): l1 = g.Segment(p1=p1, p2=p2) l2 = l1.perpendicular_line(p1) # l2 = g.Segment(l2.p1, l2.p2).unit() l4 = l1.perpendicular_line(p2) # Get x3 point if float(p2.y) == float(0): x3 = 0 y3 = h elif float(p2.x) == float(0): x3 = -h y3 = 0 else: numerator = np.power(h, 2) denominator = 1 + np.power((float(p2.x) / float(p2.y)), 2) x3 = np.sqrt((numerator / denominator)) y3 = l2.slope * (x3) p3 = g.Point(x3, y3) l3 = l2.perpendicular_line(p3) p4 = l3.intersection(l4)[0] return p1, p2, p3, p4
def expanded(self, distance: float) -> "Polygon2D": expanded_lines = [] for s in self._segments(): # Get the direction vector for the segment direction = Vector2D(s.end.x - s.start.x, s.end.y - s.start.y).normalized() # Get the perpendicular normal vector normal = Vector2D(-direction.y, direction.x) # Scale the normal to the desired distance diff = normal.scaled(distance) # Use the scaled normal vector to create the expanded line expanded_line = Line2D( Vector2D(s.mid().x + diff.x, s.mid().y + diff.y), direction ) expanded_lines.append(expanded_line) # Too lazy to write intersection logic so convert to SymPy's line class # and use that to calculate the intersection points sympy_lines = [ spg.Line( spg.Point(l.point.x, l.point.y), spg.Point(l.point.x + l.direction.x, l.point.y + l.direction.y), ) for l in expanded_lines ] expanded_vertices = [] for curr in range(0, len(sympy_lines)): prev = curr - 1 if curr > 0 else len(sympy_lines) - 1 intersections = sympy_lines[prev].intersection(sympy_lines[curr]) if len(intersections) != 1: raise Exception("TODO") if not isinstance(intersections[0], spg.Point2D): raise Exception("TODO") expanded_vertices.append( Vector2D(float(intersections[0].x), float(intersections[0].y)) ) return Polygon2D(expanded_vertices)
def testSympyCircle(): print "++ Sympy Arc ++" p1 = Point(0, 1) arg = {"ARC_0": p1, "ARC_1": 5, "ARC_2": 0, "ARC_3": 6.2831} arc = Arc(arg) sympCircle = arc.getSympy() print "sympCircle", sympCircle sympCircel = geoSympy.Circle(geoSympy.Point(10, 10), 10) arc.setFromSympy(sympCircel) print "Pythonca Arc ", arc print "-- Sympy Arc --"
def testSympyEllipse(): print "++ Sympy Ellipse ++" p1 = Point(0, 1) arg = {"ELLIPSE_0": p1, "ELLIPSE_1": 100, "ELLIPSE_2": 50} eli = Ellipse(arg) sympEli = eli.getSympy() print "sympEllipse", sympEli sympEli1 = geoSympy.Ellipse(geoSympy.Point(10, 10), 300, 200) eli.setFromSympy(sympEli1) print "Pythonca Ellipse ", eli print "-- Sympy Ellipse --"
def __getBorderPoints(self, borderLIDs, polygon): import sympy.geometry as sg borderPoints = [] for borderLID in borderLIDs: bpid = self.__vectorMap.line[borderLID]["BPID"] fpid = self.__vectorMap.line[borderLID]["FPID"] blat, blng = self.__vectorMap.point[bpid][ "lat"], self.__vectorMap.point[bpid]["lng"] flat, flng = self.__vectorMap.point[fpid][ "lat"], self.__vectorMap.point[fpid]["lng"] for arrowID, arrow in self.__arrows.items(): for i in range(1, len(arrow["waypointIDs"])): abpid = arrow["waypointIDs"][i - 1] afpid = arrow["waypointIDs"][i] ablat, ablng = self.__vectorMap.point[abpid][ "lat"], self.__vectorMap.point[abpid]["lng"] aflat, aflng = self.__vectorMap.point[afpid][ "lat"], self.__vectorMap.point[afpid]["lng"] if self.isIentersected(blat, blng, flat, flng, ablat, ablng, aflat, aflng): intersection = sg.intersection( sg.Segment(sg.Point(blat, blng), sg.Point(flat, flng)), sg.Segment(sg.Point(ablat, ablng), sg.Point(aflat, aflng))) toIn = self.__pointInnerPolygon((aflat, aflng), polygon) borderPoint = { "arrowID": arrowID, "prevWaypointID": arrow["waypointIDs"][i - 1], "nextWaypointID": arrow["waypointIDs"][i], "toIn": toIn, "lat": float(intersection[0].x), "lng": float(intersection[0].y), } if borderPoint not in borderPoints: borderPoints.append(borderPoint) return borderPoints
def split_border(img, a, b, num=20): """ Split table border with a and b coordinates of endings into num amount of square samples to find holes in. Returns np.array of the result images (reshaped with dataset_img_shape) and np.array of (x, y, r) for each sample image (where (x, y) is the sample image center coordinates and r is the sample image radius). """ a = geom.Point(a) b = geom.Point(b) (n, m, _) = img.shape r = max(round(a.distance(b) / num), 1) border_images = [] border_squares = [] for i in range(num // 10, num * 9 // 10): mid = (a * i + b * (num - i)) / num x, y = round(mid[0]), round(mid[1]) if 0 <= y - r and y + r < n and 0 <= x - r and x + r < m: border_images.append(get_model_input(img, x, y, r)) border_squares.append((x, y, r)) return np.array(border_images), np.array(border_squares)
def findcross(one_line, second_line): """Линии состоят из [[x1,y1],[x2,y2]] для поиска пересечений, исключая крайние точки. Если пересечения нет, на выходе """ x1, y1, x2, y2 = one_line[0][0], one_line[0][1], one_line[1][0], one_line[ 1][1] x3, y3, x4, y4 = second_line[0][0], second_line[0][1], second_line[1][ 0], second_line[1][1] p1, p2, p3, p4 = symg.Point(x1, y1), symg.Point(x2, y2), symg.Point( x3, y3), symg.Point(x4, y4) l1, l2 = symg.Segment(p1, p2), symg.Segment(p3, p4) pointxy = symg.intersection(l1, l2) if pointxy: pointxy = [pointxy[0].x, pointxy[0].y] """ кажется, что if работает быстрее try: pointxy = [pointxy[0].x, pointxy[0].y] except IndexError: return pointxy """ return pointxy
def __init__(self, tower, monster): self.x = tower.x - 1 + (tower.width + 1) // 2 # stupid console self.y = tower.y - 1 + (tower.height + 1) // 2 self.width = 0 self.height = 0 self.speed = 4 self.collision_zone = g.Point(self.x, self.y) self.enemy_type = "all" self.alive = True self.target = monster self.parent_tower = tower self.texture = "*"
def policzPktyZaokraglenia(geometria, temp): """ Funkcja ma na celu obliczenie punktów na krzywej wirnika w górnej jego części (zob. krzywą :math:`ED` na rysunku przekroju wirnika). Procedura obliczania punktów na krzywej jest identyczna jak w przypadku funkcji :func:`dodajWspolrzedne`. :param geometria: obiekt klasy Geometry zawierający dane geometryczne wirnika :type geometria: Geometry :param temp: tymczasowy kontener na dane, użyty w celu przechowywania informacji. :type temp: dictionary :return kolo_BC: obiekt *list* zawierający punkty leżące na zaokrągleniu w górnej części wirnika. """ lopatka_XYZ = geometria.lopatka_XYZ r2 = geometria.r2 R = geometria.R C = temp['C'] R_pos = temp['R_pos'] pc = temp['pc'] pkty_XYZ = temp['pkty_XYZ'] def krzywiznaParametrycznie(t): x = (-R_pos[0] + R * np.cos(t)) y = R_pos[1] + R * np.sin(t) return M([x, y]) R_C = sg.Line(pc, sg.Point(C[0], C[1])) R_B = sg.Line(pc, sg.Point(r2, lopatka_XYZ[-2][2])) ang = 2 * np.pi - float(sympy.N(R_C.angle_between(R_B))) vec_I = np.linspace(ang, 2. * np.pi, num=5) kolo_BC = [] for i in vec_I: temp = [0.0] temp.extend(krzywiznaParametrycznie(i)) kolo_BC.append(temp) kolo_BC.append(pkty_XYZ[-2]) kolo_BC = np.array(kolo_BC)[1:] return kolo_BC
def generate_base_region(n: int): min_x = -np.power(2, float(n + 1)) max_x = np.power(2, float(n + 1)) min_y = min_x max_y = max_x points = [] for x in np.arange(min_x, max_x, step=1): for y in np.arange(min_y, max_y, step=1): points.append(g.Point(x, y)) combinations = itr.combinations(points, r=3)
def chose_poit(point_index_f, pointsall_f, lines_all_f): """point_index_f - индекс последней точки pointsall_f - список всех точек выбор следующей точки по критерию уникальности новой линии, возвращает точку [x,y]""" one_more = 1 next_point1_f = [] rand_range = list(range(len(pointsall_f) - 1)) #.remove(point_index_f) print(rand_range) while one_more == 1: chose1_f = random.choice(rand_range) while chose1_f == point_index_f: # чтобы не было совпадений с точкой начала rand_range.remove(chose1_f) chose1_f = random.choice(rand_range) # выбор точки, куда потянеться линя из первой точки next_point1_f = pointsall_f[chose1_f] # создание линии для проверки на совпадение p01 = symg.Point(pointsall_f[point_index_f][0], pointsall_f[point_index_f][1]) p02 = symg.Point(next_point1_f[0], next_point1_f[1]) one_more = 0 for j in range(len(lines_all_f) - 1): p1 = symg.Point(lines_all_f[j][0], lines_all_f[j][1]) p2 = symg.Point(lines_all_f[j + 1][0], lines_all_f[j + 1][1]) # проверка на коллинеарность из-за возможных наложений линий при несовпадении их длин, начала и конца if symg.Point.is_collinear(p1, p2, p01, p02): one_more = 1 # удалить из списка неудачную точку rand_range.remove(chose1_f) break return next_point1_f
def generate_triangles(n: int, bases: [g.Segment]): area = np.power(2, n) triangles = [] for base in bases: height = (2 * area) / float(base.length) try: p1, p2, p3, p4 = generate_parallelogram(base.p1, base.p2, height) al = g.Segment(p3, p4) y = lambda x: al.slope * (x - float(p3.x)) + float(p3.y) min_x = np.ceil(float(p3.x)) max_x = np.floor(float(p4.x)) for x in np.arange(min_x, max_x, step=1): x_test = float(x) % 1 == 0 y_p = y(x) y_test = float(y_p) % 1 == 0 if x_test and y_test: p3 = g.Point(x, y_p) t = g.Triangle(base.p1, base.p2, p3) triangles.append(t) except ValueError: pass acute_output = [] for t in triangles: append = True for vertex, angle in t.angles.items(): if float(angle) > np.pi / 2 or angle <= 0: append = False if append: acute_output.append(t) try: output = [acute_output[0]] for ao in acute_output[1:]: additional = [] for o in output: if not congruent(ao, o): additional.append(ao) new_output = list(set(output + additional)) output = new_output output = list(set(output)) except IndexError: output = [] return output
def __addStopPointToArrows(self): import sympy.geometry as sg for stopLine in self.__vectorMap.stopline.values(): bpid = self.__vectorMap.line[stopLine["LID"]]["BPID"] fpid = self.__vectorMap.line[stopLine["LID"]]["FPID"] blat, blng = self.__vectorMap.point[bpid][ "lat"], self.__vectorMap.point[bpid]["lng"] flat, flng = self.__vectorMap.point[fpid][ "lat"], self.__vectorMap.point[fpid]["lng"] for arrowID, arrow in self.__arrows.items(): for i in range(1, len(arrow["waypointIDs"])): abpid = arrow["waypointIDs"][i - 1] afpid = arrow["waypointIDs"][i] ablat, ablng = self.__vectorMap.point[abpid][ "lat"], self.__vectorMap.point[abpid]["lng"] aflat, aflng = self.__vectorMap.point[afpid][ "lat"], self.__vectorMap.point[afpid]["lng"] if self.isIentersected(blat, blng, flat, flng, ablat, ablng, aflat, aflng): intersection = sg.intersection( sg.Segment(sg.Point(blat, blng), sg.Point(flat, flng)), sg.Segment(sg.Point(ablat, ablng), sg.Point(aflat, aflng))) stopPoints = self.__arrows[arrowID].get( "stopPoints", []) stopPoints.append({ "nextWaypointID": arrow["waypointIDs"][i], "lat": float(intersection[0].x), "lng": float(intersection[0].y), }) self.__arrows[arrowID]["stopPoints"] = stopPoints
def draw_ellipse(draw, rect, width): pad = 40 minx = rect.min.x + pad miny = rect.min.y + pad maxx = rect.max.x - pad maxy = rect.max.y - pad draw.ellipse([(minx, miny), (maxx, maxy)], fill="black", width=width) # values for min and max and area of ellipses to pass to dataframe width_df = (maxx - minx) height_df = (maxy - miny) r1 = (width_df / 2) r2 = (height_df / 2) p1 = geometry.Point(0, 0) e1 = geometry.Ellipse(p1, r1, r2) area = sympy.N(e1.area) return width_df, height_df, area
def add_cell(self, network): cell = Circle((self.centre_x, self.centre_y), self.radius) nodes = network.vertices ridges = network.ridge_vertices nodes_to_delete = [] ridges_to_delete = [] for i in range(len(nodes)): if cell.contains_point(nodes[i]) == True: nodes_to_delete = np.append(nodes_to_delete, i) for i in range(len(ridges)): if ridges[i][0] in nodes_to_delete and ridges[i][ 1] in nodes_to_delete: ridges_to_delete = np.append(ridges_to_delete, i) ridges_to_delete = np.array(sorted(ridges_to_delete, reverse=True)) for ridge in ridges_to_delete: network.ridge_vertices = np.delete(network.ridge_vertices, int(ridge), axis=0) center = sg.Point(self.centre_x, self.centre_y) circ = sg.Circle(center, self.radius) k = 0 for node in nodes_to_delete: node = int(node) for ridge in network.ridge_vertices: if ridge[0] == node: if len(nodes[node]) == 3: In_point = sg.Point(nodes[node][0], nodes[node][1], nodes[node][2]) Out_point = sg.Point(nodes[ridge[1]][0], nodes[ridge[1]][1], nodes[ridge[1]][1]) elif len(nodes[node]) == 2: In_point = sg.Point(nodes[node][0], nodes[node][1]) Out_point = sg.Point(nodes[ridge[1]][0], nodes[ridge[1]][1]) line = sg.Line(In_point, Out_point) intersec = sg.intersection(circ, line) if length_square(nodes[ridge[1]] - intersec[0]) >= length_square( nodes[ridge[1]] - intersec[1]): nodes = np.append( nodes, [[float(intersec[1].x), float(intersec[1].y)]], axis=0) else: nodes = np.append( nodes, [[float(intersec[0].x), float(intersec[0].y)]], axis=0) ridge[0] = len(nodes) - 1 k += 1 if ridge[1] == node: if len(nodes[node]) == 3: In_point = sg.Point(nodes[node][0], nodes[node][1], nodes[node][2]) Out_point = sg.Point(nodes[ridge[0]][0], nodes[ridge[0]][1], nodes[ridge[0]][1]) elif len(nodes[node]) == 2: In_point = sg.Point(nodes[node][0], nodes[node][1]) Out_point = sg.Point(nodes[ridge[0]][0], nodes[ridge[0]][1]) line = sg.Line(In_point, Out_point) intersec = sg.intersection(circ, line) if length_square(nodes[ridge[0]] - intersec[0]) >= length_square( nodes[ridge[0]] - intersec[1]): nodes = np.append( nodes, [[float(intersec[1].x), float(intersec[1].y)]], axis=0) else: nodes = np.append( nodes, [[float(intersec[0].x), float(intersec[0].y)]], axis=0) ridge[1] = len(nodes) - 1 k += 1 nodes_to_delete = np.array(sorted(nodes_to_delete, reverse=True)) for point in nodes_to_delete: nodes = np.delete(nodes, int(point), 0) # Renumber points after deleting some for ridge in network.ridge_vertices: for i in range(2): r = 0 for node in nodes_to_delete: if node < ridge[i]: r += 1 ridge[i] = ridge[i] - r network.vertices = nodes network.vertices_ini = np.array(network.vertices.tolist()) network = network.create_ridge_node_list() network = network.sort_nodes() network.interior_nodes = network.interior_nodes[:-k] self.boundary_cell = list(range(len(nodes) - k, len(nodes))) return network
def wspolrzednePktPrzekroju(geometria, temp): r""" Funkcja służąca do obliczenia niezbędnych wymiarów wirnika. Na poniższym rysunku został przedstawiony przekrój wirnika i punkty określające jego wymiary. .. figure:: ./image/przekroj.png :align: center :alt: Szkic przekroju wirnika :figclass: align-center :scale: 20% Szkic przekroju wirnika Punkty te odpowiadają następującym wymiarowm pobranym z GUI: * Promień otworu - odl. od osi pionowej do punktu A * Promień zewnętrzny - odl. od osi pionowej do punktu B * Promień u wylotu - odl. od osi pion * Wysokość łopatki - odcinek :math:`|BC|` * Kąt alfa - kąt :math:`\alpha` * Promień zaokrąglenia - odcinek :math:`|RD|=|RE|` * Wysokość pod naddatek - odcinek :math:`|EF|` * Wysokość wirnika - odległość od punktu F do osi poziomej. W celu stworzenia geometrii w programie GMSH należy obliczyć położenie punktu :math:`D`. Punkt ten jest określane poprzez sprawdzenie punktów wspólnych okręglu zakreślonego w punkcie :math:`R` o promieniu :math:`|RD|` z prostą przechodzącą przez punkt :math:`C` odchyloną od poziomu o kąt :math:`\alpha`. Zadanie to zostało wykonane przy użyciu modułu SymPy. :param geometria: obiekt klasy Geometry zawierający dane geometryczne wirnika :type geometria: Geometry :param temp: tymczasowy kontener na dane, użyty w celu przechowywania informacji. :type temp: dictionary :return temp: uaktualniony kontener na dane. """ # Deklaracja zmiennych alfa = geometria.alfa h1 = geometria.h1 h2 = geometria.h2 h3 = geometria.h3 r3 = geometria.r3 r4 = geometria.r4 R = geometria.R # Deklaracja punktow na przekroju A = M([r3, h1]) C = M([r4, h2]) D = M([r4, h3]) R_pos = M([(r4 + R), C[1]]) temp['C'] = C temp['R_pos'] = R_pos # Tworzenie funkcji liniowej okreslajacej pochylenie wirnika a = np.tan(np.deg2rad(-alfa)) b = h1 - a * r3 funLin = lambda x: a * x + b temp['funLin'] = funLin # Wykorzystanie biblioteki Sympy do okreslenia punktu przeciecia sie # zaokraglonej czesci wirnika z pochylona plaszczyzna p1 = sg.Point(A[0], A[1]) p2 = sg.Point(r3 - 2.0, funLin(r3 - 2.0)) l = sg.Line(p1, p2) pc = sg.Point(R_pos[0], R_pos[1]) c = sg.Circle(pc, R) temp['pc'] = pc # Punkty przeciecia sie okregu z prosta punkty = sg.intersection(c, l) # Okresl czy istnieja punkty przeciecia i wybierz poprawne if len(punkty) == 0: text = "Powierzchnia wylotu nie moze zostać stworzona. Zmien wartosc \ wymiaru wysokosci lopatki, kat alfa, badz promien zaokraglenia" raise ValueError(text) if len(punkty) == 2: w = min(punkty, key=lambda p: p.y) B = M([sympy.N(w).x, sympy.N(w).y]) else: w = punkty B = M([sympy.N(punkty).x, sympy.N(punkty).y]) # Zbierz wszystkie punkty w jednej macierzy 'pkty_YZ' pkty_YZ = M([A, B, C, D, R_pos]) # Przystosuj zmienne do obliczen w GMSH'u for i in pkty_YZ: i[0], i[1] = float(i[0]), float(i[1]) i[0] = -i[0] # Dodaj trzeci wymiar do obliczonych punktow pkty_XYZ = np.insert(pkty_YZ, 0, 0.0, axis=1) temp['pkty_XYZ'] = pkty_XYZ return temp
def standardize(self): # Fix p1 to the origin and translate triangle points = self.vertices fixed = points[0] points = [p - fixed for p in points] t_fix = g.Triangle(*points) # Rotate triangle into Q1 and fix side to x-axis origin = g.Point(0, 0) origin_sides = [] for s in t_fix.sides: if s.p1 == origin or s.p2 == origin: origin_sides.append(s) xvector = g.Line(p1=origin, p2=g.Point(1, 0)) angle_segments = [] for os in origin_sides: if os.p1 == origin: other = os.p2 else: other = os.p1 sg_orient = g.Segment(p1=origin, p2=other) angle = xvector.angle_between(sg_orient) angle_segments.append((float(angle), sg_orient)) print(angle_segments) rotate_angle, rotate_segment = max(angle_segments, key=lambda t: float(t[0])) print(rotate_angle, rotate_segment) # Check which quadrant the evaluation segment is in. If Q3 or Q4, do nothing to angle; if Q1 or Q2, negate angle if float(rotate_segment.p2.y) > 0: rotate_angle = -rotate_angle rotate_points = t_fix.vertices t_rot = g.Triangle(*[i.rotate(rotate_angle) for i in rotate_points]) # Reflect the triangle about its base midpoint if the angle from the origin is less than or equal to 45 origin_angle = float(t_rot.angles[origin]) print(t_fix) base_points = [] alterior_vertex = None for v in t_rot.vertices: if float(v.y) == float(0): base_points.append(v) else: alterior_vertex = v base = g.Segment(*base_points) if origin_angle <= (np.pi / 4): midpoint = base.midpoint x_dist = alterior_vertex.x - midpoint.x new_av = g.Point(x=(midpoint.x - x_dist), y=alterior_vertex.y) vertices = base_points + [new_av] t = g.Triangle(*vertices) else: t = t_rot return t
def init(self): # select random point for each obstacle for obs in self.obstacles: obs.bk = obs.samplePosition() self.obsBkPairLines = [] for i in range(len(self.obstacles)): for j in range(i + 1, len(self.obstacles)): bk1 = self.obstacles[i].bk bk2 = self.obstacles[j].bk pline = symgeo.Line(symgeo.Point(bk1[0], bk1[1]), symgeo.Point(bk2[0], bk2[1])) self.obsBkPairLines.append(pline) # select central point c self.centralPoint = (self.width / 2, self.height / 2) foundCP = False while foundCP == False: if (self.isInObstacle(self.centralPoint) == False) and (self.isInObsBkLinePair(self.centralPoint) == False): foundCP = True else: cpX = np.random.normal() * ( self.sampleWidthScale) + self.width / 2 cpY = np.random.random() * ( self.sampleHeightScale) + self.height / 2 self.centralPoint = (int(cpX), int(cpY)) #print "Resampling " + str(self.centralPoint) # init four boundary line self.boundary_lines = [] self.x_axis = symgeo.Line(symgeo.Point(0, 0), symgeo.Point(self.width - 1, 0)) self.y_axis = symgeo.Line(symgeo.Point(0, 0), symgeo.Point(0, self.height - 1)) self.x_high = symgeo.Line( symgeo.Point(0, self.height - 1), symgeo.Point(self.width - 1, self.height - 1)) self.y_high = symgeo.Line( symgeo.Point(self.width - 1, 0), symgeo.Point(self.width - 1, self.height - 1)) self.boundary_lines.append(self.x_axis) self.boundary_lines.append(self.y_high) self.boundary_lines.append(self.x_high) self.boundary_lines.append(self.y_axis) # init lines from center point to four corners self.center_corner_lines_info = [] self.center_corner_lines_info.append([ (0, 0), numpy.arctan2(float(-self.centralPoint[1]), float(-self.centralPoint[0])) ]) self.center_corner_lines_info.append([ (0, self.height), numpy.arctan2(float(self.height - self.centralPoint[1]), float(-self.centralPoint[0])) ]) self.center_corner_lines_info.append([ (self.width, self.height), numpy.arctan2(float(self.height - self.centralPoint[1]), float(self.width - self.centralPoint[0])) ]) self.center_corner_lines_info.append([ (self.width, 0), numpy.arctan2(float(-self.centralPoint[1]), float(self.width - self.centralPoint[0])) ]) for ccl_info in self.center_corner_lines_info: if ccl_info[1] < 0: ccl_info[1] += 2 * numpy.pi self.center_corner_lines_info.sort(key=lambda x: x[1], reverse=False) #print "CENTER CORNER LINES " #print self.center_corner_lines_info self.ray_info_list = [] # init alpah and beta segments for obs in self.obstacles: obs.alpha_ray = symgeo.Ray( symgeo.Point(obs.bk[0], obs.bk[1]), symgeo.Point(self.centralPoint[0], self.centralPoint[1])) obs.beta_ray = symgeo.Ray( symgeo.Point(obs.bk[0], obs.bk[1]), symgeo.Point(2 * obs.bk[0] - self.centralPoint[0], 2 * obs.bk[1] - self.centralPoint[1])) a_pt = self.findIntersectionWithBoundary(obs.alpha_ray) #print str(obs.alpha_ray) + " --> " + str(a_pt) b_pt = self.findIntersectionWithBoundary(obs.beta_ray) #print str(obs.beta_ray) + " --> " + str(b_pt) obs.alpha_seg = None obs.beta_seg = None if a_pt != None: alpha_seg = shpgeo.LineString([obs.bk, (a_pt.x, a_pt.y)]) obs.alpha_seg = LineSegmentMgr(alpha_seg, 'A', obs) if b_pt != None: beta_seg = shpgeo.LineString([obs.bk, (b_pt.x, b_pt.y)]) obs.beta_seg = LineSegmentMgr(beta_seg, 'B', obs) alpha_ray_rad = numpy.arctan(float(obs.alpha_ray.slope)) if obs.alpha_ray.p1.x > obs.alpha_ray.p2.x: alpha_ray_rad += numpy.pi if alpha_ray_rad < 0: alpha_ray_rad += 2 * numpy.pi alpha_ray_info = (obs.idx, 'A', alpha_ray_rad) beta_ray_rad = numpy.arctan(float(obs.beta_ray.slope)) if obs.beta_ray.p1.x > obs.beta_ray.p2.x: beta_ray_rad += numpy.pi if beta_ray_rad < 0: beta_ray_rad += 2 * numpy.pi beta_ray_info = (obs.idx, 'B', beta_ray_rad) #print "ALPHA RAY SLOPE " + str(alpha_ray_info) #print "BETA RAY SLOPE " + str(beta_ray_info) self.ray_info_list.append(alpha_ray_info) self.ray_info_list.append(beta_ray_info) obs.alpha_seg_info = ((a_pt.x, a_pt.y), alpha_ray_rad) obs.beta_seg_info = ((b_pt.x, b_pt.y), beta_ray_rad) self.ray_info_list.sort(key=lambda x: x[2], reverse=False)
def dodajWspolrzedne(wek): r""" Funkcja zawiera opis krzywizny łopatki we współrzędnych parametrycznych. W pierwszym etapie zostają wyznaczone kąty :math:`{\kappa}_{1}` i :math:`{\kappa}_{2}`. Następnie tworzona jest tablica zawierająca osiem równoodległych wartości z pomiędzy tych kątów. Tak otrzymane dane zostają użyte przy określaniu punktów leżących na krzywej :math:`AC`. .. figure:: ./image/kat.png :align: center :alt: Krzywizna łopatki :figclass: align-center :scale: 18% Szkic krzywizny łopatki :param wek: tablica zawierająca położenie punktów :math:`A`, :math:`B` i :math:`C`. :type wek: lista zawierająca współrzędne punktów na krzywiźnie łopatki """ # Deklaracja zmiennych srOk = M([wek[2][0], wek[2][1]]) L1 = sg.Point(wek[0][0], wek[0][1]) L6 = sympy.N(sg.Point(wek[1][0], wek[1][1])) # Srodek okregu, ktory zawiera krzywizne wirnika L_cent = sg.Point(srOk[0], srOk[1]) # Zwroc promien wirnika promien = sympy.N(L1.distance(L_cent)) # Prosta pozioma przechodzaca przez srodek ukladu wspolrzednych hl = sg.Line(sg.Point(0., 0.), sg.Point(1., 0.)) # Prosta przechodzaca przez srodek krzywizny i punkt poczatkowy lopatki l_6 = sg.Line(L6, L_cent) # Prosta przechodzaca przez srodek krzywizny i punkt koncowy lopatki l_1 = sg.Line(L1, L_cent) # Oblicz kat pomiedzy prosta l_6 a prosta pozioma ang_6_hl = float(sympy.N(l_6.angle_between(hl)) + np.pi) # Oblicz kat pomiedzy prosta l_1 a prosta pozioma ang_1_hl = float(sympy.N(l_1.angle_between(hl)) + np.pi) # Zdefiniuj w ilu punktach krzywizna wirnika powinna zostac obliczona podzial = 8 # Stworz wektor zawierajacy katy, ktore zostana uzyte do obliczenia punktow vec_I = np.linspace(ang_6_hl, ang_1_hl, num=podzial)[1:-1] # Funkcja opisujace krzywizne lopatki w sposob parametryczny def krzywiznaParametrycznie(t): x = srOk[0] + promien * np.cos(t) y = srOk[1] + promien * np.sin(t) return [x, y] # Stworz wektor zawierajacy wspolrzedne punktow opisujacych lopatke r_temp = [ [L6.x, L6.y], ] for i in vec_I: # Oblicz polozenie punktu na podstawie parametrycznej funkcji opisujacej # krzywizne lopatki i kata okreslajacego wspolrzedne. krzyw = krzywiznaParametrycznie(i) r_temp.append(krzyw) r_temp.append([L1.x, L1.y]) r_temp.reverse() r_temp.append(srOk) return r_temp