Beispiel #1
0
    def postprocess(self):
        """
        Some operations on parsed data
        """
        log.debug('%i geometries found' % (len(self.geoms)))

        if self.vector:
            log.debug('Vectors found')

        #self.geoms.consistencyCheck()
        # import conversion units
        if self.geoms[-1].to_kcalmol:
            self.to_kcalmol = self.geoms[-1].to_kcalmol
        else:
            self.to_kcalmol = 1.

        # Do we have extended data?
        if 'e' in self.geoms.props:
            if 'x' in self.geoms.props:
                self.scan = Geometry.IRC(other=self.geoms)
                log.debug('IRC plot will be shown')
            else:
                self.scan = Geometry.Scan(other=self.geoms)
                log.debug('Scan plot will be shown')

        log.debug('XYZ file parsed successfully')
Beispiel #2
0
    def addBox(self, box, colour=None):
        if not Visualiser.VISUALISER_ON:
            return
        if isinstance(box, geo.Box):
            if colour == None:
                colour = visual.color.red
            org = geo.transform_point(box.origin, box.transform)
            ext = geo.transform_point(box.extent, box.transform)
            print "Visualiser: box origin=%s, extent=%s" % (str(org), str(ext))
            size = np.abs(ext - org)

            pos = org + 0.5 * size
            print "Visualiser: box position=%s, size=%s" % (str(pos),
                                                            str(size))
            angle, direction, point = tf.rotation_from_matrix(box.transform)
            print "colour,", colour
            if colour == [0, 0, 0]:
                visual.box(pos=pos,
                           size=size,
                           opacity=0.3,
                           material=visual.materials.plastic)
            else:
                visual.box(pos=pos,
                           size=size,
                           color=geo.norm(colour),
                           opacity=0.5)
    def get_obsflags(self, location, flag_types=0xFFFFFFFF):
        flags = 0x00000000
        if flag_types & (ObsFlag.DYNAMIC_OBSTACLE | ObsFlag.ANY_OBSTACLE):
            for obs in self.dynamic_obstacles:
                vec = np.subtract(location, obs.coordinate)
                if (obs.shape == 1 and np.dot(vec, vec) < obs.radius*obs.radius) \
                 or (obs.shape == 2 and Geometry.point_inside_rectangle([obs.coordinate, obs.size], location)) \
                 or (obs.shape == 3 and np.dot(vec, vec) < max(obs.width, obs.height)**2/4 and Geometry.point_inside_ellipse(obs.coordinate, obs.width, obs.height, np.arctan2(obs.get_velocity_vector()[1], obs.get_velocity_vector()[0]), location)) \
                 or (obs.shape == 4 and obs.polygon.contains_point(location)):
                    flags |= ObsFlag.DYNAMIC_OBSTACLE
                    break

        if flag_types & (ObsFlag.STATIC_OBSTACLE | ObsFlag.ANY_OBSTACLE):
            for obs in self.static_obstacles:
                vec = np.subtract(location, obs.coordinate)
                if (obs.shape == 1 and np.dot(vec, vec) < obs.radius*obs.radius) \
                 or (obs.shape == 2 and Geometry.point_inside_rectangle([obs.coordinate, obs.size], location)) \
                 or (obs.shape == 3 and np.dot(vec, vec) < max(obs.width, obs.height)**2/4 and Geometry.point_inside_ellipse(obs.coordinate, obs.width, obs.height, np.arctan2(obs.get_velocity_vector()[1], obs.get_velocity_vector()[0]), location)) \
                 or (obs.shape == 4 and obs.polygon.contains_point(location)):
                    flags |= ObsFlag.STATIC_OBSTACLE
                    break

        if flags & (ObsFlag.DYNAMIC_OBSTACLE | ObsFlag.STATIC_OBSTACLE):
            flags |= ObsFlag.ANY_OBSTACLE

        # Make sure to only return the requested flag types
        flags = flags & flag_types

        return flags
Beispiel #4
0
    def addBox(self, box, colour=None, opacity=1., material=None):
        if not VISUAL_INSTALLED:
            return
        if isinstance(box, geo.Box):
            if colour == None:
                colour = visual.color.red
            if material is None:
                material = visual.materials.plastic
            org = geo.transform_point(box.origin, box.transform)
            ext = geo.transform_point(box.extent, box.transform)
            print "Visualiser: box origin=%s, extent=%s" % (str(org), str(ext))
            size = np.abs(ext - org)

            pos = org + 0.5 * size
            print "Visualiser: box position=%s, size=%s" % (str(pos),
                                                            str(size))
            angle, direction, point = tf.rotation_from_matrix(box.transform)
            print "colour,", colour
            if np.allclose(np.array(colour), np.array([0, 0, 0])):
                visual.box(pos=pos,
                           size=size,
                           material=material,
                           opacity=opacity)
            else:
                visual.box(pos=pos,
                           size=size,
                           color=colour,
                           materials=material,
                           opacity=opacity)
Beispiel #5
0
    def draw(self, Canvas, line):
        t_size =  8 / Canvas.Scale
        point = self.pos
        ## Make the T shape with lines
        downPoint = (point[0] , point[1]-t_size/2)
        upPoint = (point[0], point[1]+t_size)
        rightPoint = (point[0]+t_size, point[1]+t_size)
        leftPoint = (point[0]-t_size, point[1]+t_size)

        ## rotate the T shape to always be normal to the edge
        theta = Geom.angleFromXaxis(line)
        lines = [leftPoint, rightPoint , upPoint, downPoint]
        lines = Geom.rotatePointList(lines, theta, point)


        Canvas.AddLine(
            [lines[0], lines[1]],
            LineWidth=4,
            LineColor="BLUE"
        )
        Canvas.AddLine(
            [lines[2], lines[3]],
            LineWidth=4,
            LineColor="BLUE"
        )
Beispiel #6
0
def test_line():
    expected = 1, 2
    to_point = geo.point(1, 1)
    from_point = geo.point(4, 4)
    line = geo.Line(from_point, to_point)
    actual = line.tpfp()
    print_test_results(line.tpfp, expected, actual)
Beispiel #7
0
def kinect_to_cartesian(kinect_pos, calib):
    top_dist = Geometry.distFromPointToLine(kinect_pos, calib.ul, calib.ur)
    bot_dist = Geometry.distFromPointToLine(kinect_pos, calib.ul, calib.ur)
    left_dist = Geometry.distFromPointToLine(kinect_pos, calib.ul, calib.ur)
    right_dist = Geometry.distFromPointToLine(kinect_pos, calib.ul, calib.ur)

    h = []
