Python numpy.sin() Examples

The following are 30 code examples of numpy.sin(). 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: GarrettCompleteness.py    From EXOSIMS with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def mindmag(self, s):
        """Calculates the minimum value of dMag for projected separation
        
        Args:
            s (float):
                Projected separations (AU)
        
        Returns:
            mindmag (float):
                Minimum planet delta magnitude
        """
        if s == 0.0:
            mindmag = self.cdmin1
        elif s < self.rmin*np.sin(self.bstar):
            mindmag = self.cdmin1-2.5*np.log10(self.Phi(np.arcsin(s/self.rmin)))
        elif s < self.rmax*np.sin(self.bstar):
            mindmag = self.cdmin2+5.0*np.log10(s)
        elif s <= self.rmax:
            mindmag = self.cdmin3-2.5*np.log10(self.Phi(np.arcsin(s/self.rmax)))
        else:
            mindmag = np.inf
        
        return mindmag 
Example #2
Source File: generators.py    From FRIDA with MIT License 6 votes vote down vote up
def unit_vec(doa):
    """
    This function takes a 2D (phi) or 3D (phi,theta) polar coordinates
    and returns a unit vector in cartesian coordinates.

    :param doa: (ndarray) An (D-1)-by-N array where D is the dimension and
                N the number of vectors.

    :return: (ndarray) A D-by-N array of unit vectors (each column is a vector)
    """

    if doa.ndim != 1 and doa.ndim != 2:
        raise ValueError("DoA array should be 1D or 2D.")

    doa = np.array(doa)

    if doa.ndim == 0 or doa.ndim == 1:
        return np.array([np.cos(doa), np.sin(doa)])

    elif doa.ndim == 2 and doa.shape[0] == 1:
        return np.array([np.cos(doa[0]), np.sin(doa[0])])

    elif doa.ndim == 2 and doa.shape[0] == 2:
        s = np.sin(doa[1])
        return np.array([s * np.cos(doa[0]), s * np.sin(doa[0]), np.cos(doa[1])]) 
Example #3
Source File: keplerSTM.py    From EXOSIMS with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def psi2c2c3(self, psi0):

        c2 = np.zeros(len(psi0))
        c3 = np.zeros(len(psi0))

        psi12 = np.sqrt(np.abs(psi0))
        pos = psi0 >= 0
        neg = psi0 < 0
        if np.any(pos):
            c2[pos] = (1 - np.cos(psi12[pos]))/psi0[pos]
            c3[pos] = (psi12[pos] - np.sin(psi12[pos]))/psi12[pos]**3.
        if any(neg):
            c2[neg] = (1 - np.cosh(psi12[neg]))/psi0[neg]
            c3[neg] = (np.sinh(psi12[neg]) - psi12[neg])/psi12[neg]**3.

        tmp = c2+c3 == 0
        if any(tmp):
            c2[tmp] = 1./2.
            c3[tmp] = 1./6.

        return c2,c3 
Example #4
Source File: PlanetPhysicalModel.py    From EXOSIMS with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def calc_Phi(self, beta):
        """Calculate the phase function. Prototype method uses the Lambert phase 
        function from Sobolev 1975.
        
        Args:
            beta (astropy Quantity array):
                Planet phase angles at which the phase function is to be calculated,
                in units of rad
                
        Returns:
            Phi (ndarray):
                Planet phase function
        
        """
        
        beta = beta.to('rad').value
        Phi = (np.sin(beta) + (np.pi - beta)*np.cos(beta))/np.pi
        
        return Phi 
Example #5
Source File: GarrettCompleteness.py    From EXOSIMS with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def Jac(self, b):
        """Calculates determinant of the Jacobian transformation matrix to get
        the joint probability density of dMag and s
        
        Args:
            b (ndarray):
                Phase angles
                
        Returns:
            f (ndarray):
                Determinant of Jacobian transformation matrix
        
        """
        
        f = -2.5/(self.Phi(b)*np.log(10.0))*self.dPhi(b)*np.sin(b) - 5./np.log(10.0)*np.cos(b)
        
        return f 
