
    nif                        S r SSKrSSKr\R                  R	                  \R                  R                  \R                  " \R                  " 5       5      5      5      r\R                  R	                  \R                  R	                  \5      5      r	\R                  R                  R                  S\	5        SSKrSSKrSSKrSSKrSSKrSSKJr  / SQr/ SQr/ SQr/ SQr/ SQrS	rS
r/ SQr/ SQr\R:                  " S5      r\R:                  " S5      r\R:                  " S5      r Sr!S\RD                  -  r#S r$ " S S\%5      r&g)zHThis file implements the functionalities of a minitaur using pybullet.

    N)motor)r   r   皙?)r   r      )r   r   r   r   )r   g{Gzt?r   )r   {Gz?r   g@      ?)
front_left	back_leftfront_right
back_right)motor_front_leftL_jointmotor_front_leftR_jointmotor_back_leftL_jointmotor_back_leftR_jointmotor_front_rightL_jointmotor_front_rightR_jointmotor_back_rightL_jointmotor_back_rightR_jointzchassis\D*centerzmotor\D*jointzknee\D*)        r   r   r   r      c                 H   [         R                  " U 5      n[        [        U 5      5       Hs  n[        R
                  " X   [        5      X'   X   [        R                  :  a  X==   [        -  ss'   MJ  X   [        R                  * :  d  Mc  X==   [        -  ss'   Mu     U$ )z~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].
)copydeepcopyrangelenmathfmodTWO_PIpi)anglesmapped_anglesis      ^/home/james-whalen/.local/lib/python3.13/site-packages/pybullet_envs/minitaur/envs/minitaur.pyMapToMinusPiToPir#   &   s~     --'-VayyF3M477"& 		TWWH	$&   
    c                      \ rS rSrSrSSSS\R                  SSSSSS	S	\SSS4S
 jrS r	S r
S rS rS rS rS rS rS rS rSIS jrS rS rS rS rS rS rS rS rS rS  rS! rS" rS# r S$ r!S% r"S& r#S' r$S( r%S) r&SJS* jr'S+ r(S, r)S- r*S. r+S/ r,S0 r-S1 r.S2 r/S3 r0S4 r1S5 r2S6 r3S7 r4S8 r5S9 r6S: r7S; r8S< r9S= r:S> r;S? r<S@ r=SA r>SB r?SC r@SD rASE rBSF rC\DSG 5       rESHrFg)KMinitaur8   zLThe minitaur class that simulates a quadruped robot from Ghost Robotics.

   r   r   Fr   g{Gz?r   c                 h   SU l         [        U R                   S-  5      U l        Xl        X@l        X l        XPl        X`l        Xpl        / SQU l	        [        R                  " U R                   5      U l        [        R                  " U R                   5      U l        SU l        Xl        Xl        Xl        Xl        Xl        [(        R*                  " SS9U l        / U l        S/U l        / U l        / U l        / U l        Xl        UU l        UU l        U R$                  (       aF  Xl        Xl         [B        RD                  " U R8                  U R>                  U R@                  S9U l#        O.U R                  (       a  SU l        S	U l         OS
U l        S
U l         X0l$        SU l%        U RM                  SS9  g)a  Constructs a minitaur and reset it to the initial states.

Args:
  pybullet_client: The instance of BulletClient to manage different
    simulations.
  urdf_root: The path to the urdf folder.
  time_step: The time step of the simulation.
  action_repeat: The number of ApplyAction() for each control step.
  self_collision_enabled: Whether to enable self collision.
  motor_velocity_limit: The upper limit of the motor velocity.
  pd_control_enabled: Whether to use PD control for the motors.
  accurate_motor_model_enabled: Whether to use the accurate DC motor model.
  remove_default_joint_damping: Whether to remove the default joint damping.
  motor_kp: proportional gain for the accurate motor model.
  motor_kd: derivative gain for the accurate motor model.
  pd_latency: The latency of the observations (in seconds) used to calculate
    PD control. On the real hardware, it is the latency between the
    microcontroller and the motor controller.
  control_latency: The latency of the observations (in second) used to
    calculate action. On the real hardware, it is the latency from the motor
    controller, the microcontroller to the host (Nvidia TX2).
  observation_noise_stdev: The standard deviation of a Gaussian noise model
    for the sensor. It should be an array for separate sensors in the
    following order [motor_angle, motor_velocity, motor_torque,
    base_roll_pitch_yaw, base_angular_velocity]
  torque_control_enabled: Whether to use the torque control, if set to
    False, pose control will be used.
  motor_overheat_protection: Whether to shutdown the motor that has exerted
    large torque (OVERHEAT_SHUTDOWN_TORQUE) for an extended amount of time
    (OVERHEAT_SHUTDOWN_TIME). See ApplyAction() in minitaur.py for more
    details.
  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.
   r   )r+   r+   r+   r   r   r   r   g      @d   )maxlenr+   )torque_control_enabledkpkdg333333?r   r   g      )
reset_timeN)'
num_motorsintnum_legs_pybullet_client_action_repeat
_urdf_root_self_collision_enabled_motor_velocity_limit_pd_control_enabled_motor_directionnpzeros_observed_motor_torques_applied_motor_torques
_max_force_pd_latency_control_latency_observation_noise_stdev_accurate_motor_model_enabled_remove_default_joint_dampingcollectionsdeque_observation_history_control_observation_chassis_link_ids_leg_link_ids_motor_link_ids_foot_link_ids_torque_control_enabled_motor_overheat_protection_on_rack_kp_kdr   
MotorModel_motor_model	time_step_step_counterReset)selfpybullet_client	urdf_rootrU   action_repeatself_collision_enabledmotor_velocity_limitpd_control_enabledaccurate_motor_model_enabledremove_default_joint_dampingmotor_kpmotor_kd
pd_latencycontrol_latencyobservation_noise_stdevr.   motor_overheat_protectionon_racks                     r"   __init__Minitaur.__init__=   sm   j DO!+,DM+'O#9 !518D#%88DOO#<D "$((4??";DDO!+$;!)E&)E& + 1 1 =D "D TDDDD#9 &?D#DM))hh**$B^B^.2hh.2hh8d 
	!	!dhdhdhdhND 	JJ$Jr$   c                 4    U R                   U R                  -  $ N)rV   rU   rX   s    r"   GetTimeSinceResetMinitaur.GetTimeSinceReset   s    ..r$   c                     [        U R                  5       HS  nU R                  U5        U R                  R	                  5         U R                  5         U =R                  S-  sl        MU     g )Nr   )r   r6   ApplyActionr5   stepSimulationReceiveObservationrV   )rX   action_s      r"   StepMinitaur.Step   sT    4&&'
v
**,

A	 (r$   c                     g rk    rl   s    r"   	TerminateMinitaur.Terminate   s    r$   c                    / U l         U R                   HE  nU R                   R                  U R                  R	                  U R
                  U5      S   5        MG     / U l        U R                   HE  nU R                  R                  U R                  R	                  U R
                  U5      S   5        MG     U R                   HE  nU R                  R                  U R                  R	                  U R
                  U5      S   5        MG     g )Nr   )	_base_mass_urdfrJ   appendr5   getDynamicsInfo	quadruped_leg_masses_urdfrK   rL   )rX   
chassis_idleg_idmotor_ids       r"   _RecordMassInfoFromURDF Minitaur._RecordMassInfoFromURDF   s    D,,

!!



/
/

KA
NP - D$$
""



/
/
G
JL % ((
""



/
/
I!
LN )r$   c                 v   / U l         U R                  R                  U R                  5      n[	        SU5       HG  nU R                  R                  U R                  U5      S   nU R                   R                  U5        MI     U R                   Vs/ s H  o@R                   US-      PM     snU l        U R                   Vs/ s H  oPR                   US-      PM     snU l
        U R                  R                  U R                   Vs/ s H  o`R                   US-      PM     sn5        gs  snf s  snf s  snf )z/Record the inertia of each body from URDF file.r+   r   r   N)
