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 7 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_random.py    GNU Lesser General Public License v3.0 7 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 3
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 4
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 5
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 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]) 
Example 51
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: train_resnet.py    Apache License 2.0 5 votes vote down vote up
def __call__(self, num_update):
        if num_update <= self.max_update:
            self.base_lr = self.final_lr + (self.base_lr_orig - self.final_lr) * \
                (1 + cos(pi * (num_update - self.warmup_steps) / self.max_steps)) / 2
        return self.base_lr 
Example 52
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: lr_scheduler.py    Apache License 2.0 5 votes vote down vote up
def __call__(self, num_update):
        if num_update < self.warmup_steps:
            return self.get_warmup_lr(num_update)
        if num_update <= self.max_update:
            self.base_lr = self.final_lr + (self.base_lr_orig - self.final_lr) * \
                (1 + cos(pi * (num_update - self.warmup_steps) / self.max_steps)) / 2
        return self.base_lr 
Example 53
Project: helloworld   Author: pip-uninstaller-python   File: polygon .py    GNU General Public License v2.0 5 votes vote down vote up
def circle(func, r):
    n = 100
    polygon(func, n, 2 * math.pi * r / n)


# circle(turtle.Turtle(),100)

# 不完整圆1 
Example 54
Project: helloworld   Author: pip-uninstaller-python   File: polygon .py    GNU General Public License v2.0 5 votes vote down vote up
def arc1(func, r, angle):
    arc_len = 2 * math.pi * r * angle / 360
    n = 100
    cir_len = arc_len / n
    cir_angle = angle / n
    for i in range(n):
        func.fd(cir_len)
        func.lt(cir_angle)


# arc1(turtle.Turtle(), 100, 90)


# 不完整圆2 
Example 55
Project: helloworld   Author: pip-uninstaller-python   File: polygon .py    GNU General Public License v2.0 5 votes vote down vote up
def arc2(func, r, angle):
    arc_len = 2 * math.pi * r * angle / 360
    n = 100
    polygon(func, n, arc_len / n, angle) 
Example 56
Project: helloworld   Author: pip-uninstaller-python   File: test.py    GNU General Public License v2.0 5 votes vote down vote up
def area(r):
    return 2 * math.pi * r 
Example 57
Project: FCOS_GluonCV   Author: DetectionTeamUCAS   File: test_lr_scheduler.py    Apache License 2.0 5 votes vote down vote up
def test_composed_method():
    N = 1000
    constant = LRScheduler('constant', base_lr=0, target_lr=1, niters=N)
    linear = LRScheduler('linear', base_lr=1, target_lr=2, niters=N)
    cosine = LRScheduler('cosine', base_lr=3, target_lr=1, niters=N)
    poly = LRScheduler('poly', base_lr=1, target_lr=0, niters=N, power=2)
    # components with niters=0 will be ignored
    null_cosine = LRScheduler('cosine', base_lr=3, target_lr=1, niters=0)
    null_poly = LRScheduler('cosine', base_lr=3, target_lr=1, niters=0)
    step = LRScheduler('step', base_lr=1, target_lr=0, niters=N,
                       step_iter=[100, 500], step_factor=0.1)
    arr = LRSequential([constant, null_cosine, linear, cosine, null_poly, poly, step])
    # constant
    for i in range(N):
        compare(arr, i, 0)
    # linear
    for i in range(N, 2*N):
        expect_linear = 2 + (1 - 2) * (1 - (i - N) / (N - 1))
        compare(arr, i, expect_linear)
    # cosine
    for i in range(2*N, 3*N):
        expect_cosine = 1 + (3 - 1) * ((1 + cos(pi * (i - 2*N) / (N - 1))) / 2)
        compare(arr, i, expect_cosine)
    # poly
    for i in range(3*N, 4*N):
        expect_poly = 0 + (1 - 0) * (pow(1 - (i - 3*N) / (N - 1), 2))
        compare(arr, i, expect_poly)
    for i in range(4*N, 5*N):
        if i - 4*N < 100:
            expect_step = 1
        elif i - 4*N < 500:
            expect_step = 0.1
        else:
            expect_step = 0.01
        compare(arr, i, expect_step)
    # out-of-bound index
    compare(arr, 10*N, 0.01)
    compare(arr, -1, 0) 
Example 58
Project: FCOS_GluonCV   Author: DetectionTeamUCAS   File: lr_scheduler.py    Apache License 2.0 5 votes vote down vote up
def update(self, num_update):
        N = self.niters - 1
        T = num_update - self.offset
        T = min(max(0, T), N)

        if self.mode == 'constant':
            factor = 0
        elif self.mode == 'linear':
            factor = 1 - T / N
        elif self.mode == 'poly':
            factor = pow(1 - T / N, self.power)
        elif self.mode == 'cosine':
            factor = (1 + cos(pi * T / N)) / 2
        elif self.mode == 'step':
            if self.step is not None:
                count = sum([1 for s in self.step if s <= T])
                factor = pow(self.step_factor, count)
            else:
                factor = 1
        else:
            raise NotImplementedError

        if self.mode == 'step':
            self.learning_rate = self.base_lr * factor
        else:
            self.learning_rate = self.target_lr + (self.base_lr - self.target_lr) * factor 
