Ejemplo n.º 1
0
    def testIdentity(self):
        nobj = 1000
        for i in range(nobj):
            s = afwDetect.Source()
            s.setId(i)
            s.setRa(radians(10 + 0.001*i))
            s.setDec(radians(10 + 0.001*i))

            self.ss1.append(s)

            s = afwDetect.Source()
            s.setId(2*nobj + i)
            s.setRa(radians(10 + 0.001*i))
            s.setDec(radians(10 + 0.001*i))

            self.ss2.append(s)

        mat = afwDetect.matchRaDec(self.ss1, self.ss2, 1.0, False)

        self.assertEqual(len(mat), nobj)

        if False:
            s0 = mat[0][0]
            s1 = mat[0][1]
            print s0.getRa(), s1.getRa(), s0.getId(), s1.getId()
def findPointOnSphere(cx, cy, cz, radius, phi, theta):
    #phi - angle around the pole 0<= phi <= 360
    #theta - angle from plan 'up' -90 <= theta <= 90
    x = cx + radius * math.cos(math.radians(theta)) * math.cos(math.radians(phi))
    z = cz + radius * math.cos(math.radians(theta)) * math.sin(math.radians(phi))
    y = cy + radius * math.sin(math.radians(theta))
    return int(round(x,0)), int(round(y,0)), int(round(z,0))
Ejemplo n.º 3
0
    def navdata_cb(self, data):
        self.navdata = data
        self.roll = math.radians(data.rotY)
        self.pitch = math.radians(data.rotX)
        if data.tags_count > 0:
            self.tag_acquired = True
            self.theta = self.navdata.tags_orientation[0] - 180
            # These are actually switched for the controller purposes
            self.prev_tag_x = self.tag_x
            self.tag_x = self.navdata.tags_yc[0]
            self.tag_vx = (self.tag_x - self.prev_tag_x) * self.rate

            self.prev_tag_y = self.tag_y
            self.tag_y = self.navdata.tags_xc[0]
            self.tag_vy = (self.tag_y - self.prev_tag_y) * self.rate
            # Calculate the normalized values
            self.norm_prev_tag_x = self.tag_x
            self.norm_tag_x = norm.real_position(self.tag_x - 500, self.altitude, self.pitch)
            self.norm_tag_vx = (self.norm_tag_x - self.norm_prev_tag_x) * self.rate

            self.norm_prev_tag_y = self.tag_y
            self.tag_norm_y = norm.real_position(self.tag_y - 500, self.altitude, self.roll)
            self.norm_tag_vy = (self.norm_tag_y - self.norm_prev_tag_y) * self.rate

            # Polar controller
            self.r = math.hypot(self.tag_x, self.tag_y)
        else:
            self.tag_acquired = False
Ejemplo n.º 4
0
    def gps_to_kmeters(long1, lat1, long2, lat2):
        """Converts gps longitudes and latitudes distance to meters

        Keyword arguments:
        long1 -- longitude for pos 1
        lat1 -- latitute for pos 1
        long2 -- longitude for pos 2
        lat2 -- latitude for pos 2
        """

        #approx radius of earth
        R = 6373.0

        long1 = radians(long1)
        lat1 = radians(lat1)
        long2 = radians(long2)
        lat2 = radians(lat2)

        dist_long = long2 - long1
        dist_lat = lat2 - lat1

        a = sin(dist_lat / 2)**2 + cos(lat1) * cos(lat2) * sin(dist_long)**2
        c = atan2(sqrt(a), sqrt(1 - a))

        dist = R * c

        return dist
Ejemplo n.º 5
0
    def __create_board(self):
        """
        Creates a Canvas widget where Hexagon fields are marked on it
        """
        m = self.size[0]
        n = self.size[1]
        edge_length = 24
        # calculates the size of the Hexagon
        y_top, x_right = self.__Hex_size(edge_length)
        canvas_width = x_right * n + x_right * m / 2 + 50
        canvas_height = y_top * m + 100

        self.w = Canvas(self.master, width=canvas_width, height=canvas_height)
        self.w.configure(background=self.bg)
        self.w.pack()
        # creates Hexagon Grid
        for j in range(m):
            for i in range(n):
                x = 40 + x_right * i + x_right / 2 * j
                y = 50 + y_top * j
                k = 0
                for angle in range(0, 360, 60):
                    y += math.cos(math.radians(angle)) * edge_length
                    x += math.sin(math.radians(angle)) * edge_length
                    self.point_coordinates[j][i][k] = x
                    self.point_coordinates[j][i][k + 1] = y
                    k += 2
                # draws Hexagon to the canvas widget
                self.w.create_polygon(list(
                    self.point_coordinates[j][i]),
                    outline=self.tile_outline, fill=self.tile, width=3)
Ejemplo n.º 6
0
def turtlevector(magnitude, angle, origin=[0,0], time=100, gravity=(-9.8)):  #vector conversion
    global output
    xvelocity = magnitude * (cos(radians(angle)))
    yvelocity = magnitude * (sin(radians(angle)))
    output += "For vector with magnitude " + str(magnitude) + " at a " + str(angle) + " degree angle:" + "\n"
    turtlephysics(xvelocity, yvelocity, origin, time, gravity) #passes to main physics function
    return
Ejemplo n.º 7
0
def calc_dist(plyr_angl,plyr_vel):
    gravity = 9.81                #gravity 9.81 m/s^2
    vel_init_x = plyr_vel * math.cos(math.radians(plyr_angl))    #creates Vix
    vel_init_y = plyr_vel * math.sin(math.radians(plyr_angl))    #creates Viy
    time_in_air = 2 * (vel_init_y / gravity)              #solves for time
    distance_x = vel_init_x * time_in_air                #solves for distance
    return (distance_x, time_in_air)                    #returns horizontal distance, time in air
Ejemplo n.º 8
0
    def __init__(self, scale=1.0):
        self.translation = Vector3()
        self.rotation = Vector3()
        self.initialHeight = Vector3(0, 0, scale*StewartPlatformMath.SCALE_INITIAL_HEIGHT)
        self.baseJoint = []
        self.platformJoint = []
        self.q = []
        self.l = []
        self.alpha = []
        self.baseRadius = scale*StewartPlatformMath.SCALE_BASE_RADIUS
        self.platformRadius = scale*StewartPlatformMath.SCALE_PLATFORM_RADIUS
        self.hornLength = scale*StewartPlatformMath.SCALE_HORN_LENGTH
        self.legLength = scale*StewartPlatformMath.SCALE_LEG_LENGTH;

        for angle in self.baseAngles:
            mx = self.baseRadius*cos(radians(angle))
            my = self.baseRadius*sin(radians(angle))
            self.baseJoint.append(Vector3(mx, my))

        for angle in self.platformAngles:
            mx = self.platformRadius*cos(radians(angle))
            my = self.platformRadius*sin(radians(angle))
            self.platformJoint.append(Vector3(mx, my))

        self.q = [Vector3()]*len(self.platformAngles)
        self.l = [Vector3()]*len(self.platformAngles)
        self.alpha = [0]*len(self.beta)
Ejemplo n.º 9
0
    def update(self):
        if self.turning_right:
            self.rot -= 5
        if self.turning_left:
            self.rot += 5

        a = [0.0,0.0]
        if self.boost_endtime > rabbyt.get_time():
            f = 3*(self.boost_endtime - rabbyt.get_time())/self.boost_length
            a[0] += cos(radians(self.boost_rot))*f
            a[1] += sin(radians(self.boost_rot))*f
            self.create_boost_particle()

        if self.accelerating:
            a[0] += cos(radians(self.rot))*.9
            a[1] += sin(radians(self.rot))*.9
            self.create_dust_particle(self.dust_r)
            self.create_dust_particle(self.dust_l)

        ff = .9 # Friction Factor

        self.velocity[0] *= ff
        self.velocity[1] *= ff

        self.velocity[0] += a[0]
        self.velocity[1] += a[1]

        self.x += self.velocity[0]
        self.y += self.velocity[1]
Ejemplo n.º 10
0
def distance(origin, destination):
    """ 
    Calculates both distance and bearing
    """
    lat1, lon1 = origin
    lat2, lon2 = destination
    if lat1>1000:
        (lat1,lon1)=dm2dd(lat1,lon1)
        (lat2,lon2)=dm2dd(lat2,lon2)
        print('converted to from ddmm to dd.ddd')
    radius = 6371 # km
    

    dlat = math.radians(lat2-lat1)
    dlon = math.radians(lon2-lon1)
    a = math.sin(dlat/2) * math.sin(dlat/2) + math.cos(math.radians(lat1)) \
        * math.cos(math.radians(lat2)) * math.sin(dlon/2) * math.sin(dlon/2)
    c = 2 * math.atan2(math.sqrt(a), math.sqrt(1-a))
    d = radius * c
    
    def calcBearing(lat1, lon1, lat2, lon2):
       dLon = lon2 - lon1
       y = math.sin(dLon) * math.cos(lat2)
       x = math.cos(lat1) * math.sin(lat2) \
           - math.sin(lat1) * math.cos(lat2) * math.cos(dLon)
       return math.atan2(y, x)
       
    bear= math.degrees(calcBearing(lat1, lon1, lat2, lon2))  
    return d,bear
Ejemplo n.º 11
0
    def sumVectors(self, vectors):
        """ sum all vectors (including targetvector)"""
        endObstacleVector = (0,0)

        ##generate endvector of obstacles
        #sum obstaclevectors
        for vector in vectors:
            vectorX = math.sin(math.radians(vector[1])) * vector[0] # x-position
            vectorY = math.cos(math.radians(vector[1])) * vector[0] # y-position
            endObstacleVector = (endObstacleVector[0]+vectorX,endObstacleVector[1]+vectorY)
        #mean obstaclevectors
        if len(vectors) > 0:
            endObstacleVector = (endObstacleVector[0]/len(vectors), endObstacleVector[1]/len(vectors))

        #add targetvector
        targetVector = self.target
        if targetVector != 0 and targetVector != None:
            vectorX = math.sin(math.radians(targetVector[1])) * targetVector[0] # x-position
            vectorY = math.cos(math.radians(targetVector[1])) * targetVector[0] # y-position
            endVector = (endObstacleVector[0]+vectorX,endObstacleVector[1]+vectorY)
            #endVector = (endVector[0]/2, endVector[1]/2)
        else:
            endVector = endObstacleVector


        return endVector
Ejemplo n.º 12
0
    def __init__(self,figura_1, figura_2, figura_1_punto=(0,0), figura_2_punto=(0,0), angulo_minimo=None,angulo_maximo=None, fisica=None, con_colision=True):
        """ Inicializa la constante
        :param figura_1: Una de las figuras a conectar por la constante.
        :param figura_2: La otra figura a conectar por la constante.
        :param figura_1_punto: Punto de rotación de figura_1
        :param figura_2_punto: Punto de rotación de figura_2
        :param angulo_minimo: Angulo minimo de rotacion para figura_2 con respecto a figura_1_punto
        :param angulo_maximo: Angulo maximo de rotacion para figura_2 con respecto a figura_1_punto
        :param fisica: Referencia al motor de física.
        :param con_colision: Indica si se permite colisión entre las dos figuras.
        """
        if not fisica:
            fisica = pilas.escena_actual().fisica

        if not isinstance(figura_1, Figura) or not isinstance(figura_2, Figura):
            raise Exception("Las dos figuras tienen que ser objetos de la clase Figura.")

        constante = box2d.b2RevoluteJointDef()
        constante.Initialize(bodyA=figura_1._cuerpo, bodyB=figura_2._cuerpo,anchor=(0,0))
        constante.localAnchorA = convertir_a_metros(figura_1_punto[0]), convertir_a_metros(figura_1_punto[1])
        constante.localAnchorB = convertir_a_metros(figura_2_punto[0]), convertir_a_metros(figura_2_punto[1])       
        if angulo_minimo != None or angulo_maximo != None:
            constante.enableLimit = True
            constante.lowerAngle = math.radians(angulo_minimo)
            constante.upperAngle = math.radians(angulo_maximo)
        constante.collideConnected = con_colision
        self.constante = fisica.mundo.CreateJoint(constante)
Ejemplo n.º 13
0
    def calculate_initial_compass_bearing(self, pointA, pointB):
        """
        Calculates direction between two points.
        Code based on compassbearing.py module
        https://gist.github.com/jeromer/2005586

        pointA: latitude/longitude for first point (decimal degrees)
        pointB: latitude/longitude for second point (decimal degrees)
    
        Return: direction heading in degrees (0-360 degrees, with 90 = North)
        """

        if (type(pointA) != tuple) or (type(pointB) != tuple):
            raise TypeError("Only tuples are supported as arguments")
    
        lat1 = math.radians(pointA[0])
        lat2 = math.radians(pointB[0])
    
        diffLong = math.radians(pointB[1] - pointA[1])
    
        # Direction angle (-180 to +180 degrees):
        # θ = atan2(sin(Δlong).cos(lat2),cos(lat1).sin(lat2) − sin(lat1).cos(lat2).cos(Δlong))

        x = math.sin(diffLong) * math.cos(lat2)
        y = math.cos(lat1) * math.sin(lat2) - (math.sin(lat1) * math.cos(lat2) * math.cos(diffLong))
    
        initial_bearing = math.atan2(x, y)
    
        # Direction calculation requires to normalize direction angle (0 - 360)
        initial_bearing = math.degrees(initial_bearing)
        compass_bearing = (initial_bearing + 360) % 360
    
        return compass_bearing
Ejemplo n.º 14
0
 def _convert_to_cartesian(self, location):
     lat = radians(location.lat)
     lon = radians(location.long)
     x = cos(lat) * cos(lon)
     y = cos(lat) * sin(lon)
     z = sin(lat)
     return (x, y, z)
