def add_rectangles_by_path(self, path1, path2, start_offset): path_len = 0 for p in path1: path_len += p.len # path_len -= start_offset first_shift = start_offset second_shift = 0 pos_first_path = 0 pos_second_path = 0 first_len = first_shift while first_len < path_len: ed1 = path1[pos_first_path] ed2 = path2[pos_second_path] rectangle = Rectangle(ed1,ed2) rectangle.add_diagonal(self.d, self.d + first_shift - second_shift) rect_diag = rectangle.get_closest_diagonal(self.d + first_shift - second_shift) self.add_diagonal_and_conj(rect_diag) print "ADD DIAGS", rect_diag if ed2.len - second_shift < ed1.len - first_shift: pos_second_path += 1 first_shift += ed2.len - second_shift first_len += ed2.len - second_shift second_shift = 0 elif ed1.len - first_shift < ed2.len - second_shift: pos_first_path += 1 first_len += ed1.len - first_shift second_shift += ed1.len - first_shift first_shift = 0 else: first_len += ed1.len - first_shift pos_second_path += 1 pos_first_path += 1 first_shift = 0 second_shift = 0
def __init__(self): # self.id = random.uniform(0, 999999999) Rectangle.__init__(self) self.handler = Handler() self.magnetos = Magnetos() self.offset = Point() self.pivot = Point() self.selected = False self.resizing = False self.direction = NONE self.control = AUTOMATIC self.z = 0 self.hints = False from ui.canvas import Canvas self.canvas = Canvas() self.handler.is_testing = self.canvas.is_testing self.dash = [] self.thickness = 1.0 self.fill_style = COLOR self.fill_color = Color(0.25, 0.25, 0.25, 0.25) self.stroke_color = Color(0.25, 0.25, 0.25, 1.0) self.gradient = Gradient()
def update(viewAngleHorz): print "update()" # Get color image from camera ret, img = camera.read() # img.shape 640x480 image # Convert to hsv img hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) # Keep only green objects # higher s = less white, higher v = less black lowerGreen = np.array([70, 70, 180]) upperGreen = np.array([110, 130,255]) filteredGreen = cv2.inRange(hsv, lowerGreen, upperGreen) # Filter out small objects filteredGreen = cv2.morphologyEx(filteredGreen, cv2.MORPH_OPEN, np.ones((3, 3))) # Find all contours, counter is vector of points that are connected to make up a shape contours, hierarchy = cv2.findContours(filteredGreen, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) # Resetting values foundHotTarget = False; foundHorzTarget = False # Parse contours, calculate distance and check if it's the hot target for shape in contours: target = Rectangle(*cv2.boundingRect(shape)) # Filter out small contours if target.getArea() > 300 and target.getArea() < 10000: # Compensate for horizontal view of the target target.width = target.width / math.cos(viewAngle * math.PI / 180) # If the width of the target is greater than its height then it's probably the hot target if target.width >= target.height * 2.5: foundHotTarget = True distance = computeDistance(horizTarget.height, target.height) if debugMode: drawRect(img, target) viewAngle = computeAngle(horizTarget.height, target.height, 228) print "Distance: ", round(distance), ", Hot Target", viewAngle, viewAngleVert # If the height of the target is greater than the its width its probably a vert target if target.height >= target.width * 6: foundHorzTarget = True distance = computeDistance(vertTarget.height, target.height) if debugMode: drawRect(img, target) viewAngle = computeAngle(vertTarget.height, target.height, 228) print "Distance: ", round(distance), ", Vert Target", viewAngle, viewAngleVert if debugMode: cv2.imshow("color", img) cv2.waitKey(10) cv2.imshow("filtered", filteredGreen) cv2.waitKey(10)
def main(): house = Point(10, 9) print('House is at X:', house.x) print('House is at Y:', house.y) work = Point(5, 2) print('House to work distance:', house.distance_to(work)) city = Rectangle(Point(5, 5), 10, 10) print('City corner is:', city.bottom_left_corner) print('City width:', city.w) print('City height:', city.h) print('House in city:', city.contains(house)) print('Work in city:', city.contains(work)) city_center = city.find_center() print('City center:', city_center) cats_house = Point(10, 9) identical_city = Rectangle(Point(5, 5), 10, 10) different_city = Rectangle(Point(13, 13), 10, 10) print("My cat's house and mine are equal:", house == cats_house) print('Two identical cities are equal:', city == identical_city) print('Two different cities are equal:', city == different_city) house.move_by(1, -1) print('After moving my house:', house)
def __init__(self): Rectangle.__init__(self) self.hidden = False self.position = 0.0 self.direction = NONE self.control = Control() self.control.limbus = True
def main(x0, y0, x1, y1): rect = Rectangle(int(x0), int(y0), int(x1), int(y1)) msg = 'For the rectangle with corners located at (' msg += str(x0) + ', ' + str(y0) + ') and (' msg += str(x1) + ', ' + str(y1) + '):\n' print(msg) msg = 'The length is ' + str(rect.getLength()) msg += ' and the height is ' + str(rect.getHeight()) + '.' print(msg) msg = 'The area is ' + str(rect.getArea()) + '.' print(msg)
def move_rectangle(old_rec, dx, dy): """ Takes a rectangle and distances, and returns a new Rectangle object moved by those coordinates. """ new_rec = Rectangle() new_rec.height = old_rec.height new_rec.width = old_rec.width new_rec.corner = Point() new_rec.corner.x = old_rec.corner.x + dx new_rec.corner.y = old_rec.corner.y + dy return new_rec
class RectangleTest(unittest.TestCase): def setUp(self): self.rect = Rectangle() def test_get_area(self): area = self.rect.width * self.rect.height self.assertEqual(self.rect.get_area(), area) def test_get_perimeter(self): perimeter = (self.rect.width + self.rect.height) * 2 self.assertEqual(self.rect.get_perimeter(), perimeter)
def __init__(self): Rectangle.__init__(self) self.active = True self.top = 0 self.left = 0 self.bottom = 0 self.right = 0 self.control = list() index = 0 while index < 8: control = Control() self.control.append(control) index += 1
def test_overlap(self): ''' Test overlap between circles and rectangles. ''' new_rect1 = Rectangle(100, 100) new_rect2 = Rectangle(50, 150, 50, 50) circ1 = Circle(25) circ2 = Circle(30, 0, -5) self.assertEqual(-50, new_rect1.get_overlap(new_rect2)) self.assertEqual(new_rect1.get_overlap(new_rect2), new_rect2.get_overlap(new_rect1)) self.assertEqual(-50, circ1.get_overlap(new_rect1)) self.assertEqual(circ1.get_overlap(new_rect1), new_rect1.get_overlap(circ1)) self.assertAlmostEqual(math.sqrt(2)*25 - 25, circ1.get_overlap(new_rect2)) self.assertEqual(circ1.get_overlap(new_rect2), new_rect2.get_overlap(circ1)) self.assertEqual(-50, circ1.get_overlap(circ2)) self.assertEqual(circ1.get_overlap(circ2), circ2.get_overlap(circ1)) circ1.set_position(80, 50) self.assertEqual(-20, circ1.get_overlap(new_rect2)) self.assertEqual(circ1.get_overlap(new_rect2), new_rect2.get_overlap(circ1))
def add_diagonal_and_conj(self, diag): for old_diag in self.diagonals: if diag.rectangle.e1 == old_diag.rectangle.e1 and diag.rectangle.e2 == old_diag.rectangle.e2: if diag.D == old_diag.D: return rect = diag.rectangle rect_conj = Rectangle(rect.e2.conj, rect.e1.conj) conjugate(rect, rect_conj) D = diag.D - diag.rectangle.e1.len + diag.rectangle.e2.len pathset = diag.pathset.conj() if experimental.filter == experimental.Filter.pathsets else None rect_conj.add_diagonal(self.d, D, pathset) diag_conj = rect.conj.diagonals[D, pathset] conjugate(diag, diag_conj) return self.add_diagonal(diag)
def __init__(self,x, y, id): self.sprite = Image(source=self.imageLocations[id]) self.sprite.allow_stretch = True self.sprite.auto_bring_to_front = False self.id = id self.bounds = Rectangle(x,y,self.imageSizes[id].x,self.imageSizes[id].y) self.setSize(self.imageSizes[id].x, self.imageSizes[id].y) self.setPosition(x,y)
def update(prefSideLeft, isDebug): logging.debug("update() {} {}".format(isDebug, imgNameIndex)) # Get color image from camera ret, img = camera.read() # img.shape 640x480 image # Convert to hsv img hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) # Keep only green objects # higher s = less white, higher v = less black lowerGreen = np.array([70, 70, 180]) upperGreen = np.array([110, 130,255]) filteredGreen = cv2.inRange(hsv, lowerGreen, upperGreen) # Filter out small objects filteredGreen = cv2.morphologyEx(filteredGreen, cv2.MORPH_OPEN, np.ones((3, 3))) # Find all contours, countours is vector of points that are connected to make up a shape contours, hierarchy = cv2.findContours(filteredGreen, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) # Resetting foundHotTarget global foundHotTarget foundHotTarget = False; # Parse contours, calculate distance and check if it's the hot target for shape in contours: target = Rectangle(*cv2.boundingRect(shape)) # Filter out small contours if target.getArea() > 300 and target.getArea() < 10000: # If the width of the target is greater than its height then it's probably the hot target if target.width >= target.height * 2.5: foundHotTarget = inPrefSide(target.x + (target.width / 2), prefSideLeft) if isDebug: drawRect(img, target) viewAngle = computeAngle(horizTarget.height, target.height, distanceFromTarget) logging.debug("Hot Target: " + str(foundHotTarget) + ", New Angle: " + str(viewAngle)) # Save img so we can analyze it if isDebug: saveImg(img)
class RectangleTest(TestCase): def setUp(self): self.rectangle = Rectangle(1, 2, 3, 4) def test_getLength(self): assert_equal(self.rectangle.getLength(), 2) def test_getHeight(self): assert_equal(self.rectangle.getHeight(), 2) def test_getArea(self): assert_equal(self.rectangle.getArea(), 4) def test_move(self): self.rectangle.move(4, 8) self.test_getLength() self.test_getHeight() self.test_getArea()
def test_rectangle_distance_from_frame(self): ''' Test overlap between rectangles and frame. ''' rect = Rectangle(50, 50, 175, 175) self.assertAlmostEqual(200 - math.sqrt(2)*25, rect.get_distance_from_frame(200), 2) rect.set_position(200, 200) self.assertAlmostEqual(200 - math.sqrt(2)*50, rect.get_distance_from_frame(200), 2) rect.set_position(0, 350) self.assertAlmostEqual(200 - math.sqrt(2)*200, rect.get_distance_from_frame(200), 2)
class RectangleTestCase(unittest.TestCase): '''Test creation and use of a Rectangle.''' def setUp(self): self.rect = Rectangle(0, 150, 200, 50, media.forestgreen, 1) def tearDown(self): self.rect = None def testString(self): assert str(self.rect) == 'Rectangle @ ( 0 , 150 ) height = 50, ' + \ 'width = 200', 'mismatch in string version of rectangle' def testGetPriority(self): assert self.rect.get_priority() == 1, \ 'mismatch in initial priority value' def testSetGetPriority(self): self.rect.set_priority(10) assert self.rect.get_priority() == 10, \ 'mismatch in new priority value'
def traverse_to(level, key): page = self.db.get(key) min_lat, min_lon, max_lat, max_lon, pickled_ids = page.split(":") page_bounds = BBox( min_lat=float(min_lat), min_lon=float(min_lon), max_lat=float(max_lat), max_lon=float(max_lon) ) if not within(page_bounds, node): return ids = pickle.loads(pickled_ids) if level == 0: # We're at a leaf that intersects, done if node.id in ids: ids.remove(node.id) rect = Rectangle() rect.node_ids = ids rect.min_lat = float(min_lat) rect.min_lon = float(min_lon) rect.max_lat = float(max_lat) rect.max_lon = float(max_lon) self.db.put(key, str(rect)) else: # We're at an intermediate node, keep going for id in ids: traverse_to(level - 1, id)
class RectangleTest(unittest.TestCase): def setUp(self): self.rectangle = Rectangle(width=3, height=2) def test_it_has_width_and_height(self): self.rectangle.width |should| equal_to(3) self.rectangle.height |should| equal_to(2) def test_it_changes_its_width(self): self.rectangle.width = 5 self.rectangle.width |should| equal_to(5) def test_it_changes_its_height(self): self.rectangle.height = 5 self.rectangle.height |should| equal_to(5) def test_it_calculates_its_area(self): self.rectangle.area() |should| equal_to(6) def test_it_calculates_its_perimeter(self): self.rectangle.perimeter() |should| equal_to(10)
class BoundedActor( Actor ): """ Actor class with bounding rectangle """ def __init__( self, **kwargs ): """ Keyword Arguments: - model: - texture: - drawmode: - rectdim: - boundoffset: (x,y) offset of bounding rectangle from (0,0) in model coordinates, used to position the bounding rectangle within the actor model self, model, texture=None, drawmode='polygon' """ try: texture = kwargs.get( 'texture', None ) drawmode = kwargs.get( 'drawmode', 'polygon' ) self._boundoffset = kwargs.get( 'boundoffset', (0,0) ) super(BoundedActor,self).__init__( kwargs['model'], texture, drawmode ) self._bound = Rectangle( **kwargs ) except KeyError: print "Bounded Actor requires a model" #================================================================================================= def draw( self, pos, name,drawbound=False ): """ """ super(BoundedActor,self).draw(pos,name) if drawbound: self._bound.draw((pos[0]+self._boundoffset[0],pos[1]+self._boundoffset[1]),name) else: self._bound.updatepos( (pos[0]+self._boundoffset[0],pos[1]+self._boundoffset[1]) ) #================================================================================================= def collide(self,point): """ """ return self._bound.collide(point)
def __init__(self, images, **kwargs): """Merge list of images. Insert i-th image on (i-1)-th on specified position, i = n, n-1, ..., 0. This field is usefull for views to join Images (packed in ImageWrapper) Args: images (tuple): (ImageWrapper, (x, y)) image and it's position relative to the background. """ super(Flattener, self).__init__(**kwargs) self.images = images max_width = max([image.get_width() + width for image, (width, height) in images]) max_height = max([image.get_height() + height for image, (width, height) in images]) self.background = Rectangle((max_width, max_height), thickness=kwargs.get('thickness', 0))
def __init__( self, **kwargs ): """ Keyword Arguments: - model: - texture: - drawmode: - rectdim: - boundoffset: (x,y) offset of bounding rectangle from (0,0) in model coordinates, used to position the bounding rectangle within the actor model self, model, texture=None, drawmode='polygon' """ try: texture = kwargs.get( 'texture', None ) drawmode = kwargs.get( 'drawmode', 'polygon' ) self._boundoffset = kwargs.get( 'boundoffset', (0,0) ) super(BoundedActor,self).__init__( kwargs['model'], texture, drawmode ) self._bound = Rectangle( **kwargs ) except KeyError: print "Bounded Actor requires a model"
def mousePressEvent(self, QMouseEvent): x = QMouseEvent.x() y = QMouseEvent.y() if self.mouseActionType == Map.NoAction: self.dragXstart = x self.dragYstart = y self.dragObject = Rectangle() self.dragObject.updateDrag(self.dragXstart, self.dragYstart, self.dragXstart, self.dragYstart) self.mouseActionType = Map.PlaceBlockAction #TODO cleanup #print(QMouseEvent.pos()) elif self.mouseActionType == Map.PlaceRobotAction: self.robot = Robot(x, y, 0) self.setStatsWidget()
#!/usr/bin/python from swampy.World import World from rectangle import Rectangle, Point def draw_rectangle(Canvas, Rectangle): bbox = [[Rectangle.corner.x, Rectangle.corner.y], [Rectangle.corner.x + Rectangle.width, Rectangle.corner.y + Rectangle.height]] Canvas.rectangle(bbox, outline="black", width=2, fill="green4") world = World() canvas = world.ca(width=500, height=500, background="white") box = Rectangle() box.corner = Point() box.corner.x = 50 box.corner.y = 50 box.width = 100 box.height = 100 draw_rectangle(canvas, box) world.mainloop()
def __init__(self): Rectangle.__init__(self) self.active = True self.tags = list() self.magnetism = 32
pack1 = DetPack(tuberadius = .5*.0254, airgap = AIR_GAP, xstartdiff = (.0254+AIR_GAP), ysize = -1.*TUBE_LENGTH, ystartdiff = -1.*TUBE_LENGTH/128., debug=False) pack1.setNames(pixel="onepixel", tube="tubedecreasing", pack="packdecreasing") group1 = instr.makeTypeElement("Group1") for i in range(n_first): offset = i*8*128 bank = "bank%d" % (i+1) rect = Rectangle( (-y[offset+UL], x[offset+UL], z[offset+UL]), (-y[offset+LL], x[offset+LL], z[offset+LL]), (-y[offset+LR], x[offset+LR], z[offset+LR]), (-y[offset+UR], x[offset+UR], z[offset+UR]) ) det = instr.makeDetectorElement(pack1.namepack, root=group1) rect.makeLocation(instr, det, bank) # ---------- add in group2 """ ;;; source idl code N_second=23 ;z0_second=5.05/8.45*3.2 ;x0_second=2.24/8.45*3.2 ;z1_second=2.54/8.45*3.2 ;x1_second=2.24/8.45*3.2 z0_second=5.09/7.06*2.7-0.0095 x0_second=2.22/7.06*2.7
def choose_best_path(self, paired_paths, rectangeles_set, diag1, diag2, d, added_paths): best_support = 0 best_len = 10000 best_rectangles = [] best_diags = [] best_path = paired_paths[0] best_not_supported = 0 for paired_path in paired_paths: (path1, path2, path_len) = paired_path if paired_path in added_paths: continue first_shift = diag1.offseta second_shift = diag1.offsetb path1.append(diag2.rectangle.e1) path2.append(diag2.rectangle.e2) rectangles = [] diags = [] not_supported = [] path_support = 0 pos_first_path = 0 pos_second_path = 0 first_len = first_shift make_less_N50 = False while not make_less_N50 and first_len < path_len + diag2.offseta: ed1 = path1[pos_first_path] ed2 = path2[pos_second_path] rectangle = Rectangle(ed1,ed2) rectangle.add_diagonal(d, d + first_shift - second_shift) rect_diag = rectangle.get_closest_diagonal(d + first_shift - second_shift) if (not (rect_diag.key1 == diag1.key1 and rect_diag.key2 == diag1.key2) and not(rect_diag.key1 == diag2.key1 and rect_diag.key2 == diag2.key2)): can_use = [diag1.key1, diag1.key2, diag2.key1, diag2.key2] if (rect_diag.key1 in self.vs and rect_diag.key1 not in can_use) or (rect_diag.key2 in self.vs and rect_diag.key2 not in can_use): make_less_N50 = True continue diags.append(rect_diag) rectangles.append(rectangle) rectangeles_set.use_prd_diag(rect_diag) #if rect_diag.prd_support < 0.00001 and (ed2.len > 10 and ed1.len > 10): # make_less_N50 = True # continue path_support += rect_diag.prd_support if ed2.len - second_shift < ed1.len - first_shift: pos_second_path += 1 first_shift += ed2.len - second_shift first_len += ed2.len - second_shift if rect_diag.prd_support < 0.000000001: not_supported.append(ed2.len - second_shift) second_shift = 0 elif ed1.len - first_shift < ed2.len - second_shift: pos_first_path += 1 first_len += ed1.len - first_shift second_shift += ed1.len - first_shift if rect_diag.prd_support < 0.000000001: not_supported.append(ed1.len - first_shift) first_shift = 0 else: first_len += ed1.len - first_shift pos_second_path += 1 pos_first_path += 1 first_shift = 0 second_shift = 0 if not make_less_N50 and path_len > 1 and path_support / path_len < 1000 and path_support / path_len > best_support: best_support = path_support best_len = path_len best_rectangles = rectangles best_diags = diags best_path = (path1, path2, path_len) best_not_supported = not_supported return (best_support,best_len, best_rectangles, best_diags, best_path)
quarter_recs.remove(staff_quarter_recs[i]) octa_recs.append(staff_quarter_recs[i]) # 이하는 이어진 8분음표가 아닌 홀로 떨어져있는 진짜 8분음표처럼 생긴애를 quarter중에 분류하는 작업 for i in range(len(staff_boxes)): # cnt+=1 # prtline="Staff{} ".format(str(cnt)) middle_x, staff_middle_y = staff_boxes[i].middle # copy_copy_img=copy_img.copy() staff_quarter_recs = [r for r in quarter_recs if staff_boxes[i].y <= r.y and staff_boxes[i].y + staff_boxes[i].h >= r.y] staff_quarter_recs.sort(key=lambda r: r.x) # tempcnt=0 for quarter in staff_quarter_recs: # tempcnt+=1 if quarter.y > staff_middle_y - gaplist[i] / 2: # 가운데아래 음표 temp = Rectangle(quarter.x + quarter.w, quarter.y - gaplist[i] * 3 + int(quarter.h * 0.3), int(quarter.w / 2), quarter.h) if isOcta(gray_line_delete_img, temp): quarter_recs.remove(quarter) octa_recs.append(quarter) else: if quarter.y > staff_middle_y - gaplist[i] * 0.8: # 가운데줄 음표 temp = Rectangle(quarter.x + int(quarter.w * 0.2), quarter.y + gaplist[i] * 3 - int(quarter.h * 0.3), int(quarter.w / 2), quarter.h) if isOcta(gray_line_delete_img, temp): quarter_recs.remove(quarter) octa_recs.append(quarter) else: # 가운데 위 음표 temp = Rectangle(quarter.x + int(quarter.w * 0.2), quarter.y + gaplist[i] * 3 - int(quarter.h * 0.3), int(quarter.w / 2), quarter.h) if isOcta(gray_line_delete_img, temp): quarter_recs.remove(quarter)
def test_eq(self): self.assertTrue(Rectangle(1, 2, 3, 6.7) == Rectangle(1, 2, 3, 6.7)) self.assertTrue(Rectangle(1.5, 2, 3, 6.23) != Rectangle(4, 1, 8, 9)) self.assertTrue(Rectangle(5, 1, 12, 9) != Rectangle(5, 1, 9, 2))
def test_print(self): self.assertEqual(str(Rectangle(1, 2, 3, 6)), "[(1, 2), (3, 6)]") self.assertEqual(str(Rectangle(5, -2.5, 8.23, 7)), "[(5, -2.5), (8.23, 7)]") self.assertEqual(repr(Rectangle(2, -2, 5, 5)), "Rectangle(2, -2, 5, 5)")
def __init__(self): Rectangle.__init__(self) self.active = False
from rectangle import Rectangle r = Rectangle(1, 2, 3, 4) print r print "Original area:", r.getArea() r.move(1,2) print r print "Area is invariante under rigid motions:", r.getArea() r += Rectangle(0,0,1,1) print r print "Now the aread is:", r.getArea() r.setsize(3) print r.getsize()
def test_area(self): self.assertEqual(Rectangle(1, 2, 5.2, 6).area(), 16.8) self.assertEqual(Rectangle(-1, 1, 7, 8).area(), 56) self.assertEqual(Rectangle(-2, -3.8, 1, 5).area(), 26.4) self.assertEqual(Rectangle(-9, 0.5, -5.5, 1).area(), 1.75)
from rectangle import Rectangle from triangle import Triangle rec = Rectangle() rec.setValues(50, 40) print(rec.area()) tri = Triangle() tri.setValues(50, 40) print(tri.area())
class Map(QtGui.QFrame): msg2Statusbar = QtCore.pyqtSignal(str) changedStatus = QtCore.pyqtSignal(bool) MapWidth = 1024 MapHeight = 640 Speed = 100 NoAction = 0 PlaceBlockAction = 1 PlaceRobotAction = 2 PlaceTargetAction = 3 def __init__(self, parent): super(Map, self).__init__(parent) self.parent = parent self.initMap() def initMap(self): QtCore.qDebug('sim_map.Map.initMap') self.timer = QtCore.QBasicTimer() self.setFrameStyle(QtGui.QFrame.Panel | QtGui.QFrame.Raised) self.objects = [] self.setFocusPolicy(QtCore.Qt.StrongFocus) self.setFixedSize(Map.MapWidth, Map.MapHeight) self.isStarted = False self.isPaused = False self.clearMap() self.dragXstart = -1 self.dragYstart = -1 self.dragXend = -1 self.dragYend = -1 self.dragObject = None self.mouseActionType = Map.NoAction self.saveToImage = True self.mapChanged = False self.robot = None self.target = None self.vbox = QtGui.QVBoxLayout() self.setLayout(self.vbox) self.simStats = SimStats(self) def load(self, fname): print("[sim_map.Map.load]") with open(fname) as fp: fp.readline() line = fp.readline().strip().split() Map.MapWidth = int(line[0]) Map.MapHeight = int(line[1]) Map.Speed = int(line[2]) fp.readline() line = fp.readline().strip() nObjects = int(line) fp.readline() for i in range(nObjects): line = fp.readline().strip().split() x = int(line[0]) y = int(line[1]) w = int(line[2]) h = int(line[3]) print(line) self.objects.append(Rectangle(x, y, w, h)) self.setFixedSize(Map.MapWidth, Map.MapHeight) self.repaint() def save(self, fname): print("[sim_map.Map.save]") self.setChanged(False) with open(fname, 'w') as fp: fp.write('# MapWidth MapHeight Speed\n') fp.write(str(Map.MapWidth) + ' ' + str(Map.MapHeight) + ' ' + str(Map.Speed) + '\n') fp.write('# Number of objects\n') fp.write(str(len(self.objects)) + '\n') fp.write('# x y width height\n') for obj in self.objects: fp.write(str(obj) + '\n') def start(self): QtCore.qDebug('sim_map.Map.start') if self.isPaused: return self.isStarted = True self.clearMap() self.msg2Statusbar.emit(str(0)) self.timer.start(Map.Speed, self) def pause(self): QtCore.qDebug('sim_map.Map.pause') if not self.isStarted: return self.isPaused = not self.isPaused if self.isPaused: self.timer.stop() self.msg2Statusbar.emit("paused") else: self.timer.start(Map.Speed, self) self.msg2Statusbar.emit(str(0)) self.update() def mousePressEvent(self, QMouseEvent): x = QMouseEvent.x() y = QMouseEvent.y() if self.mouseActionType == Map.NoAction: self.dragXstart = x self.dragYstart = y self.dragObject = Rectangle() self.dragObject.updateDrag(self.dragXstart, self.dragYstart, self.dragXstart, self.dragYstart) self.mouseActionType = Map.PlaceBlockAction #TODO cleanup #print(QMouseEvent.pos()) elif self.mouseActionType == Map.PlaceRobotAction: self.robot = Robot(x, y, 0) self.setStatsWidget() def mouseMoveEvent(self, QMouseEvent): x = QMouseEvent.x() y = QMouseEvent.y() if self.mouseActionType == Map.PlaceBlockAction: self.dragXend = x self.dragYend = y self.dragObject.updateDrag(self.dragXstart, self.dragYstart, self.dragXend, self.dragYend) #TODO cleanup #print(QMouseEvent.pos()) self.repaint() elif self.mouseActionType == Map.PlaceRobotAction: ab = x - self.robot.posX mb = math.sqrt(math.pow(x - self.robot.posX, 2) + math.pow(y - self.robot.posY, 2)) if mb == 0: newTheta = 0 else: newTheta = math.acos(ab / mb) if y < self.robot.posY: newTheta = math.pi - newTheta + math.pi print('theta: %f' % newTheta) self.robot.setOrientation(newTheta) if self.target is not None: # I am computing the angle relative to Ox ax. x = self.target.x - self.robot.posX y = self.target.y - self.robot.posY ab = x mb = math.sqrt(x * x + y * y) if mb == 0: theta = 0 else: theta = math.acos(ab / mb) if self.target.y < self.robot.posY: theta = math.pi - theta + math.pi theta = theta - newTheta if theta < 0: theta = theta + 2 * math.pi self.robot.setTargetDirection(theta) self.repaint() def mouseReleaseEvent(self, QMouseEvent): x = QMouseEvent.x() y = QMouseEvent.y() if self.mouseActionType == Map.PlaceRobotAction: self.mouseActionType = Map.NoAction self.simStats.btPlaceRobot.setEnabled(False) ab = x - self.robot.posX mb = math.sqrt(math.pow(x - self.robot.posX, 2) + math.pow(y - self.robot.posY, 2)) if mb == 0: newTheta = 0 else: newTheta = math.acos(ab / mb) if y < self.robot.posY: newTheta = math.pi - newTheta + math.pi self.robot.setOrientation(newTheta) if self.target is not None: # I am computing the angle relative to Ox ax. x = self.target.x - self.robot.posX y = self.target.y - self.robot.posY ab = x mb = math.sqrt(x * x + y * y) if mb == 0: theta = 0 else: theta = math.acos(ab / mb) if self.target.y < self.robot.posY: theta = math.pi - theta + math.pi theta = theta - newTheta if theta < 0: theta = theta + 2 * math.pi self.robot.setTargetDirection(theta) self.repaint() elif self.mouseActionType == Map.PlaceTargetAction: self.target = Target(x, y) self.mouseActionType = Map.NoAction self.simStats.btPlaceTarget.setEnabled(False) self.simStats.btPlaceRobot.setEnabled(True) self.repaint() elif self.mouseActionType == Map.PlaceBlockAction: self.dragXend = x self.dragYend = y self.dragObject.updateDrag(self.dragXstart, self.dragYstart, self.dragXend, self.dragYend) self.objects.append(self.dragObject) self.dragObject = None self.saveToImage = True self.setChanged(True) self.mouseActionType = Map.NoAction #TODO #print(QMouseEvent.pos()) self.repaint() def paintEvent(self, event): rect = self.contentsRect() if self.saveToImage == True: ImageMap.image = QtGui.QImage(rect.right(), rect.bottom(), QtGui.QImage.Format_RGB32) imagePainter = QtGui.QPainter(ImageMap.image) self.draw(imagePainter) ImageMap.image.save('image.jpg') self.saveToImage = False painter = QtGui.QPainter(self) self.draw(painter) def draw(self, painter): rect = self.contentsRect() painter.setPen(QtGui.QColor(0xff0000)) #TODO #QtCore.qDebug('[sim_map.Map.paintEvent] %d %d %d %d' % (rect.top(), rect.left(), rect.bottom(), rect.right())) painter.fillRect(0, 0, rect.right(), rect.bottom(), QtGui.QColor(0xffffff)) for obj in self.objects: obj.draw(painter) if not self.dragObject is None: self.dragObject.draw(painter) if self.robot is not None and self.saveToImage != True: self.robot.draw(painter) if self.target is not None and self.saveToImage != True: self.target.draw(painter) def keyPressEvent(self, event): key = event.key() if key == QtCore.Qt.Key_S: self.start() return if not self.isStarted: super(Map, self).keyPressEvent(event) return if key == QtCore.Qt.Key_P: self.pause() return if self.isPaused: return elif key == QtCore.Qt.Key_Q: self.robot.increaseLeftMotorSpeed(10) elif key == QtCore.Qt.Key_A: self.robot.increaseLeftMotorSpeed(-10) elif key == QtCore.Qt.Key_E: self.robot.increaseRightMotorSpeed(10) elif key == QtCore.Qt.Key_D: self.robot.increaseRightMotorSpeed(-10) else: super(Map, self).keyPressEvent(event) def timerEvent(self, event): if event.timerId() == self.timer.timerId(): if self.robot is not None: self.robot.move() self.repaint() else: super(Map, self).timerEvent(event) def clearMap(self): self.objects = [] def changed(self): return self.mapChanged def setChanged(self, mapChanged): self.mapChanged = mapChanged self.changedStatus.emit(bool(self.mapChanged)) def getStatsWidget(self): widgets = [] widgets.append(self.simStats) if self.robot is not None: widgets.append(self.robot.getStatsWidget()) return widgets def setStatsWidget(self): widgets = [] widgets.append(self.simStats) if self.robot is not None: widgets.append(self.robot.getStatsWidget()) self.parent.setStatsWidgets(widgets) def placeRobot(self): self.mouseActionType = Map.PlaceRobotAction def placeTarget(self): self.mouseActionType = Map.PlaceTargetAction
def delete_missing_loops(self, DG_loops, K, L, threshold): begs_related_to_loop = dict() begin_loops = dict() end_loops = dict() for eeid1, (long_eid1, long_eid2, busheids, path, visited_vs) in DG_loops.items(): for k, be in self.es.items(): for diag in be.diagonals: rect = diag.rectangle eids = [rect.e1.eid, rect.e2.eid ] if rect.e1.eid not in busheids or rect.e2.eid not in busheids: continue for eid in eids: if eid not in busheids: continue if rect.e1.eid == long_eid1: if rect.e2.eid == long_eid1: begin_loops[long_eid1] = (diag, be) if rect.e2.eid == long_eid2: if rect.e1.eid == long_eid2: end_loops[long_eid1] = (diag, be) if eeid1 not in begs_related_to_loop: begs_related_to_loop[eeid1] = set() begs_related_to_loop[eeid1].add(be) diag_to_add = set() for eid, begs in begs_related_to_loop.items(): (long_eid1, long_eid2, busheids, path, visited_vs) = DG_loops[eid] if len(begs) < 2: continue if eid not in begin_loops or eid not in end_loops: print "not find begin_end" continue begin_diag = begin_loops[eid][0] end_diag = end_loops[eid][0] path.append(end_loops[eid][0].rectangle.e1) first_shift = begin_diag.offseta second_shift = begin_diag.offsetb path_len = 0 for e in path: path_len += e.len rectangles = [] diags = [] pos_first_path = 0 pos_second_path = 0 first_len = first_shift while first_len < path_len and pos_second_path < len(path): ed1 = path[pos_first_path] ed2 = path[pos_second_path] rectangle = Rectangle(ed1,ed2) rectangle.add_diagonal(self.d, self.d + first_shift - second_shift) rect_diag = rectangle.get_closest_diagonal(self.d + first_shift - second_shift) rectangles.append(rectangle) diags.append(rect_diag) if ed2.len - second_shift < ed1.len - first_shift: pos_second_path += 1 first_shift += ed2.len - second_shift first_len += ed2.len - second_shift second_shift = 0 elif ed1.len - first_shift < ed2.len - second_shift: pos_first_path += 1 first_len += ed1.len - first_shift second_shift += ed1.len - first_shift first_shift = 0 else: first_len += ed1.len - first_shift pos_second_path += 1 pos_first_path += 1 first_shift = 0 second_shift = 0 for diag in diags: diag_to_add.add(diag) for bedge in begs: self.__remove_bedge__(bedge) self.__remove_bedge__(bedge.conj) for diag in bedge.diagonals: if diag.rectangle.e1.eid not in busheids or diag.rectangle.e2.eid not in busheids: diag_to_add.add(diag) if begin_diag in bedge.diagonals: for diag in bedge.diagonals: if diag == begin_diag: break diag_to_add.add(diag) elif end_diag in bedge.diagonals: bedge.diagonals.reverse() for diag in bedge.diagonals: if diag == end_diag: break diag_to_add.add(diag) for diag in diag_to_add: self.add_diagonal_and_conj(diag)
from rectangle import Rectangle r2 = Rectangle(12, 6) print("r2.width=", r2.width) print("r2.height=", r2.height) print("r2.get_width=", r2.get_width()) print("r2.get_height=", r2.get_height()) print("r2.get_area=", r2.get_area())
def test_center(self): self.assertEqual(Rectangle(1.5, 2, 5.5, 6).center(), Point(3.5, 4)) self.assertEqual(Rectangle(-1, -1, 1, 1).center(), Point(0, 0)) self.assertEqual(Rectangle(-2, -3, 1, 5).center(), Point(-0.5, 1)) self.assertEqual( Rectangle(-9, 0.5, -5.5, 1).center(), Point(-7.25, 0.75))