Example 59
Project: soccer-matlab   Author: utra-robosoccer   File: minitaur_randomize_terrain_gym_env.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _reset(self):
    self._pybullet_client.resetSimulation()
    self._pybullet_client.setPhysicsEngineParameter(
        numSolverIterations=self._num_bullet_solver_iterations)
    self._pybullet_client.setTimeStep(self._time_step)
    terrain_visual_shape_id = -1
    terrain_mass = 0
    terrain_position = [0, 0, 0]
    terrain_orientation = [0, 0, 0, 1]
    terrain_file_name = self.load_random_terrain(FLAGS.terrain_dir)
    terrain_collision_shape_id = self._pybullet_client.createCollisionShape(
        shapeType=self._pybullet_client.GEOM_MESH,
        fileName=terrain_file_name,
        flags=1,
        meshScale=[0.5, 0.5, 0.5])
    self._pybullet_client.createMultiBody(terrain_mass,
                                          terrain_collision_shape_id,
                                          terrain_visual_shape_id,
                                          terrain_position,
                                          terrain_orientation)
    self._pybullet_client.setGravity(0, 0, -10)
    self.minitaur = (minitaur.Minitaur(
        pybullet_client=self._pybullet_client,
        urdf_root=self._urdf_root,
        time_step=self._time_step,
        self_collision_enabled=self._self_collision_enabled,
        motor_velocity_limit=self._motor_velocity_limit,
        pd_control_enabled=self._pd_control_enabled,
        on_rack=self._on_rack))
    self._last_base_position = [0, 0, 0]
    for _ in xrange(100):
      if self._pd_control_enabled:
        self.minitaur.ApplyAction([math.pi / 2] * 8)
      self._pybullet_client.stepSimulation()
    return self._get_observation() 
Example 60
Project: soccer-matlab   Author: utra-robosoccer   File: minitaur.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def GetTrueMotorAngles(self):
    """Gets the eight motor angles at the current moment, mapped to [-pi, pi].

    Returns:
      Motor angles, mapped to [-pi, pi].
    """
    motor_angles = [
        self._pybullet_client.getJointState(self.quadruped, motor_id)[0]
        for motor_id in self._motor_id_list
    ]
    motor_angles = np.multiply(motor_angles, self._motor_direction)
    return motor_angles 
Example 61
Project: soccer-matlab   Author: utra-robosoccer   File: minitaur.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def GetMotorAngles(self):
    """Gets the eight motor angles.

    This function mimicks the noisy sensor reading and adds latency. The motor
    angles that are delayed, noise polluted, and mapped to [-pi, pi].

    Returns:
      Motor angles polluted by noise and latency, mapped to [-pi, pi].
    """
    motor_angles = self._AddSensorNoise(
        np.array(self._control_observation[0:self.num_motors]),
        self._observation_noise_stdev[0])
    return MapToMinusPiToPi(motor_angles) 
Example 62
Project: soccer-matlab   Author: utra-robosoccer   File: minitaur_randomize_terrain_gym_env_example.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def SinePolicyExample():
  """An example of minitaur walking with a sine gait."""
  env = minitaur_randomize_terrain_gym_env.MinitaurRandomizeTerrainGymEnv(
      render=True,
      motor_velocity_limit=np.inf,
      pd_control_enabled=True,
      on_rack=False)
  sum_reward = 0
  steps = 200
  amplitude_1_bound = 0.5
  amplitude_2_bound = 0.5
  speed = 40

  for step_counter in xrange(steps):
    time_step = 0.01
    t = step_counter * time_step

    amplitude1 = amplitude_1_bound
    amplitude2 = amplitude_2_bound
    steering_amplitude = 0
    if t < 10:
      steering_amplitude = 0.5
    elif t < 20:
      steering_amplitude = -0.5
    else:
      steering_amplitude = 0

    # Applying asymmetrical sine gaits to different legs can steer the minitaur.
    a1 = math.sin(t * speed) * (amplitude1 + steering_amplitude)
    a2 = math.sin(t * speed + math.pi) * (amplitude1 - steering_amplitude)
    a3 = math.sin(t * speed) * amplitude2
    a4 = math.sin(t * speed + math.pi) * amplitude2
    action = [a1, a2, a2, a1, a3, a4, a4, a3]
    _, reward, _, _ = env.step(action)
    sum_reward += reward 
