
    h3                         S SK r S SKJrJrJrJrJr  S SKrS SK	r
S SKJr  S SKJr  S SKJr  S SKJr  S SKJr  S SKJrJrJr  S S	KJrJrJr  S S
KJrJ r J!r!J"r"J#r#  \" SSS9r$ " S S\5      r%g)    N)AnyClassVarOptionalTypeVarUnion)spaces)
functional)ReplayBuffer)OffPolicyAlgorithm)
BasePolicy)GymEnvMaybeCallbackSchedule)LinearScheduleget_parameters_by_namepolyak_update)	CnnPolicy	DQNPolicy	MlpPolicyMultiInputPolicyQNetworkSelfDQNDQN)boundc            7       R  ^  \ rS rSr% Sr\\\S.r\	\
\\\   4      \S'   \\S'   \\S'   \\S'   \\S'                           S:S\\\\   4   S
\\\4   S\\\4   S\S\S\S\S\S\\\\\4   4   S\S\\\      S\\
\\4      S\S\S\S\S\S\S\S\S\\   S\\
\\4      S\S \\   S!\\R8                  \4   S"\S#S	46U 4S$ jjjrS;U 4S% jjrS;S& jrS;S' jr S<S\S\S#S	4S( jjr!   S=S)\\"RF                  \
\\"RF                  4   4   S*\\\"RF                  S+4      S,\\"RF                     S-\S#\\"RF                  \\\"RF                  S+4      4   4
S. jjr$     S>S/\%S0\S1\&S2\S3\S4\S5\S#\%4U 4S6 jjjr'S#\(\   4U 4S7 jjr)S#\\(\   \(\   4   4S8 jr*S9r+U =r,$ )?r      a  
Deep Q-Network (DQN)

Paper: https://arxiv.org/abs/1312.5602, https://www.nature.com/articles/nature14236
Default hyperparameters are taken from the Nature paper,
except for the optimizer and learning rate that were taken from Stable Baselines defaults.

:param policy: The policy model to use (MlpPolicy, CnnPolicy, ...)
:param env: The environment to learn from (if registered in Gym, can be str)
:param learning_rate: The learning rate, it can be a function
    of the current progress remaining (from 1 to 0)
:param buffer_size: size of the replay buffer
:param learning_starts: how many steps of the model to collect transitions for before learning starts
:param batch_size: Minibatch size for each gradient update
:param tau: the soft update coefficient ("Polyak update", between 0 and 1) default 1 for hard update
:param gamma: the discount factor
:param train_freq: Update the model every ``train_freq`` steps. Alternatively pass a tuple of frequency and unit
    like ``(5, "step")`` or ``(2, "episode")``.
:param gradient_steps: How many gradient steps to do after each rollout (see ``train_freq``)
    Set to ``-1`` means to do as many gradient steps as steps done in the environment
    during the rollout.
:param replay_buffer_class: Replay buffer class to use (for instance ``HerReplayBuffer``).
    If ``None``, it will be automatically selected.
:param replay_buffer_kwargs: Keyword arguments to pass to the replay buffer on creation.
:param optimize_memory_usage: Enable a memory efficient variant of the replay buffer
    at a cost of more complexity.
    See https://github.com/DLR-RM/stable-baselines3/issues/37#issuecomment-637501195
:param n_steps: When n_step > 1, uses n-step return (with the NStepReplayBuffer) when updating the Q-value network.
:param target_update_interval: update the target network every ``target_update_interval``
    environment steps.
:param exploration_fraction: fraction of entire training period over which the exploration rate is reduced
:param exploration_initial_eps: initial value of random action probability
:param exploration_final_eps: final value of random action probability
:param max_grad_norm: The maximum value for the gradient clipping
:param stats_window_size: Window size for the rollout logging, specifying the number of episodes to average
    the reported success rate, mean episode length, and mean reward over
:param tensorboard_log: the log location for tensorboard (if None, no logging)
:param policy_kwargs: additional arguments to be passed to the policy on creation. See :ref:`dqn_policies`
:param verbose: Verbosity level: 0 for no output, 1 for info messages (such as device or wrappers used), 2 for
    debug messages
:param seed: Seed for the pseudo random generators
:param device: Device (cpu, cuda, ...) on which the code should be run.
    Setting it to auto, the code will be run on the GPU if possible.
