Python math.pi() Examples

The following are code examples for showing how to use math.pi(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: pyblish-win   Author: pyblish   File: test_byteswap.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_endian_float(self):
        if sys.byteorder == "little":
            self.assertIs(c_float.__ctype_le__, c_float)
            self.assertIs(c_float.__ctype_be__.__ctype_le__, c_float)
        else:
            self.assertIs(c_float.__ctype_be__, c_float)
            self.assertIs(c_float.__ctype_le__.__ctype_be__, c_float)
        s = c_float(math.pi)
        self.assertEqual(bin(struct.pack("f", math.pi)), bin(s))
        # Hm, what's the precision of a float compared to a double?
        self.assertAlmostEqual(s.value, math.pi, 6)
        s = c_float.__ctype_le__(math.pi)
        self.assertAlmostEqual(s.value, math.pi, 6)
        self.assertEqual(bin(struct.pack("<f", math.pi)), bin(s))
        s = c_float.__ctype_be__(math.pi)
        self.assertAlmostEqual(s.value, math.pi, 6)
        self.assertEqual(bin(struct.pack(">f", math.pi)), bin(s)) 
Example 2
Project: pyblish-win   Author: pyblish   File: test_byteswap.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_endian_double(self):
        if sys.byteorder == "little":
            self.assertIs(c_double.__ctype_le__, c_double)
            self.assertIs(c_double.__ctype_be__.__ctype_le__, c_double)
        else:
            self.assertIs(c_double.__ctype_be__, c_double)
            self.assertIs(c_double.__ctype_le__.__ctype_be__, c_double)
        s = c_double(math.pi)
        self.assertEqual(s.value, math.pi)
        self.assertEqual(bin(struct.pack("d", math.pi)), bin(s))
        s = c_double.__ctype_le__(math.pi)
        self.assertEqual(s.value, math.pi)
        self.assertEqual(bin(struct.pack("<d", math.pi)), bin(s))
        s = c_double.__ctype_be__(math.pi)
        self.assertEqual(s.value, math.pi)
        self.assertEqual(bin(struct.pack(">d", math.pi)), bin(s)) 
Example 3
Project: pyblish-win   Author: pyblish   File: turtle.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def settiltangle(self, angle):
        """Rotate the turtleshape to point in the specified direction

        Optional argument:
        angle -- number

        Rotate the turtleshape to point in the direction specified by angle,
        regardless of its current tilt-angle. DO NOT change the turtle's
        heading (direction of movement).


        Examples (for a Turtle instance named turtle):
        >>> turtle.shape("circle")
        >>> turtle.shapesize(5,2)
        >>> turtle.settiltangle(45)
        >>> stamp()
        >>> turtle.fd(50)
        >>> turtle.settiltangle(-45)
        >>> stamp()
        >>> turtle.fd(50)
        """
        tilt = -angle * self._degreesPerAU * self._angleOrient
        tilt = (tilt * math.pi / 180.0) % (2*math.pi)
        self.pen(resizemode="user", tilt=tilt) 
Example 4
Project: pyblish-win   Author: pyblish   File: turtle.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def tiltangle(self):
        """Return the current tilt-angle.

        No argument.

        Return the current tilt-angle, i. e. the angle between the
        orientation of the turtleshape and the heading of the turtle
        (its direction of movement).

        Examples (for a Turtle instance named turtle):
        >>> turtle.shape("circle")
        >>> turtle.shapesize(5,2)
        >>> turtle.tilt(45)
        >>> turtle.tiltangle()
        """
        tilt = -self._tilt * (180.0/math.pi) * self._angleOrient
        return (tilt / self._degreesPerAU) % self._fullcircle 
Example 5
Project: pyblish-win   Author: pyblish   File: test_random.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def gamma(z, sqrt2pi=(2.0*pi)**0.5):
    # Reflection to right half of complex plane
    if z < 0.5:
        return pi / sin(pi*z) / gamma(1.0-z)
    # Lanczos approximation with g=7
    az = z + (7.0 - 0.5)
    return az ** (z-0.5) / exp(az) * sqrt2pi * fsum([
        0.9999999999995183,
        676.5203681218835 / z,
        -1259.139216722289 / (z+1.0),
        771.3234287757674 / (z+2.0),
        -176.6150291498386 / (z+3.0),
        12.50734324009056 / (z+4.0),
        -0.1385710331296526 / (z+5.0),
        0.9934937113930748e-05 / (z+6.0),
        0.1659470187408462e-06 / (z+7.0),
    ]) 
Example 6
Project: pyblish-win   Author: pyblish   File: test_decimal.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_create_decimal_from_float(self):
        context = Context(prec=5, rounding=ROUND_DOWN)
        self.assertEqual(
            context.create_decimal_from_float(math.pi),
            Decimal('3.1415')
        )
        context = Context(prec=5, rounding=ROUND_UP)
        self.assertEqual(
            context.create_decimal_from_float(math.pi),
            Decimal('3.1416')
        )
        context = Context(prec=5, traps=[Inexact])
        self.assertRaises(
            Inexact,
            context.create_decimal_from_float,
            math.pi
        )
        self.assertEqual(repr(context.create_decimal_from_float(-0.0)),
                         "Decimal('-0')")
        self.assertEqual(repr(context.create_decimal_from_float(1.0)),
                         "Decimal('1')")
        self.assertEqual(repr(context.create_decimal_from_float(10)),
                         "Decimal('10')") 
Example 7
Project: building-boundary   Author: Geodan   File: angle.py    MIT License 6 votes vote down vote up
def min_angle_difference(a1, a2):
    """
    Returns the minimal angle difference between two orientations.

    Parameters
    ----------
    a1 : float
        An angle in radians
    a2 : float
        Another angle in radians

    Returns
    -------
    angle : float
        The minimal angle difference in radians
    """
    pos1 = abs(math.pi - abs(abs(a1 - a2) - math.pi))
    if a1 < math.pi:
        pos2 = abs(math.pi - abs(abs((a1 + math.pi) - a2) - math.pi))
    elif a2 < math.pi:
        pos2 = abs(math.pi - abs(abs(a1 - (a2 + math.pi)) - math.pi))
    else:
        return pos1
    return pos1 if pos1 < pos2 else pos2 
Example 8
Project: building-boundary   Author: Geodan   File: angle.py    MIT License 6 votes vote down vote up
def angle_difference(a1, a2):
    """
    Returns the angle difference between two orientations.

    Parameters
    ----------
    a1 : float
        An angle in radians
    a2 : float
        Another angle in radians

    Returns
    -------
    angle : float
        The angle difference in radians
    """
    return math.pi - abs(math.pi - abs(a1 - a2) % (math.pi*2)) 
Example 9
Project: building-boundary   Author: Geodan   File: angle.py    MIT License 6 votes vote down vote up
def to_positive_angle(angle):
    """
    Converts an angle to positive.

    Parameters
    ----------
    angle : float
        The angle in radians

    Returns
    -------
    angle : float
        The positive angle
    """
    angle = angle % math.pi
    if angle < 0:
        angle += math.pi
    return angle 
Example 10
Project: building-boundary   Author: Geodan   File: angle.py    MIT License 6 votes vote down vote up
def perpendicular(angle):
    """
    Returns the perpendicular angle to the given angle.

    Parameters
    ----------
    angle : float or int
        The given angle in radians

    Returns
    -------
    perpendicular : float
        The perpendicular to the given angle in radians
    """
    perp = angle + math.pi/2
    if perp > math.pi:
        perp = angle - math.pi/2
    return perp 
Example 11
Project: Kaggle-Statoil-Challenge   Author: adodd202   File: utils.py    MIT License 6 votes vote down vote up
def sgdr(period, batch_idx):
    # returns normalised anytime sgdr schedule given period and batch_idx
    # best performing settings reported in paper are T_0 = 10, T_mult=2
    # so always use T_mult=2
    batch_idx = float(batch_idx)
    restart_period = period
    while batch_idx / restart_period > 1.:
        batch_idx = batch_idx - restart_period
        restart_period = restart_period * 2.

    radians = math.pi * (batch_idx / restart_period)
    return 0.5 * (1.0 + math.cos(radians))


# def adjust_learning_rate(optimizer, epoch):
#     global lr
#     """Sets the learning rate to the initial LR decayed by 10 every 30 epochs"""
#     lr = lr * (0.01 ** (epoch // 10))
#     for param_group in optimizer.state_dict()['param_groups']:
#         param_group['lr'] = lr 
Example 12
Project: mesh_heal   Author: tkeskita   File: op_clean_mesh.py    GNU General Public License v3.0 6 votes vote down vote up
def triangulate_twists(ob):
    """Triangulate Twisted Faces (Mesh Heal)"""

    import bmesh
    import math
    bpy.ops.object.mode_set(mode = 'EDIT')
    bm = bmesh.from_edit_mesh(ob.data)

    twistfaces = []

    # Maximum absolute cosine of angle between face normal vector and
    # center-to-corner vector
    angle = bpy.context.scene.mesh_heal.max_abs_twist_angle
    max_abs_cos_alpha = math.cos((90.0 - angle) / 90.0 * math.pi / 2.0)

    # Find all twisted faces
    for f in bm.faces:
        norvec = f.normal
        co = f.calc_center_median()
        for v in f.verts:
            vertvec = v.co - co
            vertvec.normalize()
            abs_cos_alpha = abs(vertvec @ norvec)
            l.debug("face %d abs_cos_alpha %f" % (f.index, abs_cos_alpha))
            if abs_cos_alpha > max_abs_cos_alpha:
                if f not in twistfaces:
                    twistfaces.append(f)
                    f.select = True

    # Triangulate twisted faces
    bmesh.ops.triangulate(bm, faces=twistfaces)

    bmesh.update_edit_mesh(ob.data, True)
    bm.free()
    return len(twistfaces) 
Example 13
Project: soccer-matlab   Author: utra-robosoccer   File: minitaur_gym_env.py    BSD 2-Clause "Simplified" License 6 votes vote down vote up
def _get_observation_upper_bound(self):
    """Get the upper bound of the observation.

    Returns:
      The upper bound of an observation. See GetObservation() for the details
        of each element of an observation.
    """
    upper_bound = np.zeros(self._get_observation_dimension())
    num_motors = self.minitaur.num_motors
    upper_bound[0:num_motors] = math.pi  # Joint angle.
    upper_bound[num_motors:2 * num_motors] = (
        motor.MOTOR_SPEED_LIMIT)  # Joint velocity.
    upper_bound[2 * num_motors:3 * num_motors] = (
        motor.OBSERVED_TORQUE_LIMIT)  # Joint torque.
    upper_bound[3 * num_motors:] = 1.0  # Quaternion of base orientation.
    return upper_bound 
Example 14
Project: soccer-matlab   Author: utra-robosoccer   File: minitaur.py    BSD 2-Clause "Simplified" License 6 votes vote down vote up
def MapToMinusPiToPi(angles):
  """Maps a list of angles to [-pi, pi].

  Args:
    angles: A list of angles in rad.
  Returns:
    A list of angle mapped to [-pi, pi].
  """
  mapped_angles = copy.deepcopy(angles)
  for i in range(len(angles)):
    mapped_angles[i] = math.fmod(angles[i], TWO_PI)
    if mapped_angles[i] >= math.pi:
      mapped_angles[i] -= TWO_PI
    elif mapped_angles[i] < -math.pi:
      mapped_angles[i] += TWO_PI
  return mapped_angles 
Example 15
Project: soccer-matlab   Author: utra-robosoccer   File: minitaur_randomize_terrain_gym_env_example.py    BSD 2-Clause "Simplified" License 6 votes vote down vote up
def ResetTerrainExample():
  """An example showing resetting random terrain env."""
  num_reset = 10
  steps = 100
  env = minitaur_randomize_terrain_gym_env.MinitaurRandomizeTerrainGymEnv(
      render=True,
      leg_model_enabled=False,
      motor_velocity_limit=np.inf,
      pd_control_enabled=True)
  action = [math.pi / 2] * 8
  for _ in xrange(num_reset):
    env.reset()
    for _ in xrange(steps):
      _, _, done, _ = env.step(action)
      if done:
        break 
Example 16
Project: soccer-matlab   Author: utra-robosoccer   File: minitaur_trotting_env.py    BSD 2-Clause "Simplified" License 6 votes vote down vote up
def _gen_signal(self, t, phase):
    """Generates a sinusoidal reference leg trajectory.

    The foot (leg tip) will move in a ellipse specified by extension and swing
    amplitude.

    Args:
      t: Current time in simulation.
      phase: The phase offset for the periodic trajectory.

    Returns:
      The desired leg extension and swing angle at the current time.
    """
    period = 1 / self._step_frequency
    extension = self._extension_amplitude * math.cos(
        2 * math.pi / period * t + phase)
    swing = self._swing_amplitude * math.sin(2 * math.pi / period * t + phase)
    return extension, swing 
Example 17
Project: soccer-matlab   Author: utra-robosoccer   File: minitaur_trotting_env.py    BSD 2-Clause "Simplified" License 6 votes vote down vote up
def _signal(self, t):
    """Generates the trotting gait for the robot.

    Args:
      t: Current time in simulation.

    Returns:
      A numpy array of the reference leg positions.
    """
    # Generates the leg trajectories for the two digonal pair of legs.
    ext_first_pair, sw_first_pair = self._gen_signal(t, 0)
    ext_second_pair, sw_second_pair = self._gen_signal(t, math.pi)

    trotting_signal = np.array([
        sw_first_pair, sw_second_pair, sw_second_pair, sw_first_pair,
        ext_first_pair, ext_second_pair, ext_second_pair, ext_first_pair
    ])
    signal = np.array(self._init_pose) + trotting_signal
    return signal 
Example 18
Project: soccer-matlab   Author: utra-robosoccer   File: minitaur_ball_gym_env.py    BSD 2-Clause "Simplified" License 6 votes vote down vote up
def _get_observation(self):
    world_translation_minitaur, world_rotation_minitaur = (
        self._pybullet_client.getBasePositionAndOrientation(
            self.minitaur.quadruped))
    world_translation_ball, world_rotation_ball = (
        self._pybullet_client.getBasePositionAndOrientation(self._ball_id))
    minitaur_translation_world, minitaur_rotation_world = (
        self._pybullet_client.invertTransform(world_translation_minitaur,
                                              world_rotation_minitaur))
    minitaur_translation_ball, _ = (
        self._pybullet_client.multiplyTransforms(minitaur_translation_world,
                                                 minitaur_rotation_world,
                                                 world_translation_ball,
                                                 world_rotation_ball))
    distance = math.sqrt(minitaur_translation_ball[0]**2 +
                         minitaur_translation_ball[1]**2)
    angle = math.atan2(minitaur_translation_ball[0],
                       minitaur_translation_ball[1])
    self._observation = [angle - math.pi / 2, distance]
    return self._observation 
Example 19
Project: soccer-matlab   Author: utra-robosoccer   File: minitaur_reactive_env.py    BSD 2-Clause "Simplified" License 6 votes vote down vote up
def _get_observation_upper_bound(self):
    """Get the upper bound of the observation.

    Returns:
      The upper bound of an observation. See _get_true_observation() for the
      details of each element of an observation.
    """
    upper_bound_roll = 2 * math.pi
    upper_bound_pitch = 2 * math.pi
    upper_bound_roll_dot = 2 * math.pi / self._time_step
    upper_bound_pitch_dot = 2 * math.pi / self._time_step
    upper_bound_motor_angle = 2 * math.pi
    upper_bound = [
        upper_bound_roll, upper_bound_pitch, upper_bound_roll_dot,
        upper_bound_pitch_dot
    ]

    if self._use_angle_in_observation:
      upper_bound.extend([upper_bound_motor_angle] * NUM_MOTORS)
    return np.array(upper_bound) 
Example 20
Project: soccer-matlab   Author: utra-robosoccer   File: minitaur_gym_env_example.py    BSD 2-Clause "Simplified" License 6 votes vote down vote up
def ResetPoseExample(log_path=None):
  """An example that the minitaur stands still using the reset pose."""
  steps = 10000
  environment = minitaur_gym_env.MinitaurGymEnv(
      urdf_version=minitaur_gym_env.DERPY_V0_URDF_VERSION,
      render=True,
      leg_model_enabled=False,
      motor_velocity_limit=np.inf,
      pd_control_enabled=True,
      accurate_motor_model_enabled=True,
      motor_overheat_protection=True,
      hard_reset=False,
      log_path=log_path)
  action = [math.pi / 2] * 8
  for _ in range(steps):
    _, _, done, _ = environment.step(action)
    time.sleep(1./100.)
    if done:
      break 
Example 21
Project: soccer-matlab   Author: utra-robosoccer   File: minitaur_terrain_randomizer.py    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 22
Project: unicorn-hat-hd   Author: pimoroni   File: demo.py    MIT License 5 votes vote down vote up
def tunnel(x, y, step):
    speed = step / 100.0
    x -= (u_width / 2)
    y -= (u_height / 2)
    xo = math.sin(step / 27.0) * 2
    yo = math.cos(step / 18.0) * 2
    x += xo
    y += yo
    if y == 0:
        if x < 0:
            angle = -(math.pi / 2)
        else:
            angle = (math.pi / 2)
    else:
        angle = math.atan(x / y)
    if y > 0:
        angle += math.pi
    angle /= 2 * math.pi  # convert angle to 0...1 range
    hyp = math.sqrt(math.pow(x, 2) + math.pow(y, 2))
    shade = hyp / 2.1
    shade = 1 if shade > 1 else shade
    angle += speed
    depth = speed + (hyp / 10)
    col1 = hue_to_rgb[step % 255]
    col1 = (col1[0] * 0.8, col1[1] * 0.8, col1[2] * 0.8)
    col2 = hue_to_rgb[step % 255]
    col2 = (col2[0] * 0.3, col2[1] * 0.3, col2[2] * 0.3)
    col = col1 if int(abs(angle * 6.0)) % 2 == 0 else col2
    td = .3 if int(abs(depth * 3.0)) % 2 == 0 else 0
    col = (col[0] + td, col[1] + td, col[2] + td)
    col = (col[0] * shade, col[1] * shade, col[2] * shade)
    return (col[0] * 255, col[1] * 255, col[2] * 255) 
Example 23
Project: kicker-module   Author: EvanTheB   File: trueskill.py    GNU General Public License v3.0 5 votes vote down vote up
def gaussian_at(x, mean=0.0, standard_dev=1.0):
    """
    gaussian function at x
    """
    # // See http://mathworld.wolfram.com/NormalDistribution.html
    # // 1 -(x-mean)^2 / (2*stdDev^2)
    # // P(x) = ------------------- * e
    # // stdDev * sqrt(2*pi)
    multiplier = 1.0 / (standard_dev * math.sqrt(2 * math.pi))
    exp_part = (-1.0 * (x - mean) ** 2 / (2 * (standard_dev ** 2)))
    result = multiplier * math.exp(exp_part)
    return result 
Example 24
Project: chainer-openai-transformer-lm   Author: soskek   File: model_py.py    MIT License 5 votes vote down vote up
def gelu(x):
    return 0.5 * x * (1 + F.tanh(math.sqrt(2 / math.pi)
                                 * (x + 0.044715 * (x ** 3)))) 
Example 25
Project: pepper-robot-programming   Author: maverickjoy   File: asthama_search.py    MIT License 5 votes vote down vote up
def _transformTheta(self, theta):
        # CONVERTING THETA { THETA' % 360}
        if (float(theta) == math.radians(360)):
            theta = 0.0

        if (float(theta) == -(math.radians(360))):
            theta = 0.0

        if (float(theta) == math.radians(270)):
            theta = -math.pi/2

        if (float(theta) == -(math.radians(270))):
            theta = math.pi/2

        return theta 
Example 26
Project: pyblish-win   Author: pyblish   File: test_float.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_floats(self):
        for num in [1617161771.7650001, math.pi, math.pi**100,
                    math.pi**-100, 3.1]:
            self.assertEqual(float(self.dumps(num)), num)
            self.assertEqual(self.loads(self.dumps(num)), num)
            self.assertEqual(self.loads(unicode(self.dumps(num))), num) 
Example 27
Project: pyblish-win   Author: pyblish   File: turtle.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def rotate(self, angle):
        """rotate self counterclockwise by angle
        """
        perp = Vec2D(-self[1], self[0])
        angle = angle * math.pi / 180.0
        c, s = math.cos(angle), math.sin(angle)
        return Vec2D(self[0]*c+perp[0]*s, self[1]*c+perp[1]*s) 
Example 28
Project: pyblish-win   Author: pyblish   File: turtle.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def radians(self):
        """ Set the angle measurement units to radians.

        No arguments.

        Example (for a Turtle instance named turtle):
        >>> turtle.heading()
        90
        >>> turtle.radians()
        >>> turtle.heading()
        1.5707963267948966
        """
        self._setDegreesPerAU(2*math.pi) 
Example 29
Project: pyblish-win   Author: pyblish   File: turtle.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def heading(self):
        """ Return the turtle's current heading.

        No arguments.

        Example (for a Turtle instance named turtle):
        >>> turtle.left(67)
        >>> turtle.heading()
        67.0
        """
        x, y = self._orient
        result = round(math.atan2(y, x)*180.0/math.pi, 10) % 360.0
        result /= self._degreesPerAU
        return (self._angleOffset + self._angleOrient*result) % self._fullcircle 
Example 30
Project: pyblish-win   Author: pyblish   File: test_fractions.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def testApproximatePi(self):
        # Algorithm borrowed from
        # http://docs.python.org/lib/decimal-recipes.html
        three = F(3)
        lasts, t, s, n, na, d, da = 0, three, 3, 1, 0, 0, 24
        while abs(s - lasts) > F(1, 10**9):
            lasts = s
            n, na = n+na, na+8
            d, da = d+da, da+32
            t = (t * n) / d
            s += t
        self.assertAlmostEqual(math.pi, s) 
Example 31
Project: pyblish-win   Author: pyblish   File: test_math.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def testAcos(self):
        self.assertRaises(TypeError, math.acos)
        self.ftest('acos(-1)', math.acos(-1), math.pi)
        self.ftest('acos(0)', math.acos(0), math.pi/2)
        self.ftest('acos(1)', math.acos(1), 0)
        self.assertRaises(ValueError, math.acos, INF)
        self.assertRaises(ValueError, math.acos, NINF)
        self.assertTrue(math.isnan(math.acos(NAN))) 
Example 32
Project: pyblish-win   Author: pyblish   File: test_math.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def testAsin(self):
        self.assertRaises(TypeError, math.asin)
        self.ftest('asin(-1)', math.asin(-1), -math.pi/2)
        self.ftest('asin(0)', math.asin(0), 0)
        self.ftest('asin(1)', math.asin(1), math.pi/2)
        self.assertRaises(ValueError, math.asin, INF)
        self.assertRaises(ValueError, math.asin, NINF)
        self.assertTrue(math.isnan(math.asin(NAN))) 
Example 33
Project: pyblish-win   Author: pyblish   File: test_math.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def testAtan(self):
        self.assertRaises(TypeError, math.atan)
        self.ftest('atan(-1)', math.atan(-1), -math.pi/4)
        self.ftest('atan(0)', math.atan(0), 0)
        self.ftest('atan(1)', math.atan(1), math.pi/4)
        self.ftest('atan(inf)', math.atan(INF), math.pi/2)
        self.ftest('atan(-inf)', math.atan(NINF), -math.pi/2)
        self.assertTrue(math.isnan(math.atan(NAN))) 
Example 34
Project: pyblish-win   Author: pyblish   File: test_math.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def testCos(self):
        self.assertRaises(TypeError, math.cos)
        self.ftest('cos(-pi/2)', math.cos(-math.pi/2), 0)
        self.ftest('cos(0)', math.cos(0), 1)
        self.ftest('cos(pi/2)', math.cos(math.pi/2), 0)
        self.ftest('cos(pi)', math.cos(math.pi), -1)
        try:
            self.assertTrue(math.isnan(math.cos(INF)))
            self.assertTrue(math.isnan(math.cos(NINF)))
        except ValueError:
            self.assertRaises(ValueError, math.cos, INF)
            self.assertRaises(ValueError, math.cos, NINF)
        self.assertTrue(math.isnan(math.cos(NAN))) 
Example 35
Project: pyblish-win   Author: pyblish   File: test_math.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def testFactorial(self):
        def fact(n):
            result = 1
            for i in range(1, int(n)+1):
                result *= i
            return result
        values = range(10) + [50, 100, 500]
        random.shuffle(values)
        for x in values:
            for cast in (int, long, float):
                self.assertEqual(math.factorial(cast(x)), fact(x), (x, fact(x), math.factorial(x)))
        self.assertRaises(ValueError, math.factorial, -1)
        self.assertRaises(ValueError, math.factorial, math.pi) 
Example 36
Project: pyblish-win   Author: pyblish   File: test_math.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def testRadians(self):
        self.assertRaises(TypeError, math.radians)
        self.ftest('radians(180)', math.radians(180), math.pi)
        self.ftest('radians(90)', math.radians(90), math.pi/2)
        self.ftest('radians(-45)', math.radians(-45), -math.pi/4) 
Example 37
Project: pyblish-win   Author: pyblish   File: test_math.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def testSin(self):
        self.assertRaises(TypeError, math.sin)
        self.ftest('sin(0)', math.sin(0), 0)
        self.ftest('sin(pi/2)', math.sin(math.pi/2), 1)
        self.ftest('sin(-pi/2)', math.sin(-math.pi/2), -1)
        try:
            self.assertTrue(math.isnan(math.sin(INF)))
            self.assertTrue(math.isnan(math.sin(NINF)))
        except ValueError:
            self.assertRaises(ValueError, math.sin, INF)
            self.assertRaises(ValueError, math.sin, NINF)
        self.assertTrue(math.isnan(math.sin(NAN))) 
Example 38
Project: pyblish-win   Author: pyblish   File: test_math.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def testTan(self):
        self.assertRaises(TypeError, math.tan)
        self.ftest('tan(0)', math.tan(0), 0)
        self.ftest('tan(pi/4)', math.tan(math.pi/4), 1)
        self.ftest('tan(-pi/4)', math.tan(-math.pi/4), -1)
        try:
            self.assertTrue(math.isnan(math.tan(INF)))
            self.assertTrue(math.isnan(math.tan(NINF)))
        except:
            self.assertRaises(ValueError, math.tan, INF)
            self.assertRaises(ValueError, math.tan, NINF)
        self.assertTrue(math.isnan(math.tan(NAN))) 
Example 39
Project: pyblish-win   Author: pyblish   File: test_random.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_von_mises_range(self):
        # Issue 17149: von mises variates were not consistently in the
        # range [0, 2*PI].
        g = random.Random()
        N = 100
        for mu in 0.0, 0.1, 3.1, 6.2:
            for kappa in 0.0, 2.3, 500.0:
                for _ in range(N):
                    sample = g.vonmisesvariate(mu, kappa)
                    self.assertTrue(
                        0 <= sample <= random.TWOPI,
                        msg=("vonmisesvariate({}, {}) produced a result {} out"
                             " of range [0, 2*pi]").format(mu, kappa, sample)) 
Example 40
Project: comet-commonsense   Author: atcbosselut   File: opt.py    Apache License 2.0 5 votes vote down vote up
def warmup_cosine(x, warmup=0.002):
    s = 1 if x <= warmup else 0
    return s*(x/warmup) + (1-s)*(0.5 * (1 + torch.cos(math.pi * x))) 
Example 41
Project: comet-commonsense   Author: atcbosselut   File: gpt.py    Apache License 2.0 5 votes vote down vote up
def gelu(x):
    return (0.5 * x * (1 + torch.tanh(math.sqrt(2 / math.pi) *
            (x + 0.044715 * torch.pow(x, 3))))) 
Example 42
Project: MakeyPiano   Author: merose   File: playScale.py    Apache License 2.0 5 votes vote down vote up
def play_tone(frequency, amplitude, duration, fs, stream):
    N = int(fs / frequency)
    T = int(frequency * duration)  # repeat for T cycles
    dt = 1.0 / fs
    # 1 cycle
    tone = (amplitude * math.sin(2 * math.pi * frequency * n * dt)
            for n in xrange(N))
    # todo: get the format from the stream; this assumes Float32
    data = ''.join(struct.pack('f', samp) for samp in tone)
    for n in xrange(T):
        stream.write(data) 
Example 43
Project: PyPadPlusPlus   Author: bitagoras   File: __init__.py    GNU General Public License v3.0 5 votes vote down vote up
def preCalculateMarkers(self):
        if self.specialMarkers is None:
            self.specialMarkers = {}
            fade = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
                255, 255, 255, 255, 255, 255, 255, 252, 246, 240, 234, 228, 223,
                217, 211, 205, 199, 193, 188, 182, 176, 170, 164, 159, 153, 147,
                141, 135, 130, 124, 118, 112, 106, 101, 95, 89, 83, 77, 71, 66,
                60, 54, 48, 42, 37, 31, 25]
            self.markerHeight = len(fade)

            # pre-calculate animated "active" marker
            animation = []
            for iCycle in range(10):
                n = len(fade)
                nh = n//2
                rgba = []
                rgba_r = []
                c1 = 110, 110, 110 # basic color
                c2 = 170, 175, 200 # second color
                for iFade,f in enumerate(fade):
                    x = min(0, -(iFade - nh))
                    a = sin(pi*(4*(x / float(n))**2 - iCycle / 10.))**2
                    rgb = ''.join([chr(int(c1[i]*(1-a)+c2[i]*a)) for i in 0,1,2]) + chr(f)
                    rgba.append(rgb*self.markerWidth)
                    x = -min(0, (iFade - nh))
                    a = sin(pi*(4*(x / float(n))**2 + iCycle / 10.))**2
                    rgb = ''.join([chr(int(c1[i]*(1-a)+c2[i]*a)) for i in 0,1,2])  + chr(fade[n-1-iFade])
                    rgba_r.append(rgb*self.markerWidth)
                rgb = tuple([(int(c1[i]*(1-a)+c2[i]*a)) for i in 0,1,2])
                rgba = ''.join(rgba)
                rgba_r = ''.join(rgba_r)
                animation.append((rgb, rgba, rgba_r)) 