Example 63
Project: soccer-matlab   Author: utra-robosoccer   File: minitaur_stand_gym_env_example.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def StandUpExample():
  """An example that the minitaur stands up."""
  steps = 1000
  environment = minitaur_stand_gym_env.MinitaurStandGymEnv(
      render=True,
      motor_velocity_limit=np.inf)
  action = [0.5]
  _, _, done, _ = environment.step(action)
  for t in range(steps):
    # A policy that oscillates between -1 and 1
    action = [math.sin(t * math.pi * 0.01)]
    _, _, done, _ = environment.step(action)
    if done:
      break 
Example 64
Project: soccer-matlab   Author: utra-robosoccer   File: minitaur_ball_gym_env.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def __init__(self,
               urdf_root=pybullet_data.getDataPath(),
               self_collision_enabled=True,
               pd_control_enabled=False,
               leg_model_enabled=True,
               on_rack=False,
               render=False):
    """Initialize the minitaur and ball gym environment.

    Args:
      urdf_root: The path to the urdf data folder.
      self_collision_enabled: Whether to enable self collision in the sim.
      pd_control_enabled: Whether to use PD controller for each motor.
      leg_model_enabled: Whether to use a leg motor to reparameterize the action
        space.
      on_rack: Whether to place the minitaur on rack. This is only used to debug
        the walking gait. In this mode, the minitaur's base is hanged midair so
        that its walking gait is clearer to visualize.
      render: Whether to render the simulation.
    """
    super(MinitaurBallGymEnv, self).__init__(
        urdf_root=urdf_root,
        self_collision_enabled=self_collision_enabled,
        pd_control_enabled=pd_control_enabled,
        leg_model_enabled=leg_model_enabled,
        on_rack=on_rack,
        render=render)
    self._cam_dist = 2.0
    self._cam_yaw = -70
    self._cam_pitch = -30
    self.action_space = spaces.Box(np.array([-1]), np.array([1]))
    self.observation_space = spaces.Box(np.array([-math.pi, 0]),
                                        np.array([math.pi, 100])) 
Example 65
Project: soccer-matlab   Author: utra-robosoccer   File: minitaur_ball_gym_env.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _apply_steering_to_locomotion(self, action):
    # A hardcoded feedforward walking controller based on sine functions.
    amplitude_swing = 0.5
    amplitude_extension = 0.5
    speed = 200
    steering_amplitude = 0.5 * action[0]
    t = self.minitaur.GetTimeSinceReset()
    a1 = math.sin(t * speed) * (amplitude_swing + steering_amplitude)
    a2 = math.sin(t * speed + math.pi) * (amplitude_swing - steering_amplitude)
    a3 = math.sin(t * speed) * amplitude_extension
    a4 = math.sin(t * speed + math.pi) * amplitude_extension
    action = [a1, a2, a2, a1, a3, a4, a4, a3]
    return action 
Example 66
Project: soccer-matlab   Author: utra-robosoccer   File: minitaur_stand_gym_env.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _transform_action_to_motor_command(self, action):
    """Method to transform the one dimensional action to rotate bottom two legs.

    Args:
      action: A double between -1 and 1, where 0 means keep the legs parallel
        to the body.
    Returns:
      actions: The angles for all motors.
    Raises:
      ValueError: The action dimension is not the same as the number of motors.
      ValueError: The magnitude of actions is out of bounds.
    """
    action = action[0]
    # Scale the action from [-1 to 1] to [-range to +range] (angle in radians).
    action *= RANGE_OF_LEG_MOTION
    action_all_legs = [
        math.pi,  # Upper leg pointing up.
        0,
        0,  # Bottom leg pointing down.
        math.pi,
        0,  # Upper leg pointing up.
        math.pi,
        math.pi,  # Bottom leg pointing down.
        0
    ]
    action_all_legs = [angle - 0.7 for angle in action_all_legs]

    # Use the one dimensional action to rotate both bottom legs.
    action_delta = [0, 0, -action, action, 0, 0, action, -action]
    action_all_legs = map(add, action_all_legs, action_delta)
    return action_all_legs 
Example 67
Project: soccer-matlab   Author: utra-robosoccer   File: minitaur_alternating_legs_env.py    BSD 2-Clause "Simplified" License 5 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())
    upper_bound[0:2] = 2 * math.pi  # Roll, pitch, yaw of the base.
    upper_bound[2:4] = 2 * math.pi / self._time_step  # Roll, pitch, yaw rate.
    return upper_bound 
Example 68
Project: soccer-matlab   Author: utra-robosoccer   File: minitaur_four_leg_stand_env.py    BSD 2-Clause "Simplified" License 5 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 = [2 * math.pi] * 2  # Roll, pitch the base.
    if self._use_angular_velocity_in_observation:
      upper_bound.extend([2 * math.pi / self._time_step] * 2)
    if self._use_motor_angle_in_observation:
      upper_bound.extend([2 * math.pi] * 8)
    return np.array(upper_bound) 
