
    %g(                         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mZ ddlmZmZ ddlmZ dd	lmZ  G d
 d      Zy)z0Container for the result of running optimization    )OrderedDict)DictOptionalTupleUnionN)MethodOptimizeArgs)
get_loggerscan_optimize_csv   )InferenceMetadata)RunSetc                      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edf   fd       Zedefd       Zede	j                  fd       Zedee	j                     fd       Zedej.                  fd       Zedeej.                     fd       Zedeee	j6                  f   fd       Zddddedededee	j                  ef   fdZ	 ddedeeee	j                  ef   f   fdZddee   ddfdZ y)
CmdStanMLEzh
    Container for outputs from CmdStan optimization.
    Created by :meth:`CmdStanModel.optimize`.
    runsetreturnNc                    |j                   t        j                  k(  s$t        dj	                  |j                               || _        |j                         | _        | j
                  j                  j                  }t        |t              sJ |j                  | _        | j                  |j                  d          y)zInitialize object.z?Wrong runset method, expecting optimize runset, found method {}r   N)methodr   OPTIMIZE
ValueErrorformatr   _check_retcodes	converged_argsmethod_args
isinstancer	   save_iterations_save_iterations_set_mle_attrs	csv_files)selfr   optimize_argss      R/var/www/dash_apps/app1/venv/lib/python3.12/site-packages/cmdstanpy/stanfit/mle.py__init__zCmdStanMLE.__init__   s    }}/""(&"7  //1))55<
 	
 
 '4&C&CF,,Q/0    c                    dj                  | j                  j                  | j                  j                  j                  j                  dg             }dj                  |dj                  | j                  j                        dj                  | j                  j                              }| j                  s"dj                  |      }dj                  |      }|S )NzCmdStanMLE: model={}{}r   )cmdz#{}
 csv_file:
	{}
 output_file:
	{}z
	z{}
 Warning: invalid estimate, z#{} optimization failed to converge.)
r   r   modelr   r   composejoinr    stdout_filesr   )r!   reprs     r#   __repr__zCmdStanMLE.__repr__'   s    '..KKt{{00<<DDQBDO
 ;AAKK--.KK001

 ~~5<<TBD8??ED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CmdStanMLE.__getattr__5   sV    ??3 #9$!@AA	*%%d++ 	* !&&))	*s   2 	AAAsample_csv_0c                     t        || j                        }t        |      | _        |d   | _        |d   | _        | j                  r|d   | _        y y )Ncolumn_namesmle	all_iters)r   r   r   	_metadata_column_names_mle
_all_iters)r!   r7   metas      r#   r   zCmdStanMLE._set_mle_attrs?   sR     t/D/DE*40.2>.B $U	  *.{*;DO !r%   .c                     | j                   S )z
        Names of estimated quantities, includes joint log probability,
        and all parameters, transformed parameters, and generated quantities.
        )r=   r!   s    r#   r9   zCmdStanMLE.column_namesG   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<   rB   s    r#   metadatazCmdStanMLE.metadataO   s     ~~r%   c                 d    | j                   st               j                  d       | j                  S )z
        Returns all final estimates from the optimizer as a numpy.ndarray
        which contains all optimizer outputs, i.e., the value for `lp__`
        as well as all Stan program variables.
        2Invalid estimate, optimization failed to converge.)r   r
   warningr>   rB   s    r#   optimized_params_npzCmdStanMLE.optimized_params_npX   s*     ~~L  D yyr%   c                     | j                   st               j                  d       y| j                  st               j                  d       | j                  S )z
        Returns all saved iterations from the optimizer and final estimate
        as a numpy.ndarray which contains all optimizer outputs, i.e.,
        the value for `lp__` as well as all Stan program variables.

        lIntermediate iterations not saved to CSV output file. Rerun the optimize method with "save_iterations=True".NrF   )r   r
   rG   r   r?   rB   s    r#   optimized_iterations_npz"CmdStanMLE.optimized_iterations_npe   sN     $$L  I ~~L  D r%   c                     | j                   j                         st               j                  d       t	        j
                  | j                  g| j                        S )z
        Returns all final estimates from the optimizer as a pandas.DataFrame
        which contains all optimizer outputs, i.e., the value for `lp__`
        as well as all Stan program variables.
        rF   columns)r   r   r
   rG   pd	DataFramer>   r9   rB   s    r#   optimized_params_pdzCmdStanMLE.optimized_params_pdy   sF     {{**,L  D ||TYYK1B1BCCr%   c                     | j                   st               j                  d       y| j                  st               j                  d       t	        j
                  | j                  | j                        S )z
        Returns all saved iterations from the optimizer and final estimate
        as a pandas.DataFrame which contains all optimizer outputs, i.e.,
        the value for `lp__` as well as all Stan program variables.

        rJ   NrF   rM   )r   r
   rG   r   rO   rP   r?   r9   rB   s    r#   optimized_iterations_pdz"CmdStanMLE.optimized_iterations_pd   s_     $$L  I ~~L  D ||DOOT5F5FGGr%   c                     | j                   j                         st               j                  d       t	        t        | j                  | j                              S )z
        Returns all estimates from the optimizer, including `lp__` as a
        Python Dict.  Only returns estimate from final iteration.
        rF   )r   r   r
   rG   r   zipr9   r>   rB   s    r#   optimized_params_dictz CmdStanMLE.optimized_params_dict   sE     {{**,L  D 3t00$))<==r%   FTinc_iterationswarnvarrX   rY   c                *   || j                   j                  vr5t        d| ddj                  | j                   j                        z         |r'|r%| j                  st               j                  d       |r3| j                  j                         st               j                  d       |r| j                  r| j                  }n| j                  }	 | j                   j                  |   j                  |      }|j                  dk(  s|j                  dk(  r)t               j                  d       |j                         S |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

        :param inc_iterations: When ``True`` and the intermediate estimates
            are included in the output, i.e., the optimizer was run with
            ``save_iterations=True``, then intermediate estimates are included.
            Default value is ``False``.

        See Also
        --------
        CmdStanMLE.stan_variables
        CmdStanMCMC.stan_variable
        CmdStanPathfinder.stan_variable
        CmdStanVB.stan_variable
        CmdStanGQ.stan_variable
        CmdStanLaplace.stan_variable
        zUnknown variable name: z