Example #6
Source File: stft.py    From stft with MIT License 6 votes vote down vote up
def cosine(M):
    """Gernerate a halfcosine window of given length

    Uses :code:`scipy.signal.cosine` by default. However since this window
    function has only recently been merged into mainline SciPy, a fallback
    calculation is in place.

    Parameters
    ----------
    M : int
        Length of the window.

    Returns
    -------
    data : array_like
        The window function

    """
    try:
        import scipy.signal
        return scipy.signal.cosine(M)
    except AttributeError:
        return numpy.sin(numpy.pi / M * (numpy.arange(0, M) + .5)) 
Example #7
Source File: test_analytical.py    From pywr with GNU General Public License v3.0 6 votes vote down vote up
def test_analytical():
    """
    Run the test model though a year with analytical solution values to
    ensure reservoir just contains sufficient volume.
    """

    S = 100.0  # supply amplitude
    D = S  # demand
    w = 2*np.pi/365  # frequency (annual)
    V0 = S/w  # initial reservoir level

    model = make_simple_model(S, D, w, V0)

    T = np.arange(1, 365)
    V_anal = S*(np.sin(w*T)/w+T) - D*T + V0
    V_model = np.empty(T.shape)

    for i, t in enumerate(T):
        model.step()
        V_model[i] = model.nodes['reservoir'].volume[0]

    # Relative error from initial volume
    error = np.abs(V_model - V_anal) / V0
    assert np.all(error < 1e-4) 
Example #8
Source File: util.py    From neuropythy with GNU Affero General Public License v3.0 6 votes vote down vote up
def rotation_matrix_3D(u, th):
    """
    rotation_matrix_3D(u, t) yields a 3D numpy matrix that rotates any vector about the axis u
    t radians counter-clockwise.
    """
    # normalize the axis:
    u = normalize(u)
    # We use the Euler-Rodrigues formula;
    # see https://en.wikipedia.org/wiki/Euler-Rodrigues_formula
    a = math.cos(0.5 * th)
    s = math.sin(0.5 * th)
    (b, c, d) = -s * u
    (a2, b2, c2, d2) = (a*a, b*b, c*c, d*d)
    (bc, ad, ac, ab, bd, cd) = (b*c, a*d, a*c, a*b, b*d, c*d)
    return np.array([[a2 + b2 - c2 - d2, 2*(bc + ad),         2*(bd - ac)],
                     [2*(bc - ad),       a2 + c2 - b2 - d2,   2*(cd + ab)],
                     [2*(bd + ac),       2*(cd - ab),         a2 + d2 - b2 - c2]]) 
Example #9
Source File: GFK.py    From transferlearning with MIT License 6 votes vote down vote up
def subspace_disagreement_measure(self, Ps, Pt, Pst):
        """
        Get the best value for the number of subspaces
        For more details, read section 3.4 of the paper.
        **Parameters**
          Ps: Source subspace
          Pt: Target subspace
          Pst: Source + Target subspace
        """

        def compute_angles(A, B):
            _, S, _ = np.linalg.svd(np.dot(A.T, B))
            S[np.where(np.isclose(S, 1, atol=self.eps) == True)[0]] = 1
            return np.arccos(S)

        max_d = min(Ps.shape[1], Pt.shape[1], Pst.shape[1])
        alpha_d = compute_angles(Ps, Pst)
        beta_d = compute_angles(Pt, Pst)
        d = 0.5 * (np.sin(alpha_d) + np.sin(beta_d))
        return np.argmax(d) 