:param _init_setup_model: Whether or not to build the network at the creation of the instance
)r   r   r   policy_aliasesexploration_scheduleq_netq_net_targetpolicyNenvlearning_ratebuffer_sizelearning_starts
batch_sizetaugamma
train_freqgradient_stepsreplay_buffer_classreplay_buffer_kwargsoptimize_memory_usagen_stepstarget_update_intervalexploration_fractionexploration_initial_epsexploration_final_epsmax_grad_normstats_window_sizetensorboard_logpolicy_kwargsverboseseeddevice_init_setup_modelreturnc                    > [         TU ]  UUUUUUUUU	U
S UUUUUUUUUUS[        R                  4SS9  UU l        UU l        UU l        Xl        SU l        UU l	        SU l
        U(       a  U R                  5         g g )NFT)action_noiser+   r,   r-   r.   r6   r4   r5   r7   r9   r8   sde_supportsupported_action_spacessupport_multi_envr   g        )super__init__r   Discreter1   r2   r0   r/   _n_callsr3   exploration_rate_setup_model)selfr!   r"   r#   r$   r%   r&   r'   r(   r)   r*   r+   r,   r-   r.   r/   r0   r1   r2   r3   r4   r5   r6   r7   r8   r9   r:   	__class__s                              S/home/james-whalen/.local/lib/python3.13/site-packages/stable_baselines3/dqn/dqn.pyrB   DQN.__init__M   s    : 	 3!5"7'/+%+__$6"1 	 	
6 (?$%:"$8!&<#* #     c           	        > [         TU ]  5         U R                  5         [        U R                  S/5      U l        [        U R                  S/5      U l        [        U R                  U R                  U R                  5      U l        U R                  S:  aZ  U R                  U R                  :  a?  [        R                   " SU R                   SU R                   SU R                   S35        g g g )Nrunning_   zTThe number of environments used is greater than the target network update interval (z > zc), therefore the target network will be updated after each call to env.step() which corresponds to z steps.)rA   rF   _create_aliasesr   r   batch_norm_statsr    batch_norm_stats_targetr   r1   r2   r0   r   n_envsr/   warningswarnrG   rH   s    rI   rF   DQN._setup_model   s     6tzzJ< P'=d>O>OR\Q]'^$$2((&&%%%
! ;;?{{T888((,}C8S8S7T U,,0KK=A 9 rK   c                 p    U R                   R                  U l        U R                   R                  U l        g )N)r!   r   r    rG   s    rI   rO   DQN._create_aliases   s%    [[&&
 KK44rK   c                    U =R                   S-  sl         U R                   [        U R                  U R                  -  S5      -  S:X  ah  [	        U R
                  R                  5       U R                  R                  5       U R                  5        [	        U R                  U R                  S5        U R                  U R                  5      U l        U R                  R                  SU R                  5        g)z
Update the exploration rate and target network if needed.
This method is called in ``collect_rollouts()`` after each step in the environment.
rN   r         ?zrollout/exploration_rateN)rD   maxr/   rR   r   r   
parametersr    r'   rP   rQ   r   _current_progress_remainingrE   loggerrecordrX   s    rI   _on_stepDQN._on_step   s    
 	 ==3t::dkkI1MMQRR$**//143D3D3O3O3QSWS[S[\$//1M1MsS $ 9 9$:Z:Z [5t7L7LMrK   c                 z   U R                   R                  S5        U R                  U R                   R                  5        / n[	        U5       GH  nU R
                  R                  X R                  S9nUR                  b  UR                  OU R                  n[        R                  " 5          U R                  UR                  5      nUR                  SS9u  ptUR                  SS5      nUR                   SUR"                  -
  U-  U-  -   nS S S 5        U R%                  UR&                  5      n	[        R(                  " U	SUR*                  R-                  5       S9n	[.        R0                  " U	W5      n
UR3                  U
R5                  5       5        U R                   R                  R7                  5         U
R9                  5         [        R:                  R<                  R?                  U R                   RA                  5       U RB                  5        U R                   R                  RE                  5         GM     U =RF                  U-  sl#        U RH                  RK                  SU RF                  SS	9  U RH                  RK                  S
[L        RN                  " U5      5        g ! , (       d  f       GN= f)NT)r"   rN   )dim)rd   indexztrain/n_updatestensorboard)excludez
train/loss)(r!   set_training_mode_update_learning_rate	optimizerrangereplay_buffersample_vec_normalize_env	discountsr(   thno_gradr    next_observationsr\   reshaperewardsdonesr   observationsgatheractionslongFsmooth_l1_lossappenditem	zero_gradbackwardnnutilsclip_grad_norm_r]   r3   step
_n_updatesr_   r`   npmean)rG   r*   r&   losses_replay_datarp   next_q_valuestarget_q_valuescurrent_q_valueslosss              rI   train	DQN.train   s	   %%d+""4;;#8#89~&A,,33JD[D[3\K1<1F1F1R--X\XbXbI $ 1 1+2O2O P#0#4#4#4#;  - 5 5b! <"-"5"5[=N=N9NR[8[^k8k"k   $zz+*B*BC  "yy)9qH[H[H`H`Hbc ##$4oFDMM$))+& KK!!++-MMOEEKK''(>(>(@$BTBTUKK!!&&(? 'D 	>),doo}U<9? s   /A!J++
J:	observationstate.episode_startdeterministicc                    U(       Gd  [         R                  R                  5       U R                  :  a  U R                  R                  U5      (       a  [        U[        5      (       a3  U[        [        UR                  5       5      5         R                  S   nOUR                  S   n[         R                  " [        U5       Vs/ s H  o`R                  R                  5       PM     sn5      nXr4$ [         R                  " U R                  R                  5       5      n Xr4$ U R                  R!                  XX45      u  prXr4$ s  snf )a  
Overrides the base_class predict function to include epsilon-greedy exploration.

:param observation: the input observation
:param state: The last states (can be None, used in recurrent policies)
:param episode_start: The last masks (can be None, used in recurrent policies)
:param deterministic: Whether or not to return deterministic actions.
:return: the model's action and the next state
    (used in recurrent policies)
r   )r   randomrandrE   r!   is_vectorized_observation
isinstancedictnextiterkeysshapearrayrl   action_spacern   predict)rG   r   r   r   r   n_batchr   actions           rI   r   DQN.predict   s   " !1D4I4I!I{{44[AAk400)$tK4D4D4F/G*HIOOPQRG)//2GuW~"V~!#4#4#;#;#=~"VW
 } $"3"3":":"<= } !KK//MaMF} #Ws   	#E	rG   total_timestepscallbacklog_intervaltb_log_namereset_num_timestepsprogress_barc           	      (   > [         TU ]  UUUUUUS9$ )N)r   r   r   r   r   r   )rA   learn)rG   r   r   r   r   r   r   rH   s          rI   r   	DQN.learn  s-     w}+%# 3%  
 	
rK   c                 ,   > / [         TU ]  5       QSPSP$ )Nr   r    )rA   _excluded_save_paramsrU   s    rI   r   DQN._excluded_save_params  s     J.0J'J>JJrK   c                     SS/nU/ 4$ )Nr!   zpolicy.optimizer )rG   state_dictss     rI   _get_torch_save_paramsDQN._get_torch_save_params  s    !34BrK   )rD   rP   rQ   r2   r0   r1   rE   r   r3   r   r    r/   )g-C6?i@B d       r[   gGz?   rN   NNFrN   i'  g?r[   g?
   r   NNr   NautoT)r;   N)r   )NNF)Nr   r   TF)-__name__
