Python numpy.deg2rad() Examples

The following are 30 code examples for showing how to use numpy.deg2rad(). 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 numpy , or try the search function .

Example 1
Project: aospy   Author: spencerahill   File: vertcoord.py    License: Apache License 2.0 6 votes vote down vote up
def to_radians(arr, is_delta=False):
    """Force data with units either degrees or radians to be radians."""
    # Infer the units from embedded metadata, if it's there.
    try:
        units = arr.units
    except AttributeError:
        pass
    else:
        if units.lower().startswith('degrees'):
            warn_msg = ("Conversion applied: degrees -> radians to array: "
                        "{}".format(arr))
            logging.debug(warn_msg)
            return np.deg2rad(arr)
    # Otherwise, assume degrees if the values are sufficiently large.
    threshold = 0.1*np.pi if is_delta else 4*np.pi
    if np.max(np.abs(arr)) > threshold:
        warn_msg = ("Conversion applied: degrees -> radians to array: "
                    "{}".format(arr))
        logging.debug(warn_msg)
        return np.deg2rad(arr)
    return arr 
Example 2
Project: simnibs   Author: simnibs   File: optimize_tms.py    License: GNU General Public License v3.0 6 votes vote down vote up
def _rotate_system(R, angle_limits, angle_res):
    ''' Rotates the vector "y" aroud "z" between the given limits and in the given
    resolution and return rotation matrices'''
    # Define rotation matrix around Z
    n_steps = int((angle_limits[1] - angle_limits[0])/angle_res + 1)
    angles = np.linspace(angle_limits[0], angle_limits[1], n_steps)
    angles = np.deg2rad(angles[(angles > -180.1) * (angles < 180.)])
    matrices = []
    for a in angles:
        Rz = np.array((
            (np.cos(a), -np.sin(a), 0),
            (np.sin(a), np.cos(a), 0),
            (0, 0, 1),
        ))
        matrices.append(R.dot(Rz))
    return matrices 
Example 3
Project: simnibs   Author: simnibs   File: test_optimization_methods.py    License: GNU General Public License v3.0 6 votes vote down vote up
def test_both_limit_angle_inactive(self, optimization_variables_avg):
        l, Q, A = optimization_variables_avg
        Q_in = 5e1 * np.eye(len(l))
        max_angle = 45
        m = 2e-3
        m1 = 4e-3
        f = .02
        x = optimization_methods.optimize_focality(l, Q, f,
                                                   max_el_current=m,
                                                   max_total_current=m1,
                                                   Qin=Q_in,
                                                   max_angle=max_angle)
        x_sp = optimize_focality(
            l, Q, f, max_el_current=m, max_total_current=m1,
            Qin=Q_in, max_angle=max_angle)

        assert np.linalg.norm(x, 1) <= 2 * m1 + 1e-4
        assert np.all(np.abs(x) <= m + 1e-4)
        assert np.isclose(np.sum(x), 0)
        assert np.isclose(l.dot(x), f)
        assert np.arccos(l.dot(x) / np.sqrt(x.dot(Q_in).dot(x))) <= np.deg2rad(max_angle)
        assert np.allclose(x.dot(Q.dot(x)), x_sp.dot(Q.dot(x_sp)), rtol=1e-4, atol=1e-5) 
Example 4
Project: simnibs   Author: simnibs   File: test_optimization_methods.py    License: GNU General Public License v3.0 6 votes vote down vote up
def test_both_limit_angle_limit(self, optimization_variables_avg):
        l, Q, A = optimization_variables_avg
        Q_in = 5e1 * np.eye(len(l))
        max_angle = 25
        m = 2e-3
        m1 = 4e-3
        f = .02
        x = optimization_methods.optimize_focality(l, Q, f,
                                                   max_el_current=m,
                                                   max_total_current=m1,
                                                   Qin=Q_in,
                                                   max_angle=max_angle)
        x_sp = optimize_focality(
            l, Q, f, max_el_current=m, max_total_current=m1,
            Qin=Q_in, max_angle=max_angle)
        assert np.linalg.norm(x, 1) <= 2 * m1 + 1e-4
        assert np.all(np.abs(x) <= m + 1e-4)
        assert np.isclose(np.sum(x), 0)
        assert np.isclose(l.dot(x), f)
        assert np.arccos(l.dot(x) / np.sqrt(x.dot(Q_in).dot(x))) <= np.deg2rad(max_angle)
        assert np.allclose(x.dot(Q.dot(x)), x_sp.dot(Q.dot(x_sp)), rtol=1e-4, atol=1e-5) 
