def getCircle(self, p1, p2, p3):

        x1 = float(p1[0])
        x2 = float(p2[0])
        x3 = float(p3[0])

        y1 = float(p1[1])
        y2 = float(p2[1])
        y3 = float(p3[1])

        centerEstimate = Point()
        divisor = (2 * (x1 * (y2 - y3) - y1 * (x2 - x3) + x2 * y3 - x3 * y2))
        if divisor == 0:
            return (None, -1)
        # Calculate center of circle using formula.
        centerEstimate.x = (x1 * x1 + y1 * y1) * (y2 - y3) + (x2 * x2 + y2 * y2) * (y3 - y1) + (x3 * x3 + y3 * y3) * (y1 - y2)

        centerEstimate.x = centerEstimate.x / divisor

        centerEstimate.y = (x1 * x1 + y1 * y1) * (x3 - x2) + (x2 * x2 + y2 * y2) * (x1 - x3) + (x3 * x3 + y3 * y3) * (x2 - x1)
        centerEstimate.y = centerEstimate.y / divisor

        radiusEstimate = math.sqrt((centerEstimate.x - x1)**2 + (centerEstimate.y - y1)**2)

        return (centerEstimate, radiusEstimate)
Example #2
0
    def PentagonX(self, marime):
   
        poly = self.CreatePolygon(5, marime)
        marime = int(marime/10)
        polygonC = Polygon()

        polygonC.polygonName = "pentagon"
        polygonC.polygonPerimeter = marime * 5

        Point1 = Point(poly[0][0], poly[0][1])
        Point1.pOwner = polygonC.polygonName

        Point2 = Point(poly[1][0], poly[1][1])
        Point2.pOwner = polygonC.polygonName

        Point3 = Point(poly[2][0], poly[2][1])
        Point3.pOwner = polygonC.polygonName

        Point4 = Point(poly[3][0], poly[3][1])
        Point4.pOwner = polygonC.polygonName

        Point5 = Point(poly[4][0], poly[4][1])
        Point5.pOwner = polygonC.polygonName

        polygonC.points.append(Point1)
        polygonC.points.append(Point2)
        polygonC.points.append(Point3)
        polygonC.points.append(Point4)
        polygonC.points.append(Point5)
        polygonC.points.append(Point1)

        polygonC.polygonArea = int(self.GetArea(polygonC))

        self.itemsInContainer.append(polygonC)
	def CreateAndDrawRandomPoints(self):
		self.DrawLine(self.kMargin,self.b1Margin, lineColor = 'r')
		self.DrawLine(self.kMargin,self.b2Margin, lineColor = 'b')

		currNumPoints = 0
		while currNumPoints <= NumPoints:
			x = random.uniform(XLeftBound,XRightBound)
			y = random.uniform(YDownBound,YUpBound)
			newPoint = Point(x,y,True)
			if self.LabelPositive(x,y):
				newPoint.label = True
				self.samplePoints.append(newPoint)
				currNumPoints += 1
			elif self.LabelNegative(x,y):
				newPoint.label = False
				self.samplePoints.append(newPoint)
				currNumPoints += 1

		plt.figure(1)
		plt.axis([XLeftBound,XRightBound,YDownBound,YUpBound])

		for point in self.samplePoints:
			if point.label == True:
				plt.plot(point.x, point.y, 'ro')
			else:
				plt.plot(point.x, point.y, 'b*')
Example #4
0
def importa():
    print(codis_linia)
    codis_check = []
    for i, v in codis_linia.items():
        if v.get() == 1 or v.get() == True:
            codis_check.append(str(i))
        print("el codi {} te el valor {}".format(i, v.get()))
    Point.importa(name, grup, codis_check)
Example #5
0
def manipulation(pointCloud):
    startSize = len(pointCloud.points)

    # TODO: it would be a lot better to parameterize this in the input file . . . but laziness . . .
    print "\tManipulation: Adding two spheres"
    pointCloud.addPoints( Point.generateSpherePoints( centerPos=Util.vector([0,-0.1,0.9,1]), radius=0.05, lightPos=Util.vector([0,-2,0,1]), albedo=np.array([255,0,0]), numPoints=20000 ) )
    pointCloud.addPoints( Point.generateSpherePoints( centerPos=Util.vector([0.2,0.1,1.15,1]), radius=0.1, lightPos=Util.vector([0,-2,0,1]), albedo=np.array([0,255,0]), numPoints=70000 ) )

    print "\tManipulation added " + str( len(pointCloud.points) - startSize ) + " points"
def find_center(rect):
    """Pure function that returns a Point object representing the center of a 
    rectangle. 
    
    """
    p = Point()
    p.x = rect.corner.x + rect.width / 2.0
    p.y = rect.corner.y + rect.height / 2.0
    return p
class testPoint(unittest.TestCase):
    """
    A test class for the Point class
    """

    def setUp(self):
        """
        set up data used in the tests.
        setUp is called before each test function execution.
        """
        self.point = Point(3, 4)

    def testConstructor(self):
        """constructor test"""
        self.assertEqual("3,4", self.point.display())

    def testMoveBy5and2(self):
        """moveBy test(1)"""
        self.point.moveBy(5, 2)
        self.assertEqual("8,6", self.point.display())
        
    def testMoveBy5and2version2(self):
        """moveBy test(2)"""
        self.point.moveBy(5, 2)
        self.assertEqual("8,7", self.point.display())

    def testDistanceIs5(self):
        """distance test(1)"""
        self.assertTrue(5 == self.point.get_distance())

    def testDistanceIs5_1(self):
        """distance test(2)"""
        self.assertTrue(5.1 == self.point.get_distance())
Example #8
0
	def add_points(self):
		self.statusBar.showMessage(STATUS_TIP+"Running...")
		points_text = self.inputText.toPlainText()  # 获取输入
		source_type = self.sourceType.currentIndex()
		if_mars = 'true' if (source_type == 0) else 'false'

		if points_text == "":  # 使用示例输入
			points_text = SAMPLE_DATA
			self.inputText.setPlainText(points_text)

		points = Point.points_parser(points_text)  # 解析输入
		lats = [p.lat for p in points]
		lons = [p.lon for p in points]

		N = len(lats)  # 共N组经纬度
		G = math.ceil((N - 1) / 9)  # 每10个一组,首尾相接,共G组

		if N == 1:
			G = 1

		for g in range(G):  # 0,1,...,G-1
			index_s = 9 * g
			index_e = 9 * g + 10
			index_e = N if (index_e > N) else index_e
			latsStr = "[" + ",".join(lats[index_s:index_e]) + "]"
			lonsStr = "[" + ",".join(lons[index_s:index_e]) + "]"
			script = "addSimpleMarker(%s,%s,%s);" % (latsStr, lonsStr, if_mars)
			self.run_script(script)
			time.sleep(0.1)  # seconds,延时0.1秒,避免回调函数的执行顺序被打乱

		self.statusBar.showMessage(STATUS_TIP+"Done")
Example #9
0
def init_listpoints(resrequete):
	listpoints = []

	for req in resrequete:
		listpoints.append(Point.point(req[0],req[1],req[2]))

	return listpoints	
Example #10
0
    def SegmentX(self, marime):
        poly = self.CreatePolygon(1, marime)  #create segment
        marime = int(marime/10) #reduce the size  
        polygonC = Polygon() #create an instance of polygon
        polygonC.polygonName = "segment" #set name
        polygonC.polygonArea = 0 #set area
        polygonC.polygonPerimeter = marime * 1 #set perimeter

        Point1 = Point(poly[0][0], poly[0][1]) #setpoint 1
        Point1.pOwner = polygonC.polygonName 

        Point2 = Point(poly[1][0], poly[1][1]) #setpoint 2
        Point2.pOwner = polygonC.polygonName

        polygonC.points.append(Point1) #append point to polygon
        polygonC.points.append(Point2) #append point to polygon
        self.itemsInContainer.append(polygonC) #append polygon to container 
Example #11
0
def myputText(img,text,font,scale,origin,color,thickness,lineType):

    thickness=int(thickness)
    scale=int(scale)
    color=Point.point_int(color)
	font = cv2.FONT_HERSHEY_SIMPLEX
	if linetype == 8 :
        
		cv2.putText(img,text,org,font,scale,color, thickness,lineType=8)
Example #12
0
	def rotate_around (self, point, angle):
		""" Return a point rotated around a point with a given angle"""

		# Create a new point to do our calculations on
		realpoint2 = Point(self.x, self.y)

		# Calculate the cosine and sine to be used in the rotation matrix
		cosangle = cos(angle)
		sinangle = sin(angle)

		# Translate so that point is the new origin
		realpoint2.x -= point.x
		realpoint2.y -= point1.y

		# Multiply by the rotation matrix of the angle
		realpoint2.x = realpoint2.x * cosangle - realpoint2.y * sinangle
		realpoint2.y = realpoint2.x * sinangle + realpoint2.y * cosangle

		return realpoint2
def getLongestDimension(square):
	p1 = Point(square[0][0], square[0][1])
	p2 = Point(square[1][0], square[1][1])
	p3 = Point(square[2][0], square[2][1])
	p4 = Point(square[3][0], square[3][1])
	
	dist = p1.getDistance(p2)
	dist = max(dist, p2.getDistance(p3))
	dist = max(dist, p3.getDistance(p4))
	dist = max(dist, p4.getDistance(p1))
	
	return dist
Example #14
0
def blur(img,kernel_size):
    
    if img is None:
        print 'Error in input Image'
        return 0
    

    kernel_size=Point.point_int(kernel_size)
    
    blurimage = cv2.blur(img,kernel_size)

    return blurimage