_link_urdfr5   getNumJointsr   r   r~   r}   rJ   _base_inertia_urdfrK   _leg_inertia_urdfextendrL   )rX   
num_bodiesbody_idinertiar   r   r   s          r"   _RecordInertiaInfoFromURDF#Minitaur._RecordInertiaInfoFromURDF   s   DO&&33DNNCJZ(%%55dnngNqQg
ooW% ) ;?:P:P:PJ
Q':PD IMHZHZ[HZfoofqj9HZ[D!!7;7K7KL7K8A	&7KLN	 \Ls   D,D1	D6c                    U R                   R                  U R                  5      n0 U l        [	        U5       HM  nU R                   R                  U R                  U5      nUS   U R                  US   R                  S5      '   MO     g )Nr   r   UTF-8)r5   r   r   _joint_name_to_idr   getJointInfodecoderX   
num_jointsr!   
joint_infos       r"   _BuildJointNameToIdDict Minitaur._BuildJointNameToIdDict   sr    &&33DNNCJD:((55dnnaHj>HmdZ]11':; r$   c                    U R                   R                  U R                  5      nS/U l        / U l        / U l        / U l        [        U5       GH  nU R                   R                  U R                  U5      nUS   R                  S5      nU R                  U   n[        R                  U5      (       a  U R                  R                  U5        M  [        R                  U5      (       a  U R
                  R                  U5        M  [        R                  U5      (       a  U R                  R                  U5        M  U R                  R                  U5        GM     U R                  R!                  U R                  5        U R                  R#                  5         U R
                  R#                  5         U R                  R#                  5         U R                  R#                  5         g)z2Build the link Ids from its name in the URDF file.r+   r   r   N)r5   r   r   rJ   rK   rL   rM   r   r   r   r   _CHASSIS_NAME_PATTERNmatchr}   _MOTOR_NAME_PATTERN_KNEE_NAME_PATTERNr   sort)rX   r   r!   r   
joint_namejoint_ids         r"   _BuildUrdfIdsMinitaur._BuildUrdfIds   st   &&33DNNCJ TDDDD:((55dnnaHja=''0j''
3h		$	$Z	0	0%%h/$$Z00##H-##J//""8,!!(+  	d112!r$   c                     U R                   R                  U R                  5      n[        U5       HH  nU R                   R	                  U R                  U5      nU R                   R                  US   SSSS9  MJ     g )Nr   r+   )linearDampingangularDamping)r5   r   r   r   r   changeDynamicsr   s       r"   _RemoveDefaultJointDamping#Minitaur._RemoveDefaultJointDamping   si    &&33DNNCJ:((55dnnaHj
**:a="A^_*` r$   c                 ^    [          Vs/ s H  oR                  U   PM     snU l        g s  snf rk   )MOTOR_NAMESr   _motor_id_list)rX   
motor_names     r"   _BuildMotorIdListMinitaur._BuildMotorIdList   s'    P[\P[*11*=P[\D\s   *c                     g)a<  Whether the observation is valid for the current time step.

In simulation, observations are always valid. In real hardware, it may not
be valid from time to time when communication error happens between the
Nvidia TX2 and the microcontroller.

Returns:
  Whether the observation is valid for the current time step.
Trx   rl   s    r"   IsObservationValidMinitaur.IsObservationValid   s     r$   Nc                    U R                   (       a  [        nO[        nU(       Ga  U R                  (       aM  U R                  R                  SU R                  -  UU R                   U R                  R                  S9U l        O7U R                  R                  SU R                  -  UU R                   S9U l        U R                  5         U R                  5         U R                  (       a  U R                  5         U R                  5         U R                  5         U R                  5         U R!                  SS9  OeU R                  R#                  U R                  U[$        5        U R                  R'                  U R                  / SQ/ SQ5        U R!                  SS9  [(        R*                  " U R,                  5      U l        S/U R,                  -  U l        SU l        U R4                  R7                  5         U R8                  (       d  US	:  a  U R;                  5         [=        S
5       H]  nU R?                  [@        RB                  S-  /U R,                  -  5        U R                  RE                  5         U R;                  5         M_     Ubd  [G        X0RH                  -  5      n[=        U5       H>  nU R?                  U5        U R                  RE                  5         U R;                  5         M@     U R;                  5         g)a<  Reset the minitaur to its initial states.

Args:
  reload_urdf: Whether to reload the urdf file. If not, Reset() just place
    the minitaur back to its starting position.
  default_motor_angles: The default motor angles. If it is None, minitaur
    will hold a default pose (motor angle math.pi / 2) for 100 steps. In
    torque control mode, the phase of holding the default pose is skipped.
  reset_time: The duration (in seconds) to hold the default motor angles. If
    reset_time <= 0 or in torque control mode, the phase of holding the
    default pose is skipped.
z%s/quadruped/minitaur.urdf)useFixedBaseflags)r   T)add_constraintr   r   r   Fr   r   r,   r   N)%rP   INIT_RACK_POSITIONINIT_POSITIONr8   r5   loadURDFr7   URDF_USE_SELF_COLLISIONr   r   r   rE   r   r   r   r   	ResetPoseresetBasePositionAndOrientationINIT_ORIENTATIONresetBaseVelocityr<   r=   r2   _overheat_counter_motor_enabled_listrV   rH   clearrN   rr   r   rp   r   r   rq   r3   rU   )rX   reload_urdfdefault_motor_anglesr1   init_positionrt   num_steps_to_resets          r"   rW   Minitaur.Reset   s[    }}(m#m		%	%..77(4??:''??	 8 A ..778T8<9H8EEI]] 8 T ""$
		+	+'')