Example 69
Project: pepper-robot-programming   Author: maverickjoy   File: robot_velocity_caliberation.py    MIT License 4 votes vote down vote up
def main(session):
    navigation_service = session.service("ALNavigation")
    motion_service = session.service("ALMotion")
    posture_service = session.service("ALRobotPosture")

    # Wake up robot
    motion_service.wakeUp()
    posture_service.goToPosture("StandInit", 0.1)
    motion_service.moveInit()

    listOfTime = []
    print "Starting Calculation : "
    noOfIterations = 3


    for i in xrange(noOfIterations * 2):
        units = 0
        units = moveForward(motion_service)

        if units == -1:
            print "OBSTACLE In between Caliberation INCOMPLETE EXITING"
            exit()

        listOfTime.append(units)
        time.sleep(2)
        res = _turnTheta(motion_service,math.pi)

        if not res :
            print "OBSTACLE In between Caliberation INCOMPLETE EXITING"
            exit()

        time.sleep(2)

    avgUnits = 0

    for unitTime in listOfTime :
        print "Unit Time : ",unitTime
        avgUnits += unitTime

    avgUnits /= (noOfIterations * 2)

    print "Caliberation Succesfull Time Units : ",avgUnits

    return 
Example 70
Project: pyblish-win   Author: pyblish   File: random.py    GNU Lesser General Public License v3.0 4 votes vote down vote up
def vonmisesvariate(self, mu, kappa):
        """Circular data distribution.

        mu is the mean angle, expressed in radians between 0 and 2*pi, and
        kappa is the concentration parameter, which must be greater than or
        equal to zero.  If kappa is equal to zero, this distribution reduces
        to a uniform random angle over the range 0 to 2*pi.

        """
        # mu:    mean angle (in radians between 0 and 2*pi)
        # kappa: concentration parameter kappa (>= 0)
        # if kappa = 0 generate uniform random angle

        # Based upon an algorithm published in: Fisher, N.I.,
        # "Statistical Analysis of Circular Data", Cambridge
        # University Press, 1993.

        # Thanks to Magnus Kessler for a correction to the
        # implementation of step 4.

        random = self.random
        if kappa <= 1e-6:
            return TWOPI * random()

        s = 0.5 / kappa
        r = s + _sqrt(1.0 + s * s)

        while 1:
            u1 = random()
            z = _cos(_pi * u1)

            d = z / (r + z)
            u2 = random()
            if u2 < 1.0 - d * d or u2 <= (1.0 - d) * _exp(d):
                break

        q = 1.0 / r
        f = (q + z) / (1.0 + q * z)
        u3 = random()
        if u3 > 0.5:
            theta = (mu + _acos(f)) % TWOPI
        else:
            theta = (mu - _acos(f)) % TWOPI

        return theta