Example #15
0
    def TriunghiX(self, marime):
        
        poly = self.CreatePolygon(3, marime)
        marime = int(marime/10)
        polygonC = Polygon()

        polygonC.polygonName = "triunghi"
        polygonC.polygonPerimeter = marime * 3

        Point1 = Point(poly[0][0], poly[0][1])
        Point1.pOwner = polygonC.polygonName

        Point2 = Point(poly[1][0], poly[1][1])
        Point2.pOwner = polygonC.polygonName

        Point3 = Point(poly[2][0], poly[2][1])
        Point3.pOwner = polygonC.polygonName

        polygonC.points.append(Point1)
        polygonC.points.append(Point2)
        polygonC.points.append(Point3)
        polygonC.points.append(Point1)

        polygonC.polygonArea = int(self.GetArea(polygonC))
        self.itemsInContainer.append(polygonC) 
Example #16
0
 def addScaleHandle(self, pos, center, axes=None, item=None, name=None):
     pos = Point(pos)
     center = Point(center)
     info = {'name': name, 'type': 's', 'center': center, 'pos': pos, 'item': item}
     if pos.x() == center.x():
         info['xoff'] = True
     if pos.y() == center.y():
         info['yoff'] = True
     return self.addHandle(info)
Example #17
0
 def updateMatrix(self, propagate=True):
     #print "udpateMatrix:"
     translate = Point(self.range.center())
     if self.range.width() == 0 or self.range.height() == 0:
         return
     scale = Point(self.size().width()/self.range.width(), self.size().height()/self.range.height())
     
     m = QtGui.QTransform()
     
     ## First center the viewport at 0
     self.resetMatrix()
     center = self.viewportTransform().inverted()[0].map(Point(self.width()/2., self.height()/2.))
     if self.yInverted:
         m.translate(center.x(), center.y())
         #print "  inverted; translate", center.x(), center.y()
     else:
         m.translate(center.x(), -center.y())
         #print "  not inverted; translate", center.x(), -center.y()
         
     ## Now scale and translate properly
     if self.aspectLocked:
         scale = Point(scale.min())
     if not self.yInverted:
         scale = scale * Point(1, -1)
     m.scale(scale[0], scale[1])
     #print "  scale:", scale
     st = translate
     m.translate(-st[0], -st[1])
     #print "  translate:", st
     self.setTransform(m)
     self.currentScale = scale
     #self.emit(QtCore.SIGNAL('viewChanged'), self.range)
     self.sigRangeChanged.emit(self, self.range)
     
     if propagate:
         for v in self.lockedViewports:
             v.setXRange(self.range, padding=0)
Example #18
0
def kernel(kernel_type,array_size):

    size=Point.point_int(array_size)
    kernel_type=int(kernel_type)

    if kernel_type==1:
        kernel=cv2.getStructuringElement(cv2.MORPH_RECT,size)

    if kernel_type==2:
        kernel=cv2.getStructuringElement(cv2.MORPH_ELLIPSE,size)

    if kernel_type==3:
        kernel=cv2.getStructuringElement(cv2.MORPH_CROSS,size)

    return kernel
Example #19
0
	def setCircleLocations(self, circles, maxRad):
		openCenters = self.squareCenters[:]
		
		for i in circles[0,:]:
			p = Point(i[0], i[1])
			
			minDist = None
			index = 0
			for cluster in openCenters:
				dist = p.getDistance(cluster.center)
				if(minDist == None):
					minDist = (dist, index)
				else:
					if(dist < minDist[0]):
						minDist = (dist, index)
				index += 1
				
			if(minDist[0] > maxRad):
				continue

			if(openCenters[minDist[1]].centerFound == False):
				openCenters[minDist[1]].center = p

			self.boardState[minDist[1]] = 1
def detectXs(board, lines, maxRad, img):
	centers = board.getOpenCenters()
	centerMap = defaultdict(list)
	
	proximity = maxRad * .75
	
	xLocations = np.zeros(9)

	#create a hashmap of game board squares to all hough lines located within
	#the corresponding square
	for x1,y1,x2,y2 in lines[0]:
		p1 = Point(x1, y1)
		p2 = Point(x2, y2)
	
		for cluster, index in centers:
			
			if(cluster.centerFound == False):
				if(p1.getDistance(cluster.center) <= maxRad or p2.getDistance(cluster.center) <= maxRad):
					centerMap[index].append(LineSegment(p1, p2))
			else:
				if(p1.getDistance(cluster.center) <= proximity or p2.getDistance(cluster.center) <= proximity):
					centerMap[index].append(LineSegment(p1, p2))
					break;
				
	
	minDist = 7 #minimum distance between ends of lines 
	minAngle = 41 #minimum angle between hough lines
	
	for center, lines in centerMap.iteritems():
		
		otherLines = lines[:]
		index = 0
		count = 0
		#check that two hough lines are within mindist and have an angle
		#greater than minAngle if find 2 within the same square, it is an X
		for line in lines:
			del otherLines[index]
			
			for otherLine in otherLines:
				if(line.point1.getDistance(otherLine.point1) <= minDist or
					line.point1.getDistance(otherLine.point2) <= minDist or
					line.point2.getDistance(otherLine.point1) <= minDist or
					line.point2.getDistance(otherLine.point2) <= minDist):
					
					if(line.getAngleDif(otherLine) > minAngle):
						count += 1
						if(count == 2):
							break;
						
			if(count == 2):
				break;
				
		if(count == 2):
			xLocations[center] = 2
			
	return xLocations
def get_driver_points_from_file(abs_file_path):
    path_list = []
    try:
        with open(abs_file_path, 'r') as myfile:
            myfile.readline() # info line

            while True:
                line = myfile.readline()
                if line == "":
                    break
                point = Point.from_file_line(line)
                path_list.append(point)
    except IOError:
        print("Error reading file!")
    return path_list
Example #22
0
	def update(self):
		xavg = 0
		yavg = 0
		for point in self.points:
			xavg += point.x
			yavg += point.y
		
		numPoints = len(self.points)
		if(numPoints == 0):
			return
		else :
			xavg = int(xavg / len(self.points))
			yavg = int(yavg / len(self.points))
			self.center = Point(xavg, yavg)	
			self.centerFound = True
    def find_min_distanse(self):
        px = self._parrel._x
        py = self._parrel._y
        pz = self._parrel._z

        sx = self._spider._x
        sy = self._spider._y
        sz = self._spider._z

        fx = self._fly._x
        fy = self._fly._y
        fz = self._fly._z

        # block 1
        new_spider = Point(sx,sy-sz)
        new_fly = Point(fx,fy+fz)
        min_dist_3d = Point3D(sx, sy-sz, 0).distanse(Point3D(fx, fy+fz, 0))
        min_dist = new_spider.distanse(new_fly)
        self.set_intersection_points(Vector(new_spider, new_fly), Vector(Point(0, 0), Point(px, 0)), Vector(Point(0, py), Point(px, py)), 'z', 0)

        # block 2
        new_spider = Point(sx, sy-pz+sz)
        new_fly = Point(fx,fy+pz-fz)
        temp_min_dist = new_spider.distanse(new_fly)
        if temp_min_dist < min_dist:
            min_dist = temp_min_dist
            self.set_intersection_points(Vector(new_spider, new_fly), Vector(Point(0, 0), Point(px, 0)), Vector(Point(0, py), Point(px, py)), 'z', pz)

        # block 3
        new_spider = Point(sz,sy-sx)
        new_fly = Point(fz,fy+fx)
        temp_min_dist = new_spider.distanse(new_fly)
        if temp_min_dist < min_dist:
            min_dist = temp_min_dist
            self.set_intersection_points(Vector(new_spider, new_fly), Vector(Point(0, 0), Point(pz, 0)), Vector(Point(0, py), Point(pz, py)), 'x', 0)

        # block 4
        new_spider = Point(sz, sy-px+sx)
        new_fly = Point(fz,fy+px-fx)
        temp_min_dist = new_spider.distanse(new_fly)
        if temp_min_dist < min_dist:
            min_dist = temp_min_dist
            self.set_intersection_points(Vector(new_spider, new_fly), Vector(Point(0, 0), Point(pz, 0)), Vector(Point(0, py), Point(pz, py)), 'x', pz)

        return min_dist
Example #24
0
def ORB(image,features,scaleFactor,color,displayimage):
    color=Point.point_int(color)
    features=int(features)
    scaleFactor=int(scaleFactor)
    if image is None:
        print 'Error in input Image'
        return 0,0
    orb = cv2.ORB(features,scaleFactor)
    kp, des = orb.detectAndCompute(image,None)
    img2 = cv2.drawKeypoints(image,kp,color, flags=0)
    if displayimage==1:
        cv2.imshow("image",img2)
        cv2.waitKey(0)
    

    return (kp,des)
Example #25
0
def grabcut(image,mask,bgdModel,fgdModel,rect,iterations,mode):
    iterations=int(iterations)

    rect = Point.point_int(rect)
    if mode ==1:
        cv2.grabCut(image,mask,rect,bgdModel,fgdModel,iterations,cv2.GC_INIT_WITH_RECT)

        mask2 = np.where((mask==2)|(mask==0),0,1).astype('uint8')
        image = image*mask2[:,:,np.newaxis]
    elif mode==2:
        newmask=mask
        mask[newmask == 0] = 0
        mask[newmask == 255] = 1
        mask, bgdModel, fgdModel = cv2.grabCut(image,mask,None,bgdModel,fgdModel,iterations,cv2.GC_INIT_WITH_MASK)
        mask = np.where((mask==2)|(mask==0),0,1).astype('uint8')
        image = image*mask[:,:,np.newaxis]

    else:
        print "Please check the mode"
    return image