Example #10
Source File: transform_utils.py    From robosuite with MIT License 6 votes vote down vote up
def random_quat(rand=None):
    """Return uniform random unit quaternion.
    rand: array like or None
        Three independent random variables that are uniformly distributed
        between 0 and 1.
    >>> q = random_quat()
    >>> np.allclose(1.0, vector_norm(q))
    True
    >>> q = random_quat(np.random.random(3))
    >>> q.shape
    (4,)
    """
    if rand is None:
        rand = np.random.rand(3)
    else:
        assert len(rand) == 3
    r1 = np.sqrt(1.0 - rand[0])
    r2 = np.sqrt(rand[0])
    pi2 = math.pi * 2.0
    t1 = pi2 * rand[1]
    t2 = pi2 * rand[2]
    return np.array(
        (np.sin(t1) * r1, np.cos(t1) * r1, np.sin(t2) * r2, np.cos(t2) * r2),
        dtype=np.float32,
    ) 
Example #11
Source File: Collection.py    From fullrmc with GNU Affero General Public License v3.0 6 votes vote down vote up
def get_rotation_matrix(rotationVector, angle):
    """
    Calculate the rotation (3X3) matrix about an axis (rotationVector)
    by a rotation angle.

    :Parameters:
        #. rotationVector (list, tuple, numpy.ndarray): Rotation axis
           coordinates.
        #. angle (float): Rotation angle in rad.

    :Returns:
        #. rotationMatrix (numpy.ndarray): Computed (3X3) rotation matrix
    """
    angle = float(angle)
    axis = rotationVector/np.sqrt(np.dot(rotationVector , rotationVector))
    a = np.cos(angle/2)
    b,c,d = -axis*np.sin(angle/2.)
    return np.array( [ [a*a+b*b-c*c-d*d, 2*(b*c-a*d), 2*(b*d+a*c)],
                       [2*(b*c+a*d), a*a+c*c-b*b-d*d, 2*(c*d-a*b)],
                       [2*(b*d-a*c), 2*(c*d+a*b), a*a+d*d-b*b-c*c] ] , dtype = FLOAT_TYPE) 
Example #12
Source File: robot_pendula.py    From soccer-matlab with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def calc_state(self):
		self.theta, theta_dot = self.j1.current_position()
		x, vx = self.slider.current_position()
		assert( np.isfinite(x) )

		if not np.isfinite(x):
			print("x is inf")
			x = 0

		if not np.isfinite(vx):
			print("vx is inf")
			vx = 0

		if not np.isfinite(self.theta):
			print("theta is inf")
			self.theta = 0

		if not np.isfinite(theta_dot):
			print("theta_dot is inf")
			theta_dot = 0

		return np.array([
			x, vx,
			np.cos(self.theta), np.sin(self.theta), theta_dot
			]) 
Example #13
Source File: robot_manipulators.py    From soccer-matlab with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def calc_state(self):
		theta, self.theta_dot = self.central_joint.current_relative_position()
		self.gamma, self.gamma_dot = self.elbow_joint.current_relative_position()
		target_x, _ = self.jdict["target_x"].current_position()
		target_y, _ = self.jdict["target_y"].current_position()
		self.to_target_vec = np.array(self.fingertip.pose().xyz()) - np.array(self.target.pose().xyz())
		return np.array([
			target_x,
			target_y,
			self.to_target_vec[0],
			self.to_target_vec[1],
			np.cos(theta),
			np.sin(theta),
			self.theta_dot,
			self.gamma,
			self.gamma_dot,
		]) 