Example 5
Project: simnibs   Author: simnibs   File: test_optimization_methods.py    License: GNU General Public License v3.0 6 votes vote down vote up
def test_both_limit_angle_Q_iteration(self, optimization_variables_avg_QCQP):
        l, Q, A, Q_in = optimization_variables_avg_QCQP
        # l, Q, A = optimization_variables_avg
        # Q_in = 6 * np.eye(len(l)) + np.outer(l, l)
        max_angle = 20
        m = 2e-3
        m1 = 4e-3
        f = .01
        x = optimization_methods.optimize_focality(l, Q, f,
                                                   max_el_current=m,
                                                   max_total_current=m1,
                                                   Qin=Q_in,
                                                   max_angle=max_angle)
        x_sp = optimize_focality(
            l, Q, f, max_el_current=m, max_total_current=m1,
            Qin=Q_in, max_angle=max_angle)
        assert np.linalg.norm(x, 1) <= 2 * m1 + 1e-4
        assert np.all(np.abs(x) <= m + 1e-4)
        assert np.isclose(np.sum(x), 0)
        assert np.isclose(l.dot(x), f)
        assert np.arccos(l.dot(x) / np.sqrt(x.dot(Q_in).dot(x))) <= np.deg2rad(max_angle)
        assert np.allclose(x.dot(Q.dot(x)), x_sp.dot(Q.dot(x_sp)), rtol=1e-4, atol=1e-5) 
Example 6
Project: simnibs   Author: simnibs   File: test_optimization_methods.py    License: GNU General Public License v3.0 6 votes vote down vote up
def test_both_limit_angle_infeasible_field(self, optimization_variables_avg_QCQP):
        l, Q, A, Q_in = optimization_variables_avg_QCQP
        max_angle = 15
        m = 2e-3
        m1 = 4e-3
        f = 2
        x = optimization_methods.optimize_focality(l, Q, f,
                                                   max_el_current=m,
                                                   max_total_current=m1,
                                                   Qin=Q_in,
                                                   max_angle=max_angle)

        assert np.linalg.norm(x, 1) <= 2 * m1 + 1e-4
        assert np.all(np.abs(x) <= m + 1e-4)
        assert np.isclose(np.sum(x), 0)
        assert np.arccos(l.dot(x) / np.sqrt(x.dot(Q_in).dot(x))) <= np.deg2rad(max_angle) 
Example 7
Project: simnibs   Author: simnibs   File: test_optimization_methods.py    License: GNU General Public License v3.0 6 votes vote down vote up
def test_limit_nr_angle(seld, optimization_variables_avg_QCQP):
        l, Q, A, Q_in = optimization_variables_avg_QCQP
        max_angle = 15
        m = 2e-3
        m1 = 4e-3
        f = 2
        n = 4
        x = optimization_methods.optimize_focality(l, Q, f,
                                                   max_el_current=m,
                                                   max_total_current=m1,
                                                   Qin=Q_in,
                                                   max_angle=max_angle,
                                                   max_active_electrodes=n)

        assert np.linalg.norm(x, 1) <= 2 * m1 + 1e-4
        assert np.all(np.abs(x) <= m + 1e-4)
        assert np.isclose(np.sum(x), 0)
        assert np.linalg.norm(x, 0) <= n
        assert np.arccos(l.dot(x) / np.sqrt(x.dot(Q_in).dot(x))) <= np.deg2rad(max_angle) 
Example 8
Project: simnibs   Author: simnibs   File: test_optimization_methods.py    License: GNU General Public License v3.0 6 votes vote down vote up
def test_limit_nr_angle_change_Q(seld, optimization_variables_avg_QCQP):
        l, Q, A, Q_in = optimization_variables_avg_QCQP
        max_angle = 15
        m = 2e-3
        m1 = 4e-3
        f = .01
        n = 4
        x = optimization_methods.optimize_focality(l, Q, f,
                                                   max_el_current=m,
                                                   max_total_current=m1,
                                                   Qin=Q_in,
                                                   max_angle=max_angle,
                                                   max_active_electrodes=n)

        assert np.linalg.norm(x, 1) <= 2 * m1 + 1e-4
        assert np.all(np.abs(x) <= m + 1e-4)
        assert np.isclose(np.sum(x), 0)
        assert np.linalg.norm(x, 0) <= n
        assert np.arccos(l.dot(x) / np.sqrt(x.dot(Q_in).dot(x))) <= np.deg2rad(max_angle) 
