
    jJ                        d Z ddlZddlZddlZddlmZ ddlmZmZ ddl	Z
ddlmZ ddlmZ ddlmZmZ ded	ee
j        ee
j                 e
j        f         fd
Zde
j        de
j        ded	e
j        fdZded	ee         fdZded	ee
j                 fdZded	e
j        fdZde
j        ded	e
j        fdZde
j        dededed	ee
j        ee
j                 f         f
dZd	efdZdede
j        d	e
j        fdZ dede
j        de
j        d	eee
j        f         fdZ!	 d7d!e
j        ded"e
j        d#ee
j                 deded	ee
j        ee
j                 f         fd$Z"	 	 	 	 	 	 d8d*ed+e#d,e$deded-ed.ed	dfd/Z%	 	 	 	 	 d9d*ed+e#d,e$ded-ed.ed	dfd0Z&	 	 	 	 	 	 d8d*ed+e#d,e$deded-ed.ed	dfd1Z'	 	 	 d:d2e
j        d3ee
j                 ded,e$ded*ee         d4ed5         d.ed	dfd6Z(dS );a  Replay recorded arm motion.

Two source formats are supported, selected automatically based on the contents
of the episode directory:

Raw (``robot_data.npz``)
    Joint commands are streamed directly at the original ~100 Hz timing,
    resampled to ``control_hz``.  No IK is required.

Processed (``lowdim/<frame>.pkl``)
    EE-pose action sequence at ~30 fps is loaded, IK is solved at each
    keyframe, and the result is interpolated to ``control_hz``.

    The action layout stored in lowdim is::

        [l_pos(3), l_rot9(9), l_gripper(1), r_pos(3), r_rot9(9), r_gripper(1)]

    Poses are in the left-arm base frame.  The right arm target is transformed
    back to right-arm base coordinates using the bimanual calibration before IK.
    N)Path)OptionalTuple)
Kinematics)get_yam_4310_linear_xml_path)RobotControllersmooth_move_jointsep_dirreturnc                    | dz  }|                                 st          d|            t          j        |          }|d                             t          j                  }|                    d          }||                    t          j                  nd}|d                             t          j                  }|||fS )u  Load joint commands from a raw ``robot_data.npz`` file.

    Returns:
        joints_l: (N, 7) float32 — left arm commanded joint positions.
        joints_r: (N, 7) float32 or None — right arm commanded joint positions.
        timestamps: (N,) int64 nanoseconds.
    robot_data.npzzNo robot_data.npz in follower_l_joint_cmdfollower_r_joint_cmdN
timestamps)existsFileNotFoundErrornploadastypefloat32getint64)r
   npz_pathdatajoints_ljoints_r_rawjoints_rr   s          :/home/robot-lab/cameron/raiden_fork/raiden/robot/replay.py_load_raw_jointsr   #   s     ((H?? B @ @ @AAA78D*+222:>>H88233L2>2J|""2:...PTHl#**2844JXz))    jointstimestamps_ns
control_hzc                 j    |dz  t          t          d         d         z
  |z                      dz   }t          j        d         d         |          t          j         fdt           j        d                   D             d                              t          j                  S )zLResample a joint trajectory from variable-rate timestamps to ``control_hz``.    eAr      c           	      P    g | ]"}t          j        d d |f                   #S Nr   interp).0dr!   t_finet_srcs     r   
<listcomp>z$_resample_joints.<locals>.<listcomp>B   s3    PPPA65&A,	/	/PPPr    axis)	introundr   linspacestackrangeshaper   r   )r!   r"   r#   n_outr.   r/   s   `   @@r   _resample_jointsr:   8   s     CEuRy58+z9::;;a?E[q59e44F8PPPPPPv|A9O9OPPP   fRZr    c                 p   | dz  }t          |                    d                    }|s"t          |                    d                    }|st          d|           g }|D ]Q}t          |d          5 }|                    t          j        |                     ddd           n# 1 swxY w Y   R|S )z<Return all per-frame lowdim dicts from an episode directory.lowdimz??????????.pklz?????????.pklzNo lowdim .pkl files found in rbN)sortedglobr   openappendpickler   )r
   