Ejemplo n.º 15
0
    def set_3d(self):
        """ Configure OpenGL to draw in 3d.

        """
        width, height = self.get_size()

        gl.glEnable(gl.GL_DEPTH_TEST)

        gl.glViewport(0, 0, width, height)
        gl.glMatrixMode(gl.GL_PROJECTION)
        gl.glLoadIdentity()
        gl.gluPerspective(65.0, width / float(height), 0.1, DIST)
        gl.glMatrixMode(gl.GL_MODELVIEW)
        gl.glLoadIdentity()

        x, y = self.rotation
        gl.glRotatef(x, 0, 1, 0)
        gl.glRotatef(-y, math.cos(math.radians(x)), 0, math.sin(math.radians(x)))
        x, y, z = self.position
        gl.glTranslatef(-x, -y, -z)

        gl.glEnable(gl.GL_LIGHTING)
        gl.glLightModelfv(gl.GL_LIGHT_MODEL_AMBIENT, GLfloat4(0.05,0.05,0.05,1.0))
        gl.glEnable(gl.GL_COLOR_MATERIAL)
        gl.glColorMaterial(gl.GL_FRONT, gl.GL_AMBIENT_AND_DIFFUSE)
        #gl.glLightfv(gl.GL_LIGHT1,gl.GL_SPOT_DIRECTION, GLfloat3(0,0,-1))
        gl.glLightfv(gl.GL_LIGHT1, gl.GL_AMBIENT, GLfloat4(0.5,0.5,0.5,1.0))
        gl.glLightfv(gl.GL_LIGHT1, gl.GL_DIFFUSE, GLfloat4(1.0,1.0,1.0,1.0))
        gl.glLightfv(gl.GL_LIGHT1, gl.GL_POSITION, GLfloat4(0.35,1.0,0.65,0.0))
        #gl.glLightfv(gl.GL_LIGHT0,gl.GL_SPECULAR, GLfloat4(1,1,1,1))
        gl.glDisable(gl.GL_LIGHT0)
        gl.glEnable(gl.GL_LIGHT1)
Ejemplo n.º 16
0
def angle_to_vector(ang):
    """
    :param ang its an angle in degrees in the regular right-oriented Descartes
    But in pyGame coordinates are left oriented plus cos and sin take arguments
    in radians that is why this convertation is needed
    """
    return [math.cos(math.radians(ang)), -math.sin(math.radians(ang))]
Ejemplo n.º 17
0
	def getDec(self,j):
		j=float(j)
		m = 357.0+(0.9856*j) 
		c = (1.914*sin(radians(m))) + (0.02*sin(radians(2.0*m)))
		l = 280.0 + c + (0.9856*j)
		sinDec= 0.3978*sin(radians(l))
		return degrees(asin(sinDec))
Ejemplo n.º 18
0
def albers_projection(origin, parallels, translate, scale):
    """Return an Albers projection from geographic positions to x-y positions.

    Derived from Mike Bostock's Albers javascript implementation for D3
    http://mbostock.github.com/d3
    http://mathworld.wolfram.com/AlbersEqual-AreaConicProjection.html

    origin -- a geographic position
    parallels -- bounding latitudes
    translate -- x-y translation to place the projection within a larger map
    scale -- scaling factor
    """
    phi1, phi2 = [radians(p) for p in parallels]
    base_lat = radians(latitude(origin))
    s, c = sin(phi1), cos(phi1)
    base_lon = radians(longitude(origin))
    n = 0.5 * (s + sin(phi2))
    C = c*c + 2*n*s
    p0 = sqrt(C - 2*n*sin(base_lat))/n

    def project(position):
        lat, lon = radians(latitude(position)), radians(longitude(position))
        t = n * (lon - base_lon)
        p = sqrt(C - 2*n*sin(lat))/n
        x = scale * p * sin(t) + translate[0]
        y = scale * (p * cos(t) - p0) + translate[1]
        return (x, y)
    return project
Ejemplo n.º 19
0
 def project(position):
     lat, lon = radians(latitude(position)), radians(longitude(position))
     t = n * (lon - base_lon)
     p = sqrt(C - 2*n*sin(lat))/n
     x = scale * p * sin(t) + translate[0]
     y = scale * (p * cos(t) - p0) + translate[1]
     return (x, y)
Ejemplo n.º 20
0
def vert_sep():
    """This function collects all of the coordinates and elevations necessary to calculate the vertical separation between a drone being flown under
    an established approach path, runs all of the calculations, and prints the separation in feet. All coordinates are entered by the user in degrees
    minutes seconds format with no special characters. Degrees minutes and seconds are separated with spaces. All elevations and altitudes are entered
    in feet. The approach path glide slope angle is entered in degrees. The example coordinates, elevations, and altitudes are
    for Gainesville Runway 5 ILS and RNAV approaches."""
    drone_northing_dms = raw_input("Enter the northing of the location that the drone will fly in DMS format. ex. 34 14 21.25 :")
    drone_northing_dd = dms_to_dd(drone_northing_dms)
    drone_easting_dms = raw_input("Enter the easting of the location that the drone will fly in DMS format. ex. 83 52 1.75 :")
    drone_easting_dd = dms_to_dd(drone_easting_dms)
    iaf_northing_dms = raw_input("Enter the northing of the initial approach fix in DMS format. ex. 34 12 12.11 :")
    iaf_northing_dd = dms_to_dd(iaf_northing_dms)
    iaf_easting_dms = raw_input("Enter the easting of the initial approach fix in DMS format. ex. 83 54 22.74 :")
    iaf_easting_dd = dms_to_dd(iaf_easting_dms)
    
    long_degree_dist_ft = (math.cos(math.radians(float(drone_northing_dd))) * 69.172) * 5280
    easting_distance_ft = (abs(float(iaf_easting_dd)) - float(drone_easting_dd)) * float(long_degree_dist_ft)
    northing_distance_ft = (abs(float(iaf_northing_dd) - float(drone_northing_dd))) * 364320
    distance_ft = ((float(easting_distance_ft) ** 2.0) + (float(northing_distance_ft) ** 2.0)) ** (1/2.0)
    tdze = raw_input("Enter the elevation of the touch down zone in feet. ex 1276 :")
    iaf_alt = raw_input("Enter the altitude above mean sea level of the initial approach fix in feet. ex 3100 :")
    gsa = raw_input("Enter the glide slope angle in degrees. ex 3.00 :")
    study_area_elevation = raw_input("Enter the elevation of the location that the drone will fly in feet. ex. 1162 :")
    drone_alt = raw_input("Enter the altitude above ground level that the drone will fly in feet. ex 270 :")
    adjactnt_side = float(iaf_alt) - float(tdze)
    alt_above_tdze = (math.tan(math.radians(float(gsa)))) * float(distance_ft)
    elevation_diff = float(tdze) - float(study_area_elevation)
    approach_path_alt = float(alt_above_tdze) + float(elevation_diff)
    vert_sep = float(approach_path_alt) - float(drone_alt)
    print ("There will be {} feet of vertical separation between the drone and the approach path.").format(round(vert_sep, 1))
Ejemplo n.º 21
0
def xy(lng, lat, truncate=False):
    """Convert longitude and latitude to web mercator x, y

    Parameters
    ----------
    lng, lat : float
        Longitude and latitude in decimal degrees.
    truncate : bool, optional
        Whether to truncate or clip inputs to web mercator limits.

    Returns
    -------
    x, y : float
        y will be inf at the North Pole (lat >= 90) and -inf at the
        South Pole (lat <= -90).
    """
    if truncate:
        lng, lat = truncate_lnglat(lng, lat)
    x = 6378137.0 * math.radians(lng)
    if lat <= -90:
        y = float('-inf')
    elif lat >= 90:
        y = float('inf')
    else:
        y = 6378137.0 * math.log(
            math.tan((math.pi * 0.25) + (0.5 * math.radians(lat))))
    return x, y
Ejemplo n.º 22
0
 def headServosPut(self,params):
     if params.has_key('pan_position'):
         #self.yaw=-math.radians(float(params['pan_position']))
         grados=80*(float(params['pan_position']))/90
         self.yaw=-math.radians(grados)
     if params.has_key('pan_speed'):
         #Anadir velocuidad
         pass
     if params.has_key('tilt_position'):
         grados=-(float(params['tilt_position']))/90
         if grados<0:
             grados=grados*20
         else:
             grados=grados*40
         self.pitch=-math.radians(grados)
     if params.has_key('tilt_speed'):
         #Anadir velocuidad
         pass
     if params.has_key('panBlocked') and params['panBlocked'] is True:
         #se quita el stall
         pass
     if params.has_key('tiltBlocked') and params['tiltBlocked'] is True:
         #se quita el stall
         pass
     self.sendHeadPose()
Ejemplo n.º 23
0
def distance_to_coords_formula(latitude, longitude, bearing1, bearing2):
    """ math formula for calculating the lat, lng based on
        distance and bearing """

    # one degree of latitude is approximately 10^7 / 90 = 111,111 meters.
    # http://stackoverflow.com/questions/2187657/calculate-second-point-
    # knowing-the-starting-point-and-distance
    # one degree of latitude is approximately 10^7 / 90 = 111,111 meters
    # http://stackoverflow.com/questions/13836416/geohash-and-max-distance
    distance = 118  # meters

    east_displacement_a = distance * sin(radians(bearing1)) / 111111
    north_displacement_a = distance * cos(radians(bearing1)) / 111111

    east_displacement_b = distance * sin(radians(bearing2)) / 111111
    north_displacement_b = distance * cos(radians(bearing2)) / 111111

    # calculate the total displacement for N, S respectively
    waypoint_latitude_a = latitude + north_displacement_a
    waypoint_longitude_a = longitude + east_displacement_a

    waypoint_latitude_b = latitude + north_displacement_b
    waypoint_longitude_b = longitude + east_displacement_b

    return [(waypoint_latitude_a, waypoint_longitude_a),
            (waypoint_latitude_b, waypoint_longitude_b)]
Ejemplo n.º 24
0
def create_circle(cx, cy, r, a1, a2):
    points = []
    for a in range(a1, a2 + 1):
        x = cx + r * cos(radians(a))
        y = cy + r * sin(radians(a))
        points.append((x, y))
    return points
Ejemplo n.º 25
0
def dayLength(date, latitude):
    # Formulas from: http://www.gandraxa.com/length_of_day.xml
    # I don't really understand them, and the numbers don't quite match
    # what I get from calendar sites. Perhaps this is measuring the exact
    # moment the center of the sun goes down, as opposed to civil twilight?
    # But I think it's close enough to get the idea across.

    # Tilt of earth's axis relative to its orbital plane ("obliquity of ecliptic")
    axis = math.radians(23.439)

    # Date of winter solstice in this year. Not quite right, but good
    # enough for our purposes.
    solstice = date.replace(month=12, day=21)

    # If a year is a full circle, this is the angle between the solstice
    # and this date, in radians. May be negative if we haven't reached the
    # solstice yet.
    dateAngle = (date - solstice).days * 2 * math.pi / 365.25

    latitude = math.radians(latitude)
    m = 1 - math.tan(latitude) * math.tan(axis * math.cos(dateAngle))

    # If m is less than zero, the sun never rises; if greater than two, it never sets.
    m = min(2, max(0, m))
    return math.acos(1 - m) / math.pi
Ejemplo n.º 26
0
    def precisionToDim(self):
        """Convert precision from Wikibase to GeoData's dim and return the latter.

        dim is calculated if the Coordinate doesn't have a dimension, and precision is set.
        When neither dim nor precision are set, ValueError is thrown.

        Carrying on from the earlier derivation of precision, since
        precision = math.degrees(dim/(radius*math.cos(math.radians(self.lat)))), we get
            dim = math.radians(precision)*radius*math.cos(math.radians(self.lat))
        But this is not valid, since it returns a float value for dim which is an integer.
        We must round it off to the nearest integer.

        Therefore::
            dim = int(round(math.radians(precision)*radius*math.cos(math.radians(self.lat))))

        @rtype: int or None
        """
        if self._dim is None and self._precision is None:
            raise ValueError('No values set for dim or precision')
        if self._dim is None and self._precision is not None:
            radius = 6378137
            self._dim = int(
                round(
                    math.radians(self._precision) * radius * math.cos(math.radians(self.lat))
                )
            )
        return self._dim
Ejemplo n.º 27
0
    def set_3d(self):
        """ Configure OpenGL to draw in 3d.

		"""
        width, height = self.get_size()
        glEnable(GL_DEPTH_TEST)
        glViewport(0, 0, width, height)
        glMatrixMode(GL_PROJECTION)
        glLoadIdentity()
        # gluPerspective(45.0f,(GLfloat)width/(GLfloat)height,near distance,far distance);
        # gluPerspective(65.0, width / float(height), 0.1, 60.0)
        gluPerspective(65.0, width / float(height), 0.1, 6000.0)
        glMatrixMode(GL_MODELVIEW)
        glLoadIdentity()

        # glDepthMask(GL_FALSE)
        # drawSkybox()
        # glDepthMask(GL_TRUE)

        x, y = self.rotation
        # http://wiki.delphigl.com/index.php/glRotate
        # procedure glRotatef(angle: TGLfloat; x: TGLfloat; y: TGLfloat; z: TGLfloat);
        glRotatef(x, 0, 1, 0)
        glRotatef(-y, math.cos(math.radians(x)), 0, math.sin(math.radians(x)))
        x, y, z = self.position
        glTranslatef(-x, -y, -z)
Ejemplo n.º 28
0
 def distance(a, b):
     """Calculates distance between two latitude-longitude coordinates."""
     R = 3963  # radius of Earth (miles)
     lat1, lon1 = math.radians(a[0]), math.radians(a[1])
     lat2, lon2 = math.radians(b[0]), math.radians(b[1])
     return math.acos( math.sin(lat1)*math.sin(lat2) +
         math.cos(lat1)*math.cos(lat2)*math.cos(lon1-lon2) ) * R
Ejemplo n.º 29
0
def bird_blave(timestamp, place, tilt=0, azimuth=180, cloudCover=0.0):
    #SUN Position
    o = ephem.Observer()
    o.date = timestamp #'2000/12/21 %s:00:00' % (hour - self.tz)
    latitude, longitude = place
    o.lat = radians(latitude)
    o.lon = radians(longitude)
    az = ephem.Sun(o).az
    alt = ephem.Sun(o).alt

    #Irradiance
    day = dayOfYear(timestamp)
    record = {}
    record['utc_datetime'] = timestamp
    Z = pi/2-alt
    aaz = radians(azimuth+180)
    slope = radians(tilt)

    #incidence angle
    theta = arccos(cos(Z)*cos(slope) + \
            sin(slope)*sin(Z)*cos(az - pi - aaz))
    ETR = apparentExtraterrestrialFlux(day)
    #pressure?
    t, Bh, Gh = bird(theta, 1010.0)
    Dh = diffuseHorizontal(alt, Bh, day)

    record['DNI (W/m^2)'] = Bh #8 Direct normal irradiance
    record['GHI (W/m^2)'] = Gh #5 Global horizontal irradiance
    record['DHI (W/m^2)'] = Dh #11 Diffuse horizontal irradiance
    record['ETR (W/m^2)'] = ETR
    return record