Example 9
Project: PyRadarMet   Author: nguy   File: geometry.py    License: GNU General Public License v2.0 6 votes vote down vote up
def half_power_radius(r, bwhalf):
    """
    Half-power radius [m].

    Battan (1973),

    Parameters
    ----------
    r : float or array
        Range [m]
    bwhalf : float
        Half-power beam width [degrees]
    """
    # Convert earth's radius to km for common dN/dH values and then
    # multiply by 1000 to return radius in meters
    return (np.asarray(r) * np.deg2rad(bwhalf)) / 2. 
Example 10
Project: PyRadarMet   Author: nguy   File: geometry.py    License: GNU General Public License v2.0 6 votes vote down vote up
def sample_vol_ideal(r, bw_h, bw_v, pulse_length):
    """
    Idealized Sample volume [m^3] assuming all power in half-power beamwidths.

    From Rinehart (1997), Eqn 5.2

    Parameters
    ----------
    r : float or array
        Distance to sample volume from radar [m]
    bw_h : float
        Horizontal beamwidth [deg]
    bw_v : float
        Vertical beamwidth deg]
    pulse_length : float
        Pulse length [m]

    Notes
    -----
    This form assumes all transmitted energy is in the half-power beamwidths.
    A more realistic solution is found in the sample_vol_gauss function
    """
    return (np.pi * (np.asarray(r) * np.deg2rad(bw_h)/2.) * (np.asarray(r) *
            np.deg2rad(bw_v)/2.) * (pulse_length/2.)) 
Example 11
Project: DIB-R   Author: nv-tlabs   File: utils_perspective.py    License: MIT License 6 votes vote down vote up
def camera_info(param):
    theta = np.deg2rad(param[0])
    phi = np.deg2rad(param[1])

    camY = param[3] * np.sin(phi)
    temp = param[3] * np.cos(phi)
    camX = temp * np.cos(theta)    
    camZ = temp * np.sin(theta)        
    cam_pos = np.array([camX, camY, camZ])        

    axisZ = cam_pos.copy()
    axisY = np.array([0, 1, 0], dtype=np.float32)
    axisX = np.cross(axisY, axisZ)
    axisY = np.cross(axisZ, axisX)
    
    # cam_mat = np.array([axisX, axisY, axisZ])
    cam_mat = np.array([unit(axisX), unit(axisY), unit(axisZ)])
    
    return cam_mat, cam_pos


##################################################### 
Example 12
Project: isic2019   Author: ngessert   File: auto_augment.py    License: MIT License 6 votes vote down vote up
def rotate(img, magnitude):
    img = np.array(img)
    magnitudes = np.linspace(-30, 30, 11)
    theta = np.deg2rad(random.uniform(magnitudes[magnitude], magnitudes[magnitude+1]))
    transform_matrix = np.array([[np.cos(theta), -np.sin(theta), 0],
                                 [np.sin(theta), np.cos(theta), 0],
                                 [0, 0, 1]])
    transform_matrix = transform_matrix_offset_center(transform_matrix, img.shape[0], img.shape[1])
    affine_matrix = transform_matrix[:2, :2]
    offset = transform_matrix[:2, 2]
    img = np.stack([ndimage.interpolation.affine_transform(
                    img[:, :, c],
                    affine_matrix,
                    offset) for c in range(img.shape[2])], axis=2)
    img = Image.fromarray(img)
    return img 
Example 13
Project: typhon   Author: atmtools   File: ppath.py    License: MIT License 6 votes vote down vote up
def wzeniths(zeniths):
    n = len(zeniths)
    if not n:
        return np.array([0, 180]), np.array([1, 1])
    inds = np.argsort(zeniths)
    zaz = np.deg2rad(zeniths[inds])
    cz = np.cos(zaz)

    wz = np.zeros((2*n))
    za = np.zeros((2*n))
    for i in range(n-1):
        N = i*2
        za[N:N+2] = zaz[i:i+2]
        wz[0+N] = wz[1+N] = 0.5 * (cz[i] - cz[i+1])

    return za, wz 