lowdim_dir	pkl_filesframespfs         r   _load_lowdim_pklsrH   G   s    ("Jz'78899I =:???;;<<	 O M M MNNNF * *!T]] 	*aMM&+a..)))	* 	* 	* 	* 	* 	* 	* 	* 	* 	* 	* 	* 	* 	* 	*Ms   6(B**B.	1B.	c                 t    t          |           }d|d         vrdS t          j        d |D                       S )zReturn (N, 14) float32 commanded joint positions from lowdim pkls, or None.

    Layout: ``[l_arm(6), l_gripper(1), r_arm(6), r_gripper(1)]``.
    Returns None if ``action_joints`` is absent from the lowdim files.
    action_jointsr   Nc                 Z    g | ](}t          j        |d          t           j                  )S )rJ   dtyper   asarrayr   r,   rG   s     r   r0   z(_load_joint_sequence.<locals>.<listcomp>`   s.    JJJaAo&bj	9	9	9JJJr    )rH   r   r6   r
   rE   s     r   _load_joint_sequencerR   V   sJ     v&&FfQi''t8JJ6JJJ  r    c                     t          |           }d|d         vrt          d|            t          j        d |D                       S )zAReturn (N, 26) float32 array of EE poses loaded from lowdim pkls.actionr   z+'action' key missing in lowdim files under c                 Z    g | ](}t          j        |d          t           j                  )S )rT   rL   rN   rP   s     r   r0   z)_load_action_sequence.<locals>.<listcomp>j   s-    CCCqAhKrz	2	2	2CCCr    )rH   KeyErrorr   r6   rQ   s     r   _load_action_sequencerW   d   sZ    v&&Fvay  MVMMNNN8CCFCCC  r    
action_vecoffsetc                 ,   | ||dz                                 t          j                  }| |dz   |dz                                dd                               t          j                  }t          j        d          }||dddf<   ||ddddf<   |S )u   Extract a 4×4 TCP pose from a 26-D action vector.

    Args:
        action_vec: (26,) array.
        offset: 0 for left arm, 13 for right arm.
             N)r   r   float64reshapeeye)rX   rY   posrotTs        r   _pose_from_actionrd   n   s     Vfqj(
)
0
0
<
<C
VaZ&2+-
.
6
6q!
<
<
C
CBJ
O
OC
q		AAbqb!eHAbqb"1"fIHr    	joint_seq	use_right	camera_hzc                 `  
 t          |           }||z  }|dz
  |z  dz   }t          j        |t          j                  t          j        d|dz
  |          
dt          j        dt          j        f
fd} || ddddf                   }|r || dddd	f                   nd}	||	fS )
zLinearly interpolate (N, 14) joint commands from camera_hz to control_hz.

    Returns:
        traj_l: (M, 7) left arm trajectory.
        traj_r: (M, 7) right arm trajectory or None.
    r'   rL   r   colsr   c                      t          j         fdt           j        d                   D             d                              t           j                  S )Nc           	      P    g | ]"}t          j        d d |f                   #S r)   r*   )r,   r-   ri   r.   t_keyss     r   r0   z5_upsample_joints.<locals>._interp.<locals>.<listcomp>   3    QQQqRYvvtAAAqDz22QQQr    r'   r1   r   r6   r7   r8   r   r   )ri   r.   rl   s   `r   _interpz!_upsample_joints.<locals>._interp   \    xQQQQQQE$*Q-<P<PQQQ
 
 
 &

	r    N      )lenr   aranger^   r5   ndarray)re   rf   r#   rg   n_keysupsampleMro   traj_ltraj_rr.   rl   s             @@r   _upsample_jointsr{   }   s     ^^FY&H	!x!#AYvRZ000F[FQJ**Fbj RZ        WYqqq"1"u%&&F,5?WWYqqq!B$w'(((4F6>r    c                  :    t          t                      d          S )N
grasp_site)r   r    r    r   _get_kinematicsr      s    244lCCCr    kinq6c                     | j         j        j        }t          j        |t          j                  }||dd<   |                     |          dddf                             t          j                  S )z.Return (3,) EE position from 6-DOF arm joints.rL   N   r[   )	_configurationmodelnqr   zerosr^   fkr   r   )r   r   r   qs       r   
_fk_ee_xyzr      s`    			!	$B
2:&&&AAbqbE66!99RaRU""2:...r    target_poseinit_qc                    | j         j        j        }t          |          |k     r6t	          j        |t          j                  }||dt          |          <   |}|                     |d|          \  }}||dd         fS )zJIK wrapper that pads init_q to model nq and returns only the 6 arm joints.rL   Nr}   )r   r   )r   r   r   rs   r   r   r^   ik)r   r   r   r   q_fullsuccessr   s          r   _ik_6dofr      s     
		!	$B
