# Python numpy.degrees() Examples

The following are 30 code examples for showing how to use numpy.degrees(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module , or try the search function .

Example 1
 Project: dustmaps   Author: gregreen   File: test_iphas.py    License: GNU General Public License v2.0 6 votes
```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 2
 Project: PyRadarMet   Author: nguy   File: BeamBlock.py    License: GNU General Public License v2.0 6 votes
```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 3
 Project: pysat   Author: pysat   File: omni_hro.py    License: BSD 3-Clause "New" or "Revised" License 6 votes
```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 4
 Project: differentiable-renderer   Author: ndrplz   File: rototranslation.py    License: MIT License 6 votes
```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 5
 Project: pvlib-python   Author: pvlib   File: tools.py    License: BSD 3-Clause "New" or "Revised" License 6 votes
```def sind(angle):
"""
Sine with angle input in degrees

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

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

return res ```
Example 6
 Project: pvlib-python   Author: pvlib   File: tools.py    License: BSD 3-Clause "New" or "Revised" License 6 votes
```def tand(angle):
"""
Tan with angle input in degrees

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

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

return res ```
Example 7
 Project: pvlib-python   Author: pvlib   File: tools.py    License: BSD 3-Clause "New" or "Revised" License 6 votes
```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 8
 Project: pvlib-python   Author: pvlib   File: tracking.py    License: BSD 3-Clause "New" or "Revised" License 6 votes
```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 9
 Project: orbital   Author: RazerM   File: elements.py    License: MIT License 6 votes
```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 10
```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))
valid_lines = lines[point_indices[inlier_mask], :, :]
else:
valid_lines = []
return valid_lines ```
Example 11
```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))
valid_lines = lines[point_indices[inlier_mask], :, :]
else:
valid_lines = []
return valid_lines ```
Example 12
 Project: python3_ios   Author: holzschu   File: custom_scale.py    License: BSD 3-Clause "New" or "Revised" License 6 votes
```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(
axis.set_major_formatter(DegreeFormatter())
axis.set_minor_formatter(DegreeFormatter()) ```
Example 13
 Project: orbitdeterminator   Author: aerospaceresearch   File: sgp4_prop.py    License: MIT License 6 votes
```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
"""

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 14
 Project: innstereo   Author: innstereo   File: main_ui.py    License: GNU General Public License v2.0 6 votes
```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 15
 Project: innstereo   Author: innstereo   File: main_ui.py    License: GNU General Public License v2.0 6 votes
```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 16
 Project: napari   Author: napari   File: shapes.py    License: BSD 3-Clause "New" or "Revised" License 6 votes
```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.
"""
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 17
 Project: astrobase   Author: waqasbhatti   File: pkl_utils.py    License: MIT License 6 votes
```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 18
 Project: astrobase   Author: waqasbhatti   File: coordutils.py    License: MIT License 6 votes
```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 19
 Project: dustmaps   Author: gregreen   File: test_marshall.py    License: GNU General Public License v2.0 5 votes
```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 20
 Project: QCElemental   Author: MolSSI   File: misc.py    License: BSD 3-Clause "New" or "Revised" License 5 votes
```def measure_coordinates(coordinates, measurements, degrees=False):
"""
Measures a geometry array based on 0-based indices provided, automatically detects distance, angle,
and dihedral based on length of measurement input.
"""

coordinates = np.atleast_2d(coordinates)
num_coords = coordinates.shape[0]

single = False
if isinstance(measurements[0], int):
measurements = [measurements]
single = True

ret = []
for num, m in enumerate(measurements):
if any(x >= num_coords for x in m):
raise ValueError(f"An index of measurement {num} is out of bounds.")

kwargs = {}
if len(m) == 2:
func = compute_distance
elif len(m) == 3:
func = compute_angle
kwargs = {"degrees": degrees}
elif len(m) == 4:
func = compute_dihedral
kwargs = {"degrees": degrees}
else:
raise KeyError(f"Unrecognized number of arguments for measurement {num}, found {len(m)}, expected 2-4.")

val = func(*[coordinates[x] for x in m], **kwargs)
ret.append(float(val))

if single:
return ret[0]
else:
return ret ```
Example 21
 Project: QCElemental   Author: MolSSI   File: misc.py    License: BSD 3-Clause "New" or "Revised" License 5 votes
```def compute_angle(points1, points2, points3, *, degrees: bool = False) -> np.ndarray:
"""
Computes the angle (p1, p2 [vertex], p3) between the provided points on a per-row basis.

Parameters
----------
points1 : np.ndarray
The first list of points, can be 1D or 2D
points2 : np.ndarray
The second list of points, can be 1D or 2D
points3 : np.ndarray
The third list of points, can be 1D or 2D
degrees : bool, options
Returns the angle in degrees rather than radians if True

Returns
-------
angles : np.ndarray
The angle between the three points in radians

Notes
-----
Units are not considered inside these expressions, please preconvert to the same units before using.
"""

points1 = np.atleast_2d(points1)
points2 = np.atleast_2d(points2)
points3 = np.atleast_2d(points3)

v12 = points1 - points2
v23 = points2 - points3

denom = _norm(v12) * _norm(v23)
cosine_angle = np.einsum("ij,ij->i", v12, v23) / denom

angle = np.pi - np.arccos(cosine_angle)

if degrees:
return np.degrees(angle)
else:
return angle ```
Example 22
 Project: PyRadarMet   Author: nguy   File: BeamBlock.py    License: GNU General Public License v2.0 5 votes
```def draw_beam_terrain_profile(self, fig, ax, ymin=None, ymax=None):
'''Draw the Beam height along with terrain and PBB'''
if ymin is None:
ymin = 0.
if ymax is None:
ymax = 5000.

bc, = ax.plot(self.rng_gnd / 1000., self.h / 1000., '-b',
linewidth=3, label='Beam Center')
b3db, = ax.plot(self.rng_gnd / 1000., (self.h + self.a) / 1000., ':b',
linewidth=1.5, label='3 dB Beam width')
ax.plot(self.rng_gnd / 1000., (self.h - self.a) / 1000., ':b')
tf = ax.fill_between(self.rng_gnd / 1000., 0.,
self.terr[self.Az_plot, :] / 1000.,
color='0.75')
ax.set_xlim(0., self.range)
ax.set_ylim(ymin / 1000., ymax / 1000.)
ax.set_title(r'dN/dh = %d km\$^{-1}\$; Elevation angle = %g degrees at %d azimuth'% \
(self.dNdH, self.E, self.Az_plot), fontdict=TITLEDICT)
ax.set_xlabel('Range (km)')
ax.set_ylabel('Height (km)')

axb = ax.twinx()
bbf, = axb.plot(self.rng_gnd / 1000., self.CBB[self.Az_plot, :], '-k',
label='BBF')
axb.set_ylabel('Beam-blockage fraction')
axb.set_ylim(0., 1.)
axb.set_xlim(0., self.range)

ax.legend((bc, b3db, bbf), ('Beam Center', '3 dB Beam width', 'BBF'),
loc='upper left', fontsize=10) ```
Example 23
 Project: kaggle-code   Author: CNuge   File: taxi_xgboost.py    License: MIT License 5 votes
```def bearing_array(lat1, lng1, lat2, lng2):
AVG_EARTH_RADIUS = 6371  # in km
lat1, lng1, lat2, lng2 = map(np.radians, (lat1, lng1, lat2, lng2))
y = np.sin(lng_delta_rad) * np.cos(lat2)
x = np.cos(lat1) * np.sin(lat2) - np.sin(lat1) * np.cos(lat2) * np.cos(lng_delta_rad)
return np.degrees(np.arctan2(y, x)) ```
Example 24
 Project: ratcave   Author: ratcave   File: coordinates.py    License: MIT License 5 votes
```def to_degrees(self):
return RotationEulerDegrees(*np.degrees(self._array), axes=self.axes) ```
Example 25
 Project: ratcave   Author: ratcave   File: coordinates.py    License: MIT License 5 votes
```def to_quaternion(self):
return RotationQuaternion(*R.from_euler(self._axes[1:],self._array,degrees=False).as_quat()) ```
Example 26
 Project: ratcave   Author: ratcave   File: coordinates.py    License: MIT License 5 votes
```def to_matrix(self):
mat = np.eye(4)
mat[:3, :3] = R.from_euler(self.axes[1:],self._array,degrees=False).as_dcm() # scipy as_matrix() not available
return mat ```
Example 27
 Project: ratcave   Author: ratcave   File: coordinates.py    License: MIT License 5 votes
```def to_euler(self, units='rad'):
assert units.lower() in ['rad', 'deg']
if units.lower() == 'rad':
else:
return RotationEulerDegrees(*np.degrees(self._array), axes=self.axes) ```
Example 28
 Project: ratcave   Author: ratcave   File: coordinates.py    License: MIT License 5 votes
```def from_matrix(cls, matrix, axes='rxyz'):
coords = R.from_matrix(matrix[:3, :3]).as_euler(axes[1:], degrees=False)
return cls(*coords) ```
Example 29
 Project: ratcave   Author: ratcave   File: coordinates.py    License: MIT License 5 votes
```def to_euler(self, units='rad'):
euler_data = R.from_quat(self).as_euler(axes='xyz',degrees=False)
assert units.lower() in ['rad', 'deg']
if units.lower() == 'rad':
else:
return RotationEulerDegrees(*np.degrees(euler_data)) ```
Example 30
 Project: typhon   Author: atmtools   File: aster.py    License: MIT License 5 votes
```def reflection_angles(self):
"""Calculate the reflected sun angle, theta_r, of specular reflection
of sunlight into an instrument sensor.

Returns:
(ndarray): 2d field of size `cloudmask` of reflection
angles in [°] for eachannel pixel.

References:
Kang Yang, Huaguo Zhang, Bin Fu, Gang Zheng, Weibing Guan, Aiqin Shi
& Dongling Li (2015) Observation of submarine sand waves using ASTER
stereo sun glitter imagery, International Journal of Remote Sensing,
36:22, 5576-5592, DOI: 10.1080/01431161.2015.1101652
"""
sun_azimuth = (
self.solardirection.azimuth + 180
)  # +180° corresponds to "anti-/reflected" sun
sun_zenith = (
90 - self.solardirection.elevation
)  # sun zenith = 90 - sun elevation

sensor_zenith, sensor_azimuth = self.sensor_angles()

return np.degrees(
np.arccos(