
    %g                      p    d Z ddlmZmZmZmZmZ ddlZddl	m
Z
 ddlmZ ddlmZ ddlmZ  G d d	      Zy)
z1
Container for the result of running Pathfinder.
    )DictListOptionalTupleUnionN)Method)InferenceMetadata)RunSet)scan_generic_csvc                      e Zd ZdZdefdZ	 ddee   dedee	e
eej                  f      e
eej                  f   f   fdZdefd	Zdd
Zdedej                  fdZde
eej                  f   fdZde
eej                  f   fdZdej                  fdZdedej                  fdZdefdZedefd       Zedeedf   fd       Zedefd       Zddee   ddfdZy)CmdStanPathfinderzp
    Container for outputs from the Pathfinder algorithm.
    Created by :meth:`CmdStanModel.pathfinder()`.
    runsetc                    |j                   t        j                  k(  s$t        dj	                  |j                               || _        t        j                  d      | _        t        |j                  d         }t        |      | _        y)zInitialize object.zAWrong runset method, expecting Pathfinder runset, found method {} r   N)methodr   
PATHFINDER
ValueErrorformat_runsetnparray_drawsr   	csv_filesr	   	_metadata)selfr   configs      Y/var/www/dash_apps/app1/venv/lib/python3.12/site-packages/cmdstanpy/stanfit/pathfinder.py__init__zCmdStanPathfinder.__init__   sm    }} 1 11""(&"7  "$((2,!&"2"21"56*62    Nseedchainsreturnc                 d   | j                          t        j                  j                  |      }|j	                  | j
                  j                  d   |d      }|dk(  rY| j
                  |d      }| j                  j                  j                         D ci c]  \  }}||j                  |       c}}S |D cg c]V  }| j                  j                  j                         D ci c]$  \  }}||j                  | j
                  |         & c}}X c}}}S c c}}w c c}}w c c}}}w )a&  
        Create initial values for the parameters of the model
        by randomly selecting draws from the Pathfinder approximation.

        :param seed: Used for random selection, defaults to None
        :param chains: Number of initial values to return, defaults to 4
        :return: The initial values for the parameters of the model.

        If ``chains`` is 1, a dictionary is returned, otherwise a list
        of dictionaries is returned, in the format expected for the
        ``inits`` argument. of :meth:`CmdStanModel.sample`.
        r   F)sizereplace   )_assemble_drawsr   randomdefault_rngchoicer   shaper   	stan_varsitemsextract_reshape)	r   r    r!   rngidxsdrawnamevaridxs	            r   create_initszCmdStanPathfinder.create_inits#   s    	ii##D)zz$++++A.VUzKQ;;;tAw'D "&!9!9!?!?!AD# c))$//    
  &*^^%=%=%C%C%E!c #--dkk#.>?? s   D?,D++)D%D+%D+c                 b   dj                  | j                  j                  | j                  j                  j                  j                  dg             }dj                  |dj                  | j                  j                        dj                  | j                  j                              }|S )NzCmdStanPathfinder: model={}{}r   )cmdz%{}
 csv_files:
	{}
 output_files:
	{}z
	)	r   r   model_argsmethod_argscomposejoinr   stdout_files)r   reps     r   __repr__zCmdStanPathfinder.__repr__D   s    -44LLLL**221"2=
 <BBKK../KK112

 
r   c                 n   | j                   j                  dk7  ry t        | j                  j                  d   d      5 }|j                         j                  d      r!	 |j                         j                  d      r!t        j                  |t        ddd      | _         d d d        y # 1 sw Y   y xY w)N)r   r   r#   ,)dtypendmin	delimitercomments)
r   r+   openr   r   readline
startswithr   loadtxtfloat)r   fds     r   r'   z!CmdStanPathfinder._assemble_drawsQ   s    ;;$$,,((+S1 		R;;=,,S1 ;;=,,S1**DK		 		 		s   A B+?#B++B4r3   c                 ,   | j                          	 | j                  j                  |   j                  | j                        }|S # t
        $ rD t        d| ddj                  | j                  j                  j                               z         w xY w)a  
        Return a numpy.ndarray which contains the estimates for the
        for the named Stan program variable where the dimensions of the
        numpy.ndarray match the shape of the Stan program variable.

        This functionaltiy is also available via a shortcut using ``.`` -
        writing ``fit.a`` is a synonym for ``fit.stan_variable("a")``

        :param var: variable name

        See Also
        --------
        CmdStanPathfinder.stan_variables
        CmdStanMLE.stan_variable
        CmdStanMCMC.stan_variable
        CmdStanVB.stan_variable
        CmdStanGQ.stan_variable
        CmdStanLaplace.stan_variable
        zUnknown variable name: z
