Python numpy.degrees() Examples

The following are 30 code examples of numpy.degrees(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module numpy , or try the search function .
Example #1
Source File: custom_scale.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 7 votes vote down vote up
def set_default_locators_and_formatters(self, axis):
        """
        Override to set up the locators and formatters to use with the
        scale.  This is only required if the scale requires custom
        locators and formatters.  Writing custom locators and
        formatters is rather outside the scope of this example, but
        there are many helpful examples in ``ticker.py``.

        In our case, the Mercator example uses a fixed locator from
        -90 to 90 degrees and a custom formatter class to put convert
        the radians to degrees and put a degree symbol after the
        value::
        """
        class DegreeFormatter(Formatter):
            def __call__(self, x, pos=None):
                return "%d\N{DEGREE SIGN}" % np.degrees(x)

        axis.set_major_locator(FixedLocator(
            np.radians(np.arange(-90, 90, 10))))
        axis.set_major_formatter(DegreeFormatter())
        axis.set_minor_formatter(DegreeFormatter()) 
Example #2
Source File: main_ui.py    From innstereo with GNU General Public License v2.0 6 votes vote down vote up
def add_eigenvector_feature(self, datastore, dip_direct=0, dip=0, value=0):
        """
        Adds an eigenvector feature.

        Checks if the values lie in the normal range of degrees. Then the
        row is appended to the treestore that is passed to the method.
        """
        while dip_direct > 360:
            dip_direct = dip_direct - 360
        while dip_direct < 0:
            dip_direct = dip_direct + 360
        while dip > 90:
            dip = dip - 90
        while dip < 0:
            dip = dip + 90

        itr = datastore.append([dip_direct, dip, value])
        return itr 
Example #3
Source File: pkl_utils.py    From astrobase with MIT License 6 votes vote down vote up
def _xyzdist_to_distarcsec(xyzdist):
    '''This inverts the xyz unit vector distance -> angular distance relation.

    Parameters
    ----------

    xyzdist : float or array-like
        This is the distance in xyz vector space generated from a transform of
        (RA,Dec) - > (x,y,z)

    Returns
    -------

    dist_arcseconds : float or array-like
        The distance in arcseconds.

    '''

    return np.degrees(2.0*np.arcsin(xyzdist/2.0))*3600.0 
Example #4
Source File: BeamBlock.py    From PyRadarMet with GNU General Public License v2.0 6 votes vote down vote up
def plot_range_ring(self, range_ring_location_km, bm=None,
                        color='k', ls='-'):
        """
        Plot a single range ring.
        Parameters::
        ----------
        range_ring_location_km : float
            Location of range ring in km.
        npts: int
            Number of points in the ring, higher for better resolution.
        ax : Axis
            Axis to plot on. None will use the current axis.
        """
        npts = 100
        bm.tissot(self.rlon, self.rlat, 
                  np.degrees(range_ring_location_km * 1000. / RE), npts,
                  fill=False, color='black', linestyle='dashed')
    
################
# Save methods #
################ 
Example #5
Source File: shapes.py    From napari with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _rotate_box(self, angle, center=[0, 0]):
        """Perfrom a rotation on the selected box.

        Parameters
        ----------
        angle : float
            angle specifying rotation of shapes in degrees.
        center : list
            coordinates of center of rotation.
        """
        theta = np.radians(angle)
        transform = np.array(
            [[np.cos(theta), np.sin(theta)], [-np.sin(theta), np.cos(theta)]]
        )
        box = self._selected_box - center
        self._selected_box = box @ transform.T + center 
Example #6
Source File: omni_hro.py    From pysat with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def calculate_clock_angle(inst):
    """ Calculate IMF clock angle and magnitude of IMF in GSM Y-Z plane

    Parameters
    -----------
    inst : pysat.Instrument
        Instrument with OMNI HRO data
    """

    # Calculate clock angle in degrees
    clock_angle = np.degrees(np.arctan2(inst['BY_GSM'], inst['BZ_GSM']))
    clock_angle[clock_angle < 0.0] += 360.0
    inst['clock_angle'] = pds.Series(clock_angle, index=inst.data.index)

    # Calculate magnitude of IMF in Y-Z plane
    inst['BYZ_GSM'] = pds.Series(np.sqrt(inst['BY_GSM']**2 +
                                         inst['BZ_GSM']**2),
                                 index=inst.data.index)

    return 
Example #7
Source File: coordutils.py    From astrobase with MIT License 6 votes vote down vote up
def hms_str_to_decimal(hms_string):
    '''Converts a HH:MM:SS string to decimal degrees.

    Parameters
    ----------

    hms_string : str
        A right ascension coordinate string of the form: 'HH:MM:SS.sss'
        or 'HH MM SS.sss'.

    Returns
    -------

    float
        The RA value in decimal degrees (wrapped around 360.0 deg if necessary.)

    '''
    return hms_to_decimal(*hms_str_to_tuple(hms_string)) 
Example #8
Source File: test_iphas.py    From dustmaps with GNU General Public License v2.0 6 votes vote down vote up
def test_bounds(self):
        """
        Test that out-of-bounds coordinates return NaN reddening, and that
        in-bounds coordinates do not return NaN reddening.
        """

        for mode in (['random_sample', 'random_sample_per_pix',
                      'median', 'samples', 'mean']):
            # Draw random coordinates on the sphere
            n_pix = 10000
            u, v = np.random.random((2,n_pix))
            l = 360. * u
            b = 90. - np.degrees(np.arccos(2.*v - 1.))
            c = coords.SkyCoord(l, b, frame='galactic', unit='deg')

            A_calc = self._iphas(c, mode=mode)

            in_bounds = (l > 32.) & (l < 213.) & (b < 4.5) & (b > -4.5)
            out_of_bounds = (l < 28.) | (l > 217.) | (b > 7.) | (b < -7.)

            n_nan_in_bounds = np.sum(np.isnan(A_calc[in_bounds]))
            n_finite_out_of_bounds = np.sum(np.isfinite(A_calc[out_of_bounds]))

            self.assertTrue(n_nan_in_bounds == 0)
            self.assertTrue(n_finite_out_of_bounds == 0) 
Example #9
Source File: main_ui.py    From innstereo with GNU General Public License v2.0 6 votes vote down vote up
def convert_xy_to_dirdip(self, event):
        """
        Converts xy-coordinates of a matplotlib-event into dip-direction/dip
        by using the inverse transformation of mplstereonet. Returns floats in
        degree.
        """
        alpha = np.arctan2(event.xdata, event.ydata)
        alpha_deg = np.degrees(alpha)
        if alpha_deg < 0:
            alpha_deg += 360

        xy = np.array([[event.xdata, event.ydata]])
        xy_trans = self.inv.transform(xy)

        x = float(xy_trans[0,0:1])
        y = float(xy_trans[0,1:2])

        array = mplstereonet.stereonet_math._rotate(np.degrees(x),
                    np.degrees(y), (-1)*alpha_deg)

        gamma = float(array[1])
        gamma_deg = 90 - np.degrees(gamma)
        return alpha_deg, gamma_deg 
Example #10
Source File: sgp4_prop.py    From orbitdeterminator with MIT License 6 votes vote down vote up
def __true_to_mean(T,e):
    """Converts true anomaly to mean anomaly.

       Args:
           T(float): true anomaly in degrees
           e(float): eccentricity

       Returns:
           float: the mean anomaly in degrees
    """

    T = np.radians(T)
    E = np.arctan2((1-e**2)*np.sin(T),e+np.cos(T))
    M = E - e*np.sin(E)
    M = np.degrees(M)
    M = M%360
    return M

# Parts of this method have been copied from:
# https://github.com/brandon-rhodes/python-sgp4/blob/master/sgp4/io.py 
Example #11
Source File: rectify.py    From facade-segmentation with MIT License 6 votes vote down vote up
def _hlines(lines, ctrs=None, lengths=None, vecs=None, angle_lo=20, angle_hi=160, ransac_options=RANSAC_OPTIONS):
    ctrs = ctrs if ctrs is not None else lines.mean(1)
    vecs = vecs if vecs is not None else lines[:, 1, :] - lines[:, 0, :]
    lengths = lengths if lengths is not None else np.hypot(vecs[:, 0], vecs[:, 1])

    angles = np.degrees(np.arccos(vecs[:, 1] / lengths))
    points = np.column_stack([ctrs[:, 1], angles])
    point_indices, = np.nonzero((angles > angle_lo) & (angles < angle_hi))
    points = points[point_indices]
    if len(points) > 2:
        model_ransac = linear_model.RANSACRegressor(**ransac_options)
        model_ransac.fit(points[:, 0].reshape(-1, 1), points[:, 1].reshape(-1, 1))
        inlier_mask = model_ransac.inlier_mask_
        valid_lines = lines[point_indices[inlier_mask], :, :]
    else:
        valid_lines = []
    return valid_lines 
Example #12
Source File: rectify.py    From facade-segmentation with MIT License 6 votes vote down vote up
def _vlines(lines, ctrs=None, lengths=None, vecs=None, angle_lo=20, angle_hi=160, ransac_options=RANSAC_OPTIONS):
    ctrs = ctrs if ctrs is not None else lines.mean(1)
    vecs = vecs if vecs is not None else lines[:, 1, :] - lines[:, 0, :]
    lengths = lengths if lengths is not None else np.hypot(vecs[:, 0], vecs[:, 1])

    angles = np.degrees(np.arccos(vecs[:, 0] / lengths))
    points = np.column_stack([ctrs[:, 0], angles])
    point_indices, = np.nonzero((angles > angle_lo) & (angles < angle_hi))
    points = points[point_indices]
    if len(points) > 2:
        model_ransac = linear_model.RANSACRegressor(**ransac_options)
        model_ransac.fit(points[:, 0].reshape(-1, 1), points[:, 1].reshape(-1, 1))
        inlier_mask = model_ransac.inlier_mask_
        valid_lines = lines[point_indices[inlier_mask], :, :]
    else:
        valid_lines = []
    return valid_lines 
Example #13
Source File: elements.py    From orbital with MIT License 6 votes vote down vote up
def __str__(self):
        return ('{name}:\n'
                '    Semimajor axis (a)                           = {a:10.3f} km\n'
                '    Eccentricity (e)                             = {self.e:13.6f}\n'
                '    Inclination (i)                              = {i:8.1f} deg\n'
                '    Right ascension of the ascending node (raan) = {raan:8.1f} deg\n'
                '    Argument of perigee (arg_pe)                 = {arg_pe:8.1f} deg\n'
                '    Mean anomaly at reference epoch (M0)         = {M0:8.1f} deg\n'
                '    Period (T)                                   = {T}\n'
                '    Reference epoch (ref_epoch)                  = {self.ref_epoch!s}\n'
                '        Mean anomaly (M)                         = {M:8.1f} deg\n'
                '        Time (t)                                 = {t}\n'
                '        Epoch (epoch)                            = {self.epoch!s}'
                ).format(
                    name=self.__class__.__name__,
                    self=self,
                    a=self.a / kilo,
                    i=degrees(self.i),
                    raan=degrees(self.raan),
                    arg_pe=degrees(self.arg_pe),
                    M0=degrees(self.M0),
                    M=degrees(self.M),
                    T=timedelta(seconds=self.T),
                    t=timedelta(seconds=self.t)) 
Example #14
Source File: tracking.py    From pvlib-python with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def singleaxis(self, apparent_zenith, apparent_azimuth):
        """
        Get tracking data. See :py:func:`pvlib.tracking.singleaxis` more
        detail.

        Parameters
        ----------
        apparent_zenith : float, 1d array, or Series
            Solar apparent zenith angles in decimal degrees.

        apparent_azimuth : float, 1d array, or Series
            Solar apparent azimuth angles in decimal degrees.

        Returns
        -------
        tracking data
        """
        tracking_data = singleaxis(apparent_zenith, apparent_azimuth,
                                   self.axis_tilt, self.axis_azimuth,
                                   self.max_angle,
                                   self.backtrack, self.gcr)

        return tracking_data 
Example #15
Source File: rototranslation.py    From differentiable-renderer with MIT License 6 votes vote down vote up
def __init__(self, rotation: Vector, translation: Vector, angle_unit: str, notation: str='XYZ'):
        self.rotation    = rotation
        self.translation = translation

        self.angle_unit = angle_unit
        if self.angle_unit == 'degrees':
            self.rotation = Vector(*[radians(alpha) for alpha in rotation])

        self.R_x = None
        self.R_y = None
        self.R_z = None
        self.T   = None

        self.matrix = None
        self.notation = notation

        self._update_matrix() 
Example #16
Source File: tools.py    From pvlib-python with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def asind(number):
    """
    Inverse Sine returning an angle in degrees

    Parameters
    ----------
    number : float
        Input number

    Returns
    -------
    result : float
        arcsin result
    """

    res = np.degrees(np.arcsin(number))
    return res 
Example #17
Source File: tools.py    From pvlib-python with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def tand(angle):
    """
    Tan with angle input in degrees

    Parameters
    ----------
    angle : float
        Angle in degrees

    Returns
    -------
    result : float
        Tan of the angle
    """

    res = np.tan(np.radians(angle))
    return res 
Example #18
Source File: tools.py    From pvlib-python with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def sind(angle):
    """
    Sine with angle input in degrees

    Parameters
    ----------
    angle : float
        Angle in degrees

    Returns
    -------
    result : float
        Sin of the angle
    """

    res = np.sin(np.radians(angle))
    return res 
Example #19
Source File: CoordTransforms3.py    From PyGPS with GNU Affero General Public License v3.0 5 votes vote down vote up
def xy2angles(x,y):
    elout = 90-np.hypot(x,y)
    azout = np.degrees(np.arctan2(x,y))
    return (azout,elout) 
Example #20
Source File: teme_to_ecef.py    From orbitdeterminator with MIT License 5 votes vote down vote up
def conv_to_ecef(coords):
    """Converts coordinates in TEME frame to ECEF frame.

       Args:
           coords(nx4 numpy array): list of coordinates in the format [t,x,y,z]

       Returns:
           nx4 numpy array: list of coordinates in the format
                            [t, latitude, longitude, altitude]

                            Note that these coordinates are with respect to the
                            surface of the Earth. Latitude, longitude are in degrees.
    """

    t = coords[:,0]
    x = coords[:,1]
    y = coords[:,2]
    z = coords[:,3]

    alt = (x**2+y**2+z**2)**0.5
    lat = np.degrees(np.arcsin(z/alt))
    lng = np.degrees(np.arctan2(y,x)%(2*np.pi))

    midnight = datetime.fromtimestamp(t[0],tz=timezone.utc)
    midnight = midnight.replace(hour=0,minute=0,second=0,microsecond=0)
    t_mid = midnight.timestamp()

    J2000 = 946728000
    Tu = (t_mid-J2000)/86400/36525
    tg0h = 24110.54841 + 8640184.812866*Tu + 0.093104*Tu**2 - 6.2e-6*Tu**3
    we = 1.00273790935
    tgt = tg0h + we*(t-t_mid)
    era = (tgt%86400)*360/86400
    lng = lng-era
    return np.column_stack((t,lat,lng,alt)) 
Example #21
Source File: CoordTransforms3.py    From PyGPS with GNU Affero General Public License v3.0 5 votes vote down vote up
def cartisian2Sphereical(cartcoords):
    """This function will convert Cartisian coordinates to Spherical coordinates.
    Input
    cartcoords - A 3xN numpy array with X, Y and Z in a Cartisian coordinate space.
    The coordinates are in units of kilometers.
    Output
    spherecoords - A 3xN numpy array with rows of range (in km) azimuth (in degrees)
    and elevation (in degrees)."""
    r2d = 180/np.pi
    (dir1,dir2) = cartcoords.shape
    transcoords = False
    if dir2==3:
        cartcoords = np.transpose(cartcoords)
        transcoords  = True
    if 3 not in cartcoords.shape:
        raise ValueError('Neither of the dimensions are of length 3')
    (x,y,z) = cartcoords[:]

    R = np.sqrt(x**2+y**2+z**2)
    Az = np.arctan2(y,x)*r2d
    El = np.arcsin(z/R)*r2d

    spherecoords = np.array([R,Az,El])

    if transcoords:
        spherecoords=np.transpose(spherecoords)
    return spherecoords 
Example #22
Source File: main_ui.py    From innstereo with GNU General Public License v2.0 5 votes vote down vote up
def convert_lonlat_to_dipdir(self, lon, lat):
        """
        Converts lat-lon data to dip-direction and dip.

        Expects a longitude and a latitude value. The measurment is forward
        transformed into stereonet-space. Then the azimut (dip-direction) and
        diping angle are calculated. Returns two values: dip-direction and dip.
        """
        #The longitude and latitude have to be forward-transformed to get
        #the corect azimuth angle
        xy = np.array([[lon, lat]])
        xy_trans = self.trans.transform(xy)
        x = float(xy_trans[0,0:1])
        y = float(xy_trans[0,1:2])
        alpha = np.arctan2(x, y)
        alpha_deg = np.degrees(alpha)
        if alpha_deg < 0:
            alpha_deg += 360

        #Longitude and Latitude don't need to be converted for rotation.
        #The correct dip is the array[1] value once the vector has been
        #rotated in north-south position.
        array = mplstereonet.stereonet_math._rotate(np.degrees(lon),
                                                    np.degrees(lat),
                                                    alpha_deg * (-1))
        gamma = float(array[1])
        gamma_deg = 90 - np.degrees(gamma)

        #If the longitude is larger or small than pi/2 the measurment lies
        #on the upper hemisphere and needs to be corrected.
        if lon > (np.pi / 2) or lon < (-np.pi / 2):
            alpha_deg = alpha_deg + 180

        return alpha_deg, gamma_deg 
Example #23
Source File: spa.py    From pvlib-python with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def geocentric_sun_declination(apparent_sun_longitude, true_ecliptic_obliquity,
                               geocentric_latitude):
    delta = np.degrees(np.arcsin(np.sin(np.radians(geocentric_latitude)) *
                                 np.cos(np.radians(true_ecliptic_obliquity)) +
                                 np.cos(np.radians(geocentric_latitude)) *
                                 np.sin(np.radians(true_ecliptic_obliquity)) *
                                 np.sin(np.radians(apparent_sun_longitude))))
    return delta 
Example #24
Source File: coordutils.py    From astrobase with MIT License 5 votes vote down vote up
def angle_wrap(angle, radians=False):
    '''Wraps the input angle to 360.0 degrees.

    Parameters
    ----------

    angle : float
        The angle to wrap around 360.0 deg.

    radians : bool
        If True, will assume that the input is in radians. The output will then
        also be in radians.

    Returns
    -------

    float
        Wrapped angle. If radians is True: input is assumed to be in radians,
        output is also in radians.

    '''

    if radians:
        wrapped = angle % (2.0*pi_value)
        if wrapped < 0.0:
            wrapped = 2.0*pi_value + wrapped

    else:

        wrapped = angle % 360.0
        if wrapped < 0.0:
            wrapped = 360.0 + wrapped

    return wrapped 
Example #25
Source File: spa.py    From pvlib-python with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def geocentric_sun_right_ascension(apparent_sun_longitude,
                                   true_ecliptic_obliquity,
                                   geocentric_latitude):
    num = (np.sin(np.radians(apparent_sun_longitude))
           * np.cos(np.radians(true_ecliptic_obliquity))
           - np.tan(np.radians(geocentric_latitude))
           * np.sin(np.radians(true_ecliptic_obliquity)))
    alpha = np.degrees(np.arctan2(num, np.cos(
        np.radians(apparent_sun_longitude))))
    return alpha % 360 
Example #26
Source File: coordutils.py    From astrobase with MIT License 5 votes vote down vote up
def decimal_to_dms(decimal_value):
    '''Converts from decimal degrees (for declination coords) to DD:MM:SS.

    Parameters
    ----------

    decimal_value : float
        A decimal value to convert to degrees, minutes, seconds sexagesimal
        format.

    Returns
    -------

    tuple
        A four element tuple is returned: (sign, HH, MM, SS.ssss...)

    '''

    if decimal_value < 0:
        negative = True
        dec_val = fabs(decimal_value)
    else:
        negative = False
        dec_val = decimal_value

    degrees = trunc(dec_val)
    minutes_deg = dec_val - degrees

    minutes_mm = minutes_deg * 60.0
    minutes_out = trunc(minutes_mm)
    seconds = (minutes_mm - minutes_out)*60.0

    if negative:
        degrees = degrees
        return '-', degrees, minutes_out, seconds
    else:
        return '+', degrees, minutes_out, seconds 
Example #27
Source File: test_marshall.py    From dustmaps with GNU General Public License v2.0 5 votes vote down vote up
def test_bounds(self):
        """
        Test that out-of-bounds coordinates return NaN reddening, and that
        in-bounds coordinates do not return NaN reddening.
        """

        for return_sigma in [False, True]:
            # Draw random coordinates on the sphere
            n_pix = 10000
            u, v = np.random.random((2,n_pix))
            l = 360. * u - 180.
            b = 90. - np.degrees(np.arccos(2.*v - 1.))
            d = 5. * np.random.random(l.shape)
            c = coords.SkyCoord(l*units.deg, b*units.deg,
                                distance=d*units.kpc, frame='galactic')

            res = self._marshall(c, return_sigma=return_sigma)

            if return_sigma:
                self.assertTrue(len(res) == 2)
                A, sigma = res
                np.testing.assert_equal(A.shape, sigma.shape)
            else:
                self.assertFalse(isinstance(res, tuple))
                A = res

            in_bounds = (l > -99.) & (l < 99.) & (b < 9.5) & (b > -9.5)
            out_of_bounds = (l < -101.) | (l > 101.) | (b > 10.5) | (b < -10.5)

            n_nan_in_bounds = np.sum(np.isnan(A[in_bounds]))
            n_finite_out_of_bounds = np.sum(np.isfinite(A[out_of_bounds]))

            self.assertTrue(n_nan_in_bounds == 0)
            self.assertTrue(n_finite_out_of_bounds == 0) 
Example #28
Source File: solarposition.py    From pvlib-python with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _hour_angle_to_hours(times, hourangle, longitude, equation_of_time):
    """converts hour angles in degrees to hours as a numpy array"""
    naive_times = times.tz_localize(None)  # naive but still localized
    tzs = 1 / NS_PER_HR * (
        naive_times.astype(np.int64) - times.astype(np.int64))
    hours = (hourangle - longitude - equation_of_time / 4.) / 15. + 12. + tzs
    return np.asarray(hours) 
Example #29
Source File: utils.py    From momepy with MIT License 5 votes vote down vote up
def _azimuth(point1, point2):
    """azimuth between 2 shapely points (interval 0 - 180)"""
    angle = np.arctan2(point2[0] - point1[0], point2[1] - point1[1])
    return np.degrees(angle) if angle > 0 else np.degrees(angle) + 180 
Example #30
Source File: spa.py    From pvlib-python with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def topocentric_astronomers_azimuth(topocentric_local_hour_angle,
                                    topocentric_sun_declination,
                                    observer_latitude):
    num = np.sin(np.radians(topocentric_local_hour_angle))
    denom = (np.cos(np.radians(topocentric_local_hour_angle))
             * np.sin(np.radians(observer_latitude))
             - np.tan(np.radians(topocentric_sun_declination))
             * np.cos(np.radians(observer_latitude)))
    gamma = np.degrees(np.arctan2(num, denom))
    return gamma % 360