Beispiel #8
0
    def Update(self, ShapeObj1, ShapeObj2):
        if ShapeObj1 == None or ShapeObj2 == None:
            return
        if ShapeObj2.isLine():
            tmp = ShapeObj1
            ShapeObj1 = ShapeObj2
            ShapeObj2 = tmp

        if ShapeObj1.isRing() == False:
            self.m_start = Geometry.GetMidPoint(ShapeObj1.m_start,
                                                ShapeObj1.m_end)
        else:
            pathPaint = QPainterPath()
            startPoint = QPoint(
                ShapeObj1.m_start.x() +
                (ShapeObj1.m_end.x() - ShapeObj1.m_start.x()) / 4,
                ShapeObj1.m_start.y())
            end = QPoint(
                ShapeObj1.m_start.x() +
                (ShapeObj1.m_end.x() - ShapeObj1.m_start.x()) / 4 * 3,
                ShapeObj1.m_start.y())
            startPoint += QPoint(
                0.0, (ShapeObj1.m_start.y() - ShapeObj1.m_end.y()) / 2)
            endPoint = startPoint + QPoint(end.x() - startPoint.x(), 0)
            self.m_start = Geometry.GetMidPoint(startPoint, endPoint)

        lMPoint = ShapeObj2.GetConnerPoints()
        nMinLen = 1000000
        nLen = len(lMPoint)
        for i in range(nLen):
            nDis = Geometry.GetDistance(lMPoint[i], self.m_start)
            if nDis < nMinLen:
                nMinLen = nDis
                self.m_end = lMPoint[i]
        return
Beispiel #9
0
 def __init__(self, name, origin):
     self.name = name
     if not isinstance(origin, Base.Vector):
         raise RuntimeError("origin is not a Vector!")
     self.origin = origin
     self.center = Engine(name + "_center", origin, size='E24')
     self.centermount = BodyTube(name+"_centermount",\
                                 origin.add(Base.Vector(0,0,6.35)),\
                                 size='BT-50',length=95)
     self.centermountlowerring = EngineMountRing(\
                 name+"_centermountlowerring",\
                 origin.add(Base.Vector(0,0,50.8-(95-(70 + 6.35))+6.35)),\
                 enginesize='E24',tubesize='BT-55')
     self.centermountupperring = EngineMountRing(\
                 name+"_centermountlowerring",\
                 origin.add(Base.Vector(0,0,95)),\
                 enginesize='E24',tubesize='BT-55')
     self.stage2 = BodyTube(name+"_stage2",\
                            origin.add(Base.Vector(0,0,6.35)),\
                            size='BT-55',length=400)
     self.fin1 = FinType1(self.name+"_fin1",\
                          origin.add(Geometry.pointXdeltaatang(60,17,6.35+70)),\
                          orient=60,height=70,angle=30,length=200)
     self.fin2 = FinType1(self.name+"_fin2",\
                          origin.add(Geometry.pointXdeltaatang(180,17,6.35+70)),\
                          orient=180,height=70,angle=30,length=200)
     self.fin3 = FinType1(self.name+"_fin3",\
                          origin.add(Geometry.pointXdeltaatang(300,17,6.35+70)),\
                          orient=300,height=70,angle=30,length=200)
Beispiel #10
0
    def UpdateLigandAnchorPoint(self):

        try: 
                                    
            if self.Translation:
                index = int(float(self.Line[self.colNo:self.colNo+10]))
                
                coordX = self.top.GridVertex[index][0]     # The atom X coordinate
                coordY = self.top.GridVertex[index][1]     # The atom Y coordinate
                coordZ = self.top.GridVertex[index][2]     # The atom Z coordinate
                
                pointA = [coordX, coordY, coordZ]
                pointB = [self.top.OriX[0], self.top.OriX[1], self.top.OriX[2]]
                pointC = [self.top.Ori[0], self.top.Ori[1], self.top.Ori[2]]
                pointD = [self.top.OriY[0], self.top.OriY[1], self.top.OriY[2]]

                self.top.DisAngDih[self.top.VarAtoms[0]][0] = Geometry.distance(pointA, pointB)                             
                self.top.DisAngDih[self.top.VarAtoms[0]][1] = Geometry.angle(pointA, pointB, pointC)
                self.top.DisAngDih[self.top.VarAtoms[0]][2] = Geometry.dihedralAngle(pointA, pointB, pointC, pointD)

                self.colNo += 11
            
            if self.Rotation:
                self.top.DisAngDih[self.top.VarAtoms[1]][1] = float(self.Line[self.colNo:self.colNo+10])
                self.top.DisAngDih[self.top.VarAtoms[1]][2] = float(self.Line[self.colNo+11:self.colNo+21])
                self.top.DisAngDih[self.top.VarAtoms[2]][2] = float(self.Line[self.colNo+22:self.colNo+32])
                self.colNo += 33

        except:
            self.CriticalError(" Could not update ligand anchor point")
            return 1

        return 0
Beispiel #11
0
 def do_mouse_stuff(self, hand):  #Take a hand and use it as a mouse
     hand_normal_direction = Geometry.to_vector(hand.palm_normal)
     hand_direction = Geometry.to_vector(hand.direction)
     roll = hand_normal_direction.roll()
     pitch = hand_normal_direction.pitch()
     mouse_velocity = self.convert_angles_to_mouse_velocity(roll, pitch)
     self.cursor.move(mouse_velocity[0], mouse_velocity[1])
Beispiel #12
0
    def UpdateLigandAnchorPoint(self):

        try: 
                                    
            if self.Translation:
                index = int(float(self.Line[self.colNo:self.colNo+10]))
                
                coordX = self.top.GridVertex[index][0]     # The atom X coordinate
                coordY = self.top.GridVertex[index][1]     # The atom Y coordinate
                coordZ = self.top.GridVertex[index][2]     # The atom Z coordinate
                
                pointA = [coordX, coordY, coordZ]
                pointB = [self.top.OriX[0], self.top.OriX[1], self.top.OriX[2]]
                pointC = [self.top.Ori[0], self.top.Ori[1], self.top.Ori[2]]
                pointD = [self.top.OriY[0], self.top.OriY[1], self.top.OriY[2]]

                self.top.DisAngDih[self.top.VarAtoms[0]][0] = Geometry.distance(pointA, pointB)                             
                self.top.DisAngDih[self.top.VarAtoms[0]][1] = Geometry.angle(pointA, pointB, pointC)
                self.top.DisAngDih[self.top.VarAtoms[0]][2] = Geometry.dihedralAngle(pointA, pointB, pointC, pointD)

                self.colNo += 11
            
            if self.Rotation:
                self.top.DisAngDih[self.top.VarAtoms[1]][1] = float(self.Line[self.colNo:self.colNo+10])
                self.top.DisAngDih[self.top.VarAtoms[1]][2] = float(self.Line[self.colNo+11:self.colNo+21])
                self.top.DisAngDih[self.top.VarAtoms[2]][2] = float(self.Line[self.colNo+22:self.colNo+32])
                self.colNo += 33

        except:
            self.CriticalError(" Could not update ligand anchor point")
            return 1

        return 0