""$
%%'
nnDn)
;;DNNM<LN
--dnniS
nnEn*XXdoo6D $v7DD
 	##%''J,<
Sz!$''A+89,,.!  
	) nn!<=)*A


/
0



.
.
0

!
!
# + 	r$   c                 x    U R                   R                  U R                  UU R                   R                  US9  g )N)	bodyIndex
jointIndexcontrolModeforce)r5   setJointMotorControl2r   TORQUE_CONTROL)rX   r   torques      r"   _SetMotorTorqueByIdMinitaur._SetMotorTorqueById>  s6    //$..;C<@<Q<Q<`<`6< 0 >r$   c           
          U R                   R                  U R                  UU R                   R                  UU R                  U R
                  U R                  S9  g )N)r   r   r   targetPositionpositionGainvelocityGainr   )r5   r   r   POSITION_CONTROLrQ   rR   r@   )rX   r   desired_angles      r"   _SetDesiredMotorAngleById"Minitaur._SetDesiredMotorAngleByIdD  sL    //$..;C<@<Q<Q<b<b?L=AXX=AXX6:oo 0 Gr$   c                 B    U R                  U R                  U   U5        g rk   )r   r   )rX   r   r   s      r"   _SetDesiredMotorAngleByName$Minitaur._SetDesiredMotorAngleByNameM  s    ""4#9#9*#E}Ur$   c                 ^    [        U R                  5       H  nU R                  X!5        M     g)zpReset the pose of the minitaur.

Args:
  add_constraint: Whether to add a constraint at the joints of two feet.