Example #14
Source File: robot_locomotors.py    From soccer-matlab with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def alive_bonus(self, z, pitch):
		if self.frame%30==0 and self.frame>100 and self.on_ground_frame_counter==0:
			target_xyz  = np.array(self.body_xyz)
			robot_speed = np.array(self.robot_body.speed())
			angle = self.np_random.uniform(low=-3.14, high=3.14)
			from_dist   = 4.0
			attack_speed   = self.np_random.uniform(low=20.0, high=30.0)  # speed 20..30 (* mass in cube.urdf = impulse)
			time_to_travel = from_dist / attack_speed
			target_xyz += robot_speed*time_to_travel  # predict future position at the moment the cube hits the robot
			position = [target_xyz[0] + from_dist*np.cos(angle),
				target_xyz[1] + from_dist*np.sin(angle),
				target_xyz[2] + 1.0]
			attack_speed_vector = target_xyz - np.array(position)
			attack_speed_vector *= attack_speed / np.linalg.norm(attack_speed_vector)
			attack_speed_vector += self.np_random.uniform(low=-1.0, high=+1.0, size=(3,))
			self.aggressive_cube.reset_position(position)
			self.aggressive_cube.reset_velocity(linearVelocity=attack_speed_vector)
		if z < 0.8:
			self.on_ground_frame_counter += 1
		elif self.on_ground_frame_counter > 0:
			self.on_ground_frame_counter -= 1
		# End episode if the robot can't get up in 170 frames, to save computation and decorrelate observations.
		self.frame += 1
		return self.potential_leak() if self.on_ground_frame_counter<170 else -1 
Example #15
Source File: minitaur_terrain_randomizer.py    From soccer-matlab with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def sample(self):
    """Samples new points around some existing point.

    Removes the sampling base point and also stores the new jksampled points if
    they are far enough from all existing points.
    """
    active_point = self._active_list.pop()
    for _ in xrange(self._max_sample_size):
      # Generate random points near the current active_point between the radius
      random_radius = np.random.uniform(self._min_radius, 2 * self._min_radius)
      random_angle = np.random.uniform(0, 2 * math.pi)

      # The sampled 2D points near the active point
      sample = random_radius * np.array(
          [np.cos(random_angle), np.sin(random_angle)]) + active_point

      if not self._is_in_grid(sample):
        continue

      if self._is_close_to_existing_points(sample):
        continue

      self._active_list.append(sample)
      self._grid[self._point_to_index_1d(sample)] = sample 
Example #16
Source File: nav_env.py    From DOTA_models with Apache License 2.0 6 votes vote down vote up
def get_loc_axis(self, node, delta_theta, perturb=None):
    """Based on the node orientation returns X, and Y axis. Used to sample the
    map in egocentric coordinate frame.
    """
    if type(node) == tuple:
      node = np.array([node])
    if perturb is None:
      perturb = np.zeros((node.shape[0], 4))
    xyt = self.to_actual_xyt_vec(node)
    x = xyt[:,[0]] + perturb[:,[0]]
    y = xyt[:,[1]] + perturb[:,[1]]
    t = xyt[:,[2]] + perturb[:,[2]]
    theta = t*delta_theta
    loc = np.concatenate((x,y), axis=1)
    x_axis = np.concatenate((np.cos(theta), np.sin(theta)), axis=1)
    y_axis = np.concatenate((np.cos(theta+np.pi/2.), np.sin(theta+np.pi/2.)),
                            axis=1)
    # Flip the sampled map where need be.
    y_axis[np.where(perturb[:,3] > 0)[0], :] *= -1.
    return loc, x_axis, y_axis, theta 
Example #17
Source File: test_PlanetPopulation.py    From EXOSIMS with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_gen_angles(self):
        """
        Test generation of orientation angles.
        
        We expect long. and periapse to be uniformly distributed and
        inclination to be sinusoidally distributed.

        Test method: chi squares
        """

        pp = PlanetPopulation(**self.spec)

        x = 10000
        I, O, w = pp.gen_angles(x)

        #O & w are expected to be uniform
        for param,param_range in zip([O,w],[pp.Orange,pp.wrange]):
            h = np.histogram(param.to('rad').value,100,density=True)
            chi2 = scipy.stats.chisquare(h[0],[1.0/np.diff(param_range.to('rad').value)[0]]*len(h[0]))
            self.assertGreater(chi2[1], 0.95)

        #I is expected to be sinusoidal
        hI = np.histogram(I.to(u.rad).value,100,density=True)
        Ix = np.diff(hI[1])/2.+hI[1][:-1]
        Ip = np.sin(Ix)/2

        Ichi2 = scipy.stats.chisquare(hI[0],Ip)
        assert(Ichi2[1] > 0.95) 