Beispiel #13
0
def polygon_is_collision_speed_test():
    '''
    Determine how long it takes for the concave capable polygon collision check
    call takes
    '''
    print('---------- Polygon Collision checking speed test ----------')
    poly1 = geom.Polygon()
    poly1.unit_circle(40,1.)
    poly1.translate(3.,3.)

    poly2 = geom.Polygon()
    poly2.unit_circle(40,1.)
    poly2.translate(3.2,3.2)

    num_players = 1.
    num_obstacles = 2.
    fps_multiplier = 1./((4*num_players)+(2*num_obstacles))

    tic = time.time()
    collis_res = geom.polygon_is_collision(poly1,poly2)
    toc = time.time()

    print(f'Collision checking took (s): {toc-tic}')
    print(f'Results: {collis_res.any()}')
    try:
        print(f'FPS: {(1./(toc-tic))*fps_multiplier}')
    except:
        print("Couldn't compute FPS...")

    geom.polygon_plot(poly1,poly2,lim=[0,15,0,15],title=f'Collision Result: {collis_res}')
    def runningLoop(self):

        mb = pygame.mouse.get_pressed()
        k = pygame.key.get_pressed()

        for e in pygame.event.get():
            if e.type == pygame.QUIT:
                self.running = False

        if self.delay == 0:
            if mb[0] == 1:
                self.cam.screen.rotateAboutY(0.01)
                self.delay = 1
            if mb[2] == 1:
                self.cam.screen.rotateAboutY(-0.01)
                self.delay = 1
            if k[pygame.K_w]:
                self.cam.screen.translate(Geometry.AVector3(1, 0, 0))
                self.delay = 1
            if k[pygame.K_s]:
                self.cam.screen.translate(Geometry.AVector3(-1, 0, 0))
                self.delay = 1
            if k[pygame.K_a]:
                self.cam.screen.translate(Geometry.AVector3(0, 0, 1))
                self.delay = 1
            if k[pygame.K_d]:
                self.cam.screen.translate(Geometry.AVector3(0, 0, -1))
                self.delay = 1
        if self.delay > 0:
            self.delay -= 1

        self.cam.draw()
        self.screen.blit(self.cam.canvas, (0, 0))
        pygame.display.flip()
Beispiel #15
0
	def get_dynobs_at_angle(self, center, angle):
		ang_in_radians = angle * np.pi / 180.0;
		endpoint = center + Vector.unitVectorFromAngle(ang_in_radians) * self.radius;
		min_dist = -1;
		closest_dynobs = None;
		for dynobs in self._env.dynamic_obstacles:
			if dynobs.shape == 1:
				inters = Geometry.circle_line_intersection(dynobs.coordinate, dynobs.radius, [center, endpoint]);
			elif dynobs.shape == 2:
				inters = Geometry.rectangle_line_intersection([dynobs.coordinate, np.array(dynobs.size)], [center, endpoint]);
			if len(inters) == 0:
				continue;

			inters_rel = np.array(inters) - center;
			dist = 1
			if len(inters) == 1:
				dist = Vector.magnitudeOf(inters_rel[0]);
			else:
				if np.dot(inters_rel[0], inters_rel[0]) < np.dot(inters_rel[1], inters_rel[1]):
					dist = Vector.magnitudeOf(inters_rel[0]);
				else:
					dist = Vector.magnitudeOf(inters_rel[1]);

			if dist < min_dist or min_dist < 0:
				min_dist = dist;
				closest_dynobs = dynobs

		return closest_dynobs;
Beispiel #16
0
 def do_mouse_stuff(self, hand):  #Take a hand and use it as a mouse
      hand_normal_direction = Geometry.to_vector(hand.palm_normal)
      hand_direction = Geometry.to_vector(hand.direction)
      roll = hand_normal_direction.roll()
      pitch = hand_normal_direction.pitch()
      mouse_velocity = self.convert_angles_to_mouse_velocity(roll, pitch)
      self.cursor.move(mouse_velocity[0], mouse_velocity[1])
Beispiel #17
0
 def getCorner(self, p):
     if self.isRing() == False:
         lPoint = []
         lPoint.append(self.m_start)
         lPoint.append(self.m_end)
         for i in range(len(lPoint)):
             if Geometry.getDistance(lPoint[i], p) <= 10:
                 self.m_curConner = i
                 return i
         self.m_curConner = -1
     else:
         lPoint = []
         startPoint = QPoint(
             self.m_start.x() + (self.m_end.x() - self.m_start.x()) / 4,
             self.m_start.y())
         end = QPoint(
             self.m_start.x() + (self.m_end.x() - self.m_start.x()) / 4 * 3,
             self.m_start.y())
         lPoint.append(startPoint)
         lPoint.append(end)
         for i in range(len(lPoint)):
             if Geometry.getDistance(lPoint[i], p) <= 10:
                 self.m_curConner = i
                 return i
         self.m_curConner = -1
     return -1
Beispiel #18
0
 def do_scroll_continuous(self, hand):
      hand_normal_direction = Geometry.to_vector(hand.palm_normal)
      hand_direction = Geometry.to_vector(hand.direction)
      roll = hand_normal_direction.roll()
      pitch = hand_normal_direction.pitch()
      velocity = self.convert_angles_to_mouse_velocity(roll, pitch) * 100
      self.cursor.scroll(velocity[0], velocity[1])
Beispiel #19
0
    def paint(self, painter):
        self.setPainter(painter)

        lPoint = []
        lPoint.append(self.m_start)
        lPoint.append(QPoint(self.m_start.x(), self.m_end.y()))
        lPoint.append(self.m_end)
        lPoint.append(QPoint(self.m_end.x(), self.m_start.y()))

        m1 = Geometry.GetMidPoint(lPoint[0], lPoint[1])
        m2 = Geometry.GetMidPoint(lPoint[1], lPoint[2])
        m3 = Geometry.GetMidPoint(lPoint[2], lPoint[3])
        m4 = Geometry.GetMidPoint(lPoint[3], lPoint[0])

        lMPoint = [m1, m2, m3, m4]
        path = QPainterPath()
        path.moveTo(m1)
        path.lineTo(m2)
        path.lineTo(m3)
        path.lineTo(m4)
        path.lineTo(m1)
        painter.drawPath(path)

        if self.hasCorner() != -1:
            pen = QPen()
            pen.setWidth(2)
            pen.setColor(QColor(0, 255, 0))
            painter.setPen(pen)
            painter.drawEllipse(lMPoint[self.m_curConner], 5, 5)