Available variables are z, )	r'   r   r,   r.   r   KeyErrorr   r<   keys)r   r3   outs      r   stan_variablezCmdStanPathfinder.stan_variable`   s    ( 		"nn66s;KKC J 	)# /+ +))DNN4499;<= 	s   3A ABc                 h    i }| j                   j                  D ]  }| j                  |      ||<    |S )a  
        Return a dictionary mapping Stan program variables names
        to the corresponding numpy.ndarray containing the inferred values.

        See Also
        --------
        CmdStanPathfinder.stan_variable
        CmdStanMCMC.stan_variables
        CmdStanMLE.stan_variables
        CmdStanVB.stan_variables
        CmdStanGQ.stan_variables
        CmdStanLaplace.stan_variables
        )r   r,   rS   )r   resultr2   s      r   stan_variablesz CmdStanPathfinder.stan_variables   s;     NN,, 	4D--d3F4L	4r   c                     | j                          | j                  j                  j                         D ci c]!  \  }}||j	                  | j
                        # c}}S c c}}w )aH  
        Returns a dictionary of all sampler variables, i.e., all
        output column names ending in `__`.  Assumes that all variables
        are scalar variables where column name is variable name.
        Maps each column name to a numpy.ndarray (draws x chains x 1)
        containing per-draw diagnostic values.
        )r'   r   method_varsr-   r.   r   )r   r2   r3   s      r   method_variablesz"CmdStanPathfinder.method_variables   s]     	 "^^77==?
c #%%dkk22
 	
 
s   &A"c                 :    | j                          | j                  S )z
        Return a numpy.ndarray containing the draws from the
        approximate posterior distribution. This is a 2-D array
        of shape (draws, parameters).
        )r'   r   r   s    r   drawszCmdStanPathfinder.draws   s     	{{r   attrc                     |j                  d      rt        d|       	 | j                  |      S # t        $ r}t        |j                   d}~ww xY w)z)Synonymous with ``fit.stan_variable(attr)_zUnknown variable name N)rK   AttributeErrorrS   r   args)r   r]   es      r   __getattr__zCmdStanPathfinder.__getattr__   sV    ??3 #9$!@AA	*%%d++ 	* !&&))	*s   2 	AAAc                 :    | j                          | j                  S N)r'   __dict__r[   s    r   __getstate__zCmdStanPathfinder.__getstate__   s    
 	}}r   c                     | j                   S )z
        Returns object which contains CmdStan configuration as well as
        information about the names and structure of the inference method
        and model output variables.
        )r   r[   s    r   metadatazCmdStanPathfinder.metadata   s     ~~r   .c                 4    | j                   j                  d   S )a9  
        Names of all outputs from the sampler, comprising sampler parameters
        and all components of all model parameters, transformed parameters,
        and quantities of interest. Corresponds to Stan CSV file header row,
        with names munged to array notation, e.g. `beta[1]` not `beta.1`.
        column_names)r   cmdstan_configr[   s    r   rk   zCmdStanPathfinder.column_names   s     ~~,,^<<r   c                     | j                   j                  j                  dd      dkD  xrR | j                   j                  j                  dd      dv xr( | j                   j                  j                  dd      dv S )z{
        Returns True if the draws were resampled from several Pathfinder
        approximations, False otherwise.
        	num_paths   r&   psis_resample)r&   truecalculate_lp)r   rl   getr[   s    r   is_resampledzCmdStanPathfinder.is_resampled   sx     NN))--k1=A --11/1E --11.!D		
r   dirc                 :    | j                   j                  |       y)a  
        Move output CSV files to specified directory.  If files were
        written to the temporary session directory, clean filename.
        E.g., save 'bernoulli-201912081451-1-5nm6as7u.csv' as
        'bernoulli-201912081451-1.csv'.

        :param dir: directory path

        See Also
        --------
        stanfit.RunSet.save_csvfiles
        cmdstanpy.from_csv
        N)r   save_csvfiles)r   ru   s     r   rw   zCmdStanPathfinder.save_csvfiles   s     	""3'r   )Nro   )r"   Nre   ) __name__
__module____qualname____doc__r
   r   r   intr   r   r   strr   ndarrayr5   r?   r'   rS   rV   rY   r\   rc   dictrg   propertyr	   ri   r   rk   boolrt   rw   r   r   r   r   r      sb   
3v 3 9:SM25	tDbjj)*Dbjj,AA	BB
# 
     DS"**_ 5 &
$sBJJ"7 
rzz * *

 *d  +   =eCHo = = 
d 
 
(# ($ (r   r   )r{   typingr   r   r   r   r   numpyr   cmdstanpy.cmdstan_argsr   cmdstanpy.stanfit.metadatar	   cmdstanpy.stanfit.runsetr
   cmdstanpy.utils.stancsvr   r   r   r   r   <module>r      s-    6 5  ) 8 + 4^( ^(r   