N)r   r4   _ResetPoseForLeg)rX   r   r!   s      r"   r   Minitaur.ResetPoseP  s%     4==!
A. "r$   c           
         Sn[         R                  S-  nSn[        U   nU R                  R	                  U R
                  U R                  SU-   S-      U R                  SU-     U-  SS9  U R                  R	                  U R
                  U R                  SU-   S	-      U R                  SU-     U-  SS9  U R                  R	                  U R
                  U R                  SU-   S
-      U R                  SU-  S-      U-  SS9  U R                  R	                  U R
                  U R                  SU-   S-      U R                  SU-  S-      U-  SS9  U(       az  U R                  R                  U R
                  U R                  SU-   S-      U R
                  U R                  SU-   S	-      U R                  R                  / SQ[        [        5        U R                  (       d  U R                  (       a  U R                  R                  U R
                  U R                  SU-   S-      U R                  R                  SUS9  U R                  R                  U R
                  U R                  SU-   S
-      U R                  R                  SUS9  OYU R!                  SU-   S-   U R                  SU-     U-  5        U R!                  SU-   S
-   U R                  SU-  S-      U-  5        U R                  R                  U R
                  U R                  SU-   S	-      U R                  R                  SUS9  U R                  R                  U R
                  U R                  SU-   S-      U R                  R                  SUS9  g)zReset the initial pose for the leg.

Args:
  leg_id: It should be 0, 1, 2, or 3, which represents the leg at
    front_left, back_left, front_right and back_right.
  add_constraint: Whether to add a constraint at the joints of two feet.
r   g       @gPkwmotor_L_jointr   )targetVelocityknee_L_linkR_jointr   R_linkr   r   r   r   r   r   N)r   r   LEG_POSITIONr5   resetJointStater   r   r;   createConstraintJOINT_POINT2POINTKNEE_CONSTRAINT_POINT_RIGHTKNEE_CONSTRAINT_POINT_LEFTrD   r:   r   VELOCITY_CONTROLr   )rX   r   r   knee_friction_forcehalf_pi
knee_angleleg_positions          r"   r   Minitaur._ResetPoseForLegY  s    ggmGJ'L))$..*.*@*@LAXAJBK +L*.*?*?F
*Kg*U9:	 * <
 	))$..*.*@*@<AWAIBJ +K*.*?*?F
*Kj*X9:	 * <
 	))$..*.*@*@LAXAJBK +L*.*?*?F
Q*ORY*Y9:	 * <
 	))$..*.*@*@<AWAIBJ +K*.*?*?F
Q*OR\*\9:	 * <
 
,,
..$00<1G(1RS
..$00<1G(1RS



1
19>Y
$	& ))T-E-E
11NN,,X-Dy-PQ++<<# 2 % 11NN,,X-Dy-PQ++<<# 2 % &&x,'>'J'+'<'<QZ'H7'RT
&&x,'>'J'+'<'<QZ!^'Lw'VX 	//..**7\+AH+LM))::! 0 # 	//..**7\+AH+LM))::! 0 #r$   c                 T    U R                   R                  U R                  5      u  pU$ )zRGet the position of minitaur's base.

Returns:
  The position of minitaur's base.
r5   getBasePositionAndOrientationr   )rX   positionrt   s      r"   GetBasePositionMinitaur.GetBasePosition  s%     ((FFt~~VKHOr$   c                     U R                  5       nU R                  R                  U5      n[        R                  " U5      $ )zGet minitaur's base orientation in euler angle in the world frame.

Returns:
  A tuple (roll, pitch, yaw) of the base in world frame.
)GetTrueBaseOrientationr5   getEulerFromQuaternionr<   asarray)rX   orientationroll_pitch_yaws      r"   GetTrueBaseRollPitchYaw Minitaur.GetTrueBaseRollPitchYaw  s7     --/K**AA+NN::n%%r$   c                 "   [         R                  " U R                  SU R                  -  SU R                  -  S-    5      nU R                  R                  U5      nU R                  [         R                  " U5      U R                  S   5      nU$ )zGet minitaur's base orientation in euler angle in the world frame.

This function mimicks the noisy sensor reading and adds latency.
Returns:
  A tuple (roll, pitch, yaw) of the base in world frame polluted by noise
  and latency.
      )r<   arrayrI   r2   r5   r   _AddSensorNoiserC   )rX   delayed_orientationdelayed_roll_pitch_yawr  s       r"   GetBaseRollPitchYawMinitaur.GetBaseRollPitchYaw  s     ((!!!doo"5a$//6IA6MNP!22IIJ]^))"((3I*J*.*G*G*JLNr$   c                     U R                    Vs/ s H,  nU R                  R                  U R                  U5      S   PM.     nn[        R
                  " X R                  5      nU$ s  snf )zwGets the eight motor angles at the current moment, mapped to [-pi, pi].

Returns:
  Motor angles, mapped to [-pi, pi].
r   r   r5   getJointStater   r<   multiplyr;   )rX   r   motor_angless      r"   GetTrueMotorAnglesMinitaur.GetTrueMotorAngles  sg     +++H 	++DNNHEaH+   ;;|-B-BCL   3A&c                     U R                  [        R                  " U R                  SU R                   5      U R
                  S   5      n[        U5      $ )zGets 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].
r   )r  r<   r  rI   r2   rC   r#   )rX   r  s     r"   GetMotorAnglesMinitaur.GetMotorAngles  sJ     ''1J1J1T__1](^(,(E(Ea(HJLL))r$   c                     U R                    Vs/ s H,  nU R                  R                  U R                  U5      S   PM.     nn[        R
                  " X R                  5      nU$ s  snf )zRGet the velocity of all eight motors.

Returns:
  Velocities of all eight motors.
r   r  )rX   r   motor_velocitiess      r"   GetTrueMotorVelocitiesMinitaur.GetTrueMotorVelocities  si     +++H 	++DNNHEaH+   {{#35J5JKr  c                     U R                  [        R                  " U R                  U R                  SU R                  -   5      U R
                  S   5      $ )zGet the velocity of all eight motors.

This function mimicks the noisy sensor reading and adds latency.
Returns:
  Velocities of all eight motors polluted by noise and latency.