Beispiel #20
0
    def draw(self, Canvas, line):
        r_size = 10 / Canvas.Scale
        point = self.pos
        rightPoint = (point[0] - r_size, point[1])
        leftPoint = (point[0] + r_size, point[1])
        upRightPoint = (rightPoint[0], rightPoint[1]+ r_size)
        downRightPoint = (rightPoint[0], rightPoint[1]-r_size)
        upLeftPoint = (leftPoint[0], leftPoint[1]+r_size)
        downLeftPoint = (leftPoint[0], leftPoint[1]-r_size)

        theta = Geom.angleFromXaxis(line)

        firstTriangle = [point, upRightPoint, downRightPoint]
        secondTriangle = [point, upLeftPoint, downLeftPoint]

        firstTriangle = Geom.rotatePointList(firstTriangle, theta, point)
        secondTriangle = Geom.rotatePointList(secondTriangle, theta, point)


        Canvas.AddPolygon(
            firstTriangle,
            LineWidth=1,
            LineColor="BLUE",
            FillColor="BLUE",
        )
        Canvas.AddPolygon(
            secondTriangle,
            LineWidth=1,
            LineColor="BLUE",
            FillColor="BLUE",
        )
 def __init__(self, name, origin):
     self.name = name
     if not isinstance(origin, Base.Vector):
         raise RuntimeError("origin is not a Vector!")
     self.origin = origin
     XNorm = Base.Vector(1, 0, 0)
     BoardExtrude = Base.Vector(self._boardThick, 0, 0)
     boardCorner  =  origin.add(Base.Vector(-self._boardThick/2.0,\
                                            self._boardWidth/2.0,\
                                            0))
     #print("*** ComputerAssembly(): origin is ",origin.x,origin.y,origin.z,file=sys.__stderr__)
     #print("*** ComputerAssembly(): boardCorner is ",boardCorner.x,boardCorner.y,boardCorner.z,file=sys.__stderr__)
     self.telemetrypcb = Part.makePlane(self._boardLength, self._boardWidth,
                                        boardCorner,
                                        XNorm).extrude(BoardExtrude)
     ttgocp = boardCorner.add(Base.Vector(5.08, -3.81, 128.27))
     self.ttgo = Part.makePlane(45.72, 25.4, ttgocp,
                                XNorm).extrude(BoardExtrude)
     adxl345cp = boardCorner.add(Base.Vector(5.08, -5.08, 92.71))
     self.adafruit_adxl345 = Part.makePlane(25.4, 20.32, adxl345cp,
                                            XNorm).extrude(BoardExtrude)
     mpl3115a2cp = boardCorner.add(Base.Vector(5.08, -5.08, 68.5))
     self.adafruit_mpl3115a2 = Part.makePlane(20.32, 17.7, mpl3115a2cp,
                                              XNorm).extrude(BoardExtrude)
     DS3231_rtccp = boardCorner.add(Base.Vector(5.08, -5.08, 40.54))
     self.adafruit_DS3231_rtc = Part.makePlane(22.05, 17.7, DS3231_rtccp,
                                               XNorm).extrude(BoardExtrude)
     self.topdisk = Part.Face(
         Part.Wire(
             Part.makeCircle(33.0 / 2, origin.add(Base.Vector(
                 0, 0,
                 177.8))))).extrude(Base.Vector(0, 0, (1.0 / 8.0) * 25.4))
     gradiusX = 26.5 / 2
     gbottom = -24.5
     gheight = 177.8 + 12 + 37.5
     gradius = (1.0 / 8.0) * 25.4
     self.guide1 = Part.Face(
         Part.Wire(
             Part.makeCircle(
                 gradius,
                 origin.add(Geometry.pointXdeltaatang(
                     90, gradiusX,
                     gbottom))))).extrude(Base.Vector(0, 0, gheight))
     self.guide2 = Part.Face(
         Part.Wire(
             Part.makeCircle(
                 gradius,
                 origin.add(
                     Geometry.pointXdeltaatang(
                         210, gradiusX,
                         gbottom))))).extrude(Base.Vector(0, 0, gheight))
     self.guide3 = Part.Face(
         Part.Wire(
             Part.makeCircle(
                 gradius,
                 origin.add(
                     Geometry.pointXdeltaatang(
                         330, gradiusX,
                         gbottom))))).extrude(Base.Vector(0, 0, gheight))
Beispiel #22
0
 def addPolygon(self, polygon, colour=None):
     if not Visualiser.VISUALISER_ON:
         return
     if isinstance(polygon, geo.Polygon):
         if colour == None:
             visual.convex(pos=polygon.pts, color=geo.norm([0.1,0.1,0.1]), material=visual.materials.plastic)
         else:
             visual.convex(pos=convex.points, color=geo.norm(colour), opacity=0.5)
Beispiel #23
0
 def addPolygon(self, polygon, colour=None, opacity=1., material=visual.materials.plastic):
     if not Visualiser.VISUALISER_ON:
         return
     if isinstance(polygon, geo.Polygon):
         if colour == None:
             visual.convex(pos=polygon.pts, color=geo.norm([0.1,0.1,0.1]), material=material)
         else:
             visual.convex(pos=polygon.pts, color=geo.norm(colour), material=material)
Beispiel #24
0
 def equalsTo(self, b):
     sb = self.box
     bb = b.box
     dim = self.dp.samplingDimension
     efact = 0.9
     retval = Geometry.inside(sb, bb, efact, dim) and Geometry.inside(
         bb, sb, efact, dim)
     return retval
 def __init__(self):
     self.running = True
     self.screen = pygame.display.set_mode((600, 480))
     self.objects = [SL.Cube(0, 0, 0, 100), SL.Cube(100, 0, 0, 50)]
     canvas = Geometry.VPlane(Geometry.AVector3(1, 0, 1),
                              Geometry.AVector3(0, 1, 0),
                              Geometry.Point(0, 0, 0))
     self.cam = Camera(canvas, 150, 480, 600, self.objects)
     self.delay = 0
Beispiel #26
0
 def make_accepting(self, state):
     print("Accept Fired")
     is_accepting = self.parser.add_accepting(state)
     if is_accepting:
         state.accept_button.configure(bg=ACCEPTING)
     else:
         state.accept_button.configure(bg=NONE)
     is_entry = self.parser.is_entry(state)
     Geometry.make_accepting(self.canvas_window, state, is_accepting, is_entry)
def test_Line():
    fromPoint = geo.Point(1, 1)
    toPoint = geo.Point(4, 5)
    line1 = geo.Line(fromPoint, toPoint)

    expected = 5
    desc = "Returns line length."
    actual = line1.length
    print_test_results(geo.func, desc, expected, actual)