Example 44
Project: streetview_objectmapping   Author: vlkryl   File: objectmapping.py    MIT License 5 votes vote down vote up
def LatLonToMeters( lat, lon ):
    "Converts given lat/lon in WGS84 Datum to XY in Spherical Mercator EPSG:4326"
    originShift = 2 * pi * 6378137 / 2.0
    mx = lon * originShift / 180.0
    my = log( tan((90 + lat) * pi / 360.0 )) / (pi / 180.0)
    my = my * originShift / 180.0
    return mx, my

# conversion from meters to (lat,lon) 
Example 45
Project: streetview_objectmapping   Author: vlkryl   File: objectmapping.py    MIT License 5 votes vote down vote up
def MetersToLatLon( mx, my ):
    "Converts XY point from Spherical Mercator EPSG:4326 to lat/lon in WGS84 Datum"
    originShift = 2 * pi * 6378137 / 2.0
    lon = (mx / originShift) * 180.0
    lat = (my / originShift) * 180.0
    lat = 180 / pi * (2 * atan(exp(lat * pi / 180.0)) - pi / 2.0)
    return lat, lon


# haversine distance formula between two points specified by their GPS coordinates 
Example 46
Project: spqrel_tools   Author: LCAS   File: moveto.py    MIT License 5 votes vote down vote up
def actionThread_exec(params):
    global memory_service

    t = threading.currentThread()
    memory_service = getattr(t, "mem_serv", None)

    print "Action " + actionName + " started with params " + str(params)

    # action init
    p = params.split('_')
    target = [float(p[0]), float(p[1]), float(p[2])/180.0*math.pi]
    print "  -- MoveTo: " + str(target)
    
    motion_service = getattr(t, "session", None).service("ALMotion")

    # action init
    # action init

    #print "Action "+actionName+" "+params+" exec..."
    # action exec
    #motion_service.setExternalCollisionProtectionEnabled('Move', False)
    #time.sleep(1)
    motion_service.moveTo(target[0], target[1], target[2])
    motion_service.waitUntilMoveIsFinished()
    #motion_service.setExternalCollisionProtectionEnabled('Move', True)
    # action exec
        
    # action end
    motion_service.stopMove()
    action_success(actionName,params) 