r   r   r  r<   r  rI   r2   rC   rl   s    r"   GetMotorVelocitiesMinitaur.GetMotorVelocities  sK     
**4??1t;NOP%%a(* *r$   c                 2   U R                   (       d  U R                  (       a  U R                  $ U R                   Vs/ s H,  nU R                  R                  U R                  U5      S   PM.     nn[        R                  " X R                  5      nU$ s  snf )zaGet the amount of torque the motors are exerting.

Returns:
  Motor torques of all eight motors.
r  )
rD   r:   r>   r   r5   r  r   r<   r  r;   )rX   r   motor_torquess      r"   GetTrueMotorTorquesMinitaur.GetTrueMotorTorques  s     ))T-E-E))) ---h 


-
-dnnh
G
J-   kk-1F1FGms   3Bc                     U R                  [        R                  " U R                  SU R                  -  SU R                  -   5      U R
                  S   5      $ )zGet the amount of torque the motors are exerting.

This function mimicks the noisy sensor reading and adds latency.
Returns:
  Motor torques of all eight motors polluted by noise and latency.
r   r  r  rl   s    r"   GetMotorTorquesMinitaur.GetMotorTorques  sP     
**1t+>q4???RST%%a(* *r$   c                 T    U R                   R                  U R                  5      u  pU$ )zsGet the orientation of minitaur's base, represented as quaternion.

Returns:
  The orientation of minitaur's base.
r   )rX   rt   r   s      r"   r   Minitaur.GetTrueBaseOrientation  s&     ++II$..YNAr$   c                 T    U R                   R                  U R                  5       5      $ )zGet the orientation of minitaur's base, represented as quaternion.

This function mimicks the noisy sensor reading and adds latency.
Returns:
  The orientation of minitaur's base polluted by noise and latency.
)r5   getQuaternionFromEulerr  rl   s    r"   GetBaseOrientationMinitaur.GetBaseOrientation  s$       778P8P8RSSr$   c                     U R                   R                  U R                  5      n[        R                  " US   S   US   S   US   S   /5      $ )zGet the rate of orientation change of the minitaur's base in euler angle.

Returns:
  rate of (roll, pitch, yaw) change of the minitaur's base.
r   r   r   )r5   getBaseVelocityr   r<   r   )rX   vels     r"   GetTrueBaseRollPitchYawRate$Minitaur.GetTrueBaseRollPitchYawRate$  sL     


/
/
?C::s1vay#a&)SVAY788r$   c                     U R                  [        R                  " U R                  SU R                  -  S-   SU R                  -  S-    5      U R
                  S   5      $ )zGet the rate of orientation change of the minitaur's base in euler angle.

This function mimicks the noisy sensor reading and adds latency.
Returns:
  rate of (roll, pitch, yaw) change of the minitaur's base polluted by noise
  and latency.