Example #18
Source File: ModelingCloth.py    From Modeling-Cloth with MIT License 5 votes vote down vote up
def get_quat(rad, axis):
    theta = (rad * 0.5)
    w = np.cos(theta)
    q_axis = axis * np.sin(theta)[:, nax]
    return w, q_axis 
Example #19
Source File: GarrettCompleteness.py    From EXOSIMS with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def s_bound(self, dmag, smax):
        """Calculates the bounding value of projected separation for dMag
        
        Args:
            dmag (float):
                Planet delta magnitude
            smax (float):
                maximum projected separation (AU)
        
        Returns:
            sb (float):
                boundary value of projected separation (AU)
        """
        
        if dmag < self.d1:
            s = 0.0
        elif (dmag > self.d1) and (dmag <= self.d2):
            s = self.rmin*np.sin(self.Phiinv(self.rmin**2*10.0**(-0.4*dmag)/(self.pmax*(self.Rmax*self.x)**2)))
        elif (dmag > self.d2) and (dmag <= self.d3):
            s = np.sin(self.bstar)*np.sqrt(self.pmax*(self.Rmax*self.x)**2*self.Phi(self.bstar)/10.0**(-0.4*dmag))
        elif (dmag > self.d3) and (dmag <= self.d4):
            s = self.rmax*np.sin(self.Phiinv(self.rmax**2*10.0**(-0.4*dmag)/(self.pmax*(self.Rmax*self.x)**2)))
        elif (dmag > self.d4) and (dmag <= self.d5):
            s = smax
        else:
            s = self.rmax*np.sin(np.pi - self.Phiinv(10.0**(-0.4*dmag)*self.rmax**2/(self.pmin*(self.Rmin*self.x)**2)))
    
        return s 
Example #20
Source File: hsc.py    From openISP with MIT License 5 votes vote down vote up
def lut(self):
        ind = np.array([i for i in range(360)])
        sin = np.sin(ind * np.pi / 180) * 256
        cos = np.cos(ind * np.pi / 180) * 256
        lut_sin = dict(zip(ind, [round(sin[i]) for i in ind]))
        lut_cos = dict(zip(ind, [round(cos[i]) for i in ind]))
        return lut_sin, lut_cos 
Example #21
Source File: augmentations.py    From pytorch-mri-segmentation-3D with MIT License 5 votes vote down vote up
def applyRotation(images, rot, spline_orders):
	transform_x = np.array([[1.0, 				0.0,			0.0],
                            [0.0, 				np.cos(rot[0]), -np.sin(rot[0])],
                            [0.0, 				np.sin(rot[0]), np.cos(rot[0])]])

	transform_y = np.array([[np.cos(rot[1]), 	0.0, 			np.sin(rot[1])],
                            [0.0, 				1.0, 			0.0],
                            [-np.sin(rot[1]), 	0.0, 			np.cos(rot[1])]])

	transform_z = np.array([[np.cos(rot[2]),	-np.sin(rot[2]), 	0.0],
                            [np.sin(rot[2]), 	np.cos(rot[2]), 	0.0],
                            [0.0, 				0, 					1]])
	transform = np.dot(transform_z, np.dot(transform_x, transform_y))

	new_imgs = []
	for i, img in enumerate(images):
		mid_index = 0.5 * np.asarray(img.squeeze().shape, dtype=np.int64)
		offset = mid_index - mid_index.dot(np.linalg.inv(transform))
		new_img = scipy.ndimage.affine_transform(
											input = img.squeeze(), 
											matrix = transform, 
											offset = offset, 
											order = spline_orders[i],
											mode = 'nearest')
		new_img = new_img[np.newaxis,np.newaxis,:]
		new_imgs.append(new_img)
	return new_imgs 