Example 47
Project: spqrel_tools   Author: LCAS   File: headpose.py    MIT License 5 votes vote down vote up
def actionThread_exec (params):
    t = threading.currentThread()
    memory_service = getattr(t, "mem_serv", None)
    motion_service = getattr(t, "session", None).service("ALMotion")
    print "Action "+actionName+" started with params "+params
    # action init

    stiff_head = 0.6
    print "   Stiffness -  Head ",stiff_head
        
    names = "Head"
    stiffnessLists = stiff_head
    timeLists = 1.0
    motion_service.stiffnessInterpolation(names, stiffnessLists, timeLists)

    v = params.split('_')
    yaw = 0
    pitch = 0
    try:
        if (len(v)==2):
            yaw = float(v[0])/180.0*math.pi
            pitch = float(v[1])/180.0*math.pi
    except:
        print "headpose: ERROR in values ",v[0]," ",v[1]," - (using 0,0)"
    headtime = 1.0

    moveHead(motion_service, yaw, pitch, headtime)

    count=1

    # action init
    while (getattr(t, "do_run", True) and count>0): 
        print "Action "+actionName+" "+params+" exec..."
        # action exec
        count = count - 1		
        # action exec
        time.sleep(0.5)
        
    # action end
    action_success(actionName,params) 