6{{R"BJ/// &}V}\&AAJGQAbqbE>r       actionsrobot_l_initrobot_r_initc                    t          |           }||z  }t          d           t                      }|dd                                                             t
          j                  }	|9|dd                                                             t
          j                  nd}
t          d| d           t          j        |dft
          j                  }|r"t          j        |dft
          j                  nd}| dddf                             t
          j                  }|r)| dddf                             t
          j                  nd}t          |           D ]\  }}t          |d	
          }t          |||	          \  }}	|	||<   |r,|
*t          |d
          }t          |||
          \  }}
|
||<   |dz   dz  d	k    s	||dz
  k    rt          d|dz    d| dd           t                       dt
          j        dt
          j        dt
          j        fd} |||          }|r| |||          nd}|dz
  |z  dz   }t          j        |t
          j                  t          j        d	|dz
  |          dt
          j        dt
          j        ffd} ||          }| ||          nd}||fS )a3  IK all keyframes then upsample to control_hz.

    Action poses are stored per-arm in each arm's own base frame, so no
    coordinate transform is needed before IK.

    Returns:
        traj_l: (M, 7) float32 joint trajectory for left arm.
        traj_r: (M, 7) float32 or None if right arm not used.
    zSetting up i2rt IK...Nr   zSolving IK for z keyframes...rL   r\      r   )rY      r'   r   z  IK /T)endflushkeysgripsr   c                     t          j        |                     t           j                  |d d d f         gd          S )Nr'   r1   )r   concatenater   r   )r   r   s     r   _to_mujoco_7dz)_solve_ik_sequence.<locals>._to_mujoco_7d   s?    ~[[$$eAAAtGn5A
 
 
 	
r    trajc                      t          j         fdt           j        d                   D             d                              t           j                  S )Nc           	      P    g | ]"}t          j        d d |f                   #S r)   r*   )r,   r-   r.   rl   r   s     r   r0   z7_solve_ik_sequence.<locals>._interp.<locals>.<listcomp>   rm   r    r'   r1   rn   )r   r.   rl   s   `r   ro   z#_solve_ik_sequence.<locals>._interp   rp   r    )rs   printr   copyr   r   r^   r   r   	enumeraterd   r   ru   rt   r5   )r   rf   r   r   r#   rg   rv   rw   r   q_lq_rkeys_lkeys_rgrips_lgrips_riactT_tcp_l_T_tcp_rr   traj_l_keystraj_r_keysrx   ro   ry   rz   r.   rl   s                              @@r   _solve_ik_sequencer      s,   " \\FY&H	
!"""


C rr



!
!
(
(
4
4C6B6NRaR&&rz222TX  

1F
1
1
1222Xvqk444F8AKRXvqk4444tFaaaen##BJ//G3<Fgaaaen##BJ///$GG$$ B B3#C222#w,,3q	 	'B777Gc7C00FAsF1IER<1VaZ*!a%**&**DAAAA	GGG
BJ 
rz 
bj 
 
 
 

  -00K*3T8Jfg&&&PT 
 
!x!#AYvRZ000F[FQJ**Fbj RZ        W[!!F%0%<WW[!!!$F6>r    bimanual      ?   r'   Frecording_dirarmsspeedstride	visualizec           	          | dz                                   rt          | |||||           dS | dz                                   rt          | ||||||           dS t          d|            )a  Replay a recorded episode.

    Auto-detects the source format:

    - **Raw** (``robot_data.npz`` present): streams joint commands directly,
      no IK required.
    - **Processed** (``lowdim/`` present): solves IK from EE poses.

    Args:
        recording_dir: Path to a raw or converted episode directory.
        arms: ``"bimanual"`` or ``"single"`` (left only).
        speed: Playback speed multiplier.  1.0 = real-time.
        control_hz: Command rate for streaming (default 150 Hz).
        camera_hz: Frame rate of the lowdim action sequence (default 30 Hz,
            processed source only).
        stride: Subsample every N-th frame to match the shardify stride
            (default 1 = native rate, 3 = 10 Hz from 30 Hz recordings).
    r   )r   r   r#   r   r   r<   )r   r   r#   rg   r   r   z,Neither robot_data.npz nor lowdim/ found in N)r   _run_raw_replay_run_processed_replayr   )r   r   r   r#   rg   r   r   s          r   
run_replayr      s    6 	((0022 
!	
 	
 	
 	
 	
 	
 (
"	*	*	,	, 
!	
 	
 	
 	
 	
 	
  J=JJ
 
 	
r    c           	      F   t          |           \  }}}|dk    o|du}	|dk    r%|dd|         }||dd|         nd}|dd|         }t          |||          }
|	rt          |||          nd}t          |
          }|d         |d         z
  dz  }t          d| j         d           t          d	t          |           d
|dd| d           t          d| d| d           t          d|            t          d| d           t          |
||	|||           dS )zBReplay directly from raw joint commands in robot_data.npz (no IK).r   Nr'   r&   r   r%   Recording : z  (raw)zSamples   :   (.1fz s, stride=)Control Hz: z Hz  (z frames after resample)Arms      : Speed     : x)rf   r   r#   r   )r   r:   rs   r   name_stream_trajectories)r   r   r   r#   r   r   r   r   r   rf   ry   rz   n_frames
duration_ss                 r   r   r   4  s    &6m%D%D"Hh

";xt';IzzHHfH%)1)=8HHfH%%4&)
h
J??FCLVh
J???RVF6{{HR.:a=0C7J	
4+
4
4
4555	
OX
O
O:
O
O
Of
O
O
OPPP	
L
L
L8
L
L
LMMM	


   	
!
!
!
!"""     r    c                    |dk    }t          |           }|dk    r|dd|         }||z  }	t          |          }
|
|	z  }t          d| j         d           t          d|
 d|dd	|	 d