Ejemplo n.º 30
0
    def eyelidServosPut(self,params):
        msg = JointState()
        msg.name = list()
        msg.position = list()
        msg.velocity = list()
        msg.effort = list()
        if params.has_key('leftEyelid_position'):
            msg.name.append('left_eyelid_joint') 
            msg.position.append(math.radians(float(params['leftEyelid_position'])-float(90)))
        if params.has_key('leftEyelid_speed'):
            #Anadir velocuidad
            msg.velocity.append(params['leftEyelid_speed'])
        else:
            msg.velocity.append(3.0)
        if params.has_key('rightEyelid_position'):
            msg.name.append('right_eyelid_joint')
            msg.position.append(math.radians(float(params['rightEyelid_position'])-float(90)))
        if params.has_key('rightEyelid_speed'):
            #Anadir velocuidad
            msg.velocity.append(params['rightEyelid_speed'])
        else:
            msg.velocity.append(3.0)

        msg.header.stamp = rospy.Time.now()
        self.cmd_joints_pub.publish(msg)
Ejemplo n.º 31
0
doc = App.newDocument("transformer")

# TANK
TL = 20; TW = 50; TH = 30
doc.addObject("Part::Box","tank")
doc.tank.Length = TL
doc.tank.Width = TW
doc.tank.Height = TH

# BUSHING
BA = 30  # angle between bushings in degrees
BR = 3   #radius
BH = 30 # height
BS = 10 # seperation distance between two bushings
BI = 3 # how far in bushing comes from the y-axis
BSIN = math.sin(math.radians(BA)) ; BCOS = math.cos(math.radians(BA))

doc.addObject("Part::Cylinder","centerBush")
doc.centerBush.Radius = BR
doc.centerBush.Height = BH
doc.centerBush.Placement = Placement(Base.Vector(BI+BR,TW/2,TH),Rotation(0,0,0))

doc.addObject("Part::Cylinder","leftBush")
doc.leftBush.Radius = BR
doc.leftBush.Height = BH
doc.leftBush.Placement = Placement(Base.Vector(BI+BR,TW/2-10-BR*BCOS,TH-BR*BSIN),Rotation(0,0,BA))

doc.addObject("Part::Cylinder","rightBush")
doc.rightBush.Radius = BR
doc.rightBush.Height = BH
doc.rightBush.Placement = Placement(Base.Vector(BI+BR,TW/2+10+BR*BCOS,TH-BR*BSIN),Rotation(0,0,360-BA))
Ejemplo n.º 32
0
 def __init__(self, toolhead, config):
     # Setup tower rails
     stepper_configs = [config.getsection('stepper_' + a) for a in 'abc']
     rail_a = stepper.PrinterRail(
         stepper_configs[0], need_position_minmax = False)
     a_endstop = rail_a.get_homing_info().position_endstop
     rail_b = stepper.PrinterRail(
         stepper_configs[1], need_position_minmax = False,
         default_position_endstop=a_endstop)
     rail_c = stepper.PrinterRail(
         stepper_configs[2], need_position_minmax = False,
         default_position_endstop=a_endstop)
     self.rails = [rail_a, rail_b, rail_c]
     config.get_printer().register_event_handler("stepper_enable:motor_off",
                                                 self._motor_off)
     # Setup stepper max halt velocity
     self.max_velocity, self.max_accel = toolhead.get_max_velocity()
     self.max_z_velocity = config.getfloat(
         'max_z_velocity', self.max_velocity,
         above=0., maxval=self.max_velocity)
     max_halt_velocity = toolhead.get_max_axis_halt() * SLOW_RATIO
     max_halt_accel = self.max_accel * SLOW_RATIO
     for rail in self.rails:
         rail.set_max_jerk(max_halt_velocity, max_halt_accel)
     # Read radius and arm lengths
     self.radius = radius = config.getfloat('delta_radius', above=0.)
     arm_length_a = stepper_configs[0].getfloat('arm_length', above=radius)
     self.arm_lengths = arm_lengths = [
         sconfig.getfloat('arm_length', arm_length_a, above=radius)
         for sconfig in stepper_configs]
     self.arm2 = [arm**2 for arm in arm_lengths]
     self.abs_endstops = [(rail.get_homing_info().position_endstop
                           + math.sqrt(arm2 - radius**2))
                          for rail, arm2 in zip(self.rails, self.arm2)]
     # Determine tower locations in cartesian space
     self.angles = [sconfig.getfloat('angle', angle)
                    for sconfig, angle in zip(stepper_configs,
                                              [210., 330., 90.])]
     self.towers = [(math.cos(math.radians(angle)) * radius,
                     math.sin(math.radians(angle)) * radius)
                    for angle in self.angles]
     for r, a, t in zip(self.rails, self.arm2, self.towers):
         r.setup_itersolve('delta_stepper_alloc', a, t[0], t[1])
     for s in self.get_steppers():
         s.set_trapq(toolhead.get_trapq())
         toolhead.register_step_generator(s.generate_steps)
     # Setup boundary checks
     self.need_home = True
     self.limit_xy2 = -1.
     self.home_position = tuple(
         self._actuator_to_cartesian(self.abs_endstops))
     self.max_z = min([rail.get_homing_info().position_endstop
                       for rail in self.rails])
     self.min_z = config.getfloat('minimum_z_position', 0, maxval=self.max_z)
     self.limit_z = min([ep - arm
                         for ep, arm in zip(self.abs_endstops, arm_lengths)])
     logging.info(
         "Delta max build height %.2fmm (radius tapered above %.2fmm)" % (
             self.max_z, self.limit_z))
     # Find the point where an XY move could result in excessive
     # tower movement
     half_min_step_dist = min([r.get_steppers()[0].get_step_dist()
                               for r in self.rails]) * .5
     min_arm_length = min(arm_lengths)
     def ratio_to_dist(ratio):
         return (ratio * math.sqrt(min_arm_length**2 / (ratio**2 + 1.)
                                   - half_min_step_dist**2)
                 + half_min_step_dist)
     self.slow_xy2 = (ratio_to_dist(SLOW_RATIO) - radius)**2
     self.very_slow_xy2 = (ratio_to_dist(2. * SLOW_RATIO) - radius)**2
     self.max_xy2 = min(radius, min_arm_length - radius,
                        ratio_to_dist(4. * SLOW_RATIO) - radius)**2
     logging.info("Delta max build radius %.2fmm (moves slowed past %.2fmm"
                  " and %.2fmm)" % (
                      math.sqrt(self.max_xy2), math.sqrt(self.slow_xy2),
                      math.sqrt(self.very_slow_xy2)))
     self.set_position([0., 0., 0.], ())
Ejemplo n.º 33
0
# C - : (Colon)

import math

A, B, H, M = map(int, input().split())

sub = abs(360 * ((H * 60 + M) / (12 * 60)) - 360 * (M / 60))
deg = min(sub, 360 - sub)
rad = math.radians(deg)

ans = (A**2) + (B**2) - (2 * A * B * math.cos(rad))

print(ans**(1 / 2))
Ejemplo n.º 34
0
import matplotlib.pyplot as plt
import numpy as np
import math

# -360 360
x = np.arange(math.radians(-360), math.radians(360), 0.1)
y = np.sin(x)
z = np.cos(x)

plt.plot(x, y, x, z)
plt.xlabel('x valores de -360º para 360º')
plt.ylabel('sin(x) e cos(x)')
plt.title('Gráfico de sin e cos de -360º to 360º')
plt.legend(['sin(x)', 'cos(x)'])
plt.show()
Ejemplo n.º 35
0
# Create an ASCII waveform

from time import sleep
from math import sin, cos, radians

# increase 40 to get more wave
for n in range(1, 40):
    circle_1 = 50 * (1 + sin(radians(n * 10)))
    circle_2 = 50 * (1 + cos(radians(n * 10)))
    print("#".center(int(circle_1)))
    print("*".center(int(circle_2)))
    sleep(0.05)
Ejemplo n.º 36
0
def sincos(degrees=0.0, radians=None):
    """ Rotation utility shortcut to compute sine and cosine of an angle. """
    radians = radians if radians else math.radians(degrees)
    return math.sin(radians), math.cos(radians)
Ejemplo n.º 37
0
from math import cos, sin, tan, radians

ângulo = float(input('Digite um ângulo em graus: '))

print('Seu cosseno vale {:.2f}.'.format(cos(radians(ângulo))))
print('Seu seno vale {:.2f}.'.format(sin(radians(ângulo))))
print('Sua tangente vale {:.2f}.'.format(tan(radians(ângulo))))
Ejemplo n.º 38
0
 def usdSceneItemRotation(item):
     prim = usdUtils.getPrimFromSceneItem(item)
     if not prim.HasAttribute('xformOp:rotateXYZ'):
         return proxyShapeXformFn.rotation(om.MSpace.kTransform)
     else:
         x,y,z = prim.GetAttribute('xformOp:rotateXYZ').Get()
         return  proxyShapeXformFn.rotation(om.MSpace.kTransform) + om.MEulerRotation(radians(x), radians(y), radians(z))
Ejemplo n.º 39
0
print('Path:')
path = nodes[endW][0]
for key in path:
    print(key + ': ' + str(waypoints[key][0]) + ', ' + str(waypoints[key][1]))

def normalize_turn(angle):
    while angle < -math.pi:
        angle += 2 * math.pi
    while angle > math.pi:
        angle -= 2 * math.pi
    return angle

print('Commands:')
# Move our heading such that East is 0 degrees.
heading = normalize_turn(math.radians(START_HEADING))
currentPos = START
totalDistance = 0
for key in path:
    x, y = waypoints[key]
    targetAngle = math.atan2(y - currentPos[1], x - currentPos[0])
    diffAngle = normalize_turn(heading - targetAngle)
    d = distance(currentPos, (x, y))
    currentPos = (x, y)
    heading = targetAngle
    # d should still be positive at this point, but just in case.
    totalDistance += abs(d)
    if (diffAngle > math.pi/2):
        diffAngle -= math.pi
        heading = normalize_turn(heading + math.pi)
        d = -d