Example 48
Project: spqrel_tools   Author: LCAS   File: headpitch.py    MIT License 5 votes vote down vote up
def actionThread_exec (params):
    t = threading.currentThread()
    memory_service = getattr(t, "mem_serv", None)
    motion_service = getattr(t, "session", None).service("ALMotion")
    print "Action "+actionName+" started with params "+params
    # action init

    stiff_head = 0.6
    print "   Stiffness -  Head ",stiff_head
        
    names = "Head"
    stiffnessLists = stiff_head
    timeLists = 1.0
    motion_service.stiffnessInterpolation(names, stiffnessLists, timeLists)

    v = params.split('_')
    pitch = 0
    try:
        if (len(v)==1):
            pitch = float(v[0])/180.0*math.pi
    except:
        print "headpose: ERROR in values ",v[0],"  - (using 0)"
    headtime = 1.0

    moveHead(motion_service, pitch, headtime)

    count=1

    # action init
    while (getattr(t, "do_run", True) and count>0): 
        print "Action "+actionName+" "+params+" exec..."
        # action exec
        count = count - 1		
        # action exec
        time.sleep(0.5)
        
    # action end
    action_success(actionName,params) 
Example 49
Project: spqrel_tools   Author: LCAS   File: enter.py    MIT License 5 votes vote down vote up
def actionThread_exec (params):
    t = threading.currentThread()
    
    memory_service = getattr(t, "mem_serv", None)
    motion_service = getattr(t, "session", None).service("ALMotion")


    print "Action "+actionName+" started with params "+params
    
    # action init
    print "  -- Enter: "+params
    values = params.split('_')
    x = values[0]
    y = values[1]
    t = values[2]
    time_ = values[3]
    without_collision_avoidance = values[4].lower() == 'true'

    #print "x: ",x
    #print "y: ",y
    #print "t: ",t
    # action init
    count = 1
    
    while (getattr(t, "do_run", True) and count>0): 
        print "Action "+actionName+" "+params+" cm/s exec..."
        # action exec
        if without_collision_avoidance:
            motion_service.setExternalCollisionProtectionEnabled('Move', False)
	    time.sleep(1)
        motion_service.move(float(x)/100.0,float(y)/100.0,float(t) / 180 * math.pi)
        # action exec
        time.sleep(float(time_))
	print 'done'
        motion_service.setExternalCollisionProtectionEnabled('Move', True)
        count = 0		
        
    # action end
    motion_service.stopMove()
    action_success(actionName,params) 
Example 50
Project: core   Author: lifemapper   File: colorpalette.py    GNU General Public License v3.0 5 votes vote down vote up
def prettyscale(self):
    """
    Makes a palette of appealing colors (to me anyway) for a continuous gradient.
    The colors and intensities are intended to maximize percieved separation
    of values across the range.
    """
    import math
    self.pal = []
    a = 0
    rscl = [0.0, -1.0, math.pi/(self.n*0.8)]
    gscl = [0.3, 0.7, math.pi/(self.n*1.0)]
    bscl = [0.0, 1.0, math.pi/(self.n*1.5)]
    for i in range(0,self.n+1):
      r = rscl[0] + rscl[1] * math.cos(i*rscl[2])
      g = gscl[0] + gscl[1] * math.sin(i*gscl[2])
      b = bscl[0] + bscl[1] * math.cos(i*bscl[2])
      if r < 0: r = 0
      elif r > 1.0: r = 1.0
      if g < 0: g = 0
      elif g > 1.0: g = 1.0
      if b < 0: b = 0
      elif b > 1.0: b = 1.0
      if i == self.alpha:
        a = 0
      else:
        a = 255
      self.pal.append([int(r*255), int(g*255), int(b*255), a])