## -------------------- gamma distribution -------------------- 
Example 71
Project: pyblish-win   Author: pyblish   File: test_math.py    GNU Lesser General Public License v3.0 4 votes vote down vote up
def testAtan2(self):
        self.assertRaises(TypeError, math.atan2)
        self.ftest('atan2(-1, 0)', math.atan2(-1, 0), -math.pi/2)
        self.ftest('atan2(-1, 1)', math.atan2(-1, 1), -math.pi/4)
        self.ftest('atan2(0, 1)', math.atan2(0, 1), 0)
        self.ftest('atan2(1, 1)', math.atan2(1, 1), math.pi/4)
        self.ftest('atan2(1, 0)', math.atan2(1, 0), math.pi/2)

        # math.atan2(0, x)
        self.ftest('atan2(0., -inf)', math.atan2(0., NINF), math.pi)
        self.ftest('atan2(0., -2.3)', math.atan2(0., -2.3), math.pi)
        self.ftest('atan2(0., -0.)', math.atan2(0., -0.), math.pi)
        self.assertEqual(math.atan2(0., 0.), 0.)
        self.assertEqual(math.atan2(0., 2.3), 0.)
        self.assertEqual(math.atan2(0., INF), 0.)
        self.assertTrue(math.isnan(math.atan2(0., NAN)))
        # math.atan2(-0, x)
        self.ftest('atan2(-0., -inf)', math.atan2(-0., NINF), -math.pi)
        self.ftest('atan2(-0., -2.3)', math.atan2(-0., -2.3), -math.pi)
        self.ftest('atan2(-0., -0.)', math.atan2(-0., -0.), -math.pi)
        self.assertEqual(math.atan2(-0., 0.), -0.)
        self.assertEqual(math.atan2(-0., 2.3), -0.)
        self.assertEqual(math.atan2(-0., INF), -0.)
        self.assertTrue(math.isnan(math.atan2(-0., NAN)))
        # math.atan2(INF, x)
        self.ftest('atan2(inf, -inf)', math.atan2(INF, NINF), math.pi*3/4)
        self.ftest('atan2(inf, -2.3)', math.atan2(INF, -2.3), math.pi/2)
        self.ftest('atan2(inf, -0.)', math.atan2(INF, -0.0), math.pi/2)
        self.ftest('atan2(inf, 0.)', math.atan2(INF, 0.0), math.pi/2)
        self.ftest('atan2(inf, 2.3)', math.atan2(INF, 2.3), math.pi/2)
        self.ftest('atan2(inf, inf)', math.atan2(INF, INF), math.pi/4)
        self.assertTrue(math.isnan(math.atan2(INF, NAN)))
        # math.atan2(NINF, x)
        self.ftest('atan2(-inf, -inf)', math.atan2(NINF, NINF), -math.pi*3/4)
        self.ftest('atan2(-inf, -2.3)', math.atan2(NINF, -2.3), -math.pi/2)
        self.ftest('atan2(-inf, -0.)', math.atan2(NINF, -0.0), -math.pi/2)
        self.ftest('atan2(-inf, 0.)', math.atan2(NINF, 0.0), -math.pi/2)
        self.ftest('atan2(-inf, 2.3)', math.atan2(NINF, 2.3), -math.pi/2)
        self.ftest('atan2(-inf, inf)', math.atan2(NINF, INF), -math.pi/4)
        self.assertTrue(math.isnan(math.atan2(NINF, NAN)))
        # math.atan2(+finite, x)
        self.ftest('atan2(2.3, -inf)', math.atan2(2.3, NINF), math.pi)
        self.ftest('atan2(2.3, -0.)', math.atan2(2.3, -0.), math.pi/2)
        self.ftest('atan2(2.3, 0.)', math.atan2(2.3, 0.), math.pi/2)
        self.assertEqual(math.atan2(2.3, INF), 0.)
        self.assertTrue(math.isnan(math.atan2(2.3, NAN)))
        # math.atan2(-finite, x)
        self.ftest('atan2(-2.3, -inf)', math.atan2(-2.3, NINF), -math.pi)
        self.ftest('atan2(-2.3, -0.)', math.atan2(-2.3, -0.), -math.pi/2)
        self.ftest('atan2(-2.3, 0.)', math.atan2(-2.3, 0.), -math.pi/2)
        self.assertEqual(math.atan2(-2.3, INF), -0.)
        self.assertTrue(math.isnan(math.atan2(-2.3, NAN)))
        # math.atan2(NAN, x)
        self.assertTrue(math.isnan(math.atan2(NAN, NINF)))
        self.assertTrue(math.isnan(math.atan2(NAN, -2.3)))
        self.assertTrue(math.isnan(math.atan2(NAN, -0.)))
        self.assertTrue(math.isnan(math.atan2(NAN, 0.)))
        self.assertTrue(math.isnan(math.atan2(NAN, 2.3)))
        self.assertTrue(math.isnan(math.atan2(NAN, INF)))
        self.assertTrue(math.isnan(math.atan2(NAN, NAN))) 
Example 72
Project: building-boundary   Author: Geodan   File: bounding_box.py    MIT License 4 votes vote down vote up
def rotating_calipers_bbox(points, angles):
    """
    Compute the oriented minimum bounding box using a rotating calipers
    algorithm.

    Parameters
    ----------
    points : (Mx2) array
        The coordinates of the points of the convex hull.
    angles : (Mx1) array-like
        The angles the edges of the convex hull and the x-axis.

    Returns
    -------
    corner_points : (4x2) array
        The coordinates of the corner points of the minimum oriented
        bounding box.
    """
    min_bbox = {'angle': 0,
                'minmax': (0, 0, 0, 0),
                'area': float('inf')}

    for a in angles:
        # Rotate the points and compute the new bounding box
        rotated_points = rotate_points(points, a)
        min_x = min(rotated_points[:, 0])
        max_x = max(rotated_points[:, 0])
        min_y = min(rotated_points[:, 1])
        max_y = max(rotated_points[:, 1])
        area = (max_x - min_x) * (max_y - min_y)

        # Save if the new bounding box is smaller than the current smallest
        if area < min_bbox['area']:
            min_bbox = {'angle': a,
                        'minmax': (min_x, max_x, min_y, max_y),
                        'area': area}

    # Extract the rotated corner points of the minimum bounding box
    c1 = (min_bbox['minmax'][0], min_bbox['minmax'][2])
    c2 = (min_bbox['minmax'][0], min_bbox['minmax'][3])
    c3 = (min_bbox['minmax'][1], min_bbox['minmax'][3])
    c4 = (min_bbox['minmax'][1], min_bbox['minmax'][2])
    rotated_corner_points = [c1, c2, c3, c4]

    # Rotate the corner points back to the original system
    corner_points = np.array(rotate_points(rotated_corner_points,
                                           2*math.pi-min_bbox['angle']))

    return corner_points 