Ejemplo n.º 40
0
def main(latitude, longitude, timeZone, locationName, years, months, days, hours, HOYs, srfArea, srfTiltD, srfAzimuthD, correctedSrfAzimuthD, directNormalRadiation, diffuseHorizontalRadiation, albedoL, precision, originOffset):
    
    # TOF mesh Tilt, Azimuth values
    srfTiltTOFList = []
    srfAzimuthTOFList = []
    stepSrfTilt = 90/precision
    stepSrfAzimuth = 180/precision
    if anglesClockwise == True:  # angles clockwise
        for i in range(0,precision+1,1):
            srfTiltTOFList.append(stepSrfTilt*i)
        if latitude >= 0:
            for i in range(precision,-1,-1):
                srfAzimuthTOFList.append(90+stepSrfAzimuth*i)
        elif latitude < 0:
            for i in range(0,precision+1,1):
                srfAzimuth = 270+stepSrfAzimuth*i
                if srfAzimuth >= 360:
                    srfAzimuth = srfAzimuth-360
                srfAzimuthTOFList.append(srfAzimuth)
    elif anglesClockwise == False:  # angles counterclockwise
        for i in range(0,precision+1,1):
            srfTiltTOFList.append(stepSrfTilt*i)
        if latitude >= 0:
            for i in range(0,precision+1,1):
                srfAzimuthTOFList.append(90+stepSrfAzimuth*i)
        elif latitude < 0:
            for i in range(precision,-1,-1): 
                srfAzimuth = 270+stepSrfAzimuth*i
                if srfAzimuth >= 360:
                    srfAzimuth = srfAzimuth-360
                srfAzimuthTOFList.append(srfAzimuth)
    
    # TOF mesh generation (mesh width = 80, mesh height = 45)
    meshPtStepU = 80/(len(srfAzimuthTOFList)-1)
    meshPtStepV = 45/(len(srfTiltTOFList)-1)
    
    meshPts = []
    meshLiftedPts = []
    totalRadiationPerYearL = []
    for i,srfTiltTOF in enumerate(srfTiltTOFList):
        for k,srfAzimuthTOF in enumerate(srfAzimuthTOFList):
            totalRadiationPerYear = 0
            for g,hoy in enumerate(HOYs):
                sunZenithD, sunAzimuthD, sunAltitudeD = lb_photovoltaics.NRELsunPosition(latitude, longitude, timeZone, years[hoy-1], months[hoy-1], days[hoy-1], hours[hoy-1]-1)
                Epoa, Eb, Ed_sky, Eground, AOI_R = lb_photovoltaics.POAirradiance(sunZenithD, sunAzimuthD, srfTiltTOF, srfAzimuthTOF, directNormalRadiation[hoy-1], diffuseHorizontalRadiation[hoy-1], albedoL[hoy-1])
                totalRadiationPerYear += Epoa  # in Wh/m2
            totalRadiationPerYearL.append(totalRadiationPerYear)
    
    # iterate "srfTiltTOFList" and "srfAzimuthTOFList" one more time, now that "totalRadiationPerYearL" has been generated: to find "meshPts", "liftedMeshPts"
    totalRadiationPerYear_index = 0
    for i,srfTiltTOF in enumerate(srfTiltTOFList):
        for k,srfAzimuthTOF in enumerate(srfAzimuthTOFList):
            normalized_totalRadiationPerYear = (totalRadiationPerYearL[totalRadiationPerYear_index] - min(totalRadiationPerYearL)) / (max(totalRadiationPerYearL) - min(totalRadiationPerYearL))  # normalizes each totalRadiationPerYear value from 0 to 1
            if anglesClockwise == True:  # angles clockwise
                meshPt = Rhino.Geometry.Point3d(originOffset.X + meshPtStepU*k, originOffset.Y + meshPtStepV*i, originOffset.Z)
                liftedMeshPt = Rhino.Geometry.Point3d(originOffset.X + meshPtStepU*k, originOffset.Y + meshPtStepV*i, originOffset.Z + (normalized_totalRadiationPerYear*100))  # lift each meshPt.Z coordinate by "normalized_totalRadiationPerYear*100"
            elif anglesClockwise == False:  # angles counterclockwise
                meshPt = Rhino.Geometry.Point3d(originOffset.X + meshPtStepU*k, originOffset.Y + meshPtStepV*i, originOffset.Z)
                liftedMeshPt = Rhino.Geometry.Point3d(originOffset.X + meshPtStepU*k, originOffset.Y + meshPtStepV*i, originOffset.Z + (normalized_totalRadiationPerYear*100))  # lift each meshPt.Z coordinate by "normalized_totalRadiationPerYear*100"
            meshPts.append(meshPt)
            meshLiftedPts.append(liftedMeshPt)
            totalRadiationPerYear_index += 1
    
    
    lowB, highB, numSeg, customColors, legendBasePoint, legendScale, legendFont, legendFontSize, legendBold, decimalPlaces, removeLessThan = lb_preparation.readLegendParameters(legendPar, False)
    colors = lb_visualization.gradientColor(totalRadiationPerYearL, lowB, highB, customColors)
    
    mesh = lb_meshpreparation.meshFromPoints(precision+1, precision+1, meshPts, colors)
    meshLifted = lb_meshpreparation.meshFromPoints(precision+1, precision+1, meshLiftedPts, [])
    
    maximalTotalRadiationPerYear = max(totalRadiationPerYearL)
    minimalTotalRadiationPerYear = min(totalRadiationPerYearL)
    percents = [(totalRadiationPerYear/maximalTotalRadiationPerYear)*100 for totalRadiationPerYear in totalRadiationPerYearL]
    percentsAndPts = [((totalRadiationPerYear/maximalTotalRadiationPerYear)*100, meshLiftedPts[i]) for i,totalRadiationPerYear in enumerate(totalRadiationPerYearL)]
    minimalPercent = min(percents)
    maximalPercent = max(percents)  # always 100
    percentsAndPts.sort()
    minimalPt = percentsAndPts[0][1]
    maximalPt = percentsAndPts[-1][1]
    
    
    # isoCrvs
    planesAxisLine = Rhino.Geometry.Line(Rhino.Geometry.Point3d(0, 0, minimalPt.Z), Rhino.Geometry.Point3d(0, 0, maximalPt.Z))
    planesAxisCrv = Rhino.Geometry.Line.ToNurbsCurve(planesAxisLine)
    newDomain = Rhino.Geometry.Interval(minimalPercent, maximalPercent)
    planesAxisCrv.Domain = newDomain
    
    isoCrvPlanes = []
    isoCrvPercents = []
    projectedIsoCrvs = []
    tol = Rhino.RhinoDoc.ActiveDoc.ModelAbsoluteTolerance
    percents10 = [10,20,30,40,50,60,70,80,90,94,96,98,99]
    for p in percents10:
        if (p >= minimalPercent) and (p <= maximalPercent):
            plane = Rhino.Geometry.Plane( Rhino.Geometry.Point3d(planesAxisCrv.PointAt(p)), Rhino.Geometry.Vector3d(0,0,1) )
            isoCrvPlanes.append(plane)
            isoCrvPercents.append(p)
            isoPolylinesSublist = Rhino.Geometry.Intersect.Intersection.MeshPlane(meshLifted, plane)
            isoCrvsSubList = [Rhino.Geometry.Polyline.ToNurbsCurve(polyline) for polyline in isoPolylinesSublist]
            joinedIsoCrvsSubList = Rhino.Geometry.Curve.JoinCurves(isoCrvsSubList, tol)
            projectedIsoCrvsSubList = [Rhino.Geometry.Curve.ProjectToPlane(crv, Rhino.Geometry.Plane(Rhino.Geometry.Point3d(originOffset), Rhino.Geometry.Vector3d(0,0,1))) for crv in joinedIsoCrvsSubList]
            projectedIsoCrvs.append(projectedIsoCrvsSubList)
    # last (100%) isoCrv
    plane = Rhino.Geometry.Plane( Rhino.Geometry.Point3d(planesAxisCrv.PointAt(100-tol)), Rhino.Geometry.Vector3d(0,0,1) )
    lastIsoPolylines = Rhino.Geometry.Intersect.Intersection.MeshPlane(meshLifted, plane)
    lastIsoCrvs = [Rhino.Geometry.Polyline.ToNurbsCurve(polyline) for polyline in lastIsoPolylines]
    joinedLastIsoCrvs = Rhino.Geometry.Curve.JoinCurves(lastIsoCrvs, tol)
    projectedLastIsoCrvs = [Rhino.Geometry.Curve.ProjectToPlane(crv, Rhino.Geometry.Plane(Rhino.Geometry.Point3d(originOffset), Rhino.Geometry.Vector3d(0,0,1))) for crv in joinedLastIsoCrvs]
    
    
    # optimal Tilt, Azimuth
    planarMeshAboveLiftedPts = [Rhino.Geometry.Point3d(pt.X, pt.Y, maximalPt.Z+10) for pt in meshLiftedPts]
    planarMeshAboveLifted = lb_meshpreparation.meshFromPoints(precision+1, precision+1, planarMeshAboveLiftedPts, [])
    
    def meshesClosesPts(startingPt, mesh1, mesh2):
        pt1 = startingPt
        for k in range(300):
        #for k in range(3000):
            pt2 = mesh2.ClosestMeshPoint(pt1,0.0).Point
            pt1 = mesh1.ClosestMeshPoint(pt2,0.0).Point
        return pt1
    
    if latitude >= 0:
        azimuthMeshStartValue = 90
    elif latitude < 0:
        azimuthMeshStartValue = 270
    meshLiftedCentroid = Rhino.Geometry.AreaMassProperties.Compute(meshLifted).Centroid
    optimalPt = meshesClosesPts(meshLiftedCentroid, meshLifted, planarMeshAboveLifted)
    
    if anglesClockwise == True:  # clockwise
        if latitude >= 0:
            optimalAzimuthD = round( 180-((optimalPt.X-originOffset.X) *180/80)+azimuthMeshStartValue, 1 )
        elif latitude < 0:
            optimalAzimuthD = round((180*(optimalPt.X - originOffset.X)/80 + azimuthMeshStartValue), 1)
            if optimalAzimuthD >= 360:
                optimalAzimuthD = optimalAzimuthD-360
    elif anglesClockwise == False:  # counterclockwise
        if latitude >= 0:
            optimalAzimuthD = round(((optimalPt.X-originOffset.X) *180/80)+azimuthMeshStartValue, 1 )
        elif latitude < 0:
            optimalAzimuthD = round(180-((optimalPt.X-originOffset.X) *180/80)+azimuthMeshStartValue, 1 )
            if optimalAzimuthD >= 360:
                optimalAzimuthD = optimalAzimuthD-360
    optimalTiltD = round(90*(optimalPt.Y - originOffset.Y)/45,1)
    
    # optimalRoofPitch
    optimalTiltTangent = math.tan(math.radians(optimalTiltD))
    optimalTiltNumerator = round(12*optimalTiltTangent,2)
    if optimalTiltNumerator % 1 == 0:
        optimalTiltNumerator = int(optimalTiltNumerator)
    optimalRoofPitch = "%s/12" % optimalTiltNumerator
    
    # analysisPt ("originOffset.Z+tol" due to overlap with "mesh")
    if anglesClockwise == True:  # clockwise
        if latitude >= 0:
            oppositeOriginOffset = Rhino.Geometry.Point3d(originOffset.X+15+80+15, originOffset.Y, originOffset.Z)
            analysisPt = Rhino.Geometry.Point3d( (oppositeOriginOffset.X-15-15) -((srfAzimuthD-azimuthMeshStartValue)*80/180), originOffset.Y+srfTiltD*45/90, originOffset.Z+tol)
        elif latitude < 0:
            if (srfAzimuthD >= 0) and  (srfAzimuthD < 270):
                srfAzimuthD = srfAzimuthD + 360
            analysisPt = Rhino.Geometry.Point3d(((srfAzimuthD-azimuthMeshStartValue)*80/180)+originOffset.X, originOffset.Y+srfTiltD*45/90, originOffset.Z+tol)
    elif anglesClockwise == False:  # counterclockwise
        if latitude >= 0:
            analysisPt = Rhino.Geometry.Point3d(((srfAzimuthD-azimuthMeshStartValue)*80/180)+originOffset.X, originOffset.Y+srfTiltD*45/90, originOffset.Z+tol)
        elif latitude < 0:
            if (srfAzimuthD >= 0) and  (srfAzimuthD <= 90):
                srfAzimuthD = srfAzimuthD + 360
            oppositeOriginOffset = Rhino.Geometry.Point3d(originOffset.X+15+80+15, originOffset.Y, originOffset.Z)
            analysisPt = Rhino.Geometry.Point3d( (oppositeOriginOffset.X-15-15) -((srfAzimuthD-azimuthMeshStartValue)*80/180), originOffset.Y+srfTiltD*45/90, originOffset.Z+tol)
    
    # totalRadiationPerYear of the inputted (analysed) surface
    totalRadiationPerYear = 0
    for i,hoy in enumerate(HOYs):
        sunZenithD, sunAzimuthD, sunAltitudeD = lb_photovoltaics.NRELsunPosition(latitude, longitude, timeZone, years[i], months[i], days[i], hours[i]-1)
        Epoa, Eb, Ed_sky, Eground, AOI_R = lb_photovoltaics.POAirradiance(sunZenithD, sunAzimuthD, srfTiltD, srfAzimuthD, directNormalRadiation[i], diffuseHorizontalRadiation[i], albedoL[i])
        totalRadiationPerYear += Epoa  # in Wh/m2
    
    # TOF, TSRF of the inputted (analysed) surface
    TOF = round((totalRadiationPerYear/maximalTotalRadiationPerYear)*100 ,1)  # in percent
    if TOF > 100:
        TOF = 100
    TSRF = round(TOF * ((100-annualShading)/100) ,1)  # in percent
    
    return totalRadiationPerYearL, int(maximalTotalRadiationPerYear/1000), int(totalRadiationPerYear/1000), meshPts, mesh, projectedIsoCrvs, projectedLastIsoCrvs, isoCrvPercents, optimalAzimuthD, optimalTiltD, optimalRoofPitch, analysisPt, TOF, TSRF
Ejemplo n.º 41
0
# -*- coding: utf-8 -*-
import requests
import re
from bs4 import BeautifulSoup
import pandas as pd
import time
import math
import datetime

cy = math.radians(37.62209300000001)
cx = math.radians(55.75399399999374)


def html_stripper(text):
    return re.sub('<[^<]+?>', '', str(text))


def n_stripper(text):
    return re.sub('\n', '', str(text))


def _stripper(text):
    return re.sub(' ', '', str(text))


def getPrice(flat_page):
    price = flat_page.find('div', attrs={'class': 'object_descr_price'})
    price = re.split('<div>|руб|\W', str(price))
    price = "".join([i for i in price if i.isdigit()][-3:])
    return price