Example #22
Source File: sawyer.py    From robosuite with MIT License 5 votes vote down vote up
def _get_observation(self):
        """
        Returns an OrderedDict containing observations [(name_string, np.array), ...].

        Important keys:
            robot-state: contains robot-centric information.
        """

        di = super()._get_observation()
        # proprioceptive features
        di["joint_pos"] = np.array(
            [self.sim.data.qpos[x] for x in self._ref_joint_pos_indexes]
        )
        di["joint_vel"] = np.array(
            [self.sim.data.qvel[x] for x in self._ref_joint_vel_indexes]
        )

        robot_states = [
            np.sin(di["joint_pos"]),
            np.cos(di["joint_pos"]),
            di["joint_vel"],
        ]

        if self.has_gripper:
            di["gripper_qpos"] = np.array(
                [self.sim.data.qpos[x] for x in self._ref_gripper_joint_pos_indexes]
            )
            di["gripper_qvel"] = np.array(
                [self.sim.data.qvel[x] for x in self._ref_gripper_joint_vel_indexes]
            )

            di["eef_pos"] = np.array(self.sim.data.site_xpos[self.eef_site_id])
            di["eef_quat"] = T.convert_quat(
                self.sim.data.get_body_xquat("right_hand"), to="xyzw"
            )

            # add in gripper information
            robot_states.extend([di["gripper_qpos"], di["eef_pos"], di["eef_quat"]])

        di["robot-state"] = np.concatenate(robot_states)
        return di 
Example #23
Source File: panda.py    From robosuite with MIT License 5 votes vote down vote up
def _get_observation(self):
        """
        Returns an OrderedDict containing observations [(name_string, np.array), ...].

        Important keys:
            robot-state: contains robot-centric information.
        """

        di = super()._get_observation()
        # proprioceptive features
        di["joint_pos"] = np.array(
            [self.sim.data.qpos[x] for x in self._ref_joint_pos_indexes]
        )
        di["joint_vel"] = np.array(
            [self.sim.data.qvel[x] for x in self._ref_joint_vel_indexes]
        )

        robot_states = [
            np.sin(di["joint_pos"]),
            np.cos(di["joint_pos"]),
            di["joint_vel"],
        ]

        if self.has_gripper:
            di["gripper_qpos"] = np.array(
                [self.sim.data.qpos[x] for x in self._ref_gripper_joint_pos_indexes]
            )
            di["gripper_qvel"] = np.array(
                [self.sim.data.qvel[x] for x in self._ref_gripper_joint_vel_indexes]
            )

            di["eef_pos"] = np.array(self.sim.data.site_xpos[self.eef_site_id])
            di["eef_quat"] = T.convert_quat(
                self.sim.data.get_body_xquat("right_hand"), to="xyzw"
            )

            # add in gripper information
            robot_states.extend([di["gripper_qpos"], di["eef_pos"], di["eef_quat"]])

        di["robot-state"] = np.concatenate(robot_states)
        return di 
Example #24
Source File: Observatory.py    From EXOSIMS with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def calculate_slewTimes(self,TL,old_sInd,sInds,sd,obsTimes,currentTime):
        """Finds slew times and separation angles between target stars
        
        This method determines the slew times of an occulter spacecraft needed
        to transfer from one star's line of sight to all others in a given 
        target list.
        
        Args:
            TL (TargetList module):
                TargetList class object
            old_sInd (integer):
                Integer index of the most recently observed star
            sInds (integer ndarray):
                Integer indeces of the star of interest
            sd (astropy Quantity):
                Angular separation between stars in rad
            currentTime (astropy Time):
                Current absolute mission time in MJD
                
        Returns:
            astropy Quantity:
                Time to transfer to new star line of sight in units of days
        """
    
        self.ao = self.thrust/self.scMass
        slewTime_fac = (2.*self.occulterSep/np.abs(self.ao)/(self.defburnPortion/2. - 
            self.defburnPortion**2./4.)).decompose().to('d2')

        if old_sInd is None:
            slewTimes = np.zeros(TL.nStars)*u.d
        else:
            # calculate slew time
            slewTimes = np.sqrt(slewTime_fac*np.sin(abs(sd)/2.)) #an issue exists if sd is negative
            
            #The following are debugging 
            assert np.where(np.isnan(slewTimes))[0].shape[0] == 0, 'At least one slewTime is nan'
        
        return slewTimes 