Example 73
Project: building-boundary   Author: Geodan   File: segment.py    MIT License 4 votes vote down vote up
def regularize(self, orientation, max_error=None):
        """
        Recreates the line segment based on the given orientation.

        Parameters
        ----------
        orientation : float or int
            The orientation the line segment should have. In radians from
            0 to pi (east to west counterclockwise) and
            0 to -pi (east to west clockwise).
        max_error : float or int
            The maximum error (max distance points to line) the
            fitted line is allowed to have. A ThresholdError will be
            raised if this max error is exceeded.

        Raises
        ------
        ThresholdError
            If the error of the fitted line (max distance points to
            line) exceeds the given max error.

        .. [1] https://math.stackexchange.com/questions/1377716/how-to-find-a-least-squares-line-with-a-known-slope  # noqa
        """
        prev_a = self.a
        prev_b = self.b
        prev_c = self.c

        if not np.isclose(orientation, self.orientation):
            if np.isclose(abs(orientation), math.pi / 2):
                self.a = 1
                self.b = 0
                self.c = np.mean(self.points[:, 0])
            elif (np.isclose(abs(orientation), math.pi) or
                    np.isclose(orientation, 0)):
                self.a = 0
                self.b = 1
                self.c = np.mean(self.points[:, 1])
            else:
                self.a = math.tan(orientation)
                self.b = -1
                self.c = (sum(self.points[:, 1] - self.a * self.points[:, 0]) /
                          len(self.points))

            if max_error is not None:
                error = self.error()
                if error > max_error:
                    self.a = prev_a
                    self.b = prev_b
                    self.c = prev_c
                    raise utils.error.ThresholdError(
                        "Could not fit a proper line. Error: {}".format(error)
                    )

            self._create_line_segment() 
Example 74
Project: spqrel_tools   Author: LCAS   File: sounddetected.py    MIT License 4 votes vote down vote up
def rhMonitorThread (memory_service,motion_service):

    t = threading.currentThread()
    print "sound detected thread started"

    prev_time = 0
    while getattr(t, "do_run", True):
        v = 'false'
        #print "testing sound"
        
        sound_value = memory_service.getData("ALSoundLocalization/SoundLocated")
        #print sound_value
        #print "\n"
        #print "[ SOUND ]"
        #print "    time(s):", sound_value[0][0]
        #print "    confidence: ", sound_value[1][2]
        #print "    energy: ", sound_value[1][3]

        #print "[Head Position[6D]] in FRAME_TORSO", sound_value[2]
        #print "[Head Position[6D]] in FRAME_ROBOT", sound_value[3]
        #head_pose6d = almath.Position6D(sound_value[3][0],sound_value[3][1],sound_value[3][2],
        #                                sound_value[3][3],sound_value[3][4],sound_value[3][5])
        #print head_pose6d
        #head_transform = almath.transformFromPosition6D(head_pose6d)
        #print "[Head Transform] in FRAME_ROBOT"
        #print head_transform
        #print "\n"

        if sound_value != None and len(sound_value)>1 and prev_time != sound_value[0][0]:
            prev_time = sound_value[0][0]
            #print "confidence: ", sound_value[1][2]
            confidence = sound_value[1][2]
            if (confidence > 0.35):
                v = 'true'
                sound_azimuth = sound_value[1][0]
                head_yaw = sound_value[3][5]
                turn_angle = sound_azimuth + head_yaw
                turn_angle = int(turn_angle / math.pi * 180)
                memory_service.insertData('AngleSound', str(turn_angle) + "_REL")
               # print "\n"
                print "[SoundDetected] time: ", sound_value[0][0], "azimuth(rad): ", sound_azimuth
               # print "\n"

        set_condition(memory_service,'sounddetected',v)
        if v:
            time.sleep(2) #if true we give time to process the condition

        time.sleep(0.25)

    print "sounddetected thread quit" 
Example 75
Project: spqrel_tools   Author: LCAS   File: updateheadpose.py    MIT License 4 votes vote down vote up
def actionThread_exec (params):
    global motion_service
    global memory_service

    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)

    headtime = 1.0

    count=1

    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)"
    
    moveHead(motion_service, yaw, pitch, headtime)


    # 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)
        
        yawNew =  memory_service.getData('Action/UpdateHeadPose/HeadYaw/Value')
        pitchNew = memory_service.getData('Action/UpdateHeadPose/HeadPitch/Value')

        yawNew = float(yawNew)/180.0*math.pi
        pitchNew = float(pitchNew)/180.0*math.pi

        if (yawNew != yaw) or (pitchNew != pitch):
            yaw = yawNew
            pitch= pitchNew
            moveHead(motion_service, yaw, pitch, headtime)

        
    # action end
    action_success(actionName,params) 