def main(genCumSkyResult, horAngleStep, verAngleStep, horScale, verScale, north, centerPoint, legendPar, bakeIt):
    # import the classes
    if sc.sticky.has_key('ladybug_release'):
        try:
            if not sc.sticky['ladybug_release'].isCompatible(ghenv.Component): return -1
            if sc.sticky['ladybug_release'].isInputMissing(ghenv.Component): return -1
        except:
            warning = "You need a newer version of Ladybug to use this compoent." + \
            "Use updateLadybug component to update userObjects.\n" + \
            "If you have already updated userObjects drag Ladybug_Ladybug component " + \
            "into canvas and try again."
            w = gh.GH_RuntimeMessageLevel.Warning
            ghenv.Component.AddRuntimeMessage(w, warning)
            return -1
        lb_preparation = sc.sticky["ladybug_Preparation"]()
        lb_visualization = sc.sticky["ladybug_ResultVisualization"]()
        TregenzaPatchesNormalVectors = lb_preparation.TregenzaPatchesNormalVectors
        conversionFac = lb_preparation.checkUnits()
        
        # check the input data
        warn = "Please provide a valid selctedSkyMtx!"
        try:
            if genCumSkyResult[2][:11] == 'Sky Patches':
                checkData = True
            else:
                checkData = False
                w = gh.GH_RuntimeMessageLevel.Warning
                ghenv.Component.AddRuntimeMessage(w, warn)
                print warn
                return -1
        except Exception, e:
            w = gh.GH_RuntimeMessageLevel.Warning
            ghenv.Component.AddRuntimeMessage(w, warn)
            checkData = False
            print warn
            return -1
            
        
        if checkData:
            # separate the data
            indexList, listInfo = lb_preparation.separateList(genCumSkyResult, lb_preparation.strToBeFound)
            selList = []
            [selList.append(float(x)) for x in genCumSkyResult[indexList[0]+7:indexList[1]]]
            genCumSkyResult = selList
            
            if indexList[-1] == 456: patchesNormalVectors = lb_preparation.TregenzaPatchesNormalVectors
            elif indexList[-1] == 1752: patchesNormalVectors = lb_preparation.getReinhartPatchesNormalVectors()
            
            
            # check the scale
            try:
                if float(horScale)!=0:
                    try: horScale = float(horScale)/conversionFac
                    except: horScale = 1/conversionFac
                else:
                    horScale = 1/conversionFac
            except:
                horScale = 1/conversionFac
            
            horScale = horScale * .2
            
            try:
                if float(verScale) >= 0:
                    try: verScale = float(verScale) * 1/conversionFac
                    except: verScale = 1/conversionFac
                else:
                    verScale = 1/conversionFac
            except:
                verScale = 1/conversionFac
            
            verScale= .1*verScale

            cenPt = lb_preparation.getCenPt(centerPoint)
            
            if not horAngleStep or int(horAngleStep) < 5: horAngleStep = 10
            elif int(horAngleStep)> 90: horAngleStep = 90
            else:
                try: horAngleStep = int(horAngleStep)
                except: horAngleStep = 10
            
            if not verAngleStep or int(verAngleStep) < 5: verAngleStep = 10
            elif int(verAngleStep)> 90: verAngleStep = 90
            else:
                try: verAngleStep = int(verAngleStep)
                except: verAngleStep = 10
            
            
            # find the range of angles 
            
            roseHAngles = rs.frange(0, 360, horAngleStep)
            roseVAngles = rs.frange(0, 90, verAngleStep)
            
            if round(roseHAngles[-1]) == 360: roseHAngles.remove(roseHAngles[-1])
            if round(roseVAngles[-1]) > 90: roseVAngles.remove(roseVAngles[-1])
            elif round(roseVAngles[-1]) < 90: roseVAngles.append(90)
            
            hRotationVectors = [];
            northAngle, northVector = lb_preparation.angle2north(north)
            eastVector = rc.Geometry.Vector3d(northVector); eastVector.Rotate(math.radians(-90), rc.Geometry.Vector3d.ZAxis)
            # print eastVector
            
            def radiationForVector(vec, genCumSkyResult, TregenzaPatchesNormalVectors = lb_preparation.TregenzaPatchesNormalVectors):
                radiation = 0; patchNum = 0;
                for patchNum, patchVec in enumerate(TregenzaPatchesNormalVectors):
                    vecAngle = rs.VectorAngle(patchVec, vec)
                    if  vecAngle < 90:
                        radiation = radiation + genCumSkyResult[patchNum] * math.cos(math.radians(vecAngle))
                return radiation
            
            pts = []
            ptsClean = [] # clean points doesn't have the first point of the loop at the end
            testPtsInfos = []
            testPtsVectors = []
            resultsFlatten = []
            radResult = []
            [pts.append([]) for a in range(len(roseVAngles))]
            [radResult.append([]) for a in range(len(roseVAngles))]
            
            for angleCount, angle in enumerate(roseVAngles):
                vectorVRotated = rc.Geometry.Vector3d(northVector)
                
                # rotate vertically
                vectorVRotated.Rotate(math.radians(angle), eastVector)
                
                for hAngle in roseHAngles:
                    hVector = rc.Geometry.Vector3d(vectorVRotated)
                    hVector.Rotate(-math.radians(hAngle), rc.Geometry.Vector3d.ZAxis)
                    
                    # calculate radiation for each vector
                    radiation = radiationForVector(hVector, genCumSkyResult, patchesNormalVectors)
                    radResult[angleCount].append(radiation)
                    resultsFlatten.append(radiation)
                    
                    # create the horizontal moving vector
                    movingVector = rc.Geometry.Vector3d(northVector)
                    movingVector.Rotate(-math.radians(hAngle), rc.Geometry.Vector3d.ZAxis)
                    movingVector = 100 * (angleCount + 1) * horScale * movingVector
                    
                    #Check the dome or the mesh and see what should be done with the z-scale
                    if domeOrLily_:
                        #User has requested a dome.
                        vertVector = rc.Geometry.Vector3d(vectorVRotated.X, vectorVRotated.Y, vectorVRotated.Z)
                        vertVector = rc.Geometry.Vector3d.Multiply(vertVector, 1000 * horScale)
                        pt = rc.Geometry.Point3d.Add(cenPt, vertVector)
                        pointRotation = rc.Geometry.Transform.Rotation(northVector, movingVector, cenPt)
                        pt.Transform(pointRotation)
                        pts[angleCount].append(pt)
                        ptsClean.append(pt)
                    else:
                        #User has requested a lilly
                        pt = rc.Geometry.Point3d.Add(cenPt, movingVector)
                        verticalMove = radiation * verScale * rc.Geometry.Vector3d.ZAxis
                        pt = rc.Geometry.Point3d.Add(pt, verticalMove)
                        pts[angleCount].append(pt)
                        ptsClean.append(pt)
                    
                    testPtsInfo = "%.2f"%radiation + ' ' + listInfo[0][3] + '\nHRA='+ `hAngle` + '; VRA=' + `90-angle`
                    testPtsInfos.append(testPtsInfo)
                    testPtsVectors.append(hVector)
                    
                radResult[angleCount].append(radResult[angleCount][0])
                # resultsFlatten.append(radResult[angleCount][0])
                pts[angleCount].append(pts[angleCount][0])
            
            overwriteScale = False
            if legendPar == []: overwriteScale = True
            elif legendPar[-1] == None: overwriteScale = True
            
            # generate the colors
            lowB, highB, numSeg, customColors, legendBasePoint, legendScale, legendFont, legendFontSize, legendBold, decimalPlaces, removeLessThan = lb_preparation.readLegendParameters(legendPar, False)
            
            if overwriteScale: legendScale = 0.85
            
            
            values = []
            # generate the mesh
            vaseMesh = rc.Geometry.Mesh()
            for vStep in range(len(roseVAngles)):
                
                if vStep!=0:
                    for ptCount, pt in enumerate(pts[vStep]):
                        try:
                            singleMesh = rc.Geometry.Mesh()
                            pt1 = pts[vStep-1][ptCount]
                            value1 = radResult[vStep-1][ptCount-1]
                            pt2 = pts[vStep][ptCount]
                            value2 = radResult[vStep][ptCount-1]
                            pt3 = pts[vStep-1][ptCount + 1]
                            value3 = radResult[vStep][ptCount]
                            pt4 = pts[vStep][ptCount + 1]
                            value4 = radResult[vStep-1][ptCount]
                            singleMesh.Vertices.Add(pt1)
                            singleMesh.Vertices.Add(pt2)
                            singleMesh.Vertices.Add(pt3)
                            singleMesh.Vertices.Add(pt4)
                            singleMesh.Faces.AddFace(0, 1, 3, 2)
                            values.append([value1, value2, value4, value3])
                            vaseMesh.Append(singleMesh)
                        except:
                            pass
        
            
            values = lb_preparation.flattenList(values)
            # color the mesh
            meshColors = lb_visualization.gradientColor(values, lowB, highB, customColors)
            
            # make a monotonemesh
            vaseMesh.VertexColors.CreateMonotoneMesh(System.Drawing.Color.White)
            
            #color the mesh based on the results
            for vertices in range (vaseMesh.Vertices.Count):
                vaseMesh.VertexColors[vertices] = meshColors[vertices]
            
            #Flip the mesh so that it always appears correctly in Rhino Display.
            if not domeOrLily_:
                vaseMesh.Flip(True, True, True)
            
            maxHorRadius = 100 * (angleCount + 1) * horScale
            tempCompassCrv = rc.Geometry.Circle(cenPt, 1.1*maxHorRadius).ToNurbsCurve()
            lb_visualization.calculateBB([vaseMesh, tempCompassCrv], True)
            
            # get the legend done
            legendSrfs, legendText, legendTextCrv, textPt, textSize = lb_visualization.createLegend(resultsFlatten
                    , lowB, highB, numSeg, listInfo[0][3], lb_visualization.BoundingBoxPar, legendBasePoint, legendScale, legendFont, legendFontSize, legendBold, decimalPlaces, removeLessThan)
            
            # generate legend colors
            legendColors = lb_visualization.gradientColor(legendText[:-1], lowB, highB, customColors)
            
            # color legend surfaces
            legendSrfs = lb_visualization.colorMesh(legendColors, legendSrfs)
            
            # title
            customHeading = '\n\nRadiation Calla Lily (' + listInfo[0][3] + ')'
            titleTextCurve, titleStr, titlebasePt = lb_visualization.createTitle(listInfo, lb_visualization.BoundingBoxPar, legendScale, customHeading, False, legendFont, legendFontSize, legendBold)
            
            if not domeOrLily_: cenPtMoved = rc.Geometry.Point3d.Add(cenPt, 0.9*lb_visualization.BoundingBoxPar[3]*rc.Geometry.Vector3d.ZAxis)
            else: cenPtMoved = cenPt
            compassCrvs, compassTextPts, compassText = lb_visualization. compassCircle(cenPtMoved, northVector, maxHorRadius, roseHAngles, 1.2*textSize)
            numberCrvs = lb_visualization.text2srf(compassText, compassTextPts, 'Times New Romans', textSize/1.2)
            compassCrvs = compassCrvs + lb_preparation.flattenList(numberCrvs)
            
            
            # bake
            if bakeIt > 0:
                #Put all of the curves together.
                finalCrvs = []
                for crv in compassCrvs:
                    try:
                        testPt = crv.PointAtEnd
                        finalCrvs.append(crv)
                    except: pass
                
                #Put all of the text together.
                legendText.append(titleStr)
                textPt.append(titlebasePt)
                legendText.extend(compassText)
                textPt.extend(compassTextPts)
                # check the study type
                placeName = listInfo[0][1]
                studyLayerName = 'RADIATION_LILLY'
                stMonth, stDay, stHour, endMonth, endDay, endHour = lb_visualization.readRunPeriod((listInfo[0][5], listInfo[0][6]), False)
                period = `stDay`+ ' ' + lb_visualization.monthList[stMonth-1] + ' ' + `stHour` + \
                 " - " + `endDay`+ ' ' + lb_visualization.monthList[endMonth-1] + ' ' + `endHour` 
                newLayerIndex, l = lb_visualization.setupLayers(period, 'LADYBUG', placeName, studyLayerName, False, False, 0, 0)
                
                if bakeIt == 1: lb_visualization.bakeObjects(newLayerIndex, vaseMesh, legendSrfs, legendText, textPt, textSize, legendFont, finalCrvs, decimalPlaces, True)
                else: lb_visualization.bakeObjects(newLayerIndex, vaseMesh, legendSrfs, legendText, textPt, textSize, legendFont, finalCrvs, decimalPlaces, False)
            
            #Find the max value and vector.
            maxValue = max(resultsFlatten)
            i = resultsFlatten.IndexOf(maxValue)
            maxRadPt = ptsClean[i]
            maxRadInfo = testPtsInfos[i]
            maxPtVec = testPtsVectors[i]
            
        return ptsClean, vaseMesh, [legendSrfs, lb_preparation.flattenList(legendTextCrv + titleTextCurve)], resultsFlatten, testPtsInfos, compassCrvs, maxRadPt, maxRadInfo, maxPtVec
Ejemplo n.º 43
0
 def build_rotation(self):
     objects = bpy.data.objects
     parent_object = objects["Parent Object"]
     parent_object.rotation_mode = 'XYZ'
     parent_object.delta_rotation_euler.rotate_axis(
         self.config.rotation_axis, radians(self.rotation))
Ejemplo n.º 44
0
df.isna().sum()

df.dtypes
##################################################################
# FEATURE ENGINEERING #
##################################################################

### Creating Feature With  Latitude ans Longitude Using  || HAVERSINE FORMULA ||

df['Lati'] = pd.to_numeric(df['Lati'], errors='coerce')
df['Longi'] = pd.to_numeric(df['Longi'], errors='coerce')

import math
df['LAT_rad'], df['LON_rad'] = np.radians(df['Lati']), np.radians(df['Longi'])
df['dLON'] = df['LON_rad'] - math.radians(-56.7213600)
df['dLAT'] = df['LAT_rad'] - math.radians(37.2175900)
df['distance'] = 6367 * 2 * np.arcsin(
    np.sqrt(
        np.sin(df['dLAT'] / 2)**2 + math.cos(math.radians(37.2175900)) *
        np.cos(df['LAT_rad']) * np.sin(df['dLON'] / 2)**2))

df['Vehicle.Class'] = pd.get_dummies(df['Vehicle.Class'])
df['Sales.Channel'] = pd.get_dummies(df['Sales.Channel'])
df['Renew.Offer.Type'] = pd.get_dummies(df['Renew.Offer.Type'])
df['Policy'] = pd.get_dummies(df['Policy'])
df['Policy.Type'] = pd.get_dummies(df['Policy.Type'])
df['Marital.Status'] = pd.get_dummies(df['Marital.Status'])
df['Gender'] = pd.get_dummies(df['Gender'])
df['EmploymentStatus'] = pd.get_dummies(df['EmploymentStatus'])
df['Location.Code'] = pd.get_dummies(df['Location.Code'])
Ejemplo n.º 45
0
#!/usr/bin/env python

import pylab as plt
from pylab import plot,show, scatter
from scipy.cluster.vq import *
import numpy
import math

plt.figure(1)
xp,yp,xt,yt = 0,50,0,0
for i in range(0,360):
	xe = 50*(2*math.cos(math.radians(i))-math.sin(2*math.radians(i)))
	ye = 50*(math.cos(2*math.radians(i))-2*math.sin(math.radians(i)))
	if (xe-xp) == 0:
		xe = 0.00001
	s = (ye-yp)/(xe-xp)
	ym = (ye+yp)/2
	xm = (xe+xp)/2
	xi = (s*(ym-yt)+(s*s)*xt+xm)/((s*s)+1)
	yi = yt-s*xt+s*xi
	plot(xe, ye, 'or')
	plot(xi, yi, 'ok')