def main(X,i, L,Lf1,Lf2,Lf3,d_lg,d_ztail, d_ytail,S_x, W, t_st,h_st,w_st, ):
    t_s = X[:,0][i]
    R = X[:,1][i]
    t_f = X[:,2][i]
    h_f = X[:, 3][i]
    n_s =  int(X[:, 4][i])
    y_f = R-h_f #y-loc of floor if origin if circle center
    gamma_f = np.arcsin(y_f/R) #angle between x-axis and floor
    theta_f = np.pi - 2*gamma_f #angle of sector with floor
    A_II = (R**2/2)*(theta_f - np.sin(theta_f)) # Area Cell II
    A_I = (np.pi*R**2) - A_II #Area Cell I
    w_f = Geometry.floor_width(R, h_f)
    stringer_area = t_st*(h_st + w_st)

    #Computing q and S_x taking into account the safety factor
    safetyfactor = 1.5
    q = W*3*9.81*safetyfactor/L
    S_x = S_x*safetyfactor

    #Calculating Geometrical Properties
    #Geometry.idealization(R, n_s, t_st, h_st, w_st, t_f, h_f, t_s)
    x_bar, y_bar = Geometry.centroid(R, h_f, t_f, t_s, n_s, t_st, h_st, w_st)
    floor_Ixx, fuselage_Ixx, stringer_Ixx = Geometry.MOIxx(x_bar, y_bar, stringer_area, R, h_f, t_f, t_s, n_s, t_st, h_st, w_st, w_f)
    floor_Iyy, fuselage_Iyy, stringer_Iyy = Geometry.MOIyy(x_bar, y_bar, stringer_area, R, h_f, t_f, t_s, n_s, t_st, h_st, w_st, w_f)

    Ixx_total = floor_Ixx+fuselage_Ixx+stringer_Ixx
    Iyy_total = floor_Iyy+fuselage_Iyy+stringer_Iyy

    Forces = reac.ReactionsFunction(L,Lf1,Lf2,Lf3,d_lg,d_ztail,d_ytail,S_x,q)

    zlocation = 10
    number_booms = 200




    position_of_booms_total = booms_angle, booms_distance, booms_position = reac.PositionofBooms(number_booms, zlocation,
                                                                                                 Forces, Ixx_total,
                                                                                                 Iyy_total)
    booms_area = reac.AreaBoom(booms_angle, zlocation, Ixx_total, Iyy_total, booms_distance)
    delta_T, q1, q2 = tors.deflect_T(1, A_I, A_II, position_of_booms_total, booms_area, t_s, t_f, gamma_f)
    J = tors.J(1, delta_T)

    Mx = reac.Momentx(zlocation, Forces)
    Sy = reac.Sheary(zlocation, Forces)
    My = reac.Momenty(zlocation, Forces)
    Sx = reac.Shearx(zlocation, Forces)
    T = reac.Torque(zlocation, Forces)

    # Shear
    delta_S, q1_s, q2_s = tors.shearflowsb(Sx, Sy, Ixx_total, Iyy_total, A_I, A_II, booms_area, position_of_booms_total, t_s, t_f, y_f, gamma_f)
    delta_Tf, q1_T, q2_T = tors.deflect_T(T, A_I, A_II, position_of_booms_total, booms_area, t_s, t_f, gamma_f)
    sigma_b = tors.simga_b(Mx, My, Ixx_total, Iyy_total, position_of_booms_total, booms_area, gamma_f)
    vonMises = tors.vonMises(q1_s, q2_s, q1_T, q2_T, sigma_b, t_s, t_f)
    mean = np.mean(vonMises/10)
    return mean
Beispiel #29
0
 def make_accepting(self, state):
     print("Accept Fired")
     is_accepting = self.parser.add_accepting(state)
     if is_accepting:
         state.accept_button.configure(bg=ACCEPTING)
     else:
         state.accept_button.configure(bg=NONE)
     is_entry = self.parser.is_entry(state)
     Geometry.make_accepting(self.canvas_window, state, is_accepting,
                             is_entry)
Beispiel #30
0
 def addPolygon(self, polygon, colour=None, opacity=1., material=None):
     if not VISUAL_INSTALLED:
         return
     if isinstance(polygon, geo.Polygon):
         if material is None:
             material = visual.materials.plastic
         if colour == None:
             visual.convex(pos=polygon.pts, color=geo.norm([0.1,0.1,0.1]), material=material)
         else:
             visual.convex(pos=polygon.pts, color=geo.norm(colour), material=material)
Beispiel #31
0
def loadJsoninGlobalVariable():
    global intrinsic
    intrinsic = objetintrinsic(FileManager.Load("json_in/intrinsics.json"))
    Counter_select.setIntrinsicParam(intrinsic)
    Geometry.setIntrinsicParam(intrinsic)
    Scene3D.setIntrinsicParam(intrinsic)
    global annotation_file
    annotation_file = FileManager.Load("json_in/annotations.json")
    InfoFromAnnotation.setJson(annotation_file)
    FileManager.setJson(annotation_file)
Beispiel #32
0
 def is_crashed(self, track):
     if self.crashed:
         return True
     if Geo.find_intersections(
             self.get_polyline(), track.right) or Geo.find_intersections(
                 self.get_polyline(), track.left) or Geo.find_intersections(
                     self.get_polyline(), track.start):
         self.crashed = True
         return True
     return False
Beispiel #33
0
    def parse(self):
        """
        Parses XYZ file both in standard and short (without header) formats.
        Can read parameters from comment lines in format '%s= %s'.
        If .XYZ file contains several geoemtries, a graph can be plot
        (for now, IRC mode turns on if 'e' and 'x' parameters are given
        for each geometry; if other parameter instead of 'x' is given,
        Scan mode is activated)
        """

        # Open file
        try:
            FI = open(self.file)
            log.debug('%s was opened for reading' % (self.file))
        except:
            log.error('Cannot open %s for reading' % (self.file))
            return '', ''
        #
        # Read file
        #
        geom = Geometry.Geom()
        is_FirstLine = True
        for s in FI:
            splitted = s.strip().split()
            if len(splitted) > 3:
                if is_FirstLine:  # Short XYZ
                    log.debug('Short XYZ format (without headers) recognized')
                    is_FirstLine = False
                # Read Coords
                splitted[0] = ChemicalInfo.to_elN(splitted[0])
                geom.coord.append('%s    %s  %s  %s\n' % tuple(splitted[:4]))
                # +Vectors
                if len(splitted) == 7:
                    log.debug('Displacement vectors found')
                    self.vector.append('%s  %s  %s\n' % tuple(splitted[4:]))
                #
            elif len(splitted) == 1:
                if is_FirstLine:  # Standard XYZ
                    is_FirstLine = False
                    log.debug('Standard XYZ format recognized')
                else:
                    self.geoms.append(geom)
                # New Record
                geom = Geometry.Geom()
                try:
                    geom.header_natoms = int(splitted[0])
                except:
                    log.warning('Cannot read number of atoms from the header')
                try:
                    comment = next(FI).strip()
                except:
                    log.warning('Unexpected EOF while reading comment line')
                geom.parseComment(comment)
        self.geoms.append(geom)
        FI.close()