Example #25
Source File: utils.py    From py360convert with MIT License 5 votes vote down vote up
def uv2unitxyz(uv):
    u, v = np.split(uv, 2, axis=-1)
    y = np.sin(v)
    c = np.cos(v)
    x = c * np.sin(u)
    z = c * np.cos(u)

    return np.concatenate([x, y, z], axis=-1) 
Example #26
Source File: robot_locomotors.py    From soccer-matlab with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def calc_state(self):
		j = np.array([j.current_relative_position() for j in self.ordered_joints], dtype=np.float32).flatten()
		# even elements [0::2] position, scaled to -1..+1 between limits
		# odd elements  [1::2] angular speed, scaled to show -1..+1
		self.joint_speeds = j[1::2]
		self.joints_at_limit = np.count_nonzero(np.abs(j[0::2]) > 0.99)

		body_pose = self.robot_body.pose()
		parts_xyz = np.array([p.pose().xyz() for p in self.parts.values()]).flatten()
		self.body_xyz = (
		parts_xyz[0::3].mean(), parts_xyz[1::3].mean(), body_pose.xyz()[2])  # torso z is more informative than mean z
		self.body_rpy = body_pose.rpy()
		z = self.body_xyz[2]
		if self.initial_z == None:
			self.initial_z = z
		r, p, yaw = self.body_rpy
		self.walk_target_theta = np.arctan2(self.walk_target_y - self.body_xyz[1],
											self.walk_target_x - self.body_xyz[0])
		self.walk_target_dist = np.linalg.norm(
			[self.walk_target_y - self.body_xyz[1], self.walk_target_x - self.body_xyz[0]])
		angle_to_target = self.walk_target_theta - yaw

		rot_speed = np.array(
			[[np.cos(-yaw), -np.sin(-yaw), 0],
			 [np.sin(-yaw), np.cos(-yaw), 0],
			 [		0,			 0, 1]]
		)
		vx, vy, vz = np.dot(rot_speed, self.robot_body.speed())  # rotate speed back to body point of view

		more = np.array([ z-self.initial_z,
			np.sin(angle_to_target), np.cos(angle_to_target),
			0.3* vx , 0.3* vy , 0.3* vz ,  # 0.3 is just scaling typical speed into -1..+1, no physical sense here
			r, p], dtype=np.float32)
		return np.clip( np.concatenate([more] + [j] + [self.feet_contact]), -5, +5) 
Example #27
Source File: utils.py    From py360convert with MIT License 5 votes vote down vote up
def rotation_matrix(rad, ax):
    ax = np.array(ax)
    assert len(ax.shape) == 1 and ax.shape[0] == 3
    ax = ax / np.sqrt((ax**2).sum())
    R = np.diag([np.cos(rad)] * 3)
    R = R + np.outer(ax, ax) * (1.0 - np.cos(rad))

    ax = ax * np.sin(rad)
    R = R + np.array([[0, -ax[2], ax[1]],
                      [ax[2], 0, -ax[0]],
                      [-ax[1], ax[0], 0]])

    return R 