r  r     r  rl   s    r"   GetBaseRollPitchYawRate Minitaur.GetBaseRollPitchYawRate-  s[     
**1t+>+B1tCVYZCZ[\%%a(* *r$   c                     U R                   $ )zNGet the length of the action list.

Returns:
  The length of the action list.
)r2   rl   s    r"   GetActionDimensionMinitaur.GetActionDimension9  s     ??r$   c                 r   U R                   [        R                  :  a]  U R                  5       nX@R                  U R                   -  -   nX@R                  U R                   -  -
  n[        R
                  " XU5      nUc!  [        R                  " SU R                  5      nUc!  [        R                  " SU R                  5      nU R                  (       d  U R                  (       Ga  U R                  5       u  pxU R                  5       n	U R                  (       GaJ  U R                  R                  XXX#5      u  pU R                  (       a  [!        U R"                  5       Ht  n[%        X   5      [&        :  a  U R(                  U==   S-  ss'   OSU R(                  U'   U R(                  U   [*        U R                  -  :  d  Me  SU R,                  U'   Mv     Xl        [        R0                  " XR2                  5      U l        [7        U R8                  U R4                  U R,                  5       H2  u  pnU(       a  U R;                  X5        M   U R;                  US5        M4     gSU-  Xq-
  -  X8-  -
  nUU l        [        R0                  " U R.                  U R2                  5      U l        [7        U R8                  U R<                  5       H  u  pU R;                  X5        M     g[        R0                  " XR2                  5      n[7        U R8                  U5       H  u  nnU R?                  UU5        M     g)a  Set the desired motor angles to the motors of the minitaur.

The desired motor angles are clipped based on the maximum allowed velocity.
If the pd_control_enabled is True, a torque is calculated according to
the difference between current and desired joint angle, as well as the joint
velocity. This torque is exerted to the motor. For more information about
PD control, please refer to: https://en.wikipedia.org/wiki/PID_controller.

Args:
  motor_commands: The eight desired motor angles.
  motor_kps: Proportional gains for the motor model. If not provided, it
    uses the default kp of the minitaur for all the motors.
  motor_kds: Derivative gains for the motor model. If not provided, it
    uses the default kd of the minitaur for all the motors.
Nr*   r   r   Fr+   ) r9   r<   infr  rU   clipfullrQ   rR   rD   r:   _GetPDObservationr  rT   convert_to_torquerO   r   r2   absOVERHEAT_SHUTDOWN_TORQUEr   OVERHEAT_SHUTDOWN_TIMEr   r>   r  r;   _applied_motor_torquezipr   r   r?   r   )rX   motor_commands	motor_kps	motor_kdscurrent_motor_anglemotor_commands_maxmotor_commands_minqqdot	qdot_trueactual_torqueobserved_torquer!   r   motor_torquemotor_enabledtorque_commandsmotor_commands_with_directionmotor_command_with_directions                      r"   rp   Minitaur.ApplyActionA  s     !!BFF* 335/..4C]C]2]]/..4C]C]2]]ww~CUVn''!TXX&i''!TXX&i))T-E-E-E&&(ga--/i		+	+	+)-):):)L)Lt	*F&**)a=#$'??$$Q'1,'*+d$$Q'&&q),BT^^,SS,1d&&q) * (7$ &([[@U@U%V"589L9L9=9S9S9=9Q9Q6S1HM $$X<$$Xq16S y.A,>?)BRR (7$ ')kk$2N2N262G2G'I# '*$*=*=t?Z?Z&["H

"
"8
: '\ ')kk.BWBW&X#478K8K8U5W
0(0&&x1MN5Wr$   c                 `   [         R                  " U5      nSnSn[        U R                  S-  5      n[        R
                  S-  n[        U R                  5       HO  n[        US-  5      nU* U-  XU-      U-   -  n	SU-  U-  X   -  n
Xu:  a  U
* n
[        R
                  U	-   U
-   X''   MQ     U$ )zConvert the actions that use leg model to the real motor actions.

Args:
  actions: The theta, phi of the leg model.
Returns:
  The eight desired motor angles that can be used in ApplyActions().
r   g      ?r   r  r+   )r   r   r3   r2   r   r   r   )rX   actionsmotor_anglescale_for_singularityoffset_for_singularityhalf_num_motors	quater_pir!   
action_idxforward_backward_componentextension_components              r"   ConvertFromLegModelMinitaur.ConvertFromLegModel  s     --(K $//A-.O!I4??#qAv;j 
 9
,/03IIK !  !Gi/'2EE	
	22"<<?RRkn $ r$   c                     U R                   $ )z,Get the mass of the base from the URDF file.)r|   rl   s    r"   GetBaseMassesFromURDFMinitaur.GetBaseMassesFromURDF  s    r$   c                     U R                   $ )z/Get the inertia of the base from the URDF file.)r   rl   s    r"   GetBaseInertiasFromURDF Minitaur.GetBaseInertiasFromURDF  s    """r$   c                     U R                   $ )z,Get the mass of the legs from the URDF file.)r   rl   s    r"   GetLegMassesFromURDFMinitaur.GetLegMassesFromURDF  s       r$   c                     U R                   $ )z/Get the inertia of the legs from the URDF file.)r   rl   s    r"   GetLegInertiasFromURDFMinitaur.GetLegInertiasFromURDF      !!!r$   c                 <   [        U5      [        U R                  5      :w  a7  [        SR                  [        U5      [        U R                  5      5      5      e[	        U R                  U5       H)  u  p#U R
                  R                  U R                  X#S9  M+     g)a:  Set the mass of minitaur's base.

Args:
  base_mass: A list of masses of each body link in CHASIS_LINK_IDS. The
    length of this list should be the same as the length of CHASIS_LINK_IDS.
Raises:
  ValueError: It is raised when the length of base_mass is not the same as
    the length of self._chassis_link_ids.
zJThe length of base_mass {} and self._chassis_link_ids {} are not the same.massN)r   rJ   
ValueErrorformatrC  r5   r   r   )rX   	base_massr   chassis_masss       r"   SetBaseMassesMinitaur.SetBaseMasses  s     9~T3344 ##)6#i.#d>T>T:U#VX X$'(>(>	$J 

**4>>:*Y %Kr$   c                    [        U5      [        U R                  5      [        U R                  5      -   :w  a  [        S5      e[	        U R                  U5       H)  u  p#U R
                  R                  U R                  X#S9  M+     U[        U R                  5      S n[	        U R                  U5       H)  u  pVU R
                  R                  U R                  XVS9  M+     g)a  Set the mass of the legs.

A leg includes leg_link and motor. 4 legs contain 16 links (4 links each)
and 8 motors. First 16 numbers correspond to link masses, last 8 correspond
to motor masses (24 total).

Args:
  leg_masses: The leg and motor masses for all the leg links and motors.

Raises:
  ValueError: It is raised when the length of masses is not equal to number
    of links + motors.
^The number of values passed to SetLegMasses are different than number of leg links and motors.ro  N)r   rK   rL   rq  rC  r5   r   r   )rX   
leg_massesr   leg_massmotor_masseslink_id
motor_masss          r"   SetLegMassesMinitaur.SetLegMasses  s     :#d001C8L8L4MMM H I I 2 2J?
**4>>6*Q @c$"4"4567L"4#7#7F
**4>>7*T  Gr$   c                    [        U5      [        U R                  5      :w  a7  [        SR                  [        U5      [        U R                  5      5      5      e[	        U R                  U5       Hj  u  p#U H:  n[
        R                  " U5      S:  R                  5       (       d  M1  [        S5      e   U R                  R                  U R                  UUS9  Ml     g)a{  Set the inertias of minitaur's base.

Args:
  base_inertias: A list of inertias of each body link in CHASIS_LINK_IDS.
    The length of this list should be the same as the length of
    CHASIS_LINK_IDS.
Raises:
  ValueError: It is raised when the length of base_inertias is not the same
    as the length of self._chassis_link_ids and base_inertias contains
    negative values.
zNThe length of base_inertias {} and self._chassis_link_ids {} are not the same.r   0Values in inertia matrix should be non-negative.localInertiaDiagonalN)r   rJ   rq  rr  rC  r<   r   anyr5   r   r   )rX   base_inertiasr   chassis_inertiainertia_values        r"   SetBaseInertiasMinitaur.SetBaseInertias  s     =S!7!788 ''-vc-.@#dF\F\B]'^` `'*4+A+A='Q#
*-JJ}%)..00MN
N + **4>>+5@O + Q	 (Rr$   c                    [        U5      [        U R                  5      [        U R                  5      -   :w  a  [        S5      e[	        U R                  U5       Hj  u  p#U H:  n[
        R                  " U5      S:  R                  5       (       d  M1  [        S5      e   U R                  R                  U R                  UUS9  Ml     U[        U R                  5      S n[	        U R                  U5       Hj  u  pgU H:  n[
        R                  " U5      S:  R                  5       (       d  M1  [        S5      e   U R                  R                  U R                  UUS9  Ml     g)a  Set the inertias of the legs.

A leg includes leg_link and motor. 4 legs contain 16 links (4 links each)
and 8 motors. First 16 numbers correspond to link inertia, last 8 correspond
to motor inertia (24 total).

Args:
  leg_inertias: The leg and motor inertias for all the leg links and motors.

Raises:
  ValueError: It is raised when the length of inertias is not equal to
  the number of links + motors or leg_inertias contains negative values.
rx  r   r  r  N)r   rK   rL   rq  rC  r<   r   r  r5   r   r   )rX   leg_inertiasr   leg_inertiar  motor_inertiasr|  motor_inertias           r"   SetLegInertiasMinitaur.SetLegInertias  sG    <C 2 23c$:N:N6OOO H I I"4#5#5|D'-JJ}%)..00MN
N ( **4>>+1@K + M	  E "#d&8&8"9":;N"%d&:&:N"K)-JJ}%)..00MN
N * **4>>+2@M + O	 #Lr$   c                 r    U R                    H'  nU R                  R                  U R                  X!S9  M)     g)zSet the lateral friction of the feet.

Args:
  foot_friction: The lateral friction coefficient of the foot. This value is
    shared by all four feet.
)lateralFrictionNrM   r5   r   r   )rX   foot_frictionr|  s      r"   SetFootFrictionMinitaur.SetFootFriction  s1     &&
**4>>7*b 'r$   c                 r    U R                    H'  nU R                  R                  U R                  X!S9  M)     g)zSet the coefficient of restitution at the feet.

Args:
  foot_restitution: The coefficient of restitution (bounciness) of the feet.
    This value is shared by all four feet.
)restitutionNr  )rX   foot_restitutionr|  s      r"   SetFootRestitutionMinitaur.SetFootRestitution   s1     &&
**4>>7*a 'r$   c           	          [        U R                  U5       H@  u  p#U R                  R                  U R                  UU R                  R
                  SUS9  MB     g )Nr   r   )rC  rM   r5   r   r   r   )rX   joint_frictionsknee_joint_idfrictions       r"   SetJointFrictionMinitaur.SetJointFriction*  sU    #&t':':O#L
11NN"++<< 2  $Mr$   c                 ,    [        U R                  5      $ rk   )r   rM   rl   s    r"   GetNumKneeJointsMinitaur.GetNumKneeJoints3  s    t""##r$   c                 ^    U R                   (       a  U R                  R                  U5        g g rk   )rD   rT   set_voltage)rX   voltages     r"   SetBatteryVoltageMinitaur.SetBatteryVoltage6  s$    ))
##G, *r$   c                 ^    U R                   (       a  U R                  R                  U5        g g rk   )rD   rT   set_viscous_damping)rX   viscous_dampings     r"   SetMotorViscousDampingMinitaur.SetMotorViscousDamping:  s$    ))
++O< *r$   c                 @   / nUR                  U R                  5       5        UR                  U R                  5       5        UR                  U R                  5       5        UR                  U R	                  5       5        UR                  U R                  5       5        U$ rk   )r   r  r  r"  r   r0  )rX   observations     r"   GetTrueObservationMinitaur.GetTrueObservation>  s    Kt..01t2245t//12t2245t779:r$   c                     U R                   R                  U R                  5       5        U R                  5       U l        g)zReceive the observation from sensors.

This function is called once per step. The observations are only updated
when this function is called.
N)rH   
appendleftr  _GetControlObservationrI   rl   s    r"   rr   Minitaur.ReceiveObservationG  s2     	(()@)@)BC $ ; ; =Dr$   c                    US::  d  [        U R                  5      S:X  a  U R                  S   nU$ [        XR                  -  5      nUS-   [        U R                  5      :  a  U R                  S   $ XU R                  -  -
  nX@R                  -  nSU-
  [        R
                  " U R                  U   5      -  U[        R
                  " U R                  US-      5      -  -   nU$ )zGet observation that is delayed by the amount specified in latency.

Args:
  latency: The latency (in seconds) of the delayed observation.
Returns:
  observation: The observation which was actually latency seconds ago.
r   r   r+   r   )r   rH   r3   rU   r<   r  )rX   latencyr  n_steps_agoremaining_latencyblend_alphas         r"   _GetDelayedObservationMinitaur._GetDelayedObservationP  s     !|s4445:--a0k  ..01k	qC 9 9:	:((,,!$..$@@%6kK'288D4M4Mk4Z+[[ 288D,E,EkTUo,V#WWXkr$   c                     U R                  U R                  5      nUSU R                   nXR                  SU R                  -   n[        R                  " U5      [        R                  " U5      4$ )Nr   r   )r  rA   r2   r<   r  )rX   pd_delayed_observationrJ  rK  s       r"   r=  Minitaur._GetPDObservationd  s[    !889I9IJq1A!//!doo2EFDHHQK$((r$   c                 <    U R                  U R                  5      nU$ rk   )r  rB   )rX   control_delayed_observations     r"   r  Minitaur._GetControlObservationj  s    "&"="=d>S>S"T&&r$   c                 j    US::  a  U$ U[         R                  R                  X!R                  S9-   nU$ )Nr   )scalesize)r<   randomnormalshape)rX   sensor_valuesnoise_stdevr  s       r"   r  Minitaur._AddSensorNoisen  s8    a"))"2"2K^K^"2"__Kr$   c                     Xl         g)zSet the latency of the control loop.

It measures the duration between sending an action from Nvidia TX2 and
receiving the observation from microcontroller.

Args:
  latency: The latency (in seconds) of the control loop.
NrB   )rX   r  s     r"   SetControlLatencyMinitaur.SetControlLatencyt  s
     $r$   c                     U R                   $ )zGet the control latency.

Returns:
  The latency (in seconds) between when the motor command is sent and when
    the sensor measurements are reported back to the controller.
r  rl   s    r"   GetControlLatencyMinitaur.GetControlLatency  s        r$   c                 v    Xl         X l        U R                  (       a  U R                  R	                  X5        gg)zSet the gains of all motors.

These gains are PD gains for motor positional control. kp is the
proportional gain and kd is the derivative gain.

Args:
  kp: proportional gain of the motors.
  kd: derivative gain of the motors.
N)rQ   rR   rD   rT   set_motor_gains)rX   r/   r0   s      r"   SetMotorGainsMinitaur.SetMotorGains  s0     HH))
''/ *r$   c                 2    U R                   U R                  4$ )zVGet the gains of the motor.

Returns:
  The proportional gain.
  The derivative gain.
)rQ   rR   rl   s    r"   GetMotorGainsMinitaur.GetMotorGains  s     88TXXr$   c                 z    U R                   (       a*  U R                  R                  U/U R                  -  5        gg)zSet the strength of all motors relative to the default value.

Args:
  ratio: The relative strength. A scalar range from 0.0 to 1.0.
N)rD   rT   set_strength_ratiosr2   )rX   ratios     r"   SetMotorStrengthRatioMinitaur.SetMotorStrengthRatio  s1     ))
++UGdoo,EF *r$   c                 ^    U R                   (       a  U R                  R                  U5        gg)zSet the strength of each motor relative to the default value.

Args:
  ratios: The relative strength. A numpy array ranging from 0.0 to 1.0.
N)rD   rT   r  )rX   ratioss     r"   SetMotorStrengthRatiosMinitaur.SetMotorStrengthRatios  s&     ))
++F3 *r$   c                     X l         Xl        g)zSet the time steps of the control and simulation.

Args:
  action_repeat: The number of simulation steps that the same action is
    repeated.
  simulation_step: The simulation time step.
N)rU   r6   )rX   r[   simulation_steps      r"   SetTimeStepsMinitaur.SetTimeSteps  s     %N'r$   c                     U R                   $ rk   )rJ   rl   s    r"   chassis_link_idsMinitaur.chassis_link_ids  rm  r$   )*rD   r6   rB  r?   r   r|   rJ   rB   rI   rM   r   rR   rQ   r   rK   r   r   r@   r;   r   r   rL   rT   rO   r9   rH   rC   r>   rP   r   r:   rA   r5   rE   r8   rV   rN   r7   r4   r2   r   rU   )TNg      @)NN)G__name__
__module____qualname____firstlineno____doc__r<   r:  SENSOR_NOISE_STDDEVrh   rm   ru   ry   r   r   r   r   r   r   r   rW   r   r   r   r   r   r   r  r  r  r  r  r  r"  r%  r   r+  r0  r4  r7  rp   r_  rb  re  rh  rk  ru  r~  r  r  r  r  r  r  r  r  r  rr   r  r=  r  r  r  r  r  r  r  r  r  propertyr  __static_attributes__rx   r$   r"   r&   r&   8   s    &+$&FF"',1,1"':&+).#_ B/	NN L4a]
>@>GV/H#T&*	* 	*T9
*IOV0 #!"Z U.Q.!OFcb$-=>()'	$!0G4	( " "r$   r&   )'r  osinspectpathdirnameabspathgetfilecurrentframe
currentdir	parentdirsysinsertrF   r   r   renumpyr<   pybullet_envs.minitaur.envsr   r   r   r   r   r   r@  rA  r   r   compiler   r   r   r  r   r   r#   objectr&   rx   r$   r"   <module>r     s   WW__RWW__W__W=Q=Q=S-TUV
GGOOBGGOOJ78	   1i      	  -  - +   G
 

#67 jj!12 ZZ
+ / 	
TWW$G"v G"r$   