Example #26
0
class Rectangle:
	def __init__ (self, point1, point2, angle=0):
		""" Implementation of a rectangle using two points rotated around the first point"""
		self.point1 = Point(point1.x, point1.y)
		self.point2 = Point(point2.x, point2.y)
		self.angle = angle

	def width (self):
		return abs(self.point1.x - self.point2.x)

	def height (self):
		return abs(self.point1.y - self.point2.y)

	def area (self):
		return self.width() * self.height()

	def move (self, dx, dy):
		self.p1.move(dx, dy)
		self.p2.move(dx, dy)

	def get_real_point2 ():
		""" Rotate point2 around point1"""
		return self.point2.rotate_around(self.point1, self.angle)
Example #27
0
def gaussianFilter(image, kernel_type,kernel_size, sigmaX, sigmaY):

    if image is None:
        print 'Error in input Image'
        return 0
    kernel_size=Point.point_int(kernel_size)
    
    if sigmaY==0 and sigmaX==0:
        sigmaX=kernel_size[0]
        sigmaY=kernel_size[1]
        
    kernel=Kernel.kernel(kernel_type,kernel_size)
    sigmaColor = int(sigmaX)
    sigmaSpace = int(sigmaY)

    if kernel_size[0]%2==0 and kernel_size[1]%2==0:
        print 'The kernel size should be odd'
        return 0

    image=cv2.GaussianBlur(image,kernel_size , sigmaColor, sigmaSpace)
    

    return image
Example #28
0
class Cluster:
	def __init__(self, center):
		self.center = center
		self.points = []
		self.centerFound = False
		
	def update(self):
		xavg = 0
		yavg = 0
		for point in self.points:
			xavg += point.x
			yavg += point.y
		
		numPoints = len(self.points)
		if(numPoints == 0):
			return
		else :
			xavg = int(xavg / len(self.points))
			yavg = int(yavg / len(self.points))
			self.center = Point(xavg, yavg)	
			self.centerFound = True
		
	def distance(self, point):
		return self.center.getDistance(point)
Example #29
0
#     return 2*x
#example!!!!
#d( ln(1+exp( w*(3x+9y) ))) /dx=
### (3w * exp(..) )/(1 + exp(...))
#
#

#### print(grad(antigrad,begin,0.002))

begin = np.array([3, 3])
center_0 = (-5, -5, 5)
center_1 = (5, 5, -6)
if __name__ == '__main__':
    #set Coords
    my_points = list()
    for i in Point.generatePoints(100, +1, 3, center_0, dimention=dimention):
        my_points.append(i)
    for i in Point.generatePoints(100, -1, 3, center_1, dimention=dimention):
        my_points.append(i)

    #set func
    def Q(W=np.zeros((dimention, 1))):
        ans = 0
        for point in range(len(my_points)):
            #get exp in func
            scalarMult = 0
            for dim in range(dimention):
                scalarMult += my_points[point].coords[dim] * W[dim]
            scalarMult *= my_points[point].weight

            ans += math.log1p(1 + math.exp(scalarMult))
Example #30
0
    def center(self):
        x_center = self.top_left.xCoord + round((self.bot_right.xCoord - self.top_left.xCoord) / 2)
        y_center = self.top_left.yCoord + round((self.bot_right.yCoord - self.top_left.yCoord) / 2)

        return Point.Point(x_center, y_center)
Example #31
0
 def applyGravity(self, world):
     new_topleft = Point.Point(self.top_left.xCoord, self.top_left.yCoord + Enemy.gravity)
     new_botright = Point.Point(self.bot_right.xCoord, self.bot_right.yCoord + Enemy.gravity)
     if self.__checkMoveValidity(new_topleft, new_botright, world):
         self.top_left = new_topleft
         self.bot_right = new_botright
Example #32
0
import Point
import TheGreedyRobot
import sys

x1 = eval(sys.argv[1])
y1 = eval(sys.argv[2])
x2 = eval(sys.argv[3])
y2 = eval(sys.argv[4])
p1 = Point.Point(x1,y1)
p2 = Point.Point(x2,y2)


print(TheGreedyRobot.Robot(p1,p2))
Example #33
0
def intersectionPoint(ori, dir, dist):
    x = ori.x + dir.x * dist
    y = ori.y + dir.y * dist

    return Point(x, y)
Example #34
0
        if perceptron.guess([pt.x, pt.y, pt.bias]) == pt.label:
            plt.scatter(pt.x, pt.y, c="green", marker='o', s=30)
        else:
            plt.scatter(pt.x, pt.y, c="red", marker='o', s=55)
    plt.show()