plot(0,0, 'ob')
plot(0,50, 'oy')
plt.axis([-160, 160, -160, 160])
show()
Ejemplo n.º 46
0
    def move(self):
        # odbicie
        if self.rect.colliderect(self.disc.rect) and self.dy > 0:
            b_pos = self.rect.width + self.rect.left - self.disc.rect.left - 1
            b_max = self.rect.width + self.disc.rect.width - 2
            fac = float(b_pos) / b_max
            ang = math.radians(const.ang_h - fac * (const.ang_h - const.ang_l))
            self.dx = const.b_speed * math.cos(ang)
            self.dy = -const.b_speed * math.sin(ang)

        #poruszamnie
        self.x = self.x + self.dx
        self.y = self.y + self.dy
        self.setint()

        #odbicie od ścian
        if self.rect.left < self.board.rect.left:
            self.rect.left = self.board.rect.left
            self.dx = -self.dx

        if self.rect.right > self.board.rect.right:
            self.rect.right = self.board.rect.right
            self.dx = -self.dx

        if self.rect.top < self.board.rect.top:
            self.rect.top = self.board.rect.top
            self.dy = -self.dy

        if self.rect.top > self.board.rect.bottom:
            self.update = self.start
            self.live -= 1

        sound = const.load_sound('bomb.wav')

        kost2 = pygame.sprite.spritecollide(self, self.net2,
                                            False)  #nie da się zniszczyć
        if kost2:
            for k2 in kost2:

                if self.rect.top > k2.rect.top:
                    self.rect.top = k2.rect.top
                    self.dy = -self.dy

                if self.rect.bottom < k2.rect.bottom:
                    self.rect.bottom = k2.rect.bottom
                    self.dy = -self.dy

                if self.rect.left < k2.rect.left:
                    self.rect.left = k2.rect.left
                    self.dx = -self.dx

                if self.rect.right > k2.rect.right:
                    self.rect.right = k2.rect.right
                    self.dx = -self.dx

        kost3 = pygame.sprite.spritecollide(self, self.net3, False)  # bonusy
        if kost3:
            oldrect = self.rect
            left = right = up = down = 0
            for k3 in kost3:
                if oldrect.top < k3.rect.top < oldrect.bottom < k3.rect.bottom:
                    self.rect.bottom = k3.rect.top
                    self.setint()
                    up = -1

                if k3.rect.top < oldrect.top < k3.rect.bottom < oldrect.bottom:
                    self.rect.top = k3.rect.bottom
                    self.setint()
                    down = 1

                if oldrect.left < k3.rect.left < oldrect.right < k3.rect.right:
                    self.rect.right = k3.rect.left
                    self.setint()
                    left = -1

                if k3.rect.left < oldrect.left < k3.rect.right < oldrect.right:
                    self.rect.left = k3.rect.right
                    self.setint()
                    right = 1

                k3.kill()
                nr1 = random.choice(range(1, 7, 1))
                bon = Bonus(self.disc, nr1)
                self.start_bonus = bon

        kost = pygame.sprite.spritecollide(self, self.net, False)
        if kost:
            oldrect = self.rect
            left = right = up = down = 0
            for k in kost:

                if oldrect.top < k.rect.top < oldrect.bottom < k.rect.bottom:
                    self.rect.bottom = k.rect.top
                    self.setint()
                    up = -1

                if k.rect.top < oldrect.top < k.rect.bottom < oldrect.bottom:
                    self.rect.top = k.rect.bottom
                    self.setint()
                    down = 1

                if oldrect.left < k.rect.left < oldrect.right < k.rect.right:
                    self.rect.right = k.rect.left
                    self.setint()
                    left = -1

                if k.rect.left < oldrect.left < k.rect.right < oldrect.right:
                    self.rect.left = k.rect.right
                    self.setint()
                    right = 1

                sound.play()
                self.count2 += 1
                k.kill()

            # odbicie od kostek
            if left + right != 0:
                self.dx = (left + right) * abs(self.dx)
            if up + down != 0:
                self.dy = (up + down) * abs(self.dy)
Ejemplo n.º 47
0
    def detect(self, sender: Device, img: np.ndarray,
               plate_angles: Vector2) -> CircleFeature:
        if img is not None:
            # covert to HSV space
            color = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)

            # 0 == red
            if self.config.hue is None:
                self.config.hue = 0

            # run through each triplet and perform our masking filter on it.
            # hue_mask coverts the hsv image into a grayscale image with a
            # bandpass applied centered around hue, with width sigma
            hue_mask(
                color,
                self.config.hue,
                self.config.sigma,
                self.config.bandpassGain,
                self.config.maskGain,
            )

            # convert to b&w mask from grayscale image
            mask = cv2.inRange(color, np.array((200, 200, 200)),
                               np.array((255, 255, 255)))

            # expand b&w image with a dialation filter
            mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, self.kernel)

            contours = cv2.findContours(mask, cv2.RETR_EXTERNAL,
                                        cv2.CHAIN_APPROX_SIMPLE)[-2]

            if len(contours) > 0:
                contour_peak = max(contours, key=cv2.contourArea)
                ((self.x_obs, self.y_obs),
                 radius) = cv2.minEnclosingCircle(contour_peak)

                # Determine if ball size is the appropriate size
                frameSize = sender.sensor.config.height
                norm_radius = radius / frameSize
                if self.config.ballMin < norm_radius < self.config.ballMax:
                    counter.update("hit", 1, FrequencyCounter)

                    # rotate the center coords into sensor coords
                    # the ball detector uses rotate coordinates, so we must as well
                    rot_center = Vector2(
                        self.calibration.plateXOffset,
                        self.calibration.plateYOffset).rotate(
                            math.radians(-self.calibration.rotation))

                    x_center = (rot_center.x + 0.5) * frameSize
                    y_center = (rot_center.y + 0.5) * frameSize

                    # Convert from pixels to absolute with 0,0 as center of detected plate
                    x = self.x_obs - x_center
                    y = self.y_obs - y_center
                    self.lastDetected = CircleFeature(Vector2(x, y), radius)
                    return self.lastDetected
                else:
                    counter.update("miss", 1, FrequencyCounter)

            counter.update("hit", 0, FrequencyCounter)
            counter.update("miss", 0, FrequencyCounter)

        return CircleFeature()
Ejemplo n.º 48
0
def rotate_point(x, y, heading_deg):
    c = math.cos(math.radians(heading_deg))
    s = math.sin(math.radians(heading_deg))
    xr = x * c + y * -s
    yr = x * s + y * c
    return xr, yr
    def digitalize(self, obs):
        upper_bounds = [env.observation_space.high[0], 0.5, env.observation_space.high[2], math.radians(50)]
        lower_bounds = [env.observation_space.low[0], -0.5, env.observation_space.low[2], -math.radians(50)]
        ratios = [(obs[i] + abs(lower_bounds[i])) / (upper_bounds[i] - lower_bounds[i]) for i in range(len(obs))]
        new_obs = [int(round((self.bins[i] - 1) * ratios[i])) for i in range(len(obs))]
        new_obs = [min(self.bins[i] - 1, max(0, new_obs[i])) for i in range(len(obs))]

        return tuple(new_obs)
Ejemplo n.º 50
0
def text(surface, node):
    """Draw a text ``node``."""
    font_family = (
        (node.get('font-family') or 'sans-serif').split(',')[0].strip('"\' '))
    font_style = getattr(
        cairo, ('font_slant_{}'.format(node.get('font-style')).upper()),
        cairo.FONT_SLANT_NORMAL)
    font_weight = getattr(
        cairo, ('font_weight_{}'.format(node.get('font-weight')).upper()),
        cairo.FONT_WEIGHT_NORMAL)
    surface.context.select_font_face(font_family, font_style, font_weight)
    surface.context.set_font_size(surface.font_size)
    ascent, descent, _, max_x_advance, max_y_advance = (
        surface.context.font_extents())

    text_path_href = parse_url(
        node.get('{http://www.w3.org/1999/xlink}href', '') or
        node.parent.get('{http://www.w3.org/1999/xlink}href', ''))
    if text_path_href.fragment:
        text_path = surface.paths.get(text_path_href.fragment)
    else:
        text_path = None
    letter_spacing = size(surface, node.get('letter-spacing'))
    x_bearing, y_bearing, width, height = (
        surface.context.text_extents(node.text)[:4])

    x, y, dx, dy, rotate = [], [], [], [], [0]
    if 'x' in node:
        x = [size(surface, i, 'x')
             for i in normalize(node['x']).strip().split(' ')]
    if 'y' in node:
        y = [size(surface, i, 'y')
             for i in normalize(node['y']).strip().split(' ')]
    if 'dx' in node:
        dx = [size(surface, i, 'x')
              for i in normalize(node['dx']).strip().split(' ')]
    if 'dy' in node:
        dy = [size(surface, i, 'y')
              for i in normalize(node['dy']).strip().split(' ')]
    if 'rotate' in node:
        rotate = [radians(float(i)) if i else 0
                  for i in normalize(node['rotate']).strip().split(' ')]
    last_r = rotate[-1]
    letters_positions = zip_letters(x, y, dx, dy, rotate, node.text)

    text_anchor = node.get('text-anchor')
    if text_anchor == 'middle':
        x_align = width / 2. + x_bearing
    elif text_anchor == 'end':
        x_align = width + x_bearing
    else:
        x_align = 0

    # TODO: This is a hack. The rest of the baseline alignment tags of the SVG
    # 1.1 spec (section 10.9.2) are not supported. We only try to align things
    # that look like Western horizontal fonts.
    # Finally, we add a "display-anchor" attribute for aligning the specific
    # text rather than the font baseline.
    # Nonetheless, there are times when one needs to align text vertically, and
    # this will at least make that possible.
    if max_x_advance > 0 and max_y_advance == 0:
        display_anchor = node.get('display-anchor')
        alignment_baseline = node.get('alignment-baseline')
        if display_anchor == 'middle':
            y_align = -height / 2.0 - y_bearing
        elif display_anchor == 'top':
            y_align = -y_bearing
        elif display_anchor == 'bottom':
            y_align = -height - y_bearing
        elif (alignment_baseline == 'central' or
              alignment_baseline == 'middle'):
            # TODO: This is wrong, Cairo gives no reasonable access to x-height
            # information, so we use font top-to-bottom
            y_align = (ascent + descent) / 2.0 - descent
        elif (alignment_baseline == 'text-before-edge' or
              alignment_baseline == 'before_edge' or
              alignment_baseline == 'top' or
              alignment_baseline == 'text-top'):
            y_align = ascent
        elif (alignment_baseline == 'text-after-edge' or
              alignment_baseline == 'after_edge' or
              alignment_baseline == 'bottom' or
              alignment_baseline == 'text-bottom'):
            y_align = -descent
        else:
            y_align = 0

    bounding_box = EMPTY_BOUNDING_BOX
    if text_path:
        surface.stroke_and_fill = False
        surface.draw(text_path)
        surface.stroke_and_fill = True
        cairo_path = surface.context.copy_path_flat()
        surface.context.new_path()
        length = path_length(cairo_path) + x_bearing
        start_offset = size(surface, node.get('startOffset', 0), length)
        surface.text_path_width += start_offset - x_align
        bounding_box = extend_bounding_box(bounding_box, ((start_offset, 0),))

    if node.text:
        for [x, y, dx, dy, r], letter in letters_positions:
            if x:
                surface.cursor_d_position[0] = 0
            if y:
                surface.cursor_d_position[1] = 0
            surface.cursor_d_position[0] += dx or 0
            surface.cursor_d_position[1] += dy or 0
            text_extents = surface.context.text_extents(letter)
            extents = text_extents[4]
            if text_path:
                start = surface.text_path_width + surface.cursor_d_position[0]
                start_point = point_following_path(cairo_path, start)
                middle = start + extents / 2
                middle_point = point_following_path(cairo_path, middle)
                end = start + extents
                end_point = point_following_path(cairo_path, end)
                surface.text_path_width += extents + letter_spacing
                if not all((start_point, middle_point, end_point)):
                    continue
                if not 0 <= middle <= length:
                    continue
                surface.context.save()
                surface.context.translate(*start_point)
                surface.context.rotate(point_angle(*(start_point + end_point)))
                surface.context.translate(0, surface.cursor_d_position[1])
                surface.context.move_to(0, 0)
                bounding_box = extend_bounding_box(
                    bounding_box, ((end_point[0], text_extents[3]),))
            else:
                surface.context.save()
                x = surface.cursor_position[0] if x is None else x
                y = surface.cursor_position[1] if y is None else y
                surface.context.move_to(x + letter_spacing, y)
                cursor_position = x + letter_spacing + extents, y
                surface.context.rel_move_to(*surface.cursor_d_position)
                surface.context.rel_move_to(-x_align, y_align)
                surface.context.rotate(last_r if r is None else r)
                points = (
                    (cursor_position[0] - x_align +
                     surface.cursor_d_position[0],
                     cursor_position[1] + y_align +
                     surface.cursor_d_position[1]),
                    (cursor_position[0] - x_align + text_extents[4] +
                     surface.cursor_d_position[0],
                     cursor_position[1] + y_align + text_extents[3] +
                     surface.cursor_d_position[1]))
                bounding_box = extend_bounding_box(bounding_box, points)

            # Only draw characters with 'content' (workaround for bug in cairo)
            if not letter.isspace():
                surface.context.text_path(letter)
            surface.context.restore()
            if not text_path:
                surface.cursor_position = cursor_position
    else:
        x = x[0] if x else surface.cursor_position[0]
        y = y[0] if y else surface.cursor_position[1]
        dx = dx[0] if dx else 0
        dy = dy[0] if dy else 0
        surface.cursor_position = (x + dx, y + dy)

    # If a valid bounding box is calculated store it in the node
    if is_valid_bounding_box(bounding_box):
        node['text_bounding_box'] = bounding_box
Ejemplo n.º 51
0
from easygraphics import *

init_graph(400, 400)
set_render_mode(RenderMode.RENDER_MANUAL)
translate(200, 200)

num = 0
size = 100
points = []
pi_5th = math.pi / 5
pi_2_5th = 2 * pi_5th
while is_run():
    clear()
    points.clear()
    num += 1
    rad = math.radians(num)
    x = size * math.cos(rad)
    y = size * math.sin(rad)
    x1 = x * math.cos(pi_5th) - y / 2 * math.sin(pi_5th)
    y1 = x * math.sin(pi_5th) + y / 2 * math.cos(pi_5th)
    points.append(x)
    points.append(y)
    points.append(x1)
    points.append(y1)
    for i in range(1, 5):
        x2 = x * math.cos(i * pi_2_5th) - y * math.sin(i * pi_2_5th)
        y2 = x * math.sin(i * pi_2_5th) + y * math.cos(i * pi_2_5th)
        x3 = x1 * math.cos(i * pi_2_5th) - y1 * math.sin(i * pi_2_5th)
        y3 = x1 * math.sin(i * pi_2_5th) + y1 * math.cos(i * pi_2_5th)
        points.append(x2)
        points.append(y2)