Available variables are z, rJ   rF    )r   zThe default behavior of CmdStanMLE.stan_variable() will change in a future release to always return a numpy.ndarray, even for scalar variables.)r<   	stan_varsr   r*   r   r
   rG   r   r   r?   r>   extract_reshapeshapeitemKeyErrorkeys)r!   rZ   rX   rY   dataouts         r#   r3   zCmdStanMLE.stan_variable   st   > dnn...)# /+ +-1YYt~~7O7O-PQ  N4+@+@L  I 335L  D d33??D99D	"nn66s;KKC yyB#))t"3$$@
 xxz!J 	)# /+ +))DNN4499;<= 	s   A.E E AFc                     | j                   j                         st               j                  d       i }| j                  j
                  D ]  }| j                  ||d      ||<    |S )a  
        Return a dictionary mapping Stan program variables names
        to the corresponding numpy.ndarray containing the inferred values.

        :param inc_iterations: When ``True`` and the intermediate estimates
            are included in the output, i.e., the optimizer was run with
            ``save_iterations=True``, then intermediate estimates are included.
            Default value is ``False``.


        See Also
        --------
        CmdStanMLE.stan_variable
        CmdStanMCMC.stan_variables
        CmdStanPathfinder.stan_variables
        CmdStanVB.stan_variables
        CmdStanGQ.stan_variables
        CmdStanLaplace.stan_variables
        rF   FrW   )r   r   r
   rG   r<   r]   r3   )r!   rX   resultnames       r#   stan_variableszCmdStanMLE.stan_variables   sn    , {{**,L  D NN,, 	D--^% . F4L	 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!   ri   s     r#   rk   zCmdStanMLE.save_csvfiles  s     	!!#&r%   )F)N)!__name__
__module____qualname____doc__r   r$   strr-   r   npndarrayfloatr6   r   propertyr   r9   r   rD   rH   r   rK   rO   rP   rQ   rS   r   float64rV   boolr3   rh   rk   r\   r%   r#   r   r      s   
1v 1$ 1"# * *bjj%.?(@ *<3 <4 < "eCHo " " +   
RZZ 
 
 "**)=  & 
DR\\ 
D 
D H",,)? H H& 	>tCO'< 	> 	>  %EE 	E
 E 
rzz5 	!EP &+"	c5U*++	,B'# '$ 'r%   r   )ro   collectionsr   typingr   r   r   r   numpyrq   pandasrO   cmdstanpy.cmdstan_argsr   r	   cmdstanpy.utilsr
   r   rD   r   r   r   r   r\   r%   r#   <module>r}      s/    6 # / /   7 9 ' L' L'r%   