Python numpy.rad2deg() 使用实例

The following are code examples for showing how to use . They are extracted from open source Python projects. You can vote up the examples you like or vote down the exmaples you don’t like. You can also save this page to your account.

Example 1

def transformImg(self, img, t):
        imgT = img.transform((int(img.size[0]*t[3]),int(img.size[1]*t[3])), Image.EXTENT, (0,0,img.size[0],img.size[1]), Image.BILINEAR)
        imgT = imgT.rotate(numpy.rad2deg(t[0]), Image.BILINEAR, expand=1)
        if t[4] == 1.:
            imgT = imgT.transpose(Image.FLIP_LEFT_RIGHT)

        # crop only valid part
        if self.crop:
            imgT = imgT.crop(self.getInscribedRectangle(t[0], (img.size[0]*t[3], img.size[1]*t[3])))

        # crop from translation
        imgT = imgT.resize((int(self.imgSize[0]*1.1), int(self.imgSize[1]*1.1)), Image.BILINEAR)
        xstart = int((imgT.size[0] // 2 - t[1]) - self.imgSize[0] // 2)
        ystart = int((imgT.size[1] // 2 - t[2]) - self.imgSize[1] // 2)
        assert xstart >= 0 and ystart >= 0
        return imgT.crop((xstart, ystart, xstart+self.imgSize[0], ystart+self.imgSize[1])) 

Example 2

def getApproxRotation(self):
        # do an SVD to express T as a rotation matrix.
        M = np.array([[self.T[0]+1., self.T[1]], [self.T[2], self.T[3]+1.]])
        U,S,V = np.linalg.svd(M)
        print 'approx rotation:'
        print 'M='
        print M
        print 'U='
        print U
        print 'V='
        print V
        print 'S='
        print S
        r1 = np.rad2deg(np.arctan2(U[0,1], U[0,0]))
        r2 = np.rad2deg(np.arctan2(V[0,1], V[0,0]))
        print 'r1', r1
        print 'r2', r2
        print 'rotation', r1-r2
        return r1-r2 

Example 3

def azimuth(_lAz_data):
        _inc = _lAz_data[0]
        _lat = _lAz_data[1]
        velocity_eq = _lAz_data[2]

        @jit(nopython=True)
        def _az_calc():
            inert_az = np.arcsin(max(min(np.cos(np.deg2rad(_inc)) / np.cos(np.deg2rad(_lat)), 1), -1))
            _VXRot = _lAz_data[3] * np.sin(inert_az) - velocity_eq * np.cos(np.deg2rad(_lat))
            _VYRot = _lAz_data[3] * np.cos(inert_az)

            return np.rad2deg(np.fmod(np.arctan2(_VXRot, _VYRot) + (2 * pi), (2 * pi)))
        _az = _az_calc()

        if _lAz_data[4] == "Ascending": return _az

        if _lAz_data[4] == "Descending":
            if _az <= 90: return 180 - _az
            elif _az >= 270: return 540 - _az 

Example 4

def insertion_pitch(self):
        _circ_dv = self.circ_dv()
        _t_ap_dv = self.target_apoapsis_speed_dv()
        _m = np.rad2deg(self.mean_anomaly())
        _burn_time = self.maneuver_burn_time(self.circ_dv())

        @jit(nopython=True)
        def pitch_calcs_low():
                return (_t_ap_dv * (_circ_dv / 1000)) + (_m - (180 - (_burn_time / 12)))

        @jit(nopython=True)
        def pitch_calcs_high():
                return (_t_ap_dv * (_circ_dv / 1000)) + (_m - 180)

        if self.parking_orbit_alt <= 300000: return pitch_calcs_low()
        else: return pitch_calcs_high() 

Example 5

def azimuth(_lAz_data):
        _inc = _lAz_data[0]
        _lat = _lAz_data[1]
        velocity_eq = _lAz_data[2]

        @jit(nopython=True)
        def _az_calc():
            inert_az = np.arcsin(max(min(np.cos(np.deg2rad(_inc)) / np.cos(np.deg2rad(_lat)), 1), -1))
            _VXRot = _lAz_data[3] * np.sin(inert_az) - velocity_eq * np.cos(np.deg2rad(_lat))
            _VYRot = _lAz_data[3] * np.cos(inert_az)

            return np.rad2deg(np.fmod(np.arctan2(_VXRot, _VYRot) + (2 * pi), (2 * pi)))
        _az = _az_calc()

        if _lAz_data[4] == "Ascending": return _az

        if _lAz_data[4] == "Descending":
            if _az <= 90: return 180 - _az
            elif _az >= 270: return 540 - _az 

Example 6

def azimuth(_lAz_data):
        _inc = _lAz_data[0]
        _lat = _lAz_data[1]
        velocity_eq = _lAz_data[2]

        @jit(nopython=True)
        def _az_calc():
            inert_az = np.arcsin(max(min(np.cos(np.deg2rad(_inc)) / np.cos(np.deg2rad(_lat)), 1), -1))
            _VXRot = _lAz_data[3] * np.sin(inert_az) - velocity_eq * np.cos(np.deg2rad(_lat))
            _VYRot = _lAz_data[3] * np.cos(inert_az)

            return np.rad2deg(np.fmod(np.arctan2(_VXRot, _VYRot) + (2 * pi), (2 * pi)))
        _az = _az_calc()

        if _lAz_data[4] == "Ascending": return _az

        if _lAz_data[4] == "Descending":
            if _az <= 90: return 180 - _az
            elif _az >= 270: return 540 - _az 

Example 7

def insertion_pitch(self):
        _circ_dv = self.circ_dv()
        _t_ap_dv = self.target_apoapsis_speed_dv()
        _m = np.rad2deg(self.mean_anomaly())
        _burn_time = self.maneuver_burn_time(self.circ_dv())

        @jit(nopython=True)
        def pitch_calcs_low():
                return (_t_ap_dv * (_circ_dv / 1000)) + (_m - (180 - (_burn_time / 12)))

        @jit(nopython=True)
        def pitch_calcs_high():
                return (_t_ap_dv * (_circ_dv / 1000)) + (_m - 180)

        if self.target_orbit_alt <= 250000: return pitch_calcs_low()
        else: return pitch_calcs_high() 

Example 8

def azimuth(_lAz_data):
        _inc = _lAz_data[0]
        _lat = _lAz_data[1]
        velocity_eq = _lAz_data[2]

        @jit(nopython=True)
        def _az_calc():
            inert_az = np.arcsin(max(min(np.cos(np.deg2rad(_inc)) / np.cos(np.deg2rad(_lat)), 1), -1))
            _VXRot = _lAz_data[3] * np.sin(inert_az) - velocity_eq * np.cos(np.deg2rad(_lat))
            _VYRot = _lAz_data[3] * np.cos(inert_az)

            return np.rad2deg(np.fmod(np.arctan2(_VXRot, _VYRot) + 360, 360))
        _az = _az_calc()

        if _lAz_data[4] == "Ascending": return _az

        if _lAz_data[4] == "Descending":
            if _az <= 90: return 180 - _az
            elif _az >= 270: return 540 - _az 

Example 9

def SortByAngle(kNearestPoints, currentPoint, prevPoint):
    ''' Sorts the k nearest points given by angle '''
    angles = np.zeros(kNearestPoints.shape[0])
    i = 0
    for NearestPoint in kNearestPoints:
        # calculate the angle
        angle = np.arctan2(NearestPoint[1]-currentPoint[1],
                NearestPoint[0]-currentPoint[0]) - \
                np.arctan2(prevPoint[1]-currentPoint[1],
                prevPoint[0]-currentPoint[0])
        angle = np.rad2deg(angle)
        # only positive angles
        angle = np.mod(angle+360,360)
        #print NearestPoint[0], NearestPoint[1], angle
        angles[i] = angle
        i=i+1
    return kNearestPoints[np.argsort(angles)] 

Example 10

def get_motion_level(directory,translation_threshold=2.5,rotation_threshold=2.5):
  '''Roughly classify the amount of motion per slice for calculating likelihood of signal dropouts - 1 = severe motion, 2 = moderate motion'''
  motion_path = os.path.join(directory,'motion')
  motion = np.loadtxt(motion_path)
  max_motion = np.max(motion[:,1:],axis=0)
  min_motion = np.min(motion[:,1:],axis=0)
  diff_motion = np.abs(max_motion-min_motion)
  diff_motion[:3] = diff_motion[:3]*1000
  diff_motion[3:] = np.rad2deg(diff_motion[3:])

  if np.any( diff_motion[:3] > translation_threshold):
      return 1    
  elif np.any(diff_motion[3:] > rotation_threshold):
      return 1
  elif np.any( diff_motion[:3] > 1):
      return 2    
  elif np.any(diff_motion[3:] > 1):
      return 2
  else:
      return 0 

Example 11

def calc_Tb(self, freq):
        """
        Calculate the surface brightness  temperature of the point sources.

        Parameters
        ------------
        freq: `~astropy.units.Quantity`
             Frequency, e.g., `1.0*au.MHz`

        Return
        ------
        Tb_list: list
             Point sources brightness temperature
        """
        # Tb_list
        num_ps = self.ps_catalog.shape[0]
        Tb_list = np.zeros((num_ps,))
        sr_to_arcsec2 = (np.rad2deg(1) * 3600) ** 2  # [sr] -> [arcsec^2]
        # Iteratively calculate Tb
        for i in range(num_ps):
            ps_area = self.ps_catalog['Area (sr)'][i]  # [sr]
            area = ps_area * sr_to_arcsec2
            Tb_list[i] = self.calc_single_Tb(area, freq)

        return Tb_list 

Example 12

def calc_Tb(self, freq):
        """
        Calculate the surface brightness  temperature of the point sources.

        Parameters
        ------------
        freq: `~astropy.units.Quantity`
             Frequency, e.g., `1.0*au.MHz`

        Return
        ------
        Tb_list: list
             Point sources brightness temperature
        """
        # Tb_list
        num_ps = self.ps_catalog.shape[0]
        Tb_list = np.zeros((num_ps, 3))
        sr_to_arcsec2 = (np.rad2deg(1) * 3600) ** 2  # [sr] -> [arcsec^2]
        # Iteratively calculate Tb
        for i in range(num_ps):
            ps_area = self.ps_catalog['Area (sr)'][i]  # [sr]
            area = ps_area * sr_to_arcsec2
            Tb_list[i, :] = self.calc_single_Tb(area, freq)

        return Tb_list 

Example 13

def calc_Tb(self, freq):
        """
        Calculate the surface brightness  temperature of the point sources.

        Parameters
        ------------
        freq: `~astropy.units.Quantity`
             Frequency, e.g., `1.0*au.MHz`

        Return
        ------
        Tb_list: list
             Point sources brightness temperature
        """
        # Tb_list
        num_ps = self.ps_catalog.shape[0]
        Tb_list = np.zeros((num_ps,))
        sr_to_arcsec2 = (np.rad2deg(1) * 3600) ** 2  # [sr] -> [arcsec^2]
        # Iteratively calculate Tb
        for i in range(num_ps):
            ps_area = self.ps_catalog['Area (sr)'][i]  # [sr]
            area = ps_area * sr_to_arcsec2
            Tb_list[i] = self.calc_single_Tb(area, freq)

        return Tb_list 

Example 14

def calc_Tb(self, freq):
        """
        Calculate the surface brightness  temperature of the point sources.

        Parameters
        ------------
        freq: `~astropy.units.Quantity`
             Frequency, e.g., `1.0*au.MHz`

        Return
        ------
        Tb_list: list
             Point sources brightness temperature
        """
        # Tb_list
        num_ps = self.ps_catalog.shape[0]
        Tb_list = np.zeros((num_ps,))
        sr_to_arcsec2 = (np.rad2deg(1) * 3600) ** 2  # [sr] -> [arcsec^2]
        # Iteratively calculate Tb
        for i in range(num_ps):
            ps_area = self.ps_catalog['Area (sr)'][i]  # [sr]
            area = ps_area * sr_to_arcsec2
            Tb_list[i] = self.calc_single_Tb(area, freq)

        return Tb_list 

Example 15

def insertion_pitch(self):
        _circ_dv = self.circ_dv()
        _t_ap_dv = self.target_apoapsis_speed_dv()
        _m = np.rad2deg(self.mean_anomaly())
        _burn_time = self.maneuver_burn_time(self.circ_dv())

        @jit(nopython=True)
        def pitch_calcs_low():
                return (_t_ap_dv * (_circ_dv / 1000)) + (_m - (180 - (_burn_time / 12)))

        @jit(nopython=True)
        def pitch_calcs_high():
                return (_t_ap_dv * (_circ_dv / 1000)) + (_m - 180)

        if self.parking_orbit_alt <= 300000: return pitch_calcs_low()
        else: return pitch_calcs_high() 

Example 16

def azimuth(_lAz_data):
        _inc = _lAz_data[0]
        _lat = _lAz_data[1]
        velocity_eq = _lAz_data[2]

        @jit(nopython=True)
        def _az_calc():
            inert_az = np.arcsin(max(min(np.cos(np.deg2rad(_inc)) / np.cos(np.deg2rad(_lat)), 1), -1))
            _VXRot = _lAz_data[3] * np.sin(inert_az) - velocity_eq * np.cos(np.deg2rad(_lat))
            _VYRot = _lAz_data[3] * np.cos(inert_az)

            return np.rad2deg(np.fmod(np.arctan2(_VXRot, _VYRot) + (2 * pi), (2 * pi)))
        _az = _az_calc()

        if _lAz_data[4] == "Ascending": return _az

        if _lAz_data[4] == "Descending":
            if _az <= 90: return 180 - _az
            elif _az >= 270: return 540 - _az 

Example 17

def insertion_pitch(self):
        _circ_dv = self.circ_dv()
        _t_ap_dv = self.target_apoapsis_speed_dv()
        _m = np.rad2deg(self.mean_anomaly())
        _burn_time = self.maneuver_burn_time(self.circ_dv())

        def pitch_calcs_low():
                return (_t_ap_dv * (_circ_dv / 1000)) + (_m - (180 - (_burn_time / 12)))

        def pitch_calcs_high():
                return (_t_ap_dv * (_circ_dv / 1000)) + (_m - 180)

        if self.target_orbit_alt <= 250000: 
            self.pitchMode = "INS LOW"
            return pitch_calcs_low()
        else: 
            self.pitchMode = "INS HIGH"
            return pitch_calcs_high() 

Example 18

def azimuth(_lAz_data):
        _inc = _lAz_data[0]
        _lat = _lAz_data[1]
        velocity_eq = _lAz_data[2]

        def _az_calc():
            inert_az = np.arcsin(max(min(np.cos(np.deg2rad(_inc)) / np.cos(np.deg2rad(_lat)), 1), -1))
            _VXRot = _lAz_data[3] * np.sin(inert_az) - velocity_eq * np.cos(np.deg2rad(_lat))
            _VYRot = _lAz_data[3] * np.cos(inert_az)

            return np.rad2deg(np.fmod(np.arctan2(_VXRot, _VYRot) + 360, 360))
        _az = _az_calc()

        if _lAz_data[4] == "Ascending": return _az

        if _lAz_data[4] == "Descending":
            if _az <= 90: return 180 - _az
            elif _az >= 270: return 540 - _az 

Example 19

def magic3(self):
        time_end = 5123

        real_hofong_fix_pts = pd.read_csv('20161012_HoFong/control_points_coodination.csv').sort(ascending=False)
        real_hofong_fix_pts['N'] = real_hofong_fix_pts['N'] - real_hofong_fix_pts['N'][129]
        real_hofong_fix_pts['E'] = real_hofong_fix_pts['E'] - real_hofong_fix_pts['E'][129] # last data name=2717, index=129


        N_diff = np.diff(real_hofong_fix_pts['N'])
        E_diff = np.diff(real_hofong_fix_pts['E'])

        hofong_deg = np.rad2deg(np.arctan2(N_diff, E_diff))
        hofong_deg = hofong_deg - hofong_deg[0]
        hofong_deg_diff = np.cumsum(np.diff(hofong_deg))

        interp_hofong = np.interp(np.arange(100), np.arange(hofong_deg_diff.size), hofong_deg_diff)


        #plt.plot(hofong_deg, label='hahaxd')
        #plt.plot(hofong_deg_diff, label='hehexd')
        plt.plot(interp_hofong)
        plt.legend()
        plt.show() 

Example 20

def segment_angle(line1, line2):
        """ Angle between two segments """
        vector_a = np.array([line1[0][0]-line1[1][0],
                             line1[0][1]-line1[1][1]])
        vector_b = np.array([line2[0][0]-line2[1][0],
                             line2[0][1]-line2[1][1]])
        # Get dot prod
        dot_prod = np.dot(vector_a, vector_b)
        # Get magnitudes
        magnitude_a = np.dot(vector_a, vector_a)**0.5
        magnitude_b = np.dot(vector_b, vector_b)**0.5
        # Get angle in radians and then convert to degrees
        angle = np.arccos(dot_prod/magnitude_b/magnitude_a)
        # Basically doing angle <- angle mod 360
        ang_deg = np.rad2deg(angle)%360

        if ang_deg-180 >= 0:
            # As in if statement
            return 360 - ang_deg
        else:
            return ang_deg 

Example 21

def sphere2basemap(map, azimuthangle_polarangle_radialdistance):

    ## PT axis should not be givien to this, not same convention!

    azimuth = -1* (360 - (450. - np.rad2deg(azimuthangle_polarangle_radialdistance[0]))) # 450-
    takeoff =  90. - np.rad2deg(azimuthangle_polarangle_radialdistance[1]) #90. -
    #radius = azimuthangle_polarangle_radialdistance[2]

    while len(takeoff[takeoff>90.])>0 or len(takeoff[takeoff<-90.])>0 :

        azimuth[takeoff <-90.] += 180.
        takeoff[takeoff <-90.] = -180 - takeoff[takeoff <-90.]

        azimuth[takeoff  >90.] += 180.
        takeoff[takeoff  >90.] = 180 - takeoff[takeoff >90.]


    while len(azimuth[azimuth>360.])>0 or len(azimuth[azimuth<0.])>0 :

        azimuth[azimuth   <0.] += 360.
        azimuth[azimuth >360.] -= 360.


    return map( azimuth, takeoff ) 

Example 22

def mt_diff( mt1, mt2):

    fps = np.deg2rad([mt1.get_fps(), mt2.get_fps()])
    diff = [999999999, 999999999]
    for i in range(2):
        for j in range(2):

            test = haversine(lon1=fps[0][i][0], phi1=fps[0][i][1], lon2=fps[1][j][0], phi2=fps[1][j][1], radius=1.)

            while test>np.pi/2:
                test -= np.pi/2

            if test < diff[i]:
                diff[i] = test

    return np.rad2deg(np.mean(diff)) 

Example 23

def _correct(self, x):
        i = self.traj.shape[0] - 1
        d_lat = x[1] / earth.R0
        d_lon = x[0] / (earth.R0 * np.cos(self.lat_arr[i]))
        self.lat_arr[i] -= d_lat
        self.lon_arr[i] -= d_lon

        phi = x[4:7]
        phi[2] += d_lon * np.sin(self.lat_arr[i])

        VE_new = self.VE_arr[i] - x[2]
        VN_new = self.VN_arr[i] - x[3]

        self.VE_arr[i] = VE_new - phi[2] * VN_new
        self.VN_arr[i] = VN_new + phi[2] * VE_new

        self.Cnb_arr[i] = dcm.from_rv(phi).dot(self.Cnb_arr[i])
        h, p, r = dcm.to_hpr(self.Cnb_arr[i])

        self.traj.iloc[-1] = [np.rad2deg(self.lat_arr[i]),
                              np.rad2deg(self.lon_arr[i]),
                              self.VE_arr[i], self.VN_arr[i], h, p, r] 

Example 24

def __init__(self, filename, filename_info, filetype_info,
                 prologue, epilogue):
        """Initialize the reader."""
        super(HRITGOMSFileHandler, self).__init__(filename, filename_info,
                                                  filetype_info,
                                                  (goms_hdr_map,
                                                   goms_variable_length_headers,
                                                   goms_text_headers))
        self.prologue = prologue.prologue
        self.epilogue = epilogue.epilogue
        self.chid = self.mda['spectral_channel_id']
        sublon = self.epilogue['GeometricProcessing']['TGeomNormInfo']['SubLon']
        sublon = sublon[self.chid]
        self.mda['projection_parameters']['SSP_longitude'] = np.rad2deg(sublon)

        satellite_id = self.prologue['SatelliteStatus']['SatelliteID']
        self.platform_name = SPACECRAFTS[satellite_id] 

Example 25

def _lonlat_from_geos_angle(x, y, geos_area):
    """Get lons and lats from x, y in projection coordinates."""
    h = (geos_area.proj_dict['h'] + geos_area.proj_dict['a']) / 1000
    b__ = (geos_area.proj_dict['a'] / geos_area.proj_dict['b']) ** 2

    sd = np.sqrt((h * np.cos(x) * np.cos(y)) ** 2 -
                 (np.cos(y)**2 + b__ * np.sin(y)**2) *
                 (h**2 - (geos_area.proj_dict['a'] / 1000)**2))
    #sd = 0

    sn = (h * np.cos(x) * np.cos(y) - sd) / (np.cos(y)**2 + b__ * np.sin(y)**2)
    s1 = h - sn * np.cos(x) * np.cos(y)
    s2 = sn * np.sin(x) * np.cos(y)
    s3 = -sn * np.sin(y)
    sxy = np.sqrt(s1**2 + s2**2)

    lons = np.rad2deg(np.arctan2(s2, s1)) + geos_area.proj_dict.get('lon_0', 0)
    lats = np.rad2deg(-np.arctan2(b__ * s3, sxy))

    return lons, lats 

Example 26

def xyzToSpherical(x,y,z):
    ''' 
    Convert x,y,z to spherical coordinates

    @param x: Cartesian coordinate x
    @param y: Cartesian coordinate y
    @param z: Cartesian coordinate z

    @return numpy array of latitude,longitude, and radius
    '''
    radius = np.sqrt(x**2 + y**2 + z**2)
    theta = np.rad2deg(np.arctan2(y,x))
    phi = np.rad2deg(np.arccos(z/radius))
    # lon = (theta + 180) % 360 - 180
    # lon = (theta + 360) % 360
    lon = theta
    lat = 90 - phi
    
    return np.array([lat,lon,radius]).T 

Example 27

def _calculate_zmat_values(self, construction_table):
        c_table = construction_table
        if not isinstance(c_table, pd.DataFrame):
            if isinstance(c_table, pd.Series):
                c_table = pd.DataFrame(c_table).T
            else:
                c_table = np.array(c_table)
                if len(c_table.shape) == 1:
                    c_table = c_table[None, :]
                c_table = pd.DataFrame(
                    data=c_table[:, 1:], index=c_table[:, 0],
                    columns=['b', 'a', 'd'])
        c_table = c_table.replace(constants.int_label).astype('i8')
        c_table.index = c_table.index.astype('i8')

        new_index = c_table.index.append(self.index.difference(c_table.index))
        X = self.loc[new_index, ['x', 'y', 'z']].values.astype('f8').T
        c_table = c_table.replace(dict(zip(new_index, range(len(self)))))
        c_table = c_table.values.T

        err, C = transformation.get_C(X, c_table)
        if err == ERR_CODE_OK:
            C[[1, 2], :] = np.rad2deg(C[[1, 2], :])
            return C.T 

Example 28

def orientArrow(self):
        phi = num.median(self.model.scene.phi)
        theta = num.median(self.model.scene.theta)

        angle = -num.rad2deg(phi)
        theta_f = theta / (num.pi/2)

        tipAngle = 30. + theta_f * 20.
        tailLen = 15 + theta_f * 15.

        self.arrow.setStyle(
            angle=angle,
            tipAngle=tipAngle,
            tailLen=tailLen,
            tailWidth=6,
            headLen=25)
        self.arrow.setRotation(self.arrow.opts['angle']) 

Example 29

def getCornerFeatures(img):
	gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
	corners = skimage.feature.corner_peaks(skimage.feature.corner_fast(gray, 14), min_distance=1)
	orientations = skimage.feature.corner_orientations(gray, corners, octagon(3, 2))
	corners = np.rad2deg(orientations)

	corners = np.array(corners)
	AngleBins = np.arange(0,360,45);
	AngleBinsOrientation = np.array([0, 1, 2, 1, 0, 1, 2, 1])
	OrientationHist = np.zeros((3,1))
	for a in corners:
		OrientationHist[AngleBinsOrientation[np.argmin(np.abs(a-AngleBins))]] += 1	

	if OrientationHist.sum()>0:
		OrientationHist = OrientationHist / OrientationHist.sum()
	else:
		OrientationHist = - 0.01*np.ones((3,1))

	F = []
	F.extend(OrientationHist[:,0].tolist())
	F.append(100.0*float(len(corners)) / ( gray.shape[0] * gray.shape[1] ) )
	Fnames = ["Corners-Hor", "Corners-Diag", "Corners-Ver", "Corners-Percent"]
	return (F, Fnames) 

Example 30

def __new__(cls, realpart, imagpart=None):
        """Create a new EMArray."""

        # Create complex obj
        if np.any(imagpart):
            obj = np.real(realpart) + 1j*np.real(imagpart)
        else:
            obj = np.asarray(realpart, dtype=complex)

        # Ensure its at least a 1D-Array, view cls
        obj = np.atleast_1d(obj).view(cls)

        # Store amplitude
        obj.amp = np.abs(obj)

        # Calculate phase, unwrap it, transform to degrees
        obj.pha = np.rad2deg(np.unwrap(np.angle(obj.real + 1j*obj.imag)))

        return obj


# 2. Input parameter checks for modelling

# 2.a <Check>s (alphabetically) 

Example 31

def _estimate_current_anticlockwise_degrees_using_minarearect(self, spot_xy) -> float:
        # Find the minimum area rectangle around the number
        nearby_contour_groups = contour_tools.extract_contour_groups_close_to(
            self.contour_groups, target_point_xy=spot_xy, delta=self._min_pixels_between_contour_groups)
        nearby_contours = [c for grp in nearby_contour_groups for c in grp]
        box = cv2.minAreaRect(np.row_stack(nearby_contours))
        corners_xy = cv2.boxPoints(box).astype(np.int32)
        self._log_contours_on_current_image([corners_xy], name="Minimum area rectangle")

        # Construct a vector which, once correctly rotated, goes from the bottom right corner up & left at 135 degrees
        sorted_corners = sorted(corners_xy, key=lambda pt: np.linalg.norm(spot_xy - pt))
        bottom_right_corner = sorted_corners[0]  # The closest corner to the spot
        adjacent_corners = sorted_corners[1:3]  # The next two closest corners

        unit_vectors_along_box_edge = misc.normalised(adjacent_corners - bottom_right_corner)
        up_left_diagonal = unit_vectors_along_box_edge.sum(axis=0)

        degrees_of_up_left_diagonal = np.rad2deg(np.arctan2(-up_left_diagonal[1], up_left_diagonal[0]))
        return degrees_of_up_left_diagonal - 135 

Example 32

def create_rotated_sub_image(image, centre, search_width, angle_rad):
    # Rotation transform requires x then y.
    M = cv2.getRotationMatrix2D((centre[1], centre[0]), np.rad2deg(angle_rad), 1.0)

    w = image.shape[1]
    h = centre[0] + int((image.shape[0] - centre[0]) * abs(math.sin(angle_rad)))
    rotated = cv2.warpAffine(image, M, (w, h))

    # Centre the last white centroid into the centre of the image.
    half_sub_image_width = int(min(min(search_width, centre[1]),
                                   min(rotated.shape[1] - centre[1], search_width)))

    sub_image = rotated[centre[0]:,
                centre[1] - half_sub_image_width: centre[1] + half_sub_image_width]

    return sub_image 

Example 33

def rotate_monomers(self, angle, radians=False):
        """ Rotates each Residue in the Polypeptide.

        Notes
        -----
        Each monomer is rotated about the axis formed between its
        corresponding primitive `PseudoAtom` and that of the 
        subsequent `Monomer`.

        Parameters
        ----------
        angle : float
            Angle by which to rotate each monomer.
        radians : bool
            Indicates whether angle is in radians or degrees.
        """
        if radians:
            angle = numpy.rad2deg(angle)
        for i in range(len(self.primitive) - 1):
            axis = self.primitive[i + 1]['CA'] - self.primitive[i]['CA']
            point = self.primitive[i]['CA']._vector
            self[i].rotate(angle=angle, axis=axis, point=point)
        return 

Example 34

def obj_get_joint_angle(self, handle):
		angle = self.RAPI_rc(vrep.simxGetJointPosition( self.cID,handle,
				vrep.simx_opmode_blocking
			)
		)
		return -np.rad2deg(angle[0]) 

Example 35

def cart2pol(x, y):
        rho = np.sqrt(x**2 + y**2)
        phi = 180 + np.rad2deg(np.arctan2(y, x))  # 0-360 [deg]
        return (rho, phi) 

Example 36

def max_distance_deg(self):
        return np.rad2deg(self.max_distance) 

Example 37

def process_lidar_csv_file(filename):
    with open(filename) as csvfile:
        reader = csv.DictReader(csvfile)

        csv_rows = [row for row in reader]
        print "%s lidar records" % len(csv_rows)

        n_limit_rows = 1000000

        lidar_obss = []
        bbox_obss = [[],[],[]]

        for i, row in enumerate(csv_rows):
            if i > n_limit_rows - 1:
                break

            time_ns = int(row['time'])
            x, y, z, yaw = float(row['x']), float(row['y']), float(row['z']), float(row['yaw'])
            l, w, h = float(row['l']), float(row['w']), float(row['h'])

            obs = LidarObservation(time_ns * 1e-9, x, y, z, yaw)
            lidar_obss.append(obs)

            bbox_obss[0].append(l)
            bbox_obss[1].append(w)
            bbox_obss[2].append(h)

        yaw = [np.rad2deg(o.yaw) for o in lidar_obss]
        print np.std(yaw)
        #plt.figure(figsize=(16,8))
        #plt.plot(yaw)
        #plt.grid(True)

        return lidar_obss, bbox_obss 

Example 38

def phase(z):
    val = np.angle(z)
    # val = np.rad2deg(np.unwrap(np.angle((z))))
    return val 

Example 39

def getReflectionandTransmission(sig1, sig2, f, theta_i, eps1=epsilon_0, eps2=epsilon_0, mu1=mu_0, mu2=mu_0,dtype="TE"):
    """
    Compute reflection and refraction coefficient of plane waves
    """
    theta_i = np.deg2rad(theta_i)
    omega = 2*np.pi*f

    k1 = np.sqrt(omega**2*mu1*eps1-1j*omega*mu1*sig1)
    k2 = np.sqrt(omega**2*mu2*eps2-1j*omega*mu2*sig2)

    if dtype == "TE":
        bunmo = mu2*k1*np.cos(theta_i) + mu1*(k2**2-k1**2*np.sin(theta_i)**2)**0.5
        bunja_r = mu2*k1*np.cos(theta_i) - mu1*(k2**2-k1**2*np.sin(theta_i)**2)**0.5
        bunja_t = 2*mu2*k1*np.cos(theta_i)
    elif dtype == "TM":
        bunmo = mu2*k1*(k2**2-k1**2*np.sin(theta_i)**2)**0.5 + mu1*k2**2 * np.cos(theta_i)
        bunja_r = mu2*k1*(k2**2-k1**2*np.sin(theta_i)**2)**0.5 - mu1*k2**2 * np.cos(theta_i)
        bunja_t = 2*mu1*k2**2*np.cos(theta_i)
    else:
        raise Exception("XXX")

    r = bunja_r / bunmo
    t = bunja_t / bunmo

    theta_t = np.rad2deg(abs(np.arcsin(k1/k2 * np.sin(theta_i))))
    return r, t, theta_t 

Example 40

def rotXYZ(R, unit='deg'):
    """ Compute Euler angles from matrix R using XYZ sequence."""

    angles = np.zeros(3)
    angles[0] = np.arctan2(R[2, 1], R[2, 2])
    angles[1] = np.arctan2(-R[2, 0], np.sqrt(R[0, 0]**2 + R[1, 0]**2))
    angles[2] = np.arctan2(R[1, 0], R[0, 0])

    if unit[:3].lower() == 'deg':  # convert from rad to degree
        angles = np.rad2deg(angles)

    return angles 

Example 41

def visibility(cam, footprints, targets):
    """    
    This function tests is the target points (x,y only) are "visable" (i.e.
    within the photo footprints) and calculates the "r" angle for the refraction 
    correction\n
    Vars:\n
    \t cam = Pandas dataframe (n x ~6, fields: x,y,z,yaw,pitch,roll)\n
    \t footprints = Pandas dataframe (n x 1) of Matplotlib Path objects\n
    \t targets = Pandas dataframe (n x ~3, fields: x,y,sfm_z...)\n
    
    RETURNS: r_filt = numpy array (n_points x n_cams) of filtered "r" angles.\n
    Points that are not visable to a camera will have a NaN "r" angle. 
    """
    
    # Setup boolean array for visability
    vis = np.zeros((targets.shape[0],cam.shape[0])) 
    
    # for each path objec in footprints, check is the points in targets are
    #   within the path polygon. path.contains_points returns boolean.
    #   the results are accumulated in the vis array.
    for idx in range(footprints.shape[0]):
        path = footprints.fov[idx]
        vis[:,idx] = path.contains_points(np.array([targets.x.values, targets.y.values]).T)
    
    # calculate the coord. deltas between the cameras and the target
    dx = np.atleast_2d(cam.x.values) - np.atleast_2d(targets.x.values).T
    dy = np.atleast_2d(cam.y.values) - np.atleast_2d(targets.y.values).T
    dz = np.atleast_2d(cam.z.values) - np.atleast_2d(targets.sfm_z).T
    
    # calc xy distance (d)
    d = np.sqrt((dx)**2+(dy)**2)
    
    # calc inclination angle (r) from targets to cams
    r = np.rad2deg(np.arctan(d/dz))
    
    r_filt = r * vis
    r_filt[r_filt == 0] = np.nan
          
    return r_filt 

Example 42

def visibility(cam, footprints, targets):
    """    
    This function tests is the target points (x,y only) are "visable" (i.e.
    within the photo footprints) and calculates the "r" angle for the refraction 
    correction\n
    Vars:\n
    \t cam = Pandas dataframe (n x ~6, fields: x,y,z,yaw,pitch,roll)\n
    \t footprints = Pandas dataframe (n x 1) of Matplotlib Path objects\n
    \t targets = Pandas dataframe (n x ~3, fields: x,y,sfm_z...)\n
    
    RETURNS: r_filt = numpy array (n_points x n_cams) of filtered "r" angles.\n
    Points that are not visable to a camera will have a NaN "r" angle. 
    """
    
    # Setup boolean array for visability
    vis = np.zeros((targets.shape[0],cam.shape[0])) 
    
    # for each path objec in footprints, check is the points in targets are
    #   within the path polygon. path.contains_points returns boolean.
    #   the results are accumulated in the vis array.
    for idx in range(footprints.shape[0]):
        path = footprints.fov[idx]
        vis[:,idx] = path.contains_points(np.array([targets.x.values, targets.y.values]).T)
    
    # calculate the coord. deltas between the cameras and the target
    dx = np.atleast_2d(cam.x.values) - np.atleast_2d(targets.x.values).T
    dy = np.atleast_2d(cam.y.values) - np.atleast_2d(targets.y.values).T
    dz = np.atleast_2d(cam.z.values) - np.atleast_2d(targets.sfm_z).T
    
    # calc xy distance (d)
    d = np.sqrt((dx)**2+(dy)**2)
    
    # calc inclination angle (r) from targets to cams
    r = np.rad2deg(np.arctan(d/dz))
    
    r_filt = r * vis
    r_filt[r_filt == 0] = np.nan
          
    return r_filt 

Example 43

def insertion_pitch(self):
        _circ_dv = self.circ_dv()
        _t_ap_dv = self.target_apoapsis_speed_dv()
        _m = np.rad2deg(self.mean_anomaly())
        _burn_time = self.maneuver_burn_time(self.circ_dv())

        @jit(nopython=True)
        def pitch_calcs_low():
                return (_t_ap_dv * (_circ_dv / 1000)) + (_m - (180 - (_burn_time / 6)))

        @jit(nopython=True)
        def pitch_calcs_high():
                return (_t_ap_dv * (_circ_dv / 1000)) + (_m - 180)

        # if self.parking_orbit_alt <= 250000: return pitch_calcs_low()
        # else: return pitch_calcs_high()
        return pitch_calcs_high() 

Example 44

def test(self):
        # -#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#
        #             T E S T I N G              #
        # -#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#

        while True:
            print(np.rad2deg(self.moon_mean_anomaly()))
            time.sleep(1) 

Example 45

def transfer(self):
        # -#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#
        #               L U N A R                #
        #            T R A N S F E R             #
        # -#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#

        self.control.rcs = False
        self.control.throttle = 0
        time.sleep(1)
        self.ap.reference_frame = self.vessel.orbital_reference_frame
        self.ap.target_direction = (0, 1, 0)
        self.ap.engage()
        print(self.mode)

        while self.mode != "Xfered":
            self.injection_ETA = self.xfer_ETA(self.ut() + self.seconds_finder(5, 16, 00),
                                               self.moon_LAN(), self.moon_argument_of_periapsis())

            if self.mode == "Testing":
                print(np.rad2deg(self.moon_mean_anomaly()))
                self.mode = "Xfered"

            if self.mode == "LEO Cruise":
                self.KSC.warp_to(self.ut() + self.injection_ETA - 140)
                if self.injection_ETA < 130: self.mode = "AoA"; print(self.mode); time.sleep(2)

            if self.mode == "AoA":
                print(self.injection_ETA)
                if self.injection_ETA > 170: self.mode = "LEO Cruise"
                if self.injection_ETA > 25: self.fix_aoa(self.injection_ETA)
                elif self.injection_ETA <= 25: self.xfer()

            if self.mode == "Injection":
                self.flameout("Transfer")
                if self.vessel.mass < 20: self.mode = "Xfered"; print(self.mode)

            time.sleep(.1)

        print("Done") 

Example 46

def update(self, quad):
        """
        Set the new position and rotation of the quadcopter: ``pos`` is a tuple
        (x, y, z), and rpy is a tuple (roll, pitch, yaw) expressed in
        *radians*
        """
        x, y, z = quad.position
        roll, pitch, yaw = np.rad2deg(quad.rpy)
        self.quadplot.resetTransform()
        self.quadplot.translate(x, y, z)
        self.quadplot.rotate(roll, 1, 0, 0, local=True)
        self.quadplot.rotate(pitch, 0, 1, 0, local=True)
        self.quadplot.rotate(yaw, 0, 0, 1, local=True)
        #
        self.label_t.setText('t = %5.2f' % quad.t) 

Example 47

def convert_to_degspd(u,v):
    """Convert arrays of u,v vectors to arrays of direction (in met.deg) and speed
        
    Arguments:
    u - np array of the u (east) part of the vector
    v - np array of the v (north) part of the vector
    """
    dir_spd = [] 
    wind_direction = (np.rad2deg(np.arctan2(-u,-v))) % 360.0
    wind_speed = np.sqrt(u ** 2 + v ** 2)
    dir_spd.append(wind_direction)
    dir_spd.append(wind_speed)
    return np.array(dir_spd) #[[list of wind dirs], [list of wind spds]] 

Example 48

def _rotate_interp_builtin(array, alpha, center, mode='constant', cval=0):
    '''
    Rotation with the built-in rotation function.

    The center of rotation is exactly ((dimx-1) / 2, (dimy-1) / 2),
    whatever the odd/even-ity of the image dimensions

    '''
    alpha_rad = -np.deg2rad(alpha)

    # center of rotation: ((dims[1]-1) / 2, (dims[0]-1) / 2)
    rotated = ndimage.interpolation.rotate(array, np.rad2deg(-alpha_rad), reshape=False, order=3, mode=mode, cval=cval)

    return rotated 

Example 49

def update_scene(self, x):
        x0 = x[0]
        phi1 = np.rad2deg(x[2])
        phi2 = np.rad2deg(x[4])

        # cart and shaft
        self.cart.set_x(-st.cart_length/2 + x0)
        self.pendulum_shaft.center = [x0, 0]

        t_phi1 = (mpl.transforms.Affine2D().rotate_deg_around(x0, 0, phi1)
                  + self.axes.transData)
        t_phi2 = (mpl.transforms.Affine2D().rotate_deg_around(x0, 0, phi2)
                  + self.axes.transData)

        # long pendulum
        self.long_pendulum.set_xy([-st.long_pendulum_radius + x0, 0])
        self.long_pendulum.set_transform(t_phi1)
        self.long_pendulum_weight.set_xy([-st.pendulum_weight_radius
                                          + x0, st.long_pendulum_height])
        self.long_pendulum_weight.set_transform(t_phi1)

        # short pendulum
        self.short_pendulum.set_xy(np.array([-st.short_pendulum_radius, 0])
                                   + np.array([x0, 0]))
        self.short_pendulum.set_transform(t_phi2)
        self.short_pendulum_weight.set_xy([-st.pendulum_weight_radius + x0,
                                           st.short_pendulum_height])

        self.short_pendulum_weight.set_transform(t_phi2)
        self.canvas.draw() 

Example 50

def transform(self, ppos, pdir, point):
		xr = point[0]-ppos[0]
		yr = point[1]-ppos[1]
		ang = angle_between360(pdir,northvector)
		#print np.rad2deg(ang)
		w = rotate([xr,yr],ang)
		return w+self.midpoint 
点赞