Example #28
Source File: nav_env.py    From DOTA_models with Apache License 2.0 5 votes vote down vote up
def render_nodes(self, nodes, perturb=None, aux_delta_theta=0.):
    self.set_building_visibility(True)
    if perturb is None:
      perturb = np.zeros((len(nodes), 4))

    imgs = []
    r = 2
    elevation_z = r * np.tan(np.deg2rad(self.robot.camera_elevation_degree))

    for i in range(len(nodes)):
      xyt = self.to_actual_xyt(nodes[i])
      lookat_theta = 3.0 * np.pi / 2.0 - (xyt[2]+perturb[i,2]+aux_delta_theta) * (self.task.delta_theta)
      nxy = np.array([xyt[0]+perturb[i,0], xyt[1]+perturb[i,1]]).reshape(1, -1)
      nxy = nxy * self.map.resolution
      nxy = nxy + self.map.origin
      camera_xyz = np.zeros((1, 3))
      camera_xyz[...] = [nxy[0, 0], nxy[0, 1], self.robot.sensor_height]
      camera_xyz = camera_xyz / 100.
      lookat_xyz = np.array([-r * np.sin(lookat_theta),
                             -r * np.cos(lookat_theta), elevation_z])
      lookat_xyz = lookat_xyz + camera_xyz[0, :]
      self.r_obj.position_camera(camera_xyz[0, :].tolist(),
                                 lookat_xyz.tolist(), [0.0, 0.0, 1.0])
      img = self.r_obj.render(take_screenshot=True, output_type=0)
      img = [x for x in img if x is not None]
      img = np.concatenate(img, axis=2).astype(np.float32)
      if perturb[i,3]>0:
        img = img[:,::-1,:]
      imgs.append(img)

    self.set_building_visibility(False)
    return imgs 
Example #29
Source File: tf_logits.py    From Black-Box-Audio with MIT License 5 votes vote down vote up
def compute_mfcc(audio, **kwargs):
    """
    Compute the MFCC for a given audio waveform. This is
    identical to how DeepSpeech does it, but does it all in
    TensorFlow so that we can differentiate through it.
    """

    batch_size, size = audio.get_shape().as_list()
    audio = tf.cast(audio, tf.float32)

    # 1. Pre-emphasizer, a high-pass filter
    audio = tf.concat((audio[:, :1], audio[:, 1:] - 0.97*audio[:, :-1], np.zeros((batch_size,1000),dtype=np.float32)), 1)

    # 2. windowing into frames of 320 samples, overlapping
    windowed = tf.stack([audio[:, i:i+400] for i in range(0,size-320,160)],1)

    # 3. Take the FFT to convert to frequency space
    ffted = tf.spectral.rfft(windowed, [512])
    ffted = 1.0 / 512 * tf.square(tf.abs(ffted))

    # 4. Compute the Mel windowing of the FFT
    energy = tf.reduce_sum(ffted,axis=2)+1e-30
    filters = np.load("filterbanks.npy").T
    feat = tf.matmul(ffted, np.array([filters]*batch_size,dtype=np.float32))+1e-30

    # 5. Take the DCT again, because why not
    feat = tf.log(feat)
    feat = tf.spectral.dct(feat, type=2, norm='ortho')[:,:,:26]

    # 6. Amplify high frequencies for some reason
    _,nframes,ncoeff = feat.get_shape().as_list()
    n = np.arange(ncoeff)
    lift = 1 + (22/2.)*np.sin(np.pi*n/22)
    feat = lift*feat
    width = feat.get_shape().as_list()[1]

    # 7. And now stick the energy next to the features
    feat = tf.concat((tf.reshape(tf.log(energy),(-1,width,1)), feat[:, :, 1:]), axis=2)
    
    return feat 
Example #30
Source File: Observatory.py    From EXOSIMS with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def rot(self, th, axis):
        """Finds the rotation matrix of angle th about the axis value
        
        Args:
            th (float):
                Rotation angle in radians
            axis (int): 
                Integer value denoting rotation axis (1,2, or 3)
        
        Returns:
            float 3x3 ndarray:
                Rotation matrix
        
        """
        
        if axis == 1:
            rot_th = np.array([[1., 0., 0.], 
                    [0., np.cos(th), np.sin(th)], 
                    [0., -np.sin(th), np.cos(th)]])
        elif axis == 2:
            rot_th = np.array([[np.cos(th), 0., -np.sin(th)],
                    [0., 1., 0.],
                    [np.sin(th), 0., np.cos(th)]])
        elif axis == 3:
            rot_th = np.array([[np.cos(th), np.sin(th), 0.],
                    [-np.sin(th), np.cos(th), 0.],
                    [0., 0., 1.]])
        
        return rot_th