Beispiel #34
0
def regular_polygon_filter(contour_list,
                           side_amount=6,
                           min_angle_ratio=0.9,
                           min_area_ratio=0.85,
                           min_len_ratio=0.9,
                           approx_coef=0.02):
    """
    Action: A filter that Detects regular polygon of n-sides sides
    :param contour_list: the list of contours to be filtered
    :param side_amount: the amount of sides the wanted polygon has.
    :param min_angle_ratio: the minimum ratio between the each angle and the average angle and the average angle and the
                            target angle of a shape of side_amount
    :param min_area_ratio: The minimum ratio between the contour's area and the target area
    :param min_len_ratio: The minimum ratio between the length of each side and the average length and
                          between the average length.
    :param approx_coef: the coefficient for the function cv2.approxPolyDP.
    :return:
    """
    if side_amount < 3:
        return []
    output = []
    ratio_list = []
    if type(contour_list) is not list:
        contour_list = [contour_list]
    for currentContour in contour_list:
        vertices, lengths, angles = Geometry.get_lengths_and_angles(
            currentContour, approx_coef)
        if len(vertices) == side_amount:
            target_angle = Geometry.n_polygon_angle(side_amount)
            average_length = round(sum(lengths) / float(len(lengths)), 3)
            average_angle = round(sum(angles) / float(len(lengths)), 3)
            invalid_value = False
            for length in lengths:
                if 1 - (root((length - average_length)**2, 2) /
                        average_length) < min_len_ratio:
                    invalid_value = True
                    break
            if not invalid_value:
                for angle in angles:
                    if 1 - (root((angle - average_angle)**2, 2) /
                            average_angle) < min_angle_ratio:
                        invalid_value = True
                        break
                if not invalid_value:
                    if 1 - (root((target_angle - average_angle)**2, 2) /
                            target_angle) < min_angle_ratio:
                        invalid_value = True
                    if not invalid_value:
                        ratio = cv2.contourArea(
                            currentContour) / Geometry.n_polygon_area(
                                average_length, side_amount)
                        if min_area_ratio <= ratio <= 1 / min_area_ratio:
                            ratio_list.append(ratio)
                            output.append(currentContour)
    return output, ratio_list
    def connect(self):

        plate = self._Car__env.getPlate(self)

        self._Car__rewardSocket.addReward(plate.assignReward(self))
        self._Car__rewardSocket.sendReward()
        if self._Car__stateSocket:

            if not self.n_angles:
                state = plate.id * self.fine_rot_sensor
                orientation = (geom.angVec(self._Car__direction) +
                               int(360 / (2 * self.fine_rot_sensor))) % 360
                state += int(orientation / (360 / self.fine_rot_sensor))
            else:
                dists = []
                for i in range(self.n_angles):
                    min_t = None

                    deg = np.pi * 2 / self.n_angles * i + geom.angVec(
                        self._Car__direction) / 180 * np.pi

                    ang = {}

                    ang["cos"] = np.cos(deg)
                    ang["sin"] = np.sin(deg)
                    ang["tan"] = ang["sin"] / ang["cos"] if ang[
                        "cos"] != 0 else None
                    ang["cotan"] = ang["cos"] / ang["sin"] if ang[
                        "sin"] != 0 else None

                    for wall in self._Car__env.getWalls():
                        t = wall.getDistance(self._Car__position, ang)
                        min_t = t if (not min_t or
                                      (t and t < min_t)) else min_t
                    dists.append(min_t)
                state = 0
                digit = 1

                for dist in dists:
                    state += digit * int(
                        dist / self.l_pieces if dist /
                        self.l_pieces < self.n_pieces else self.n_pieces)
                    digit *= self.n_pieces + 1

            orientation = geom.angVec(self._Car__direction)
            # orientation = int(orientation/(360/self.fine_rot_sensor))

            self._Car__stateSocket.setState(state)
            self.__direction_socket.setState(int(orientation))
            self.__move_socket.setState(plate.bestMove)
            self._Car__stateSocket.sendState()
            self.__direction_socket.sendState()
            self.__move_socket.sendState()

        self._Car__env.moveReward(plate.trail, self)
Beispiel #36
0
def has_two_pointer_fingers(hand):  #Checks if we are using two pointer fingers
    if len(hand.fingers) < 2:  #Obviously not
        return False
    sorted_fingers = sort_fingers_by_distance_from_screen(hand.fingers)
    finger1_pos = Geometry.to_vector(sorted_fingers[0].tip_position)
    finger2_pos = Geometry.to_vector(sorted_fingers[1].tip_position)
    difference = finger1_pos - finger2_pos
    if difference.norm() < 40:  #Check if the fingertips are close together
        return True
    else:
        return False
Beispiel #37
0
def has_two_pointer_fingers(hand):  #Checks if we are using two pointer fingers
    if len(hand.fingers) < 2:  #Obviously not
        return False
    sorted_fingers = sort_fingers_by_distance_from_screen(hand.fingers)
    finger1_pos = Geometry.to_vector(sorted_fingers[0].tip_position)
    finger2_pos = Geometry.to_vector(sorted_fingers[1].tip_position)
    difference = finger1_pos - finger2_pos
    if difference.norm() < 40:  #Check if the fingertips are close together
        return True
    else:
        return False
Beispiel #38
0
    def test_moixx(self):
        #Testing the moment of inertia calculations for floor contribution
        #Values are compared to hand calculated values

        x_bar, y_bar = Geometry.centroid(R, h_f, t_f, t_s, n_s, t_st, h_st,
                                         w_st)
        floor_Ixx, fuselage_Ixx, stringer_Ixx = Geometry.MOIxx(
            x_bar, y_bar, stringer_area, R, h_f, t_f, t_s, n_s, t_st, h_st,
            w_st, w_f)
        assert round(floor_Ixx, 4) == round(0.0610583336, 4)
        assert round(fuselage_Ixx, 4) == round(0.097228, 4)
        assert round(stringer_Ixx, 4) == round(0.003182835606813844, 4)
Beispiel #39
0
    def test_moiyy(self):
        #Testing the moment of inertia calculations for floor contribution
        #Values are compared to hand calculated values

        x_bar, y_bar = Geometry.centroid(R, h_f, t_f, t_s, n_s, t_st, h_st,
                                         w_st)
        floor_Iyy, fuselage_Iyy, stringer_Iyy = Geometry.MOIyy(
            x_bar, y_bar, stringer_area, R, h_f, t_f, t_s, n_s, t_st, h_st,
            w_st, w_f)
        assert round(floor_Iyy, 4) == round(0.354558415, 4)
        assert round(fuselage_Iyy, 4) == round(0.052749892705925, 4)
        assert round(stringer_Iyy, 4) == round(0.0030239999999999998, 4)
Beispiel #40
0
def test_polylines():
    test_seg_1 = geo.Line('6,6', '9,9')
    test_seg_2 = geo.Line('9,9', '10,10')
    test_seg_3 = '6,3', '6,6'
    test_poly = geo.Polyline()
    test_poly.addSegment(test_seg_1)
    test_poly.addSegment(test_seg_2)
    test_poly.addSegment(test_seg_3)
    desc = "Test of the Polyline Class."
    expected = 5.65685
    actual = test_poly.length()
    print_test_results(test_polylines, desc, expected, actual)
Beispiel #41
0
 def addConvex(self, convex, colour=None):
     """docstring for addConvex"""
     if not Visualiser.VISUALISER_ON:
         return
     if isinstance(convex, geo.Convex):
         if colour == None:
             print "Color is none"
             visual.convex(pos=polygon.pts, color=geo.norm([0.1,0.1,0.1]), material=visual.materials.plastic)
         else:
             import pdb; pdb.set_trace()
             print "Colour is", geo.norm(colour)
             visual.convex(pos=convex.points, color=geo.norm(colour), material=visual.materials.plastic)
Beispiel #42
0
 def addFinitePlane(self, plane, colour=None, opacity=0.):
     if not Visualiser.VISUALISER_ON:
         return
     if isinstance(plane, geo.FinitePlane):
         if colour == None:
             colour = visual.color.blue
         # visual doesn't support planes, so we draw a very thin box
         H = .001
         pos = (plane.length/2, plane.width/2, H/2)
         pos = geo.transform_point(pos, plane.transform)
         size = (plane.length, plane.width, H)
         axis = geo.transform_direction((0,0,1), plane.transform)
         visual.box(pos=pos, size=size, color=colour, opacity=0)