Ejemplo n.º 52
0
    def fit_bones(self, mmd_armature_object: MMDArmatureObject):
        # pylint: disable=too-many-statements
        metarig_edit_bones = self.edit_bones
        mmd_edit_bones = mmd_armature_object.strict_edit_bones
        metarig_edit_bones['spine.002'].head = mmd_edit_bones['上半身'].head

        if MMDBoneType.UPPER_BODY_2 in mmd_armature_object.exist_bone_types:
            metarig_edit_bones['spine.003'].head = mmd_edit_bones['上半身2'].head
            metarig_edit_bones['spine.003'].tail = mmd_edit_bones['上半身2'].tail
        else:
            metarig_edit_bones['spine.003'].head = self.to_bone_center(
                mmd_edit_bones['上半身'])
            metarig_edit_bones['spine.003'].tail = mmd_edit_bones['上半身'].tail

        metarig_edit_bones['spine.004'].head = mmd_edit_bones['首'].head
        metarig_edit_bones['spine.004'].tail = self.to_bone_center(
            mmd_edit_bones['首'])
        metarig_edit_bones['spine.005'].tail = mmd_edit_bones['首'].tail
        metarig_edit_bones['spine.006'].tail = mmd_edit_bones['頭'].tail

        if mmd_armature_object.has_face_bones():
            metarig_edit_bones['face'].head = mmd_edit_bones['頭'].head
            metarig_edit_bones['face'].tail = self.to_bone_center(
                mmd_edit_bones['頭'])

        metarig_edit_bones['shoulder.L'].head = mmd_edit_bones['左肩'].head
        metarig_edit_bones['shoulder.L'].tail = mmd_edit_bones['左肩'].tail
        metarig_edit_bones['shoulder.R'].head = mmd_edit_bones['右肩'].head
        metarig_edit_bones['shoulder.R'].tail = mmd_edit_bones['右肩'].tail
        metarig_edit_bones['upper_arm.L'].head = mmd_edit_bones['左腕'].head
        metarig_edit_bones['upper_arm.R'].head = mmd_edit_bones['右腕'].head
        metarig_edit_bones['forearm.L'].head = mmd_edit_bones['左ひじ'].head
        metarig_edit_bones['forearm.L'].tail = mmd_edit_bones['左ひじ'].tail
        metarig_edit_bones['forearm.R'].head = mmd_edit_bones['右ひじ'].head
        metarig_edit_bones['forearm.R'].tail = mmd_edit_bones['右ひじ'].tail

        metarig_edit_bones['hand.L'].tail = mmd_edit_bones['左手首'].tail
        metarig_edit_bones['hand.R'].tail = mmd_edit_bones['右手首'].tail

        if MMDBoneType.THUMB_0 in mmd_armature_object.exist_bone_types:
            metarig_edit_bones['thumb.01.L'].head = mmd_edit_bones['左親指0'].head
            metarig_edit_bones['thumb.01.L'].tail = mmd_edit_bones['左親指0'].tail
            metarig_edit_bones['thumb.01.R'].head = mmd_edit_bones['右親指0'].head
            metarig_edit_bones['thumb.01.R'].tail = mmd_edit_bones['右親指0'].tail
        else:
            metarig_edit_bones['thumb.01.L'].head = mmd_edit_bones[
                '左親指1'].head - mmd_edit_bones['左親指1'].vector
            metarig_edit_bones['thumb.01.L'].tail = mmd_edit_bones['左親指1'].head
            metarig_edit_bones['thumb.01.R'].head = mmd_edit_bones[
                '右親指1'].head - mmd_edit_bones['右親指1'].vector
            metarig_edit_bones['thumb.01.R'].tail = mmd_edit_bones['右親指1'].head

        metarig_edit_bones['thumb.02.L'].tail = mmd_edit_bones['左親指1'].tail
        metarig_edit_bones['thumb.02.R'].tail = mmd_edit_bones['右親指1'].tail
        metarig_edit_bones['thumb.03.L'].tail = mmd_edit_bones['左親指2'].tail
        metarig_edit_bones['thumb.03.R'].tail = mmd_edit_bones['右親指2'].tail

        if MMDBoneType.PALM in mmd_armature_object.exist_bone_types:
            metarig_edit_bones['palm.01.L'].head = mmd_edit_bones['左人指0'].head
            metarig_edit_bones['palm.01.L'].tail = mmd_edit_bones['左人指0'].tail
            metarig_edit_bones['palm.01.R'].head = mmd_edit_bones['右人指0'].head
            metarig_edit_bones['palm.01.R'].tail = mmd_edit_bones['右人指0'].tail
        else:
            metarig_edit_bones['palm.01.L'].head = self.to_stretch(
                mmd_edit_bones['左ひじ'].tail, mmd_edit_bones['左人指1'].head, 0.99)
            metarig_edit_bones['palm.01.L'].tail = mmd_edit_bones['左人指1'].head
            metarig_edit_bones['palm.01.R'].head = self.to_stretch(
                mmd_edit_bones['右ひじ'].tail, mmd_edit_bones['右人指1'].head, 0.99)
            metarig_edit_bones['palm.01.R'].tail = mmd_edit_bones['右人指1'].head

        metarig_edit_bones['f_index.01.L'].head = mmd_edit_bones['左人指1'].head
        metarig_edit_bones['f_index.01.L'].tail = mmd_edit_bones['左人指1'].tail
        metarig_edit_bones['f_index.01.R'].head = mmd_edit_bones['右人指1'].head
        metarig_edit_bones['f_index.01.R'].tail = mmd_edit_bones['右人指1'].tail
        metarig_edit_bones['f_index.02.L'].tail = mmd_edit_bones['左人指2'].tail
        metarig_edit_bones['f_index.02.R'].tail = mmd_edit_bones['右人指2'].tail
        metarig_edit_bones['f_index.03.L'].tail = mmd_edit_bones['左人指3'].tail
        metarig_edit_bones['f_index.03.R'].tail = mmd_edit_bones['右人指3'].tail

        if MMDBoneType.PALM in mmd_armature_object.exist_bone_types:
            metarig_edit_bones['palm.02.L'].head = mmd_edit_bones['左中指0'].head
            metarig_edit_bones['palm.02.L'].tail = mmd_edit_bones['左中指0'].tail
            metarig_edit_bones['palm.02.R'].head = mmd_edit_bones['右中指0'].head
            metarig_edit_bones['palm.02.R'].tail = mmd_edit_bones['右中指0'].tail
        else:
            metarig_edit_bones['palm.02.L'].head = self.to_stretch(
                mmd_edit_bones['左ひじ'].tail, mmd_edit_bones['左中指1'].head, 0.99)
            metarig_edit_bones['palm.02.L'].tail = mmd_edit_bones['左中指1'].head
            metarig_edit_bones['palm.02.R'].head = self.to_stretch(
                mmd_edit_bones['右ひじ'].tail, mmd_edit_bones['右中指1'].head, 0.99)
            metarig_edit_bones['palm.02.R'].tail = mmd_edit_bones['右中指1'].head

        metarig_edit_bones['f_middle.01.L'].head = mmd_edit_bones['左中指1'].head
        metarig_edit_bones['f_middle.01.L'].tail = mmd_edit_bones['左中指1'].tail
        metarig_edit_bones['f_middle.01.R'].head = mmd_edit_bones['右中指1'].head
        metarig_edit_bones['f_middle.01.R'].tail = mmd_edit_bones['右中指1'].tail
        metarig_edit_bones['f_middle.02.L'].tail = mmd_edit_bones['左中指2'].tail
        metarig_edit_bones['f_middle.02.R'].tail = mmd_edit_bones['右中指2'].tail
        metarig_edit_bones['f_middle.03.L'].tail = mmd_edit_bones['左中指3'].tail
        metarig_edit_bones['f_middle.03.R'].tail = mmd_edit_bones['右中指3'].tail

        if MMDBoneType.PALM in mmd_armature_object.exist_bone_types:
            metarig_edit_bones['palm.03.L'].head = mmd_edit_bones['左薬指0'].head
            metarig_edit_bones['palm.03.L'].tail = mmd_edit_bones['左薬指0'].tail
            metarig_edit_bones['palm.03.R'].head = mmd_edit_bones['右薬指0'].head
            metarig_edit_bones['palm.03.R'].tail = mmd_edit_bones['右薬指0'].tail
        else:
            metarig_edit_bones['palm.03.L'].head = self.to_stretch(
                mmd_edit_bones['左ひじ'].tail, mmd_edit_bones['左薬指1'].head, 0.99)
            metarig_edit_bones['palm.03.L'].tail = mmd_edit_bones['左薬指1'].head
            metarig_edit_bones['palm.03.R'].head = self.to_stretch(
                mmd_edit_bones['右ひじ'].tail, mmd_edit_bones['右薬指1'].head, 0.99)
            metarig_edit_bones['palm.03.R'].tail = mmd_edit_bones['右薬指1'].head

        metarig_edit_bones['f_ring.01.L'].head = mmd_edit_bones['左薬指1'].head
        metarig_edit_bones['f_ring.01.L'].tail = mmd_edit_bones['左薬指1'].tail
        metarig_edit_bones['f_ring.01.R'].head = mmd_edit_bones['右薬指1'].head
        metarig_edit_bones['f_ring.01.R'].tail = mmd_edit_bones['右薬指1'].tail
        metarig_edit_bones['f_ring.02.L'].tail = mmd_edit_bones['左薬指2'].tail
        metarig_edit_bones['f_ring.02.R'].tail = mmd_edit_bones['右薬指2'].tail
        metarig_edit_bones['f_ring.03.L'].tail = mmd_edit_bones['左薬指3'].tail
        metarig_edit_bones['f_ring.03.R'].tail = mmd_edit_bones['右薬指3'].tail

        if MMDBoneType.PALM in mmd_armature_object.exist_bone_types:
            metarig_edit_bones['palm.04.L'].head = mmd_edit_bones['左小指0'].head
            metarig_edit_bones['palm.04.L'].tail = mmd_edit_bones['左小指0'].tail
            metarig_edit_bones['palm.04.R'].head = mmd_edit_bones['右小指0'].head
            metarig_edit_bones['palm.04.R'].tail = mmd_edit_bones['右小指0'].tail
        else:
            metarig_edit_bones['palm.04.L'].head = self.to_stretch(
                mmd_edit_bones['左ひじ'].tail, mmd_edit_bones['左小指1'].head, 0.99)
            metarig_edit_bones['palm.04.L'].tail = mmd_edit_bones['左小指1'].head
            metarig_edit_bones['palm.04.R'].head = self.to_stretch(
                mmd_edit_bones['右ひじ'].tail, mmd_edit_bones['右小指1'].head, 0.99)
            metarig_edit_bones['palm.04.R'].tail = mmd_edit_bones['右小指1'].head

        metarig_edit_bones['f_pinky.01.L'].head = mmd_edit_bones['左小指1'].head
        metarig_edit_bones['f_pinky.01.L'].tail = mmd_edit_bones['左小指1'].tail
        metarig_edit_bones['f_pinky.01.R'].head = mmd_edit_bones['右小指1'].head
        metarig_edit_bones['f_pinky.01.R'].tail = mmd_edit_bones['右小指1'].tail
        metarig_edit_bones['f_pinky.02.L'].tail = mmd_edit_bones['左小指2'].tail
        metarig_edit_bones['f_pinky.02.R'].tail = mmd_edit_bones['右小指2'].tail
        metarig_edit_bones['f_pinky.03.L'].tail = mmd_edit_bones['左小指3'].tail
        metarig_edit_bones['f_pinky.03.R'].tail = mmd_edit_bones['右小指3'].tail

        metarig_edit_bones['spine'].head = mmd_edit_bones['下半身'].tail
        metarig_edit_bones['spine.001'].head = self.to_bone_center(
            mmd_edit_bones['下半身'])
        metarig_edit_bones['spine.001'].tail = mmd_edit_bones['下半身'].head

        metarig_edit_bones['pelvis.L'].head = mmd_edit_bones['下半身'].tail
        metarig_edit_bones['pelvis.R'].head = mmd_edit_bones['下半身'].tail
        metarig_edit_bones['pelvis.L'].tail[1:3] = [
            mmd_edit_bones['下半身'].tail[1] - mmd_edit_bones['下半身'].length / 2,
            mmd_edit_bones['下半身'].head[2]
        ]
        metarig_edit_bones['pelvis.R'].tail[1:3] = [
            mmd_edit_bones['下半身'].tail[1] - mmd_edit_bones['下半身'].length / 2,
            mmd_edit_bones['下半身'].head[2]
        ]

        metarig_edit_bones['thigh.L'].head = mmd_edit_bones['左足'].head
        metarig_edit_bones['thigh.L'].tail = mmd_edit_bones['左足'].tail
        metarig_edit_bones['thigh.R'].head = mmd_edit_bones['右足'].head
        metarig_edit_bones['thigh.R'].tail = mmd_edit_bones['右足'].tail
        metarig_edit_bones['shin.L'].tail = mmd_edit_bones['左ひざ'].tail
        metarig_edit_bones['shin.R'].tail = mmd_edit_bones['右ひざ'].tail

        if MMDBoneType.TOE_EX in mmd_armature_object.exist_bone_types:
            metarig_edit_bones['foot.L'].tail = Vector([
                mmd_edit_bones['左足首'].tail.x, mmd_edit_bones['左足先EX'].head.y,
                mmd_edit_bones['左足首'].tail.z
            ])
            metarig_edit_bones['foot.R'].tail = Vector([
                mmd_edit_bones['右足首'].tail.x, mmd_edit_bones['右足先EX'].head.y,
                mmd_edit_bones['右足首'].tail.z
            ])
            metarig_edit_bones['toe.L'].tail = Vector([
                mmd_edit_bones['左足首'].tail.x, mmd_edit_bones['左足先EX'].tail.y,
                mmd_edit_bones['左足首'].tail.z
            ])
            metarig_edit_bones['toe.R'].tail = Vector([
                mmd_edit_bones['右足首'].tail.x, mmd_edit_bones['右足先EX'].tail.y,
                mmd_edit_bones['右足首'].tail.z
            ])
        else:
            metarig_edit_bones['foot.L'].tail = mmd_edit_bones['左足首'].tail
            metarig_edit_bones['foot.R'].tail = mmd_edit_bones['右足首'].tail
            metarig_edit_bones[
                'toe.L'].tail = mmd_edit_bones['左足首'].tail + Vector(
                    [+0.0, -mmd_edit_bones['左足首'].length / 2, +0.0])
            metarig_edit_bones[
                'toe.R'].tail = mmd_edit_bones['右足首'].tail + Vector(
                    [+0.0, -mmd_edit_bones['右足首'].length / 2, +0.0])

        metarig_edit_bones['heel.02.L'].tail = mmd_edit_bones['左ひざ'].tail.copy(
        )
        metarig_edit_bones['heel.02.L'].tail[
            0] += +mmd_edit_bones['左ひざ'].length / 8
        metarig_edit_bones['heel.02.L'].tail[
            1] += +mmd_edit_bones['左ひざ'].length / 10
        metarig_edit_bones['heel.02.L'].tail[2] = 0
        metarig_edit_bones['heel.02.L'].head = mmd_edit_bones['左ひざ'].tail.copy(
        )
        metarig_edit_bones['heel.02.L'].head[
            0] += -mmd_edit_bones['左ひざ'].length / 8
        metarig_edit_bones['heel.02.L'].head[
            1] += +mmd_edit_bones['左ひざ'].length / 10
        metarig_edit_bones['heel.02.L'].head[2] = 0
        metarig_edit_bones['heel.02.R'].tail = mmd_edit_bones['右ひざ'].tail.copy(
        )
        metarig_edit_bones['heel.02.R'].tail[
            0] += -mmd_edit_bones['右ひざ'].length / 8
        metarig_edit_bones['heel.02.R'].tail[
            1] += +mmd_edit_bones['右ひざ'].length / 10
        metarig_edit_bones['heel.02.R'].tail[2] = 0
        metarig_edit_bones['heel.02.R'].head = mmd_edit_bones['右ひざ'].tail.copy(
        )
        metarig_edit_bones['heel.02.R'].head[
            0] += +mmd_edit_bones['右ひざ'].length / 8
        metarig_edit_bones['heel.02.R'].head[
            1] += +mmd_edit_bones['右ひざ'].length / 10
        metarig_edit_bones['heel.02.R'].head[2] = 0

        # fix straight finger bend problem
        # https://blenderartists.org/t/rigify-fingers-issue/1218987
        # limbs.super_finger
        metarig_edit_bones['thumb.01.L'].roll += math.radians(-45)
        metarig_edit_bones['thumb.02.L'].roll += math.radians(-45)
        metarig_edit_bones['thumb.03.L'].roll += math.radians(-45)
        metarig_edit_bones['f_index.01.L'].roll += math.radians(-45)
        metarig_edit_bones['f_index.02.L'].roll += math.radians(-45)
        metarig_edit_bones['f_index.03.L'].roll += math.radians(-45)
        metarig_edit_bones['f_middle.01.L'].roll += math.radians(-45)
        metarig_edit_bones['f_middle.02.L'].roll += math.radians(-45)
        metarig_edit_bones['f_middle.03.L'].roll += math.radians(-45)
        metarig_edit_bones['f_ring.01.L'].roll += math.radians(-45)
        metarig_edit_bones['f_ring.02.L'].roll += math.radians(-45)
        metarig_edit_bones['f_ring.03.L'].roll += math.radians(-45)
        metarig_edit_bones['f_pinky.01.L'].roll += math.radians(-45)
        metarig_edit_bones['f_pinky.02.L'].roll += math.radians(-45)
        metarig_edit_bones['f_pinky.03.L'].roll += math.radians(-45)

        metarig_edit_bones['thumb.01.R'].roll += math.radians(+45)
        metarig_edit_bones['thumb.02.R'].roll += math.radians(+45)
        metarig_edit_bones['thumb.03.R'].roll += math.radians(+45)
        metarig_edit_bones['f_index.01.R'].roll += math.radians(+45)
        metarig_edit_bones['f_index.02.R'].roll += math.radians(+45)
        metarig_edit_bones['f_index.03.R'].roll += math.radians(+45)
        metarig_edit_bones['f_middle.01.R'].roll += math.radians(+45)
        metarig_edit_bones['f_middle.02.R'].roll += math.radians(+45)
        metarig_edit_bones['f_middle.03.R'].roll += math.radians(+45)
        metarig_edit_bones['f_ring.01.R'].roll += math.radians(+45)
        metarig_edit_bones['f_ring.02.R'].roll += math.radians(+45)
        metarig_edit_bones['f_ring.03.R'].roll += math.radians(+45)
        metarig_edit_bones['f_pinky.01.R'].roll += math.radians(+45)
        metarig_edit_bones['f_pinky.02.R'].roll += math.radians(+45)
        metarig_edit_bones['f_pinky.03.R'].roll += math.radians(+45)

        # fix elbow pole problem
        # https://blenderartists.org/t/rigify-elbow-problem/565285
        metarig_edit_bones['upper_arm.L'].tail += Vector([0, +0.001, 0])
        metarig_edit_bones['upper_arm.R'].tail += Vector([0, +0.001, 0])

        # remove unused mmd_edit_bones
        remove_metarig_edit_bones = [
            metarig_edit_bones['breast.L'],
            metarig_edit_bones['breast.R'],
        ]
        for metarig_bone in remove_metarig_edit_bones:
            metarig_edit_bones.remove(metarig_bone)
