
    %g6!                         d Z ddlmZ ddlmZmZmZmZ ddl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 dd
lmZ  G d d      Zy)zCContainer for the results of running autodiff variational inference    )OrderedDict)DictOptionalTupleUnionN)Method)scan_variational_csv)
get_logger   )InferenceMetadata)RunSetc            	       B   e Zd ZdZdeddfdZdefdZdedee	j                  ef   fdZd	eddfd
Zedefd       Zedeedf   fd       Zedefd       Zede	j                  fd       Zedej,                  fd       Zedeee	j                  f   fd       Zedefd       Zdddedee   dee	j                  ef   fdZdddee   deeee	j                  ef   f   fdZede	j                  fd       Z edej,                  fd       Z!ddee   ddfdZ"y)	CmdStanVBzn
    Container for outputs from CmdStan variational run.
    Created by :meth:`CmdStanModel.variational`.
    runsetreturnNc                     |j                   t        j                  k(  s$t        dj	                  |j                               || _        | j                  |j                  d          y)zInitialize object.zEWrong runset method, expecting variational inference, found method {}r   N)methodr   VARIATIONAL
ValueErrorformatr   _set_variational_attrs	csv_files)selfr   s     Q/var/www/dash_apps/app1/venv/lib/python3.12/site-packages/cmdstanpy/stanfit/vb.py__init__zCmdStanVB.__init__   sV    }} 2 22""(&"7  ##F$4$4Q$78    c                 b   dj                  | j                  j                  | j                  j                  j                  j                  dg             }dj                  |dj                  | j                  j                        dj                  | j                  j                              }|S )NzCmdStanVB: model={}{}r   )cmdz#{}
 csv_file:
	{}
 output_file:
	{}z
	)	r   r   model_argsmethod_argscomposejoinr   stdout_files)r   reprs     r   __repr__zCmdStanVB.__repr__!   s    &--KKt{{00<<DDQBDO
 ;AAKK--.KK001
 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)
startswithAttributeErrorstan_variabler   args)r   r'   es      r   __getattr__zCmdStanVB.__getattr__-   sV    ??3 #9$!@AA	*%%d++ 	* !&&))	*s   2 	AAAsample_csv_0c                     t        |      }t        |      | _        |d   | _        |d   | _        |d   | _        |d   | _        y )Ncolumn_namesetavariational_meanvariational_sample)r	   r   	_metadata_column_names_eta_variational_mean_variational_sample)r   r0   metas      r   r   z CmdStanVB._set_variational_attrs7   sL    #L1*40.2>.B;	-12D-E/34H/I r   c                 ,    t        | j                        S )z
        Total number of information items returned by sampler.
        Includes approximation information and names of model parameters
        and computed quantities.
        )lenr7   r   s    r   columnszCmdStanVB.columns@   s     4%%&&r   .c                     | j                   S )z
        Names of information items returned by sampler for each draw.
        Includes approximation information and names of model parameters
        and computed quantities.
        )r7   r>   s    r   r2   zCmdStanVB.column_namesI   s     !!!r   c                     | j                   S )z3
        Step size scaling parameter 'eta'
        )r8   r>   s    r   r3   zCmdStanVB.etaR   s    
 yyr   c                     | j                   S )zB
        Returns inferred parameter means as numpy array.
        )r9   r>   s    r   variational_params_npzCmdStanVB.variational_params_npY   s    
 %%%r   c                 Z    t        j                  | j                  g| j                        S )zG
        Returns inferred parameter means as pandas DataFrame.
        r?   )pd	DataFramer9   r2   r>   s    r   variational_params_pdzCmdStanVB.variational_params_pd`   s$    
 ||T334d>O>OPPr   c                 T    t        t        | j                  | j                              S )z)Returns inferred parameter means as Dict.)r   zipr2   r9   r>   s    r   variational_params_dictz!CmdStanVB.variational_params_dictg   s"     3t00$2H2HIJJr   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.
        )r6   r>   s    r   metadatazCmdStanVB.metadatal   s     ~~r   meanvarrO   c                   |t               j                  d       d}|r| j                  }n| j                  }	 | j                  j
                  |   j                  |      }|j                  dk(  s|j                  dk(  r+|rt               j                  d       |j                         S |S # t        $ rD t        d| ddj                  | j                  j
                  j                               z         w xY w)	aw  
        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, with
        a leading axis added for the number of draws from the variational
        approximation.

        * If the variable is a scalar variable, the return array has shape
          ( draws, ).
        * If the variable is a vector, the return array has shape
          ( draws, len(vector))
        * If the variable is a matrix, the return array has shape
          ( draws, size(dim 1), size(dim 2) )
        * If the variable is an array with N dimensions, the return array
          has shape ( draws, size(dim 1), ..., size(dim N))

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

        :param var: variable name

        :param mean: if True, return the variational mean. Otherwise,
            return the variational sample.  The default behavior will
            change in a future release to return the variational sample.

        See Also
        --------
        CmdStanVB.stan_variables
        CmdStanMCMC.stan_variable
        CmdStanMLE.stan_variable
        CmdStanPathfinder.stan_variable
        CmdStanGQ.stan_variable
        CmdStanLaplace.stan_variable
        zThe default behavior of CmdStanVB.stan_variable() will change in a future release to return the variational sample, rather than the mean.
To maintain the current behavior, pass the argument mean=TrueT )r   zThe default behavior of CmdStanVB.stan_variable(mean=True) will change in a future release to always return a numpy.ndarray, even for scalar variables.zUnknown variable name: z
Available variables are z, )r
   warningr9   r:   r6   	stan_varsextract_reshapeshapeitemKeyErrorr   r#   keys)r   rP   rO   drawsouts        r   r,   zCmdStanVB.stan_variableu   s    L <L   D**E,,E	"nn66s;KKC yyB#))t"3L((0 xxz!J 	)# /+ +))DNN4499;<= 	s   A0B- +B- -AC:c                l    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
        --------
        CmdStanVB.stan_variable
        CmdStanMCMC.stan_variables
        CmdStanMLE.stan_variables
        CmdStanGQ.stan_variables
        CmdStanPathfinder.stan_variables
        CmdStanLaplace.stan_variables
        rN   )r6   rT   r,   )r   rO   resultnames       r   stan_variableszCmdStanVB.stan_variables   s@      NN,, 	?D--d->F4L	?r   c                     | j                   S )z6Returns the set of approximate posterior output draws.)r:   r>   s    r   r5   zCmdStanVB.variational_sample   s     '''r   c                 X    t        j                  | j                  | j                        S )zf
        Returns the set of approximate posterior output draws as
        a pandas DataFrame.
        rE   )rF   rG   r:   r2   r>   s    r   variational_sample_pdzCmdStanVB.variational_sample_pd   s!     ||D44d>O>OPPr   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   rc   s     r   re   zCmdStanVB.save_csvfiles   s     	!!#&r   )N)#__name__
__module____qualname____doc__r   r   strr&   r   npndarrayfloatr/   r   propertyintr?   r   r2   r3   rC   rF   rG   rH   r   rK   r   rM   r   boolr,   r_   r5   rb   re   rR   r   r   r   r      s   
9v 9$ 9
# 
* *bjj%.?(@ *J3 J4 J ' ' ' "eCHo " " U   &rzz & & Qr|| Q Q Kc2::o)> K K +   37II!)$I	rzz5 	!IX )-~	c5U*++	,* (BJJ ( ( Qr|| Q Q'# '$ 'r   r   )ri   collectionsr   typingr   r   r   r   numpyrk   pandasrF   cmdstanpy.cmdstan_argsr   cmdstanpy.utilsr	   cmdstanpy.utils.loggingr
   rM   r   r   r   r   rR   r   r   <module>rx      s2    I # / /   ) 0 . ' _' _'r   