Beispiel #43
0
 def addConvex(self, convex, colour=None, opacity=1., material=None):
     """docstring for addConvex"""
     if not VISUAL_INSTALLED:
         return
     if isinstance(convex, geo.Convex):
         if material is None:
             material = visual.materials.plastic
         if colour == None:
             print "Color is none"
             visual.convex(pos=convex.points, color=geo.norm([0.1,0.1,0.1]), material=material)
         else:
             #import pdb; pdb.set_trace()
             print "Colour is", geo.norm(colour)
             visual.convex(pos=convex.points, color=geo.norm(colour), material=material)
Beispiel #44
0
 def addFinitePlane(self, plane, colour=None, opacity=1., material=None):
     if not VISUAL_INSTALLED:
         return
     if isinstance(plane, geo.FinitePlane):
         if material is None:
             material = visual.materials.plastic
         if colour == None:
             colour = visual.color.blue
         # visual doesn't support planes, so we draw a very thin box
         H = .001
         pos = (plane.length/2, plane.width/2, H/2)
         pos = geo.transform_point(pos, plane.transform)
         size = (plane.length, plane.width, H)
         axis = geo.transform_direction((0,0,1), plane.transform)
         visual.box(pos=pos, size=size, color=colour, opacity=opacity, material=material)
Beispiel #45
0
def has_thumb(hand): #The level of accuracy with this function is surprisingly high
    if hand.fingers.empty: #We assume no thumbs
        return False
    distances = []
    palm_position = Geometry.to_vector(hand.palm_position)
    for finger in hand.fingers: #Make a list of all distances from the center of the palm
        finger_position = Geometry.to_vector(finger.tip_position)
        difference = finger_position - palm_position
        distances.append(difference.norm()) #Record the distance from the palm to the fingertip
    average = sum(distances)/len(distances)
    minimum = min(distances)
    if average - minimum > 20: #Check if the finger closest to the palm is more than 20mm closer than the average distance
        return True
    else:
        return False
Beispiel #46
0
 def addCylinder(self, cylinder, colour=None):
     if not Visualiser.VISUALISER_ON:
         return
     if colour == None:
         colour = visual.color.blue
     #angle, direction, point = tf.rotation_from_matrix(cylinder.transform)
     #axis = direction * cylinder.length
     position = geo.transform_point([0,0,0], cylinder.transform)
     axis = geo.transform_direction([0,0,1], cylinder.transform)
     print cylinder.transform, "Cylinder:transform"
     print position, "Cylinder:position"
     print axis, "Cylinder:axis"
     print colour, "Cylinder:colour"
     print cylinder.radius, "Cylinder:radius"
     visual.cylinder(pos=position, axis=axis, color=colour, radius=cylinder.radius, opacity=0.5, length = cylinder.length)
Beispiel #47
0
 def getEdgeFromPoint(self, point, margin=8):
     for node in self.nodes:
         for edge in node._neighbors:
             distance = Geom.distFromLineSeg(edge.line, point)
             if distance  <= margin:
                 return edge
     return None
    def evolve(self):
        """ Run evolution.
        """
        pop_size = 100

        seeds = []

        seed = []
        for aa in self.sequence:
            geo = Geometry.geometry(aa)
            seed.append(geo.phi)
            seed.append(geo.psi_im1)

        template_seeds = self.create_seeds(self.path + "/pdbs2")

        seeds += template_seeds

        seeds += [seed for x in range(100 - len(template_seeds))]

        self.es.terminator = terminators.evaluation_termination
        self.es.evolve(generator=self.generator,
                       evaluator=self.eval_func,
                       pop_size=pop_size,
                       maximize=False,
                       max_evaluations=2000000000,
                       bounder=self.bounder,
                       seeds=seeds,
                       neighborhood_size=10,
                       cognitive_rate=1,
                       social_rate=1,
                       num_inputs=self.c_size)
Beispiel #49
0
 def addLine(self, start, stop, colour=None, opacity=1., material=None):
     if not VISUAL_INSTALLED:
         return
     if colour == None:
         colour = visual.color.white
     axis = np.array(stop) - np.array(start)
     visual.cylinder(pos=start, axis=axis, radius=0.0001, color=geo.norm(colour), opacity=opacity, material=material)
 def on_AddNPolygonButton_clicked(self, widget):
     N = int(Gtk.Entry.get_text(self.NSidesEntry))
     Radius = float(Gtk.Entry.get_text(self.NRadiusEntry))
     Center = tuple(map(int, Gtk.Entry.get_text(self.NCenterEntry).split(",")))
     Angle = float(Gtk.Entry.get_text(self.NAngleEntry))
     Polygon = Geometry.n_Sided_Polygon(N, Radius, Center, Angle)
     self.Shapes.append(Polygon)
Beispiel #51
0
 def addLine(self, start, stop, colour=None):
     if not Visualiser.VISUALISER_ON:
         return
     if colour == None:
         colour = visual.color.white
     axis = np.array(stop) - np.array(start)
     visual.cylinder(pos=start, axis=axis, radius=0.0001, color=geo.norm(colour))
Beispiel #52
0
	def collides(self,p):
		#print Geometry.distance(self.x,self.y,p.x,p.y), self.r
		if Geometry.distance(self.x,self.y,p.x,p.y) < self.r:
			p.kill()
			return True
		else:
			return False
Beispiel #53
0
def build_all_angles_model(pdb_filename):
    parser=PDBParser()
    structure=parser.get_structure('sample', \
                                    path.join(PDBdir, pdb_filename))
    model=structure[0]
    chain=model['A']
    model_structure_geo=[]
    prev="0"
    N_prev="0"
    CA_prev="0"
    CO_prev="0"
    prev_res=""
    rad=180.0/math.pi
    for res in chain:
        if(res.get_resname() in resdict.keys()):
            geo=Geometry.geometry(resdict[res.get_resname()])
            if(prev=="0"):
                N_prev=res['N']
                CA_prev=res['CA']
                C_prev=res['C']
                prev="1"
            else:
                n1=N_prev.get_vector()
                ca1=CA_prev.get_vector()
                c1=C_prev.get_vector()
                                
                C_curr=res['C']
                N_curr=res['N']
                CA_curr=res['CA']
                                                
                c=C_curr.get_vector()
                n=N_curr.get_vector()
                ca=CA_curr.get_vector()

                geo.CA_C_N_angle=calc_angle(ca1, c1, n)*rad
                geo.C_N_CA_angle=calc_angle(c1, n, ca)*rad

                psi= calc_dihedral(n1, ca1, c1, n) ##goes to current res
                omega= calc_dihedral(ca1, c1, n, ca) ##goes to current res
                phi= calc_dihedral(c1, n, ca, c) ##goes to current res

                geo.psi_im1=psi*rad
                geo.omega=omega*rad
                geo.phi=phi*rad

                geo.N_CA_C_angle= calc_angle(n, ca, c)*rad
                ##geo.CA_C_O_angle= calc_angle(ca, c, o)*rad

                ##geo.N_CA_C_O= calc_dihedral(n, ca, c, o)*rad

                N_prev=res['N']
                CA_prev=res['CA']
                C_prev=res['C']
                ##O_prev=res['O']
                                
                        
            model_structure_geo.append(geo)
    return model_structure_geo