__module____qualname____firstlineno____doc__r   r   r   r   r   r   strtyper   __annotations__r   r   r   r   r   floatinttupler   r
   r   boolrq   r9   rB   rF   rO   ra   r   r   ndarrayr   r   r   r   listr   r   __static_attributes____classcell__)rH   s   @rI   r   r      s   ,^ ,=NHT#tJ'7"789  #"O 15$"23<@9=&+&+&)),'+!!$)-26"(."&7C c4	?*+C  63;C  UH_-	C 
 C  C  C  C  C  #uS#X./C  C  &d<&89C  'tCH~6C   $C  C   !$!C " $#C $ "'%C &  %'C ( )C * +C , "#-C .  S#X//C 0 1C 2 sm3C 4 biin%5C 6  7C 8 
9C  C J*5N ,:C ,:S ,:4 ,:b 37.2#2::tCO'<<= bjj#o./  

+	
  
rzz8E"**c/$:;;	<B #' $("


  
 	

 
 "
 
 

 
$KtCy Kd3ic.B(C  rK   )&rS   typingr   r   r   r   r   numpyr   torchrq   	gymnasiumr   torch.nnr	   r{    stable_baselines3.common.buffersr
   -stable_baselines3.common.off_policy_algorithmr   !stable_baselines3.common.policiesr   %stable_baselines3.common.type_aliasesr   r   r   stable_baselines3.common.utilsr   r   r   stable_baselines3.dqn.policiesr   r   r   r   r   r   r   r   rK   rI   <module>r      sP     : :    $ 9 L 8 Q Q ` ` f f
)5
)L
 LrK   