Ejemplo n.º 53
0
def _find_brick_iteratively(rob, mv, target, tcp, imaging_area, travel_height,
                            vel, a, max_diff=0.7, allowed_rect_area=None, use_color_vision=True, use_model=True):
    """ Move gripper above brick that matches best the target given

    At the end of the function TCP is set back to 'gripper'.
    Returns None when above the match with maximum  of 'max_diff' deviation.

    """

    # Go above imaging area
    rob.set_tcp(tcp['camera'])
    pose = deepcopy(imaging_area)
    pose[2] += travel_height
    rob.movej(pose, v=vel, a=a)

    if target[5] == '2x2':
        size = (2, 2)
    else:
        size = (2, 4)

    match = {'x': 255, 'y': 255, 'angle': 255}
    while abs(match['x']) > max_diff or abs(match['y']) > max_diff:
        try:
            if target[3] != 'parallel_to_y':
                # Turn to grab the brick in alternative direction
                use_max_edge = True
            else:
                use_max_edge = False

            if use_color_vision:
                target_color = target[4]
            else:
                target_color = None
            match = mv.find_brick(target_color, size, margin=0.2,
                                  use_max_edge=use_max_edge, draw=True, use_model=use_model)
        except NoMatches:
            random_pose = deepcopy(pose)
            rand_xy = _random_point_within_rect(allowed_rect_area[0], allowed_rect_area[1])
            random_pose[0:2] = rand_xy
            rob.movej(random_pose, v=vel, a=a)
            continue

        print(match)
        xoff = match['x'] / 1000
        yoff = match['y'] / 1000
        angle_off = match['angle']
        rpy_ = rob.rotvec2rpy(rob.get_tcp()[3:])  # rpy = [roll, pitch, yaw]
        p1 = [0, 0, 0] + rob.rotvec2rpy([0, 0, rpy_[2] - radians(180)])
        p2 = [xoff, yoff, 0] + rob.rotvec2rpy([0, 0, 0])

        # If square use the closest angle
        if size[0] == size[1]:
            if angle_off > radians(45):
                angle_off -= radians(90)
            elif angle_off < radians(-45):
                angle_off += radians(90)
        pose_ = rob.pose_trans(p1, p2)[:3] + [0, 0, angle_off]

        curr_pose_xy = rob.get_tcp()[:2]
        curr_pose_xy[0] += pose_[0]
        curr_pose_xy[1] += pose_[1]

        if allowed_rect_area:

            is_it = _is_within_rect(curr_pose_xy, allowed_rect_area[0],
                                    allowed_rect_area[1])
            if not is_it:
                # Go to random point within imaging area
                random_pose = deepcopy(pose)
                rand_xy = _random_point_within_rect(allowed_rect_area[0], allowed_rect_area[1])
                random_pose[0:2] = rand_xy
                rob.movej(random_pose, v=vel, a=a)
                continue

        rob.movej(pose_, v=vel, a=a, relative=True)

    # Move gripper where the camera is
    pose = rob.get_tcp()
    rob.set_tcp(tcp['gripper'])
    rob.movej(pose, v=vel, a=a)

    return
Ejemplo n.º 54
0
                line = ser.readline()

                data_stamp = rospy.Time.now()

                ascii_data = line.split(',')
                ascii_data = [s.strip() for s in ascii_data]

                ascii_data[0] = ascii_data[0][7:]
                if len(ascii_data) != 9:
                    print len(ascii_data)
                    rospy.loginfo_throttle(0.5, 'waiting for stream')
                    continue

                quaternion = tf.transformations.quaternion_from_euler(
                    radians(float(ascii_data[1])),
                    -radians(float(ascii_data[2])),
                    -radians(float(ascii_data[0])))
                #print ascii_data
                imu_msg = Imu()
                imu_msg.header.stamp = data_stamp
                imu_msg.header.frame_id = child_frame
                imu_msg.linear_acceleration.x = float(
                    ascii_data[3]) * gravity_accel
                imu_msg.linear_acceleration.y = float(
                    ascii_data[4]) * gravity_accel
                imu_msg.linear_acceleration.z = float(
                    ascii_data[5]) * gravity_accel
                imu_msg.angular_velocity.x = float(ascii_data[6]) * deg_to_rad
                imu_msg.angular_velocity.y = float(ascii_data[7]) * deg_to_rad
                imu_msg.angular_velocity.z = float(ascii_data[8]) * deg_to_rad
def calcula_trabalho (x,y,z):
    t=x*math.cos (math.radians(y))*z
    return t
Ejemplo n.º 56
0
#   math.tan(x)                 正切函数
#   math.asin(x)                反正弦函数
#   math.acos(x)                反余弦函数
#   math.atan(x)                反正切函数
# +---------------------------+--------------------------------------------+

# 示例
import math
print "pi =", math.pi  #输出:pi = 3.14159265359
print "e =", math.e  #输出:e = 2.71828182846
print math.ceil(3.14)  #输出:4.0
print math.ceil(4)  #输出:4.0
print math.ceil(-3.14)  #输出:-3.0
print math.floor(3.14)  #输出:3.0
print math.floor(4)  #输出:4.0
print math.floor(-3.14)  #输出:-4.0
print "pow:", math.pow(2, 3)  #输出:8.0
print "sqrt:", math.sqrt(4)  #输出:2.0
print "log:", math.log(math.e)  #输出:1.0
print "log10:", math.log10(10)  #输出:1.0
print "exp:", math.exp(2)  #输出:7.38905609893
print "degrees:", math.degrees(math.pi)  #输出:180.0
print "radians:", math.radians(360)  #输出:6.28318530718
print "sin:", math.sin(0)  #输出:0.0
print "cos:", math.cos(0)  #输出:1.0
print "tan:", math.tan(0)  #输出:0.0
print "asin:", math.asin(1)  #输出:1.57079632679(pi/2)
print "acos:", math.acos(1)  #输出:0.0
print "atan:", math.atan(1)  #输出:0.785398163397(pi/4)

Ejemplo n.º 57
0
import math

print(math.sqrt(16))
print(math.radians(180))
print(math.degrees(math.pi*2))
print(math.sin(math.pi*0.5))
print(math.floor(5.3))
print(math.trunc(5.3))
print(math.floor(-5.3))
print(math.trunc(-5.3))
Ejemplo n.º 58
0
def calibrate_camera(rob, mv, gripper, tcp, travel_height, calib,
                     brick2x2_side_mm, color, brick_base_height):
    """ Calibrates MachineVision object by imaging a 2x2 brick.

    Calibration brick's position is assumed to be the first taught build platform
    pose.

    1. Touch the origin pose (first calibrated corner).
    2. Take picture for calibration.
    3. Move a bit aside.
    4. Test calibration by trying to guide the arm back to the calibration brick
        using only machine vision.

    Parameters
    ----------
    rob : Robot
    mv : MachineVision
    gripper : dict
    tcp : dict
    travel_height : float
    calib : dict
    brick2x2_side_mm : float
        Ideal side length of the 2x2 brick.
    color : str
        Name of the color used for calibration brick.
    brick_base_height : float
        In mm the height of a brick without its studs.

    """

    rob.set_tcp(tcp['gripper'])
    wait = 0.1
    vel = 1.3
    a = 0.4
    imaging_area = calib['taught_poses']['build'][0]

    rob.popup('Press continue to start camera calibration', blocking=True)

    # Goto starting height
    pose = rob.get_tcp()
    pose[2] = imaging_area[2] + travel_height - brick_base_height / 1000
    rob.movel(pose, v=vel, a=a)
    time.sleep(wait)

    # Open gripper
    rob.grip(closed=gripper['open'])

    pose = deepcopy(imaging_area)
    pose[2] += travel_height
    rob.movej(pose, v=vel, a=a)
    time.sleep(wait)
    rob.movel(imaging_area, v=vel, a=a)
    time.sleep(wait * 2)
    rob.movel(pose, v=vel, a=a)

    rob.set_tcp(tcp['camera'])
    rob.movej(pose, v=vel, a=a)
    mv.calibrate(brick2x2_side_mm, color)  # Take calibration image

    # Move aside: x, y and yaw
    rotvec = rob.rpy2rotvec([0, 0, radians(0)])
    pose = [0.07, 0.05, 0] + rotvec
    rob.movej(pose, v=vel, a=a, relative=True)
    time.sleep(wait)

    target = [None, None, None, 'parallel_to_x', color, '2x2']

    # Find match and move above it
    _find_brick_iteratively(rob, mv, target, tcp, imaging_area, travel_height, vel, a,
                            max_diff=0.7, use_color_vision=True, use_model=False)

    # Touch the match
    pose = rob.get_tcp()
    pose[2] = imaging_area[2]
    rob.movel(pose, v=vel, a=a)
    time.sleep(wait * 2)
    pose[2] = travel_height
    rob.movel(pose, v=vel, a=a)
    time.sleep(wait)

    rob.popup('Camera calibration finished!')
    print('Camera calibration finished!')
Ejemplo n.º 59
0
def mid_ordinate(length, radius):
    half_angle = math.degrees(math.asin(length / (2 * radius)))
    mid = radius * (1 - math.cos(math.radians(half_angle)))

    return mid, half_angle
Ejemplo n.º 60
0
                     and 'deck' in process['Parameters']
                     ['output_file_settings']['folder_name'].GetString())):

                    print(process['Parameters']['output_file_settings']
                          ['folder_name'].GetString())
                    print('Old')
                    print(process['Parameters']['start_point'].GetVector())
                    print(process['Parameters']['end_point'].GetVector())

                    for label in ["start_point", "end_point"]:

                        center = [0.0, 0.0]
                        cur_coord = process['Parameters'][label].GetVector()

                        new_xy = ccw_rotate_point_around_z(
                            center, cur_coord[:-1], math.radians(static_case))
                        new_coord = [new_xy[0], new_xy[1], cur_coord[2]]
                        process['Parameters'][label].SetVector(new_coord)

                    print('New')
                    print(process['Parameters']['start_point'].GetVector())
                    print(process['Parameters']['end_point'].GetVector())
                    #wait = input('check1...')

            elif process['python_module'].GetString(
            ) == 'multiple_points_output_process':
                # only for certain types of multiple points output
                if (('pressure' in process['Parameters']
                     ['output_file_settings']['folder_name'].GetString()
                     and 'coherence' in process['Parameters']
                     ['output_file_settings']['folder_name'].GetString()) or