Beispiel #54
0
 def add_state(self):
     new_state_name = self.control_window.state_entry.get()
     print(new_state_name)
     self.control_window.state_entry.delete(0, END)
     self.states.append(State(self.control_window.frame, new_state_name))
     new_state = self.states[-1]
     new_state.state_label.grid(row=len(self.states), column=0)
     new_state.transition_button.configure(text="TRANSITION", command=lambda : self.transition(new_state))
     new_state.transition_button.grid(row=len(self.states), column=1)
     new_state.delete_button.configure(text="DELETE", command=lambda : self.delete_state(new_state))
     new_state.delete_button.grid(row=len(self.states), column=2)
     new_state.accept_button.configure(text="ACCEPT", command=lambda : self.make_accepting(new_state))
     new_state.accept_button.grid(row=len(self.states), column=3)
     new_state.entry_button.configure(text="--->", command=lambda : self.make_entry(new_state))
     new_state.entry_button.grid(row=len(self.states), column=4)
     self.parser.add_state(new_state)
     Geometry.add_state(self.canvas_window, new_state, self.states)
     pass
Beispiel #55
0
 def addRay(self, ray, colour=None):
     if not Visualiser.VISUALISER_ON:
         return
     if isinstance(ray, geo.Ray):
         if colour == None:
             colour = visual.color.white
         pos = ray.position
         axis = ray.direction * 5
         visual.cylinder(pos=pos, axis=axis, radius=0.0001, color=geo.norm(colour))
Beispiel #56
0
    def build_Grid(self):
        
        try:

            for sph in self.dictSpheres.keys():
                
                if float(1.0 / self.Spacer) - float(int(1.0 / self.Spacer)) > 0.001:
                    xmin = float(int((self.dictSpheres[sph][1][0] - self.dictSpheres[sph][0]) / self.Spacer)) * self.Spacer;
                    ymin = float(int((self.dictSpheres[sph][1][1] - self.dictSpheres[sph][0]) / self.Spacer)) * self.Spacer;
                    zmin = float(int((self.dictSpheres[sph][1][2] - self.dictSpheres[sph][0]) / self.Spacer)) * self.Spacer;
                    xmax = float(int((self.dictSpheres[sph][1][0] + self.dictSpheres[sph][0]) / self.Spacer) + 1.0) * self.Spacer;
                    ymax = float(int((self.dictSpheres[sph][1][1] + self.dictSpheres[sph][0]) / self.Spacer) + 1.0) * self.Spacer;
                    zmax = float(int((self.dictSpheres[sph][1][2] + self.dictSpheres[sph][0]) / self.Spacer) + 1.0) * self.Spacer;

                else:
                    xmin = float(int(self.dictSpheres[sph][1][0] - self.dictSpheres[sph][0] - self.Spacer));
                    ymin = float(int(self.dictSpheres[sph][1][1] - self.dictSpheres[sph][0] - self.Spacer));   
                    zmin = float(int(self.dictSpheres[sph][1][2] - self.dictSpheres[sph][0] - self.Spacer));
                    xmax = float(int(self.dictSpheres[sph][1][0] + self.dictSpheres[sph][0] + self.Spacer + 1.0))
                    ymax = float(int(self.dictSpheres[sph][1][1] + self.dictSpheres[sph][0] + self.Spacer + 1.0))
                    zmax = float(int(self.dictSpheres[sph][1][2] + self.dictSpheres[sph][0] + self.Spacer + 1.0))


                x = xmin
                y = ymin
                z = zmin
                
                sqrrad = sph.Radius
                
                while z < zmax:
                    while y < ymax:
                        while x < xmax:

                            key  = '%8.3f' % x
                            key += '%8.3f' % y
                            key += '%8.3f' % z

                            if key not in self.dictGridPoints:

                                sqrrad = self.dictSpheres[sph][0] * self.dictSpheres[sph][0]
                                if Geometry.sqrdistance( self.dictSpheres[sph][1], [ x, y, z ] ) < sqrrad:

                                    self.dictGridPoints[key] = ''

                            x += self.Spacer

                        x = xmin
                        y += self.Spacer

                    x = xmin
                    y = ymin
                    z += self.Spacer

        except:
            return 1

        return 0
Beispiel #57
0
 def mouseMovement(self, x, y):
     return Geometry.rotate2d((x, y), math.radians(self._mapRotation))
     if self.current == Constants.N:
         return (x, y)
     elif self.current == Constants.NW:
         return Geometry.rotate2d((x, y), math.radians(-45))
     elif self.current == Constants.E:
         return (-y, x)
     elif self.current == Constants.NE:
         return Geometry.rotate2d((-y, x), math.radians(-45))
     elif self.current == Constants.S:
         return (-x, -y)
     elif self.current == Constants.SE:
         return Geometry.rotate2d((-x, -y), math.radians(-45))
     elif self.current == Constants.W:
         return (y, -x)
     else:
         return Geometry.rotate2d((y, -x), math.radians(-45))
Beispiel #58
0
 def addRay(self, ray, colour=None, opacity=1., material=None):
     if not VISUAL_INSTALLED:
         return
     if isinstance(ray, geo.Ray):
         if colour == None:
             colour = visual.color.white
         pos = ray.position
         axis = ray.direction * 5
         visual.cylinder(pos=pos, axis=axis, radius=0.0001, color=geo.norm(colour), opacity=opacity, material=material)
Beispiel #59
0
 def addBox(self, box, colour=None):
     if not Visualiser.VISUALISER_ON:
         return
     if isinstance(box, geo.Box):
         if colour == None:
             colour = visual.color.red
         org = geo.transform_point(box.origin, box.transform)
         ext = geo.transform_point(box.extent, box.transform)
         print "Visualiser: box origin=%s, extent=%s" % (str(org), str(ext))
         size = np.abs(ext - org)
         
         pos = org + 0.5*size
         print "Visualiser: box position=%s, size=%s" % (str(pos), str(size))
         angle, direction, point = tf.rotation_from_matrix(box.transform)
         print "colour,", colour
         if colour == [0,0,0]:
             visual.box(pos=pos, size=size, opacity=0.3, material=visual.materials.plastic)
         else:
             visual.box(pos=pos, size=size, color=geo.norm(colour), opacity=0.5)
Beispiel #60
0
 def draw(self, Canvas, line):
     l_size = 8 / Canvas.Scale
     point = self.pos
     upPoint = (point[0], point[1]+ l_size)
     downPoint = (point[0], point[1] - l_size)
     rightPoint = (point[0] + l_size, point[1] - l_size)
     lines = [upPoint, downPoint, rightPoint]
     theta = Geom.angleFromXaxis(line)
     lines = Geom.rotatePointList(lines, theta, point)
     Canvas.AddLine(
         [lines[0], lines[1]],
         LineWidth=4,
         LineColor="BLUE"
     )
     Canvas.AddLine(
         [lines[1], lines[2]],
         LineWidth=4,
         LineColor="BLUE"
     )