
    %g%                         d Z ddlmZmZmZmZmZmZmZm	Z	 ddl
ZddlZ	 ddlZd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 d	dlmZ  G d d      Zy# e$ r dZY 8w xY w)zB
    Container for the result of running a laplace approximation.
    )AnyDictHashableListMutableMappingOptionalTupleUnionNTF)Method)build_xarray_data)scan_generic_csv   )InferenceMetadata)
CmdStanMLE)RunSetc                      e Zd Zdededd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deee   edf   dej$                  fdZ	 ddeeee   df   ddfdZedefd       Zedefd       ZdefdZdedej                  fdZdefdZedeedf   fd       Zddee   ddfdZ y)CmdStanLaplacerunsetmodereturnNc                 &   |j                   t        j                  k(  s$t        dj	                  |j                               || _        || _        t        j                  d      | _	        t        |j                  d         }t        |      | _        y)zInitialize object.z>Wrong runset method, expecting laplace runset, found method {} r   N)methodr   LAPLACE
ValueErrorformat_runset_modenparray_drawsr   	csv_filesr   	_metadata)selfr   r   configs       V/var/www/dash_apps/app1/venv/lib/python3.12/site-packages/cmdstanpy/stanfit/laplace.py__init__zCmdStanLaplace.__init__(   sr    }}.""(&"7  
"$((2,!&"2"21"56*62    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!   shapeopenr   r"   readline
startswithr   loadtxtfloat)r$   fds     r&   _assemble_drawszCmdStanLaplace._assemble_draws7   s    ;;$$,,((+S1 		R;;=,,S1 ;;=,,S1**DK		 		 		s   A B+?#B++B4varc                 ,   | 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
        --------
        CmdStanMLE.stan_variables
        CmdStanMCMC.stan_variable
        CmdStanPathfinder.stan_variable
        CmdStanVB.stan_variable
        CmdStanGQ.stan_variable
        zUnknown variable name: z
Available variables are z, )	r9   r#   	stan_varsextract_reshaper!   KeyErrorr   joinkeys)r$   r:   outs      r&   stan_variablezCmdStanLaplace.stan_variableF   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.

        :param inc_warmup: When ``True`` and the warmup draws are present in
            the MCMC sample, then the warmup draws are included.
            Default value is ``False``

        See Also
        --------
        CmdStanGQ.stan_variable
        CmdStanMCMC.stan_variables
        CmdStanMLE.stan_variables
        CmdStanPathfinder.stan_variables
        CmdStanVB.stan_variables
        )r#   r<   rB   )r$   resultnames      r&   stan_variableszCmdStanLaplace.stan_variablesg   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.
        )r9   r#   method_varsitemsr=   r!   )r$   rE   r:   s      r&   method_variableszCmdStanLaplace.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).
        )r9   r!   r$   s    r&   drawszCmdStanLaplace.draws   s     	{{r(   varsc                 L   |t        |t              r|g}n|}| j                          g }|t        j	                        D ]  }|| j
                  j                  v r|j                  |       -|| j
                  j                  v rL| j
                  j                  |   }|j                  | j                  |j                  |j                          t        d|        nt        | j                        }t        j                   | j"                  | j                        |   S )NzUnknown variable: )columns)
isinstancestrr9   dictfromkeysr#   rH   appendr<   extendcolumn_names	start_idxend_idxr   listpd	DataFramer!   )r$   rN   	vars_listcolsr:   infos         r&   draws_pdzCmdStanLaplace.draws_pd   s     $$!F	 	}}Y/ 	A$..444KK$DNN444>>33C8DKK))$..4<<H %'9#%?@@	A ))*D||DKK1B1BCDIIr(   z
xr.Datasetc           
         t         st        d      |.t        | j                  j                  j                               }nt        |t              r|g}n|}| j                          | j                  j                  }|d    d|d    d|d    |d   d}i }d	t        j                  | j                  j                  d
         i}|D ]H  }t        || j                  j                  |   | j                  ddt        j                  ddf          J t!        j"                  |||      j%                  d	d      j'                         S )z
        Returns the sampler draws as a xarray Dataset.

        :param vars: optional list of variable names.

        See Also
        --------
        CmdStanMCMC.draws_xr
        CmdStanGQ.draws_xr
        z>Package "xarray" is not installed, cannot produce draws array.Nstan_version_major.stan_version_minorstan_version_patchmodel)stan_versionrf   drawr   )coordsattrs.)XARRAY_INSTALLEDRuntimeErrorrZ   r#   r<   r@   rQ   rR   r9   cmdstan_configr   aranger!   r2   r   newaxisxrDataset	transposesqueeze)r$   rN   r]   metarj   datacoordinatesr:   s           r&   draws_xrzCmdStanLaplace.draws_xr   sA     P  <T^^55::<=Ic"II~~,,#$89:!()*!D1E,F+GI']0
 /1BIIdkk//236
  	C((-Arzz1,-	 JJtKu=Yvs#WY	
r(   c                     | j                   S )zj
        Return the maximum a posteriori estimate (mode)
        as a :class:`CmdStanMLE` object.
        )r   rL   s    r&   r   zCmdStanLaplace.mode   s     zz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#   rL   s    r&   metadatazCmdStanLaplace.metadata   s     ~~r(   c                    dj                  t        | j                        j                         D cg c]  }d|z   	 c}      dd  }dj	                  | j
                  j                  || j
                  j                  j                  j                  dg             }dj	                  |dj                  | j
                  j                        dj                  | j
                  j                              }|S c c}w )	N
	r   z&CmdStanLaplace: model={} 
mode=({})
{}r   )cmdz%{}
 csv_files:
	{}
 output_files:
	{}z
	)r?   reprr   
splitlinesr   r   rf   _argsmethod_argscomposer"   stdout_files)r$   liner   reps       r&   __repr__zCmdStanLaplace.__repr__   s    yy%)$))_%?%?%ABTTD[B

" 9??LLLL**221"2=

 <BBKK../KK112

 
 Cs   C8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)r5   AttributeErrorrB   r   args)r$   r   es      r&   __getattr__zCmdStanLaplace.__getattr__  sV    ??3 #9$!@AA	*%%d++ 	* !&&))	*s   2 	AAAc                 :    | j                          | j                  S N)r9   __dict__rL   s    r&   __getstate__zCmdStanLaplace.__getstate__  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`.
        rW   )r#   rm   rL   s    r&   rW   zCmdStanLaplace.column_names  s     ~~,,^<<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$   r   s     r&   r   zCmdStanLaplace.save_csvfiles"  s     	""3'r(   )r   Nr   )!__name__
__module____qualname__r   r   r'   r9   rR   r   ndarrayrB   r   rF   rJ   rM   r
   r   r[   r\   r`   rw   propertyr   r   rz   r   r   rS   r   r	   rW   r   r   r   r(   r&   r   r   '   s{   3v 3Z 3D 3  BS"**_ 5 ,
$sBJJ"7 
rzz  -1JDIsD()J 
J> -12
CcD()2
 
2
h j   +  #  * *

 *d  =eCHo = =(# ($ (r(   r   )__doc__typingr   r   r   r   r   r   r	   r
   numpyr   pandasr[   xarrayrp   rk   ImportErrorcmdstanpy.cmdstan_argsr   cmdstanpy.utils.data_mungingr   cmdstanpy.utils.stancsvr   rz   r   mler   r   r   r   r   r(   r&   <module>r      sf   	 	 	   * : 4 '  I( I(!  s   A AA