Example 14
Project: pylops   Author: equinor   File: bayesian.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
def prior_realization(f0, a0, phi0, sigmaf, sigmaa, sigmaphi, dt, nt, nfft):
    """Create realization from prior mean and std for amplitude, frequency and
    phase
    """
    f = np.fft.rfftfreq(nfft, dt)
    df = f[1] - f[0]
    ifreqs = [int(np.random.normal(f, sigma)/df)
              for f, sigma in zip(f0, sigmaf)]
    amps = [np.random.normal(a, sigma) for a, sigma in zip(a0, sigmaa)]
    phis = [np.random.normal(phi, sigma) for phi, sigma in zip(phi0, sigmaphi)]

    # input signal in frequency domain
    X = np.zeros(nfft//2+1, dtype='complex128')
    X[ifreqs] = np.array(amps).squeeze() * \
                np.exp(1j * np.deg2rad(np.array(phis))).squeeze()

    # input signal in time domain
    FFTop = pylops.signalprocessing.FFT(nt, nfft=nfft, real=True)
    x = FFTop.H*X
    return x

# Priors 
Example 15
Project: pytorch-auto-augment   Author: 4uiiurz1   File: auto_augment.py    License: MIT License 6 votes vote down vote up
def rotate(img, magnitude):
    img = np.array(img)
    magnitudes = np.linspace(-30, 30, 11)
    theta = np.deg2rad(random.uniform(magnitudes[magnitude], magnitudes[magnitude+1]))
    transform_matrix = np.array([[np.cos(theta), -np.sin(theta), 0],
                                 [np.sin(theta), np.cos(theta), 0],
                                 [0, 0, 1]])
    transform_matrix = transform_matrix_offset_center(transform_matrix, img.shape[0], img.shape[1])
    affine_matrix = transform_matrix[:2, :2]
    offset = transform_matrix[:2, 2]
    img = np.stack([ndimage.interpolation.affine_transform(
                    img[:, :, c],
                    affine_matrix,
                    offset) for c in range(img.shape[2])], axis=2)
    img = Image.fromarray(img)
    return img 
Example 16
Project: OpenCV-Python-Tutorial   Author: makelove   File: deconvolution.py    License: MIT License 6 votes vote down vote up
def update(_):
        ang = np.deg2rad( cv2.getTrackbarPos('angle', win) )
        d = cv2.getTrackbarPos('d', win)
        noise = 10**(-0.1*cv2.getTrackbarPos('SNR (db)', win))

        if defocus:
            psf = defocus_kernel(d)
        else:
            psf = motion_kernel(ang, d)
        cv2.imshow('psf', psf)

        psf /= psf.sum()
        psf_pad = np.zeros_like(img)
        kh, kw = psf.shape
        psf_pad[:kh, :kw] = psf
        PSF = cv2.dft(psf_pad, flags=cv2.DFT_COMPLEX_OUTPUT, nonzeroRows = kh)
        PSF2 = (PSF**2).sum(-1)
        iPSF = PSF / (PSF2 + noise)[...,np.newaxis]
        RES = cv2.mulSpectrums(IMG, iPSF, 0)
        res = cv2.idft(RES, flags=cv2.DFT_SCALE | cv2.DFT_REAL_OUTPUT )
        res = np.roll(res, -kh//2, 0)
        res = np.roll(res, -kw//2, 1)
        cv2.imshow(win, res) 
Example 17
Project: sun-position   Author: s-bear   File: sunposition.py    License: MIT License 6 votes vote down vote up
def sun_topo_azimuth_zenith(latitude, delta_prime, H_prime, temperature=14.6, pressure=1013):
        """Compute the sun's topocentric azimuth and zenith angles
        azimuth is measured eastward from north, zenith from vertical
        temperature = average temperature in C (default is 14.6 = global average in 2013)
        pressure = average pressure in mBar (default 1013 = global average)
        """
        phi = np.deg2rad(latitude)
        dr, Hr = map(np.deg2rad,(delta_prime, H_prime))
        P, T = pressure, temperature
        e0 = np.rad2deg(np.arcsin(np.sin(phi)*np.sin(dr) + np.cos(phi)*np.cos(dr)*np.cos(Hr)))
        tmp = np.deg2rad(e0 + 10.3/(e0+5.11))
        delta_e = (P/1010.0)*(283.0/(273+T))*(1.02/(60*np.tan(tmp)))
        e = e0 + delta_e
        zenith = 90 - e

        gamma = np.rad2deg(np.arctan2(np.sin(Hr), np.cos(Hr)*np.sin(phi) - np.tan(dr)*np.cos(phi))) % 360
        Phi = (gamma + 180) % 360 #azimuth from north
        return Phi, zenith 
Example 18
Project: SCvx   Author: EmbersArc   File: utils.py    License: MIT License 6 votes vote down vote up
def euler_to_quat(a):
    a = np.deg2rad(a)

    cy = np.cos(a[1] * 0.5)
    sy = np.sin(a[1] * 0.5)
    cr = np.cos(a[0] * 0.5)
    sr = np.sin(a[0] * 0.5)
    cp = np.cos(a[2] * 0.5)
    sp = np.sin(a[2] * 0.5)

    q = np.zeros(4)

    q[0] = cy * cr * cp + sy * sr * sp
    q[1] = cy * sr * cp - sy * cr * sp
    q[3] = cy * cr * sp + sy * sr * cp
    q[2] = sy * cr * cp - cy * sr * sp

    return q 
Example 19
Project: speck   Author: lucashadfield   File: noise.py    License: GNU General Public License v3.0 6 votes vote down vote up
def _generate(self, n: int) -> np.ndarray:
        return np.array(
            [
                self.scale
                * np.sin(
                    np.linspace(0, self.base_freq * 2 * np.pi, n) * factor + offset
                )
                for factor, offset in zip(
                    np.random.uniform(*self.freq_factor, self.wave_count),
                    np.random.uniform(
                        np.deg2rad(self.phase_offset_range[0]),
                        np.deg2rad(self.phase_offset_range[1]),
                        self.wave_count,
                    ),
                )
            ]
        ).prod(axis=0) 
Example 20
Project: visual_foresight   Author: SudeepDasari   File: base_mujoco_env.py    License: MIT License 6 votes vote down vote up
def project_point(self, point, camera):
        model_matrix = np.zeros((4, 4))
        model_matrix[:3, :3] = self.sim.data.get_camera_xmat(camera).T
        model_matrix[-1, -1] = 1

        fovy_radians = np.deg2rad(self.sim.model.cam_fovy[self.sim.model.camera_name2id(camera)])
        uh = 1. / np.tan(fovy_radians / 2)
        uw = uh / (self._frame_width / self._frame_height)
        extent = self.sim.model.stat.extent
        far, near = self.sim.model.vis.map.zfar * extent, self.sim.model.vis.map.znear * extent
        view_matrix = np.array([[uw, 0., 0., 0.],                        # matrix definition from
                                [0., uh, 0., 0.],                        # https://stackoverflow.com/questions/18404890/how-to-build-perspective-projection-matrix-no-api
                                [0., 0., far / (far - near), -1.],
                                [0., 0., -2*far*near/(far - near), 0.]]) # Note Mujoco doubles this quantity

        MVP_matrix = view_matrix.dot(model_matrix)
        world_coord = np.ones((4, 1))
        world_coord[:3, 0] = point - self.sim.data.get_camera_xpos(camera)

        clip = MVP_matrix.dot(world_coord)
        ndc = clip[:3] / clip[3]  # everything should now be in -1 to 1!!
        col, row = (ndc[0] + 1) * self._frame_width / 2, (-ndc[1] + 1) * self._frame_height / 2

        return self._frame_height - row, col                 # rendering flipped around in height 
Example 21
Project: Computable   Author: ktraunmueller   File: polar.py    License: MIT License 6 votes vote down vote up
def start_pan(self, x, y, button):
        angle = np.deg2rad(self._r_label_position.to_values()[4])
        mode = ''
        if button == 1:
            epsilon = np.pi / 45.0
            t, r = self.transData.inverted().transform_point((x, y))
            if t >= angle - epsilon and t <= angle + epsilon:
                mode = 'drag_r_labels'
        elif button == 3:
            mode = 'zoom'

        self._pan_start = cbook.Bunch(
            rmax          = self.get_rmax(),
            trans         = self.transData.frozen(),
            trans_inverse = self.transData.inverted().frozen(),
            r_label_angle = self._r_label_position.to_values()[4],
            x             = x,
            y             = y,
            mode          = mode
            ) 
Example 22
Project: Computable   Author: ktraunmueller   File: text.py    License: MIT License 6 votes vote down vote up
def update_bbox_position_size(self, renderer):
        """
        Update the location and the size of the bbox. This method
        should be used when the position and size of the bbox needs to
        be updated before actually drawing the bbox.
        """

        # For arrow_patch, use textbox as patchA by default.

        if not isinstance(self.arrow_patch, FancyArrowPatch):
            return

        if self._bbox_patch:
            posx, posy = self._x, self._y

            x_box, y_box, w_box, h_box = _get_textbox(self, renderer)
            self._bbox_patch.set_bounds(0., 0., w_box, h_box)
            theta = np.deg2rad(self.get_rotation())
            tr = mtransforms.Affine2D().rotate(theta)
            tr = tr.translate(posx + x_box, posy + y_box)
            self._bbox_patch.set_transform(tr)
            fontsize_in_pixel = renderer.points_to_pixels(self.get_size())
            self._bbox_patch.set_mutation_scale(fontsize_in_pixel) 
Example 23
Project: ROS-Programming-Building-Powerful-Robots   Author: PacktPublishing   File: pick_and_place_pick_working.py    License: MIT License 6 votes vote down vote up
def _add_table(self, name):
        p = PoseStamped()
        p.header.frame_id = self._robot.get_planning_frame()
        p.header.stamp = rospy.Time.now()

        p.pose.position.x = 0.5
        p.pose.position.y = 0.0
        p.pose.position.z = 0.22

        q = quaternion_from_euler(0.0, 0.0, numpy.deg2rad(90.0))
        p.pose.orientation = Quaternion(*q)

        # Table size from ~/.gazebo/models/table/model.sdf, using the values
        # for the surface link.
        self._scene.add_box(name, p, (0.5, 0.4, 0.02))

        return p.pose 
Example 24
Project: ROS-Programming-Building-Powerful-Robots   Author: PacktPublishing   File: pick_and_place_working_1.py    License: MIT License 6 votes vote down vote up
def _add_table(self, name):
        p = PoseStamped()
        p.header.frame_id = self._robot.get_planning_frame()
        p.header.stamp = rospy.Time.now()

        p.pose.position.x = 0.5
        p.pose.position.y = 0.0
        p.pose.position.z = 0.22

        q = quaternion_from_euler(0.0, 0.0, numpy.deg2rad(90.0))
        p.pose.orientation = Quaternion(*q)

        # Table size from ~/.gazebo/models/table/model.sdf, using the values
        # for the surface link.
        self._scene.add_box(name, p, (0.5, 0.4, 0.02))

        return p.pose 
Example 25
Project: MPContribs   Author: materialsproject   File: pre_submission.py    License: MIT License 5 votes vote down vote up
def load_RSM(filename):
    om, tt, psd = xu.io.getxrdml_map(filename)
    om = np.deg2rad(om)
    tt = np.deg2rad(tt)
    wavelength = 1.54056

    q_y = (1 / wavelength) * (np.cos(tt) - np.cos(2 * om - tt))
    q_x = (1 / wavelength) * (np.sin(tt) - np.sin(2 * om - tt))

    xi = np.linspace(np.min(q_x), np.max(q_x), 100)
    yi = np.linspace(np.min(q_y), np.max(q_y), 100)
    psd[psd < 1] = 1
    data_grid = griddata(
        (q_x, q_y), psd, (xi[None, :], yi[:, None]), fill_value=1, method="cubic"
    )
    nx, ny = data_grid.shape

    range_values = [np.min(q_x), np.max(q_x), np.min(q_y), np.max(q_y)]
    output_data = (
        Panel(np.log(data_grid).reshape(nx, ny, 1), minor_axis=["RSM"])
        .transpose(2, 0, 1)
        .to_frame()
    )

    return range_values, output_data 
Example 26
Project: DOTA_models   Author: ringringyi   File: depth_utils.py    License: Apache License 2.0 5 votes vote down vote up
def get_camera_matrix(width, height, fov):
  """Returns a camera matrix from image size and fov."""
  xc = (width-1.) / 2.
  zc = (height-1.) / 2.
  f = (width / 2.) / np.tan(np.deg2rad(fov / 2.))
  camera_matrix = utils.Foo(xc=xc, zc=zc, f=f)
  return camera_matrix 
Example 27
Project: DOTA_models   Author: ringringyi   File: depth_utils.py    License: Apache License 2.0 5 votes vote down vote up
def make_geocentric(XYZ, sensor_height, camera_elevation_degree):
  """Transforms the point cloud into geocentric coordinate frame.
  Input:
    XYZ                     : ...x3
    sensor_height           : height of the sensor
    camera_elevation_degree : camera elevation to rectify.
  Output:
    XYZ : ...x3
  """
  R = ru.get_r_matrix([1.,0.,0.], angle=np.deg2rad(camera_elevation_degree))
  XYZ = np.matmul(XYZ.reshape(-1,3), R.T).reshape(XYZ.shape)
  XYZ[...,2] = XYZ[...,2] + sensor_height
  return XYZ 
Example 28
Project: NeuroKit   Author: neuropsychology   File: signal_phase.py    License: MIT License 5 votes vote down vote up
def _signal_phase_binary(signal):

    phase = itertools.chain.from_iterable(np.linspace(0, 1, sum([1 for i in v])) for _, v in itertools.groupby(signal))
    phase = np.array(list(phase))

    # Convert to radiant
    phase = np.deg2rad(phase * 360)
    return phase 
Example 29
Project: simnibs   Author: simnibs   File: mesh_io.py    License: GNU General Public License v3.0 5 votes vote down vote up
def gaussian_curvature(self):
        ''' Calculates the Gaussian curvature at each node

        Returns
        ---------
        nd: NodeData
            NodeData structure with gaussian curvature for each surface node


        Rerefereces
        -------------
        https://computergraphics.stackexchange.com/a/1721
        '''
        nodes_areas = self.nodes_areas()[:]
        triangles_angles = np.deg2rad(
            np.nan_to_num(self.triangle_angles()[self.elm.triangles])
        )
        triangle_nodes = self.elm[self.elm.triangles] - 1
        triangle_nodes = triangle_nodes[:, :3]
        node_angles = np.bincount(
            triangle_nodes.reshape(-1),
            triangles_angles.reshape(-1), self.nodes.nr
        )
        nodes_areas[nodes_areas == 0] = .1
        gaussian_curvature = (2*np.pi - node_angles)/nodes_areas
        return NodeData(gaussian_curvature, 'gaussian_curvature') 
Example 30
Project: simnibs   Author: simnibs   File: test_optimization_methods.py    License: GNU General Public License v3.0 5 votes vote down vote up
def optimize_focality(l, Q, b,
                      max_el_current=None,
                      max_total_current=None,
                      Qin=None,
                      max_angle=None):
    objective = lambda x: .5 * x.dot(Q.dot(x))
    x0 = np.zeros(Q.shape[0])
    jac = lambda x: x.dot(Q)
    #hess = lambda x: Q
    m_constraint = {}
    m_constraint['type'] = 'eq'
    m_constraint['fun'] = lambda x: l.dot(x) - b
    m_constraint['jac'] = lambda x: l

    e_constraint = {}
    e_constraint['type'] = 'eq'
    e_constraint['fun'] = lambda x: np.sum(x)
    e_constraint['jac'] = lambda x: np.ones_like(x)
    constraints = (m_constraint, e_constraint)

    if max_el_current is not None:
        bounds = scipy.optimize.Bounds(-max_el_current, max_el_current)
    else:
        bounds = None
    if max_total_current is not None:
        iq_constraint = {}
        iq_constraint['type'] = 'ineq'
        iq_constraint['fun'] = lambda x: 2 * max_total_current - np.linalg.norm(x, 1)
        constraints += (iq_constraint, )
    if Qin is not None:
        a_constraint = {}
        a_constraint['type'] = 'ineq'
        a_constraint['fun'] = lambda x: (b/np.cos(np.deg2rad(max_angle)))**2 - x.dot(Qin.dot(x))
        constraints += (a_constraint, )

    res = scipy.optimize.minimize(
        objective, x0, jac=jac,
        bounds=bounds,
        constraints=constraints)
    return res.x