Example 76
Project: spqrel_tools   Author: LCAS   File: turn.py    MIT License 4 votes vote down vote up
def actionThread_exec (params):
    global goal_reached

    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

    val = params
    if (params[0]=='^'):
        print params[1:]
        val = memory_service.getData(params[1:])

    mod = "REL"
    #target_angle = 0
    if '_' not in val:
        val = val + '_' + mod
    v = val.split('_')

    target_angle = int(v[0])
    if (len(v)==2):
        mod = v[1]

    if (mod=='ABS'):
        try:
            [Rx,Ry,Rth_rad] = memory_service.getData('NAOqiLocalizer/RobotPose')
            theta = (target_angle/180.0*math.pi) - Rth_rad

            print "Robot theta: ", Rth_rad/math.pi*180, "Target theta: ", target_angle, "Diff: ", theta/math.pi*180
        except:
            print 'ERROR Turn ABS: cannot read robot pose'
            target_angle = 0
            theta = 0
    else:
        theta = target_angle/180.0*math.pi

    #Turn 90deg to the left
    x = 0.01
    y = 0.01
    
    print "Turn to ", target_angle
    motion_service.setExternalCollisionProtectionEnabled('Move', False)
    time.sleep(1)
    motion_service.moveTo(x, y, theta) #blocking function
    motion_service.waitUntilMoveIsFinished()
    motion_service.setExternalCollisionProtectionEnabled('Move', True)

    print "MOVEMENT FINISH"

    # action end
    motion_service.stopMove()
    action_success(actionName,params) 
Example 77
Project: Perspective   Author: TypesettingTools   File: perspective.py    MIT License 4 votes vote down vote up
def unrot(coord_in, org, diag=True, get_rot=False):
    screen_z = 312.5
    shift = org.mul(-1)
    coord = [c.add(shift) for c in coord_in]
    center = intersect(coord[0::2], coord[1::2])
    center = Point(center.x, center.y, screen_z)
    rays = [Point(c.x, c.y, screen_z) for c in coord]
    f = []
    for i in range(2):
        vp1 = vec_pr(rays[0+i], center).length()
        vp2 = vec_pr(rays[2+i], center).length()
        a = rays[0+i]
        c = rays[2+i].mul(vp1/vp2)
        m = a.add(c).mul(0.5)
        r = center.z/m.z;
        a = a.mul(r)
        c = c.mul(r)
        f.append((a, c))
    (a, c), (b, d) = f[0], f[1]
    ratio = abs(dist(a, b)/dist(a, d))
    diag_diff = ((dist(a, c)-dist(b, d)))/(dist(a, c)+dist(b, d))
    n = vec_pr(vector(a, b), vector(a, c))
    n0 = vec_pr(vector(rays[0], rays[1]), vector(rays[0], rays[2]))
    flip = 1 if sc_pr(n, n0)>0 else -1
    if not get_rot:
        return diag_diff if diag else ratio#*flip
    if flip<0:
        return None
    fry = math.atan(n.x/n.z)
    s = ""
    s+= "\\fry%.2f" % (-fry/math.pi*180)
    rot_n = n.rot_y(fry)
    frx = -math.atan(rot_n.y/rot_n.z)
    if n0.z < 0:
        frx += math.pi
    s+= "\\frx%.2f" % (-frx/math.pi*180)
    n = vector(a, b)
    ab_unrot = vector(a, b).rot_y(fry).rot_x(frx)
    ac_unrot = vector(a, c).rot_y(fry).rot_x(frx)
    ad_unrot = vector(a, d).rot_y(fry).rot_x(frx)
    frz = math.atan2(ab_unrot.y, ab_unrot.x)
    s += "\\frz%.2f" % (-frz/math.pi*180)
    ad_unrot = ad_unrot.rot_z(frz)
    fax = ad_unrot.x/ad_unrot.y
    if abs(fax)>0.01:
        s += "\\fax%.2f" % (fax)
    return s 