| d	           t          d| d||	z   d           t          d|            t          d| d           t	          |ddd          }|                                 	 |j        r|j                                        nt          j	        d          }|r |j
        r|j
                                        nd}t          ||o|j
        du||||	          \  }}t          |||||||           n# t          $ r t          d           Y nw xY w|                                 |                                 dS # |                                 |                                 w xY w)z>Replay from processed lowdim pkl files using IK from EE poses.r   r'   Nr   z  (processed, IK)zKeyframes : r   r   z s at z fps, stride=r   r   u    Hz  (upsample ×r   r   r   TFuse_right_followeruse_left_followeruse_right_leaderuse_left_leaderrq   )rf   r   r   r#   rg   )rf   r   r#   robotr   
Replay interrupted.)rW   rs   r   r   r   initialize_robots
follower_lget_joint_posr   r   
follower_rr   r   KeyboardInterruptmove_to_home_positionsclose)r   r   r   r#   rg   r   r   rf   r   effective_hzrv   r   r   r   r   ry   rz   s                    r   r   r   Z  s    
"I#M22Gzz((F(#&L\\F,&J	
>+
>
>
>???	\v\\*\\\\\SY\\\   

S
S
SjL6P
S
S
STTT	


   	
!
!
!
!"""$	  E 
 050@QE**,,,bhqkk 	
 #.E**,,, 	 ,@E$4D$@%%!"
 
 
 	!	
 	
 	
 	
 	
  ' ' '%&&&&&' 	$$&&& 	$$&&&s+   BE+ *F4 +FF4 FF4 4*Gry   rz   r   r   c                 
   |du }|r't          |ddd          }|                                 d}	g }
g }g }g }t          d|dz            }|rddl}ddlm} |                    d	           d
}d}|                    |          }|                    |d           d| d ||d           }t          d|            t          d| d| d| d| d	           t                      }	t          |           }	 t          d           g }|j        ?|                    t          j        t           |j        | d         fddd                     |rH|j        A|?|                    t          j        t           |j        |d         fddd                     |D ]}|                                 |D ]}|                                 t          d           d||z  z  }t)          j                    }t-          |          D ]}|||z  z   }|t)          j                    z
  }|dk    rt)          j        |           |j         |j                            | |                    |r)|j        "| |j                            ||                    |r|	||z  dk    rddl}|                    d|           |
                    t5          |	| |dd f                              |                    d!|                    |
gg d"g#                     |r^|\|                    t5          |	||dd f                              |                    d$|                    |gg d%g#                     ||j        q|                    t5          |	|j                                        dd                               |                    d&|                    |gg d'g#                     |rx|j        q|                    t5          |	|j                                        dd                               |                    d(|                    |gg d)g#                     |d*z  dk    r;t)          j                    |z
  }||z  }t          d+| d,| d-|d.d/|d.d0	d12           t          d3| d4| d5           n# t<          $ r t          d6           Y nw xY w|r*|                                 |                                  dS dS # |r)|                                 |                                  w w xY w)7zConnect to (or reuse) the robot, move to start, then stream joint trajectories.

    If *robot* is None a new ``RobotController`` is created and closed when
    done.  Pass an already-initialized controller to avoid reconnecting.
    NTFr   r'   r   r   )quoteraiden_replayi&  i&  )	grpc_port)web_portopen_browserzhttp://localhost:z?url= )safez
Rerun viewer:  zSSH tunnel:    ssh -L z:localhost:z -L z <host>
z
Moving to start position...g      @d   )time_interval_ssteps)targetargskwargszReplaying... (Ctrl-C to stop)
r   frame)sequencer   ztrajectory/commanded/left)r      r   )colorsztrajectory/commanded/right)r   x      ztrajectory/actual/left)r   P   r   ztrajectory/actual/right)r   r   r   r   z  r   z
 frames  (r   z s elapsed / z	 s total)r   )r   z
Replay complete (z frames at z Hz).r   )!r   r   maxrerunurllib.parser   init
serve_grpcserve_web_viewerr   r   rs   r   rA   	threadingThreadr	   r   startjointime	monotonicr7   sleepcommand_joint_posset_timer   logLineStrips3Dr   r   r   r   )ry   rz   rf   r   r#   r   r   r   
owns_robotrr_kin	cmd_pts_l	cmd_pts_r	act_pts_l	act_pts_r	log_everyrrr   r   r   
server_uri
viewer_urlr   threadstdt_st_startr   t_targetr   elapsedtotal_ss                                  r   r   r     s    $J "(""!	
 
 
 	!!! FIIIIAzR'((I #&&&&&&
   	]]Y]77

XEBBBTTTjr8R8R8RTT
.*..///>X > >( > >> >)2> > >	
 	
 	
 !""6{{H]-...'NN -*F1I6/2SAA      	)5&:LNN -*F1I6/2SAA      	 	AGGIIII 	 	AFFHHHH 	/000j5().""x 6	 6	AT)Ht~///Eqyy
5!!!+ 226!9=== >U-9f>P 226!9=== "V/A	MQ4F4F""""Ga000  FF1bqb5M!B!BCCC/OOYKOFF  
  !3$$Zq"1"u%F%FGGGFF4]]]OLL  
 $'3!((&vu/?/M/M/O/OPRQRPR/STT   4OOYKOOO   ! U%5%A!((&vu/?/M/M/O/OPRQRPR/STT   5OOYKOPP  
 3w!||.**W4"T/I I IX I IHI I29HI I I    	JHJJJJJKKKK ' ' '%&&&&&'  	((***KKMMMMM	 	: 	((***KKMMMM	s+   <OS T S)&T (S))T -U)r   )r   r   r   r   r'   F)r   r   r   r'   F)NNF))__doc__rB   r   r   pathlibr   typingr   r   numpyr   i2rt.robots.kinematicsr   raiden._xml_pathsr   raiden.robot.controllerr   r	   tupleru   r   r3   r:   listdictrH   rR   rW   rd   boolr{   r   r   r   r   strfloatr   r   r   r   r~   r    r   <module>r#     sB   *             " " " " " " " "     - - - - - - : : : : : : G G G G G G G G**
2:x
+RZ78* * * **J:  Z	   d tDz     (2:*>    $ 2:    "* c bj    z  	
 2:x
++,   :D D D D D/J /BJ /2: / / / /
	
"$*
68j

4
 
 
 
& J JZJJ *J 2:&	J
 J J 2:x
++,J J J J^ 1
 1
1

1
 1
 	1

 1
 1
 1
 
1
 1
 1
 1
l # ##
# # 	#
 # # 
# # # #P B BB
B B 	B
 B B B 
B B B BV %))-P PJPRZ P P 	P
 P D>P %&P P 
P P P P P Pr    