if __name__ == "__main__":
    print("The number of points is randomly generated, there are " +
          str(Point.Point.SIZE_POPULATION) + " points.")
    print("The function is randomly generated and its equation is " +
          str(Function.Function.a) + "x " + str(Function.Function.b))
    points = [0] * Point.Point.SIZE_POPULATION

    for i in range(Point.Point.SIZE_POPULATION):
        points[i] = Point.Point()

    perceptron = Perceptron.Perceptron()

    training_is_over = 0

    while training_is_over == 0:
        training_is_over = 1
        for point in points:
            if perceptron.guess([point.x, point.y, point.bias]) != point.label:
                perceptron.adapt_learning_rate()
                training_is_over = 0
                perceptron.train([point.x, point.y, point.bias], point.label)
        if training_is_over == 1:
            print(
                "The perceptron has found a line that describe pretty well the model"
Example #35
0
arch = useArchitectureIdentifiedBy(cmdLineArgs.arch)

equationsSpec = importlib.util.find_spec(cmdLineArgs.equations)
try:
  equations = equationsSpec.loader.load_module()
except:
  raise RuntimeError('Could not find kernels for ' + cmdLineArgs.equations)

adgArgs = inspect.getargspec(equations.ADERDG.__init__).args[1:]
cmdArgsDict = vars(cmdLineArgs)
args = [cmdArgsDict[key] for key in adgArgs]
adg = equations.ADERDG(*args)

g = Generator(arch)

# Equation-specific kernels
adg.addInit(g)
adg.addLocal(g)
adg.addNeighbor(g)
adg.addTime(g)

# Common kernels
DynamicRupture.addKernels(g, adg, cmdLineArgs.matricesDir, cmdLineArgs.dynamicRuptureMethod) 
Plasticity.addKernels(g, adg, cmdLineArgs.matricesDir, cmdLineArgs.PlasticityMethod)
SurfaceDisplacement.addKernels(g, adg)
Point.addKernels(g, adg)

# Generate code
gemmTools = GeneratorCollection([LIBXSMM(arch), PSpaMM(arch)])
g.generate(cmdLineArgs.outputDir, 'seissol', gemmTools)
Example #36
0
class Edge():
    def __init__(self, p0, pf, color):
        self.p0 = p0
        self.pf = pf
        self.color = color

    def x(self):
        return self.pf.x - self.p0.x

    def y(self):
        return self.pf.y - self.p0.y

    def m(self):
        return math.sqrt(self.x() * self.x() + self.y() * self.y())

    def setOrigin(self, o):
        cx = self.x()
        cy = self.y()
        self.p0.x = o.x
        self.p0.y = o.y
        self.pf.x = o.x + cx
        self.pf.y = o.y + cy

    def add(self, b):
        self.pf.x = self.p0.x + self.x() + b.x()
        self.pf.y = self.p0.y + self.y() + b.y()

    def dot(self, b):
        return self.x() * b.x() + self.y() * b.y()

    def det(self, b):
        return self.x() * b.y() - self.y() * b.x()

    def getParametric(self, t):
        return Point(self.p0.x + self.x() * t, self.p0.y + self.y() * t)

    def setM(self, m):
        self.pf = self.getParametric(m / self.m())

    def projOnto(self, b):
        return self.dot(b) / b.m()

    def perpFrom(self, b):
        return self.det(b) / b.m()

    def getProjVec(self, b):

        mSquared = b.x() * b.x() + b.y() * b.y()
        p0 = Point(0.0, 0.0)
        pf = Point(b.x() * self.dot(b) / mSquared,
                   b.y() * self.dot(b) / mSquared)

        return Edge(p0, pf, generateHTMLColor(0, 0, 255))

    def getPerpVec(self, b):

        mSquared = b.x() * b.x() + b.y() * b.y()
        p0 = Point(0.0, 0.0)
        pf = Point(b.y() * self.det(b) / mSquared,
                   -b.x() * self.det(b) / mSquared)

        return Edge(p0, pf, generateHTMLColor(255, 255, 0))

    def fromJSON(self, jsonEdge):
        self.p0 = Point(jsonEdge.p0.x, jsonEdge.p0.y)
        self.pf = Point(jsonEdge.pf.x, jsonEdge.pf.y)
        self.color = jsonEdge.color

    def toJSON(self):
        return ({
            "p0": self.p0.toJSON(),
            "pf": self.pf.toJSON(),
            "color": self.color
        })
Example #37
0
 def takeAction(self, data):
     return [Action(Point(0, 0), 0), Action(Point(0, 0), 0)]
Example #38
0
adg.addInit(g)
adg.addLocal(g)
adg.addNeighbor(g)
adg.addTime(g)
adg.add_include_tensors(include_tensors)

# Common kernels
include_tensors |= DynamicRupture.addKernels(
    NamespacedGenerator(g, namespace="dynamicRupture"), adg,
    cmdLineArgs.matricesDir, cmdLineArgs.dynamicRuptureMethod)
Plasticity.addKernels(g, adg, cmdLineArgs.matricesDir,
                      cmdLineArgs.PlasticityMethod)
NodalBoundaryConditions.addKernels(g, adg, include_tensors,
                                   cmdLineArgs.matricesDir, cmdLineArgs)
SurfaceDisplacement.addKernels(g, adg)
Point.addKernels(g, adg)

# pick up the user's defined gemm tools
gemm_tool_list = cmdLineArgs.gemm_tools.replace(" ", "").split(",")
generators = []

for tool in gemm_tool_list:
    if hasattr(gemm_configuration, tool):
        specific_gemm_class = getattr(gemm_configuration, tool)
        generators.append(specific_gemm_class(arch))
    else:
        print("YATETO::ERROR: unknown \"{}\" GEMM tool. "
              "Please, refer to the documentation".format(tool))
        sys.exit("failure")

# Generate code
Example #39
0
 def __init__(self, color):
     self.color = color
     self.coord = Point(-1, -1)
Example #40
0
def evenr_offset_to_pixel(direction):
    x = size * sqrt(3) * (direction.q - 0.5 * (direction.r&1))
    y = size * 3/2 * direction.r
    return Point(x, y)
Example #41
0
 def __init__(self, p=Point()):
     self.point = p
     self.edges = np.empty(0, Edge)
Example #42
0
 def fromJSON(self, jsonEdge):
     self.p0 = Point(jsonEdge.p0.x, jsonEdge.p0.y)
     self.pf = Point(jsonEdge.pf.x, jsonEdge.pf.y)
     self.color = jsonEdge.color
    def process_score_image(self):
        """

        :rtype: object
        """
        bms_factory = BMSFactoryTube.BMSFactory()

        notes = [[], [], [], [], [], [], []]  # レーン別のノーツの情報
        is_usable = [True, True]  # 長押しをいくつ追跡しているかをカウントする。

        img = cv2.imread(self.FILE_NAME)

        for i in range(0, self.LANE_NUM):
            self.states.append(PixelState(StateType.NONE, 0))

        #
        # ------- 画像解析開始 --------
        #

        for bar in range(1, self.BAR_NUM + 1):  # 小節に関するループ

            column_index = int((bar - 1) / self.BAR_NUM_PER_COLUMN)  # 何列目か

            for pixel_offset in range(0, self.BAR_LENGTH):  # ピクセル単位のループ(縦)

                # if bar == 11:
                #     tstr = "追跡状況:"
                #     for i in range(0, self.LANE_NUM):
                #         tstr += str(self.states[i].following_long_num) + ", "
                #     print(tstr)

                for lane_index in range(0, self.LANE_NUM):  # レーンに関するループ

                    offset_x = lane_index * self.LANE_WIDTH + column_index * self.COLUMN_WIDTH
                    offset_y = -(
                        (bar - 1) % self.BAR_NUM_PER_COLUMN) * self.BAR_LENGTH

                    lane_start_point = Point.sum(self.BASIC_START_POINT,
                                                 Point(offset_x, offset_y))
                    # print("bar, lane_index, startpoint")
                    # if bar == 1:
                    #     print(str(bar) + " " + str(lane_index) + "(" + str(lane_start_point.x) + ", " + str(lane_start_point.y) + ")")

                    bgr = img[int(lane_start_point.y) - pixel_offset,
                              int(lane_start_point.x)]
                    b = bgr[0]
                    g = bgr[1]
                    r = bgr[2]

                    # 追跡用に左右の色を取得(6が限度。7以上ずらすと真っ直ぐが追えなくなる)
                    left_bgr = img[int(lane_start_point.y) - pixel_offset,
                                   int(lane_start_point.x -
                                       self.LANE_WIDTH * 0.3)]
                    lb = left_bgr[0]
                    lg = left_bgr[1]
                    lr = left_bgr[2]

                    right_bgr = img[int(lane_start_point.y) - pixel_offset,
                                    int(lane_start_point.x +
                                        self.LANE_WIDTH * 0.3)]
                    rb = right_bgr[0]
                    rg = right_bgr[1]
                    rr = right_bgr[2]

                    lane_state = self.states[lane_index]

                    # 各ノーツを識別する
                    if lane_state.state == StateType.NONE:

                        if Pixel.is_tap_frame(b, g, r):
                            lane_state.state = StateType.IN_TAP
                            lane_state.from_pixel_index = pixel_offset + (
                                bar - 1) * self.BAR_LENGTH

                        elif Pixel.is_flick_frame(b, g, r):
                            lane_state.state = StateType.IN_PINK
                            lane_state.from_pixel_index = pixel_offset + (
                                bar - 1) * self.BAR_LENGTH

                        elif Pixel.is_green(b, g, r):
                            lane_state.state = StateType.IN_GREEN
                            lane_state.from_pixel_index = pixel_offset + (
                                bar - 1) * self.BAR_LENGTH

                        elif Pixel.is_middle_frame(b, g, r):
                            lane_state.state = StateType.IN_MIDDLE
                            lane_state.from_pixel_index = pixel_offset + (
                                bar - 1) * self.BAR_LENGTH

                        elif Pixel.is_yellow_frame(b, g, r):
                            lane_state.state = StateType.IN_YELLOW
                            lane_state.from_pixel_index = pixel_offset + (
                                bar - 1) * self.BAR_LENGTH

                    elif lane_state.state == StateType.IN_PINK:

                        # 一番下の次のピクセルの横の色から終点であるかを判断
                        is_flick_end = False
                        for pixel_x in range(
                                int(lane_start_point.x - self.LANE_WIDTH / 2),
                                int(lane_start_point.x + self.LANE_WIDTH / 2)):

                            bgr_t = img[int(lane_start_point.y) - pixel_offset,
                                        int(pixel_x)]
                            b_t = bgr_t[0]
                            g_t = bgr_t[1]
                            r_t = bgr_t[2]
                            bgr_t2 = img[int(lane_start_point.y) -
                                         pixel_offset - 2,
                                         int(pixel_x)]  # 鬼畜スライド用
                            b_t2 = bgr_t2[0]
                            g_t2 = bgr_t2[1]
                            r_t2 = bgr_t2[2]

                            if Pixel.is_connecting_green(
                                    b_t, g_t,
                                    r_t) or Pixel.is_connecting_green(
                                        b_t2, g_t2, r_t2):
                                is_flick_end = True
                                break

                        if is_flick_end:
                            lane_state.state = StateType.IN_FLICK_END
                        else:
                            lane_state.state = StateType.IN_FLICK

                    elif lane_state.state == StateType.IN_GREEN:

                        is_tap_end = False
                        for pixel_x in range(
                                int(lane_start_point.x - self.LANE_WIDTH / 2),
                                int(lane_start_point.x + self.LANE_WIDTH / 2)):

                            bgr_t = img[int(lane_start_point.y) - pixel_offset,
                                        int(pixel_x)]
                            b_t = bgr_t[0]
                            g_t = bgr_t[1]
                            r_t = bgr_t[2]
                            bgr_t2 = img[int(lane_start_point.y) -
                                         pixel_offset - 2,
                                         int(pixel_x)]  # 鬼畜スライド用
                            b_t2 = bgr_t2[0]
                            g_t2 = bgr_t2[1]
                            r_t2 = bgr_t2[2]
                            if Pixel.is_connecting_green(
                                    b_t, g_t,
                                    r_t) or Pixel.is_connecting_green(
                                        b_t2, g_t2, r_t2):
                                is_tap_end = True
                                break

                        if is_tap_end:
                            lane_state.state = StateType.IN_TAP_END
                        else:
                            lane_state.state = StateType.IN_START
                            if is_usable[0]:
                                lane_state.following_long_num = 1
                                is_usable[0] = False
                            elif is_usable[1]:
                                lane_state.following_long_num = 2
                                is_usable[1] = False
                            else:
                                print("セマフォが0です")
                                tstr = "追跡状況:"
                                for i in range(0, self.LANE_NUM):
                                    tstr += str(self.states[i].
                                                following_long_num) + ", "
                                print(tstr)
                                print("座標(y,x):" + str(
                                    int(lane_start_point.y) - pixel_offset) +
                                      ", " + str(lane_start_point.x))
                                print("レーン, 小節:" + str(lane_index + 1) + ", " +
                                      str(bar))
                                sys.exit("エラー終了")

                    elif lane_state.state == StateType.IN_TAP:

                        if Pixel.is_tap_frame(b, g, r):
                            note_pixel_index = (
                                lane_state.from_pixel_index + pixel_offset +
                                (bar - 1) * self.BAR_LENGTH) / 2
                            pos = note_pixel_index * 4 / self.BAR_LENGTH
                            # pixel_from_this_bar =
                            # pos_from_this_bar: float = pixel_from_this_bar / cls.BAR_LENGTH * 4.0
                            # pos = pos_from_this_bar + (bar - 1) * 4.0
                            notes[lane_index].append(
                                Note(NoteType.TAP, pos, lane_index))
                            # if bar == 6:
                            #     print("Tap@レーン, 小節:" + str(lane_index + 1) + ", " + str(bar))
                            #     print(pos)

                            lane_state.state = StateType.NONE
                            lane_state.from_pixel_index = pixel_offset

                    elif lane_state.state == StateType.IN_START:

                        if Pixel.is_green(b, g, r):
                            # pixel_from_this_bar = (lane_state.from_pixel_index + pixel_offset + (
                            #             bar - 1) * cls.BAR_LENGTH) / 2
                            # pos_from_this_bar: float = pixel_from_this_bar / cls.BAR_LENGTH * 4.0
                            # pos = pos_from_this_bar + (bar - 1) * 4.0
                            note_pixel_index = (
                                lane_state.from_pixel_index + pixel_offset +
                                (bar - 1) * self.BAR_LENGTH) / 2
                            pos = note_pixel_index * 4 / self.BAR_LENGTH

                            if lane_state.following_long_num == 1:
                                notes[lane_index].append(
                                    Note(NoteType.START, pos, lane_index))
                            elif lane_state.following_long_num == 2:
                                notes[lane_index].append(
                                    Note(NoteType.START2, pos, lane_index))
                            else:
                                print("following_long_numが不正です.@start:" +
                                      str(lane_state.following_long_num))
                                print("座標(y,x):" + str(
                                    int(lane_start_point.y) - pixel_offset) +
                                      ", " + str(lane_start_point.x))
                                print("レーン, 小節:" + str(lane_index + 1) + ", " +
                                      str(bar))
                                sys.exit("エラー終了")

                            # print("Start@レーン, 小節:" + str(lane_index + 1) + ", " + str(bar))
                            lane_state.state = StateType.NONE
                            lane_state.from_pixel_index = pixel_offset

                    elif lane_state.state == StateType.IN_TAP_END:

                        if Pixel.is_green(b, g, r):
                            # pixel_from_this_bar = (lane_state.from_pixel_index + pixel_offset + (
                            #         bar - 1) * cls.BAR_LENGTH) / 2
                            # pos_from_this_bar: float = pixel_from_this_bar / cls.BAR_LENGTH * 4.0
                            # pos = pos_from_this_bar + (bar - 1) * 4.0
                            note_pixel_index = (
                                lane_state.from_pixel_index + pixel_offset +
                                (bar - 1) * self.BAR_LENGTH) / 2
                            pos = note_pixel_index * 4 / self.BAR_LENGTH

                            if lane_state.following_long_num == 1:
                                notes[lane_index].append(
                                    Note(NoteType.TAP_END, pos, lane_index))
                                is_usable[0] = True
                            elif lane_state.following_long_num == 2:
                                notes[lane_index].append(
                                    Note(NoteType.TAP_END2, pos, lane_index))
                                is_usable[1] = True
                            else:
                                print("following_long_numが不正です.@tapEnd:" +
                                      str(lane_state.following_long_num))
                                print("座標(y,x):" + str(
                                    int(lane_start_point.y) - pixel_offset) +
                                      ", " + str(lane_start_point.x))
                                print("レーン, 小節:" + str(lane_index + 1) + ", " +
                                      str(bar))
                                sys.exit("エラー終了")

                            lane_state.state = StateType.NONE
                            lane_state.from_pixel_index = pixel_offset
                            lane_state.following_long_num = 0
                            lane_state.followable_direction = FollowableDirection.BOTH

                    elif lane_state.state == StateType.IN_FLICK:

                        if Pixel.is_flick_frame(b, g, r):
                            # pixel_from_this_bar = (lane_state.from_pixel_index + pixel_offset + (
                            #         bar - 1) * cls.BAR_LENGTH) / 2
                            # pos_from_this_bar: float = pixel_from_this_bar / cls.BAR_LENGTH * 4.0
                            # pos = pos_from_this_bar + (bar - 1) * 4.0
                            note_pixel_index = (
                                lane_state.from_pixel_index + pixel_offset +
                                (bar - 1) * self.BAR_LENGTH) / 2
                            pos = note_pixel_index * 4 / self.BAR_LENGTH
                            notes[lane_index].append(
                                Note(NoteType.FLICK, pos, lane_index))

                            # print("Flick@レーン, 小節:" + str(lane_index + 1) + ", " + str(bar))
                            lane_state.state = StateType.NONE
                            lane_state.from_pixel_index = pixel_offset

                    elif lane_state.state == StateType.IN_FLICK_END:

                        if Pixel.is_flick_frame(b, g, r):
                            # pixel_from_this_bar = (lane_state.from_pixel_index + pixel_offset + (
                            #         bar - 1) * cls.BAR_LENGTH) / 2
                            # pos_from_this_bar: float = pixel_from_this_bar / cls.BAR_LENGTH * 4.0
                            # pos = pos_from_this_bar + (bar - 1) * 4.0
                            note_pixel_index = (
                                lane_state.from_pixel_index + pixel_offset +
                                (bar - 1) * self.BAR_LENGTH) / 2
                            pos = note_pixel_index * 4 / self.BAR_LENGTH

                            if lane_state.following_long_num == 1:
                                notes[lane_index].append(
                                    Note(NoteType.FLICK_END, pos, lane_index))
                                is_usable[0] = True
                            elif lane_state.following_long_num == 2:
                                notes[lane_index].append(
                                    Note(NoteType.FLICK_END2, pos, lane_index))
                                is_usable[1] = True
                            else:
                                print("following_long_numが不正です.@flickEnd:" +
                                      str(lane_state.following_long_num))
                                print("座標(y,x):" + str(
                                    int(lane_start_point.y) - pixel_offset) +
                                      ", " + str(lane_start_point.x))
                                print("レーン, 小節:" + str(lane_index + 1) + ", " +
                                      str(bar))
                                sys.exit("エラー終了")

                            # print("FlickEnd@レーン, 小節:" + str(lane_index + 1) + ", " + str(bar))
                            lane_state.state = StateType.NONE
                            lane_state.from_pixel_index = pixel_offset
                            lane_state.following_long_num = 0
                            lane_state.followable_direction = FollowableDirection.BOTH

                    elif lane_state.state == StateType.IN_MIDDLE:

                        if Pixel.is_middle_frame(b, g, r):

                            note_pixel_index = (
                                lane_state.from_pixel_index + pixel_offset +
                                (bar - 1) * self.BAR_LENGTH) / 2
                            pos = note_pixel_index * 4 / self.BAR_LENGTH

                            if lane_state.following_long_num == 1:
                                notes[lane_index].append(
                                    Note(NoteType.MIDDLE, pos, lane_index))
                            elif lane_state.following_long_num == 2:
                                notes[lane_index].append(
                                    Note(NoteType.MIDDLE2, pos, lane_index))
                            else:
                                # 画像が間違っているので緊急措置
                                # if is_usable[0]:
                                #     lane_state.following_long_num = 1
                                #     is_usable[0] = False
                                #     notes[lane_index].append(Note(NoteType.START, pos, lane_index))
                                # elif is_usable[1]:
                                #     lane_state.following_long_num = 2
                                #     is_usable[1] = False
                                #     notes[lane_index].append(Note(NoteType.START2, pos, lane_index))
                                # else:
                                #     print("セマフォが0です")
                                #     tstr = "追跡状況:"
                                #     for i in range(0, self.LANE_NUM):
                                #         tstr += str(self.states[i].following_long_num) + ", "
                                #     print(tstr)
                                #     print("座標(y,x):" + str(int(lane_start_point.y) - pixel_offset) + ", " + str(
                                #         lane_start_point.x))
                                #     print("レーン, 小節:" + str(lane_index + 1) + ", " + str(bar))
                                #     sys.exit("エラー終了")

                                # 緊急措置による退避
                                print("following_long_numが不正です.@middle:" +
                                      str(lane_state.following_long_num))
                                print("座標(y,x):" + str(
                                    int(lane_start_point.y) - pixel_offset) +
                                      ", " + str(lane_start_point.x))
                                print("レーン, 小節:" + str(lane_index + 1) + ", " +
                                      str(bar))

                                tstr = "following_long_num: "
                                for t in self.states:
                                    tstr += str(t.following_long_num) + ", "
                                print(tstr)
                                sys.exit("エラー終了")
                                print("@lane_index:" + str(lane_index))

                            # print("Middle@レーン, 小節:" + str(lane_index + 1) + ", " + str(bar))
                            lane_state.state = StateType.NONE
                            lane_state.from_pixel_index = pixel_offset
                            lane_state.followable_direction = FollowableDirection.BOTH

                    elif lane_state.state == StateType.IN_YELLOW:
                        if Pixel.is_yellow_frame(b, g, r):
                            note_pixel_index = (
                                lane_state.from_pixel_index + pixel_offset +
                                (bar - 1) * self.BAR_LENGTH) / 2
                            pos = note_pixel_index * 4 / self.BAR_LENGTH

                            is_tap = True
                            for pixel_x in range(
                                    int(lane_start_point.x -
                                        self.LANE_WIDTH / 2),
                                    int(lane_start_point.x +
                                        self.LANE_WIDTH / 2)):

                                bgr_t = img[int(lane_start_point.y) -
                                            pixel_offset,
                                            int(pixel_x)]
                                b_t = bgr_t[0]
                                g_t = bgr_t[1]
                                r_t = bgr_t[2]
                                if Pixel.is_connecting_green(b_t, g_t, r_t):
                                    is_tap = False

                            if is_tap:
                                notes[lane_index].append(
                                    Note(NoteType.TAP, pos, lane_index))
                            else:
                                if is_usable[1]:
                                    notes[lane_index].append(
                                        Note(NoteType.START2, pos, lane_index))
                                    lane_state.following_long_num = 2
                                    is_usable[1] = False

                                elif is_usable[0]:
                                    notes[lane_index].append(
                                        Note(NoteType.START, pos, lane_index))
                                    lane_state.following_long_num = 1
                                    is_usable[0] = False

                                else:
                                    print("セマフォが0です")
                                    tstr = "追跡状況:"
                                    for i in range(0, self.LANE_NUM):
                                        tstr += str(states[i].
                                                    following_long_num) + ", "
                                    print(tstr)
                                    print("座標(y,x):" + str(
                                        int(lane_start_point.y) -
                                        pixel_offset) + ", " +
                                          str(lane_start_point.x))
                                    print("レーン, 小節:" + str(lane_index + 1) +
                                          ", " + str(bar))
                                    sys.exit("エラー終了")

                            # pixel_from_this_bar =
                            # pos_from_this_bar: float = pixel_from_this_bar / cls.BAR_LENGTH * 4.0
                            # pos = pos_from_this_bar + (bar - 1) * 4.0

                            lane_state.state = StateType.NONE
                            lane_state.from_pixel_index = pixel_offset

                    # 辿っている長押しのレーン変更を識別する
                    if lane_state.will_stop_following and lane_state.state == StateType.NONE:
                        lane_state.following_long_num = 0
                        lane_state.will_stop_following = False

                    if lane_state.following_long_num > 0 and not lane_state.will_stop_following:
                        if lane_state.state == StateType.NONE or lane_state.state == StateType.IN_START:
                            if lane_state.left_state == SubStateType.FOLLOWING_LONG:
                                if not Pixel.is_following_color(lb, lg, lr):
                                    if lane_state.followable_direction != FollowableDirection.TO_LEFT:
                                        if lane_state.right_state == SubStateType.FOLLOWING_LONG and not Pixel.is_following_color(
                                                rb, rg, rr):

                                            # 完全に真横からスタートする場合あり。ひとつ戻ってノーツの真横の色を見る
                                            bgr_br = img[
                                                int(lane_start_point.y) -
                                                pixel_offset + 1,
                                                int(lane_start_point.x) + 7]
                                            b_br = bgr_br[0]
                                            g_br = bgr_br[1]
                                            r_br = bgr_br[2]
                                            bgr_bl = img[
                                                int(lane_start_point.y) -
                                                pixel_offset + 1,
                                                int(lane_start_point.x) - 7]
                                            b_bl = bgr_bl[0]
                                            g_bl = bgr_bl[1]
                                            r_bl = bgr_bl[2]

                                            if Pixel.is_following_color(
                                                    b_br, g_br, r_br
                                            ) and Pixel.is_following_color(
                                                    b_bl, g_bl, r_bl):
                                                print("両方!?")
                                                print("座標(y,x):" + str(
                                                    int(lane_start_point.y) -
                                                    pixel_offset) + ", " +
                                                      str(lane_start_point.x))
                                                print("レーン: " +
                                                      str(lane_index + 1) +
                                                      ", 小節: " + str(bar))
                                                sys.exit("エラー終了")

                                            elif Pixel.is_following_color(
                                                    b_br, g_br, r_br):

                                                if not self.go_to_right(
                                                        lane_index):
                                                    tstr = "追跡状況:"
                                                    for i in range(
                                                            0, self.LANE_NUM):
                                                        tstr += str(
                                                            self.states[i].
                                                            following_long_num
                                                        ) + ", "
                                                    print(tstr)
                                                    print("座標(y,x):" + str(
                                                        int(lane_start_point.y)
                                                        - pixel_offset) +
                                                          ", " +
                                                          str(lane_start_point.
                                                              x))
                                                    print("レーン, 小節:" +
                                                          str(lane_index + 1) +
                                                          ", " + str(bar))
                                                    sys.exit("エラー終了")

                                            elif Pixel.is_following_color(
                                                    b_bl, g_bl, r_bl):

                                                if not self.go_to_left(
                                                        lane_index):
                                                    tstr = "追跡状況:"
                                                    for i in range(
                                                            0, self.LANE_NUM):
                                                        tstr += str(
                                                            self.states[i].
                                                            following_long_num
                                                        ) + ", "
                                                    print(tstr)
                                                    print("座標(y,x):" + str(
                                                        int(lane_start_point.y)
                                                        - pixel_offset) +
                                                          ", " +
                                                          str(lane_start_point.
                                                              x))
                                                    print("レーン, 小節:" +
                                                          str(lane_index + 1) +
                                                          ", " + str(bar))
                                                    sys.exit("エラー終了")

                                            else:
                                                print("左右ともに見つからない!?")
                                                print("座標(y,x):" + str(
                                                    int(lane_start_point.y) -
                                                    pixel_offset) + ", " +
                                                      str(lane_start_point.x))
                                                print("レーン: " +
                                                      str(lane_index + 1) +
                                                      ", 小節: " + str(bar))
                                                sys.exit("エラー終了")

                                        else:
                                            # print("@laneIndex:" + str(lane_index) + ", @bar:" + str(bar))
                                            # print("@x:" + str(lane_start_point.x) + ", @y:" + str(lane_start_point.y - pixel_offset))
                                            # print("state:" + str(lane_state.state))
                                            # if bar == 6:
                                            #     print("右(" + str(lane_index+1) + "→" + str(lane_index+2))
                                            # print("座標(y,x):" + str(int(lane_start_point.y) - pixel_offset) + ", " + str(
                                            #     lane_start_point.x))
                                            if not self.go_to_right(
                                                    lane_index):
                                                tstr = "追跡状況:"
                                                for i in range(
                                                        0, self.LANE_NUM):
                                                    tstr += str(
                                                        self.states[i].
                                                        following_long_num
                                                    ) + ", "
                                                print(tstr)
                                                print("座標(y,x):" + str(
                                                    int(lane_start_point.y) -
                                                    pixel_offset) + ", " +
                                                      str(lane_start_point.x))
                                                print("レーン, 小節:" +
                                                      str(lane_index + 1) +
                                                      ", " + str(bar))
                                                sys.exit("エラー終了")

                            if lane_state.right_state == SubStateType.FOLLOWING_LONG:
                                if not Pixel.is_following_color(rb, rg, rr):
                                    if lane_state.followable_direction != FollowableDirection.TO_RIGHT:
                                        # print(lane_index)
                                        # if bar == 6:
                                        #     print("左(" + str(lane_index+1) + "→" + str(lane_index))
                                        #     print(lane_state.followable_direction)
                                        #     print("座標(y,x):" + str(int(lane_start_point.y) - pixel_offset) + ", " + str(
                                        #     lane_start_point.x))
                                        if not self.go_to_left(lane_index):
                                            tstr = "追跡状況:"
                                            for i in range(0, self.LANE_NUM):
                                                tstr += str(
                                                    self.states[i].
                                                    following_long_num) + ", "
                                            print(tstr)
                                            print("座標(y,x):" + str(
                                                int(lane_start_point.y) -
                                                pixel_offset) + ", " +
                                                  str(lane_start_point.x))
                                            print("レーン, 小節:" +
                                                  str(lane_index + 1) + ", " +
                                                  str(bar))
                                            sys.exit("エラー終了")

                    if Pixel.is_following_color(lb, lg, lr):
                        lane_state.left_state = SubStateType.FOLLOWING_LONG
                    else:
                        lane_state.left_state = SubStateType.NONE

                    if Pixel.is_following_color(rb, rg, rr):
                        lane_state.right_state = SubStateType.FOLLOWING_LONG
                    else:
                        lane_state.right_state = SubStateType.NONE

        #
        # ------- ファイル作成 -------
        #

        bms_factory.write_main(notes)
 def __init__(self, point1=Pt.Point(0, 0), point2=Pt.Point(0, 0)):
     self.name = ""
     self.point1 = point1
     self.point2 = point2
Example #45
0
 def getParametric(self, t):
     return Point(self.p0.x + self.x() * t, self.p0.y + self.y() * t)
Example #46
0
def calc_leg(id, coord):
	'''
		Normalize the position of each leg arround the robot
		to match with the center of the robot.
		Thanks to it, we only put a position from center and
		a leg identifier to move a leg without take in count
		his own referential.
	'''
	new = Point()	
	if id==1:
		new.x = -coord.y - 102
		new.y = coord.x
	elif id==2:
		new = coord.copy()
		new.y = new.y + 24
		new.x = new.x - 74
	elif id==3:
		new = coord.copy()
		new.y = new.y - 24
		new.x = new.x - 74
	elif id==4:
		new.x = coord.y - 102
		new.y = -coord.x
	elif id==5:
		new = -coord.copy()
		new.y = new.y + 24
		new.x = new.x - 74
	elif id==6:
		new = -coord.copy()
		new.y = new.y - 24
		new.x = new.x - 74
	new.z = coord.z
	return new
Example #47
0
    def __init__(self, maille):
        """ Initialisation d'une liste de points à partir d'une maille
            une liste de points contient :
            - n points en hauteur
            - m points en largeur
            n et m sont calculés à partir de la maille en entrée pour plus de clarté
            si des points sont manquants aux extremités, on ajoute des points "fantômes"
            de coordonnées (-1,-1,0), il faudra les considérer dans les fonctions de
            plus haut niveau
        """
        self.n = maille.n + 1  # n le nombre de points en hauteur
        self.mailleN = maille.n
        self.m = maille.m * 2 + 2  # m le nombre de points en largeur
        self.mailleM = maille.m

        # initialisation de la liste de points à partir de la maille :
        liste = []
        nb_pts = 0
        pair = (maille.n % 2) == 0
        fantome = Point(-1, -1, 0)

        # on trace les deux premières colonnes :
        for i in range(0, maille.n, 2):
            liste.append(maille.get(i, 0).so)
            liste.append(maille.get(i, 0).no)
            nb_pts = nb_pts + 2

        # ajout d'un point encore au dessus
        if pair:
            liste.append(fantome)
            nb_pts = nb_pts + 1
        #else :
        # rien car les papillons sont déjà ajoutés en entier

        # on compte le point de la première ligne :
        for i in range(0, maille.n, 2):
            liste.append(maille.get(i, 0).sm)
            liste.append(maille.get(i, 0).nm)
            nb_pts = nb_pts + 2

        if pair:
            liste.append(maille.get(maille.n - 1, 0).no)
            nb_pts = nb_pts + 1

        # on trace le corps, à chaque coup on a deux colonnes créées :
        j = 0
        while j < maille.m:
            for i in range(0, maille.n, 2):
                liste.append(maille.get(i, j).se)
                liste.append(maille.get(i, j).ne)
                nb_pts = nb_pts + 2

            # ajout d'un point encore au dessus
            if pair:
                liste.append(maille.get(maille.n - 1, j).nm)
                nb_pts = nb_pts + 1

            # ajout du point de la première ligne éventuellemnt
            if maille.m > j + 1:
                liste.append(maille.get(0, j + 1).sm)
                nb_pts = nb_pts + 1
            else:
                liste.append(fantome)
                nb_pts = nb_pts + 1

            for i in range(1, maille.n, 2):
                liste.append(maille.get(i, j).se)
                liste.append(maille.get(i, j).ne)
                nb_pts = nb_pts + 2

            # Ajout du point en bas à droite de la grille
            if not pair:
                if maille.m > j + 1:
                    liste.append(maille.get(maille.n - 1, j + 1).nm)
                    nb_pts = nb_pts + 1
                else:
                    liste.append(fantome)
                    nb_pts = nb_pts + 1

            j = j + 1

            if not (j >= maille.m):
                for i in range(0, maille.n, 2):
                    liste.append(maille.get(i, j).se)
                    liste.append(maille.get(i, j).ne)
                    nb_pts = nb_pts + 2

                # Ajout éventuel d'un point en haut de la grille
                if pair:
                    liste.append(maille.get(maille.n - 1, j).nm)
                    nb_pts = nb_pts + 1
                # ajout du point de la première ligne
                if maille.m > j + 1:
                    liste.append(maille.get(0, j + 1).sm)
                    nb_pts = nb_pts + 1
                else:
                    liste.append(fantome)
                    nb_pts = nb_pts + 1

                for i in range(1, maille.n, 2):
                    liste.append(maille.get(i, j).se)
                    liste.append(maille.get(i, j).ne)
                    nb_pts = nb_pts + 2

                if not pair:
                    if maille.m > j + 1:
                        liste.append(maille.get(maille.n - 1, j + 1).nm)
                        nb_pts = nb_pts + 1
                    else:
                        liste.append(fantome)
                        nb_pts = nb_pts + 1

                j = j + 1

        if not pair:
            liste.append(fantome)

        self.pts = liste
Example #48
0
 def __init__(self, _id, track_data, slot):
     self.id = _id
     self.point_list = [Point(data[0], data[1]) for data in track_data]
     self.time_slot = slot
     self.feasible_slow_locations = []
     self.feasible_super_locations = []
Example #49
0
import Point



class Rectangle:
    """Rectangle class using Point, width and height"""

    def __init__(self, initP, initW, initH):

        self.__location = initP
        self.__width = initW
        self.__height = initH

loc = Point(4, 5)
r = Rectangle(loc, 6, 5)
print(r)

    def getWidth(self):
        return self.__width

    def getHeight(self):
        return self.__height

    def area(self):
        return self.__width * self.__height

    def perimeter(self):
        return 2 * (self.__height + self.__width)

    def __str__(self):
        return "point = %s \n" + str(self.__location) \
                                sens_dist.append(euc_dist)
                        try:
                            jj = np.where(dist[0, :] == np.min(sens_dist))
                            sack.append(sensors[ii, :])
                            arr.append(ii)
                            lines.append([ii, jj])
                        except:
                            print("No sensor found in row " + str(ii))
                    if len(sack) > 0:
                        num_sen -= len(arr)
                        levels.append(sack)
                        row_num.append(arr)
                        lvl_num += 1
                    else:
                        break
            p = Point.Point(sensors, sinks, R_sink)
            p.plot_points()
            """Multi-hop code END"""

            x_iter = []
            for k in range(len(row_num) - 1):

                num_sinks = len(row_num[k])
                num_nodes = len(row_num[k + 1])
                num_nodes_per_sink_avg = num_nodes / num_sinks
                dist_temp = np.zeros((len(row_num[k + 1]), len(row_num[k])))

                for kk in range(len(row_num[k + 1])):  #iterate over sensors
                    for jj in range(len(row_num[k])):  #iterate over sinks
                        if k == 0:
                            dist_temp[kk, jj] = dist1[row_num[k + 1][kk],
Example #51
0
def cree_point(nb):
    for i in range(0, nb):
        point_cree = Point.Point(canvas_width, canvas_height)
        canvas.cree_cercle(point_cree.coord, 25, "grey", point_cree.label)
        points_actif.append(point_cree)
    canvas.cree_ligne(canvas_width, canvas_height, 5)
Example #52
0
 def __init__(self, color, x, y):
     self.color = color
     self.coord = Point(x, y)
Example #53
0
def dis_func1(Point1, Point2):
    r2 = (Point1.x - Point2.x) * (Point1.x - Point2.x) + (
        Point1.y - Point2.y) * (Point1.y - Point2.y)
    return math.sqrt(r2)


path = "E:/data/shenzhen/shenzhen.mdb"
name = "shenzhen_random_split"
field = ["PN_INHABIT"]
io_dealer = IO_shp.IO()
xy_list = io_dealer.read_shp(path=path, name=name, fied_list=field)
Point_List = []

for i, xy in enumerate(xy_list):
    temp_Point = Point.Point(xy[1][0], xy[1][1], gridid=-1, ID=i, weight=xy[0])
    Point_List.append(temp_Point)
Envir = Environment.Envronment(Point_List=Point_List, dimension_x=10)
Envir.cal_dis_dict(dis_function=dis_func1)

simulate_time = 400
temp_routeList = []
for i in range(0, 10):
    #model=Model5.HomeOrWork_Model(args_model=args_model,args_t=args_time,args_steps=args_steps,environment=Envir,visited_Place=[],homeposition=random.choice(Envir.locations),workposition=random.choice(Envir.locations))
    model = agent.Nomal_Individual(args_model=args_model,
                                   args_t=args_time,
                                   args_step=args_steps,
                                   simulate_time=simulate_time,
                                   environment=Envir)
    model.simulate()
    mid = model.data_mid
Example #54
0
    def read_txt(self, path):
        if self.mid:
            self.mid = None
        temp_envir = Environment.Environment()
        temp_route = []
        with open(path, 'r') as f:
            temp_str = f.readline()
            temp_str = temp_str.rstrip('\n')
            if (temp_str == 'Environment'):
                temp_str = f.readline()
                temp_str = temp_str.rstrip('\n')
                temp_str = temp_str.split(' ')
                temp_int = [int(temp_str[0]), int(temp_str[1])]
                temp_envir.set_dimenssion(temp_int)
                temp_envir.set_grid()
            tag = True
            while (tag):
                temp_str = f.readline()
                temp_str = temp_str.rstrip('\n')
                if (temp_str != str(0)):
                    temp_str = temp_str.split(' ')
                    tempx = float(temp_str[0])
                    tempy = float(temp_str[1])
                    ID = int(temp_str[2])
                    state = int(temp_str[3])
                    weight = int(temp_str[4])
                    gridID = int(temp_str[5])
                    t = float(temp_str[6])
                    point = Point.Point([tempx, tempy],
                                        ID=ID,
                                        state=state,
                                        weight=weight,
                                        gridid=gridID,
                                        t=t)
                    temp_route.append(point)
                else:
                    break
            temp_envir.locations = temp_route

            data_mid_list = []
            temp_str = f.readline()
            while (temp_str):
                temp_route2 = []
                person_tag = 0
                temp_str = temp_str.rstrip('\n')
                if (temp_str == 'People'):
                    person_tag = int(f.readline().rstrip('\n'))
                temp_str = f.readline()
                important_loc = []
                temp = temp_str.rstrip('\n')
                if not (temp == '0'):
                    temp = temp.split(" ")
                    for i in range(int(len(temp))):
                        index = int(temp[i])
                        point = temp_envir.locations[index]
                        important_loc.append(point)
                while (True):
                    temp_str = f.readline()
                    temp_str = temp_str.rstrip('\n')
                    if (temp_str != str(0)):
                        temp_str = temp_str.split(' ')
                        tempx = float(temp_str[0])
                        tempy = float(temp_str[1])
                        ID = int(temp_str[2])
                        state = int(temp_str[3])
                        weight = int(temp_str[4])
                        gridID = int(temp_str[5])
                        t = float(temp_str[6])
                        point = Point.Point([tempx, tempy],
                                            gridid=gridID,
                                            ID=ID,
                                            state=state,
                                            weight=weight,
                                            t=t)
                        temp_route2.append(point)
                    else:
                        break
                temp_mid = data_mid.data_mid(temp_envir,
                                             person_tag=person_tag,
                                             important_loc=important_loc)
                temp_mid.add_location(temp_route2)
                data_mid_list.append(temp_mid)
                temp_str = f.readline()
            return data_mid_list
Example #55
0
    def findpath(self, points, curvature=1.0):
        """Constructs a path between the given list of points.
        
        Interpolates the list of points and determines
        a smooth bezier path betweem them.
        
        The curvature parameter offers some control on
        how separate segments are stitched together:
        from straight angles to smooth curves.
        Curvature is only useful if the path has more than  three points.
        """
        ''' (NOT IMPLEMENTED) Builds a path from a list of point coordinates.
        Curvature: 0=straight lines 1=smooth curves
        '''
        #raise NotImplementedError("findpath() isn't implemented yet (sorry)")
        #import bezier
        #path = bezier.findpath(points, curvature=curvature)
        #path.ctx = self
        #path.inheritFromContext()
        #return path

        # The list of points consists of Point objects,
        # but it shouldn't crash on something straightforward
        # as someone supplying a list of (x,y)-tuples.

        from types import TupleType
        for i, pt in enumerate(points):
            if type(pt) == TupleType:
                points[i] = Point(pt[0], pt[1])

        if len(points) == 0: return None
        if len(points) == 1:
            path = BezierPath(None)
            path.moveto(points[0].x, points[0].y)
            return path
        if len(points) == 2:
            path = BezierPath(None)
            path.moveto(points[0].x, points[0].y)
            path.lineto(points[1].x, points[1].y)
            return path

        # Zero curvature means straight lines.

        curvature = max(0, min(1, curvature))
        if curvature == 0:
            path = BezierPath(None)
            path.moveto(points[0].x, points[0].y)
            for i in range(len(points)):
                path.lineto(points[i].x, points[i].y)
            return path

        curvature = 4 + (1.0 - curvature) * 40

        dx = {0: 0, len(points) - 1: 0}
        dy = {0: 0, len(points) - 1: 0}
        bi = {1: -0.25}
        ax = {1: (points[2].x - points[0].x - dx[0]) / 4}
        ay = {1: (points[2].y - points[0].y - dy[0]) / 4}

        for i in range(2, len(points) - 1):
            bi[i] = -1 / (curvature + bi[i - 1])
            ax[i] = -(points[i + 1].x - points[i - 1].x - ax[i - 1]) * bi[i]
            ay[i] = -(points[i + 1].y - points[i - 1].y - ay[i - 1]) * bi[i]

        r = range(1, len(points) - 1)
        r.reverse()
        for i in r:
            dx[i] = ax[i] + dx[i + 1] * bi[i]
            dy[i] = ay[i] + dy[i + 1] * bi[i]

        path = BezierPath(None)
        path.moveto(points[0].x, points[0].y)
        for i in range(len(points) - 1):
            path.curveto(points[i].x + dx[i], points[i].y + dy[i],
                         points[i + 1].x - dx[i + 1],
                         points[i + 1].y - dy[i + 1], points[i + 1].x,
                         points[i + 1].y)

        return path
Example #56
0
import Environment
import Point
import IO
import IO_shp
import math


def dis_func1(Point1, Point2):
    r2 = (Point1.x - Point2.x) * (Point1.x - Point2.x) + (
        Point1.y - Point2.y) * (Point1.y - Point2.y)
    return math.sqrt(r2)


path = "E:/data/shenzhen/shenzhen.mdb"
name = "shenzhen_random_split"
field = []
io_dealer = IO_shp.IO()
xy_list = io_dealer.read_shp(path=path, name=name, fied_list=field)
Point_List = []
for i, xy in enumerate(xy_list):
    temp_Point = Point.Point(xy[0][0], xy[0][1], gridid=-1, ID=i)
    Point_List.append(temp_Point)
Envir = Environment.Envronment(Point_List=Point_List, dimension_x=10)
Envir.cal_dis_dict(Envir.dis_func1)
print(0)
Example #57
0
 def setUp(self):
     """
     set up data used in the tests.
     setUp is called before each test function execution.
     """
     self.point = Point(3, 4)
Example #58
0
    def moveClusters(self):
        for bacteriaCluster in self.bacteriaClusters:
            index = bacteriaCluster.getRelativeLocation()
            assert index is not None
            move_range = max(
                int(bacteriaCluster.getMoveSpeed() /
                    parameters.organ_grid_resolution), 1)
            concentration = []
            for i in range(-move_range, move_range + 1):
                if int(index.x + i) < 0 or int(index.x + i) >= len(self._grid):
                    continue
                for j in range(-move_range, move_range + 1):
                    if int(index.y + j) < 0 or int(index.y + j) >= len(
                            self._grid[0]):
                        continue
                    for k in range(-move_range, move_range + 1):
                        if int(index.z + k) < 0 or int(index.z + k) >= len(
                                self._grid[0][0]):
                            continue
                        exitDistanceBias = (
                            self._grid_exit.x - (index.x + i))**2 + (
                                self._grid_exit.y -
                                (index.y + j))**2 + (self._grid_exit.z -
                                                     (index.z + k))**2
                        concentration.append(
                            (exitDistanceBias,
                             self._grid[index.x + i][index.y + j]
                             [index.z + k].getBacteriaClustersConcentration(),
                             (index.x + i, index.y + j, index.z + k)))

            exitDistanceBias, concentration, loc = min(concentration)
            (new_x, new_y, new_z) = loc
            assert new_x >= 0 and new_x < len(self._grid)
            assert new_y >= 0 and new_y < len(self._grid[0])
            assert new_z >= 0 and new_z < len(self._grid[0][0])

            if (index.x != new_x or index.y != new_y or index.z != new_z):
                self._grid[index.x][index.y][index.z].removeBacteriaCluster(
                    bacteriaCluster)
                self._grid[new_x][new_y][new_z].addBacteriaCluster(
                    bacteriaCluster)
                bacteriaCluster.setRelativeLocation(Point(new_x, new_y, new_z))

        for immuneCellCluster in self.immuneCellClusters:
            index = immuneCellCluster.getRelativeLocation()
            move_range = max(
                int(immuneCellCluster.getMoveSpeed() /
                    parameters.organ_grid_resolution), 1)
            concentration = []
            for i in range(-move_range, move_range + 1):
                if (index.x + i) < 0 or (index.x + i) >= len(self._grid):
                    continue
                for j in range(-move_range, move_range + 1):
                    if (index.y + j) < 0 or (index.y + j) >= len(
                            self._grid[0]):
                        continue
                    for k in range(-move_range, move_range + 1):
                        if (index.z + k) < 0 or (index.z + k) >= len(
                                self._grid[0][0]):
                            continue
                        exitDistanceBias = (
                            self._grid_exit.x - (index.x + i))**2 + (
                                self._grid_exit.y -
                                (index.y + j))**2 + (self._grid_exit.z -
                                                     (index.z + k))**2
                        concentration.append(
                            (exitDistanceBias,
                             self._grid[index.x + i][index.y + j][
                                 index.z +
                                 k].getImmuneCellClustersConcentration(),
                             (index.x + i, index.y + j, index.z + k)))

            exitDistanceBias, concentration, loc = min(concentration)
            (new_x, new_y, new_z) = loc
            assert new_x >= 0 and new_x < len(self._grid)
            assert new_y >= 0 and new_y < len(self._grid[0])
            assert new_z >= 0 and new_z < len(self._grid[0][0])
            if (index.x != new_x or index.y != new_y or index.z != new_z):
                self._grid[index.x][index.y][
                    index.z].removeImmuneCellClusterCluster(immuneCellCluster)
                self._grid[new_x][new_y][new_z].addImmuneCellClusterCluster(
                    immuneCellCluster)
                immuneCellCluster.setRelativeLocation(
                    Point(new_x, new_y, new_z))
Example #59
0
def hex_to_pixel(direction):
    x = size * sqrt(3) * (direction.q + direction.r/2)
    y = size * 3/2 * direction.r
    return Point(x, y)
Example #60
0
class ArrowCreator:
    def __init__(self):
        window = Tk()
        window.title("Create Arrow")

        self.canvas = Canvas(window, width=500, height=300, bg="white")
        self.canvas.pack()
        self.canvas.bind("<Button-1>", self.clickArrow)
        self.canvas.bind("<B1-Motion>", self.dragArrow)

        Button(window, text="Create Arrow", command=self.generateArrow).pack()
        self.origin = Point(0, 0)
        window.mainloop()

    def clickArrow(self, event):
        self.canvas.delete("arrow")
        self.origin.setX(event.x)
        self.origin.setY(event.y)

    def dragArrow(self, event):
        self.canvas.delete("arrow")
        self.drawArrow(event.x, event.y)

    def drawArrow(self, x, y):
        self.canvas.create_line(self.origin.getX(),
                                self.origin.getY(),
                                x,
                                y,
                                tags="arrow")
        mag = self.origin.distance(Point(x, y))
        origVector = [x - self.origin.getX(), y - self.origin.getY()]
        negativeVector = [-i for i in origVector]
        scaledVector = [i * 10 / mag for i in negativeVector]
        centerX = x + scaledVector[0]
        centerY = y + scaledVector[1]
        changeVector = [
            scaledVector[0] * 0.5 - scaledVector[1] * sqrt(3) / 2,
            scaledVector[0] * sqrt(3) / 2 + scaledVector[1] * 0.5
        ]
        self.canvas.create_polygon(x,
                                   y,
                                   x + negativeVector[0] * 10 / mag,
                                   y + negativeVector[1] * 10 / mag,
                                   centerX + changeVector[0],
                                   centerY + changeVector[1],
                                   tags="arrow")
        changeVector = [
            scaledVector[0] * 0.5 + scaledVector[1] * sqrt(3) / 2,
            -scaledVector[0] * sqrt(3) / 2 + scaledVector[1] * 0.5
        ]
        self.canvas.create_polygon(x,
                                   y,
                                   x + negativeVector[0] * 10 / mag,
                                   y + negativeVector[1] * 10 / mag,
                                   centerX + changeVector[0],
                                   centerY + changeVector[1],
                                   tags="arrow")

    def generateArrow(self):
        self.canvas.delete("arrow")
        self.origin.setX(randint(0, 500))
        self.origin.setY(randint(0, 300))
        destX = randint(-1 * self.origin.getX(), 500 - self.origin.getX())
        destY = randint(-1 * self.origin.getY(), 300 - self.origin.getY())
        self.drawArrow(self.origin.getX() + destX, self.origin.getY() + destY)