Example 78
Project: FCOS_GluonCV   Author: DetectionTeamUCAS   File: test_lr_scheduler.py    Apache License 2.0 4 votes vote down vote up
def test_single_method():
    N = 1000
    constant = LRScheduler('constant', base_lr=0, target_lr=1, niters=N)
    linear = LRScheduler('linear', base_lr=1, target_lr=2, niters=N)
    cosine = LRScheduler('cosine', base_lr=3, target_lr=1, niters=N)
    poly = LRScheduler('poly', base_lr=1, target_lr=0, niters=N, power=2)
    step = LRScheduler('step', base_lr=1, target_lr=0, niters=N,
                       step_iter=[100, 500], step_factor=0.1)
    step2 = LRScheduler('step', base_lr=1, target_lr=0,
                        nepochs=2, iters_per_epoch=N/2,
                        step_iter=[100, 500], step_factor=0.1)
    step3 = LRScheduler('step', base_lr=1, target_lr=0,
                        nepochs=100, iters_per_epoch=N/100,
                        step_epoch=[10, 50], step_factor=0.1)

    # Test numerical value
    for i in range(N):
        compare(constant, i, 0)

        expect_linear = 2 + (1 - 2) * (1 - i / (N - 1))
        compare(linear, i, expect_linear)

        expect_cosine = 1 + (3 - 1) * ((1 + cos(pi * i / (N-1))) / 2)
        compare(cosine, i, expect_cosine)

        expect_poly = 0 + (1 - 0) * (pow(1 - i / (N-1), 2))
        compare(poly, i, expect_poly)

        if i < 100:
            expect_step = 1
        elif i < 500:
            expect_step = 0.1
        else:
            expect_step = 0.01
        compare(step, i, expect_step)
        compare(step2, i, expect_step)
        compare(step3, i, expect_step)

    # Test out-of-range updates
    for i in range(10):
        constant.update(i - 3)
        linear.update(i - 3)
        cosine.update(i - 3)
        poly.update(i - 3) 
Example 79
Project: soccer-matlab   Author: utra-robosoccer   File: minitaur_gym_env_example.py    BSD 2-Clause "Simplified" License 4 votes vote down vote up
def SineStandExample(log_path=None):
  """An example of minitaur standing and squatting on the floor.

  To validate the accurate motor model we command the robot and sit and stand up
  periodically in both simulation and experiment. We compare the measured motor
  trajectories, torques and gains. The results are at:
    https://colab.corp.google.com/v2/notebook#fileId=0BxTIAnWh1hb_ZnkyYWtNQ1RYdkU&scrollTo=ZGFMl84kKqRx

  Args:
    log_path: The directory that the log files are written to. If log_path is
      None, no logs will be written.
  """
  environment = minitaur_gym_env.MinitaurGymEnv(
      urdf_version=minitaur_gym_env.RAINBOW_DASH_V0_URDF_VERSION,
      render=True,
      leg_model_enabled=False,
      motor_velocity_limit=np.inf,
      motor_overheat_protection=True,
      accurate_motor_model_enabled=True,
      motor_kp=1.20,
      motor_kd=0.02,
      on_rack=False,
      log_path=log_path)
  steps = 1000
  amplitude = 0.5
  speed = 3

  actions_and_observations = []

  for step_counter in range(steps):
    # Matches the internal timestep.
    time_step = 0.01
    t = step_counter * time_step
    current_row = [t]

    action = [math.sin(speed * t) * amplitude + math.pi / 2] * 8
    current_row.extend(action)

    observation, _, _, _ = environment.step(action)
    current_row.extend(observation.tolist())
    actions_and_observations.append(current_row)
    time.sleep(1./100.)

  if FLAGS.output_filename is not None:
    WriteToCSV(FLAGS.output_filename, actions_and_observations) 
Example 80
Project: soccer-matlab   Author: utra-robosoccer   File: minitaur_gym_env_example.py    BSD 2-Clause "Simplified" License 4 votes vote down vote up
def SinePolicyExample(log_path=None):
  """An example of minitaur walking with a sine gait.

  Args:
    log_path: The directory that the log files are written to. If log_path is
      None, no logs will be written.
  """
  environment = minitaur_gym_env.MinitaurGymEnv(
      urdf_version=minitaur_gym_env.DERPY_V0_URDF_VERSION,
      render=True,
      motor_velocity_limit=np.inf,
      pd_control_enabled=True,
      hard_reset=False,
      on_rack=False,
      log_path=log_path)
  sum_reward = 0
  steps = 20000
  amplitude_1_bound = 0.5
  amplitude_2_bound = 0.5
  speed = 40

  for step_counter in range(steps):
    time_step = 0.01
    t = step_counter * time_step

    amplitude1 = amplitude_1_bound
    amplitude2 = amplitude_2_bound
    steering_amplitude = 0
    if t < 10:
      steering_amplitude = 0.5
    elif t < 20:
      steering_amplitude = -0.5
    else:
      steering_amplitude = 0

    # Applying asymmetrical sine gaits to different legs can steer the minitaur.
    a1 = math.sin(t * speed) * (amplitude1 + steering_amplitude)
    a2 = math.sin(t * speed + math.pi) * (amplitude1 - steering_amplitude)
    a3 = math.sin(t * speed) * amplitude2
    a4 = math.sin(t * speed + math.pi) * amplitude2
    action = [a1, a2, a2, a1, a3, a4, a4, a3]
    _, reward, done, _ = environment.step(action)
    time.sleep(1./100.)

    sum_reward += reward
    if done:
      tf.logging.info("Return is {}".format(sum_reward))
      environment.reset()