
    ]h@^                       S r SSKrSSKrSSKrSSKrSSKrSSK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JrJrJrJrJrJrJrJrJr  SSKrSSKJr  SS	K J!r!J"r"J#r#J$r$J%r%  SS
K&J'r'J(r(J)r)J*r*J+r+J,r,J-r-J.r.  SSK/J0r0J1r1J2r2J3r3J4r4J5r5J6r6J7r7  SSK8J9r9J:r:J;r;J<r<J=r=  SSK>J?r?J@r@  SSKAJBrC  \\D\R                  S4   rF\" S\2\3\55      rG " S S 5      rHg)CmdStanModel    N)OrderedDict)ThreadPoolExecutor)StringIO)	cpu_count)
AnyCallableDictIterableListLiteralMappingOptionalTypeVarUnion)tqdm)_CMDSTAN_REFRESH_CMDSTAN_SAMPLING_CMDSTAN_WARMUP_TMPDIRcompilation)CmdStanArgsGenerateQuantitiesArgsLaplaceArgsMethodOptimizeArgsPathfinderArgsSamplerArgsVariationalArgs)	CmdStanGQCmdStanLaplaceCmdStanMCMC
CmdStanMLECmdStanPathfinder	CmdStanVBRunSetfrom_csv)cmdstan_pathcmdstan_version_before
do_command
get_loggerreturncode_msg)
temp_initstemp_single_json   )progressFitc            @       
   \ rS rSrSr       SySS.S\\   S\S\S	\S
\\	\\
4      S\\	\\
4      S\S\\\S   S4   SS4S jjjrS\4S jr\S\4S j5       r\S\4S j5       r\S\4S j5       rS\	\\4   4S jrS\	\\
4   4S jr   SzSS.S\S\\\\\   4   S\S\SS4
S jjjr\S\	\\\\\4   4   4S j5       r\S\	\\\\4   4   4S j5       r\S\4S  j5       rS\\   4S! jr     S{SS".S\S
\\	\\
4      S\\	\\
4      S\S#\S$\SS4S% jjjr                      S|S'\\\\
4   \\R>                  S4   S(\\   S)\\\\
4   \ \\R>                  S4   S*\S+\\   S,\S-\\   S.\\    S/\\    S0\\    S1\\    S2\\    S3\\    S4\\   S5\\   S6\S7\S8\S9\\   S:\S;\\    S<\S\!4.S= jjr"                             S}SS>.S'\\\\
4   \\R>                  S4   S?\\   S@\\   SA\\   S(\\\#\   S4   SB\\\#\   S4   S)\\\\
4   \ \\#\   \#\\\
4      S4   SC\\   SD\\   SE\SF\\   SG\\   SH\\\	\\
4   \#\   \#\	\\
4      S4   SI\\ \#\    S4   SJ\SK\\    SL\\   SM\\   SN\\   SO\S*\S+\\   SP\S,\SQ\S8\S9\\   S:\S;\\    SR\\   S\$4>SS jjjr%         S~SST.S'\\\\
4   \\R>                  S4   SU\\&\#\   S4   S(\\   SV\S+\\   S8\S9\\   S:\S;\\    SW\\$\#\   S4   S\'\&   4SX jjjr(                      SSSY.S'\\\\
4   \\R>                  S4   S(\\   S)\\    S*\S+\\   SP\S,\S-\\   S5\\   SZ\\   S[\\   S\\\    SJ\S]\\   S0\\    S^\\   S_\\   S7\S8\S9\\   S:\S;\\    S`\\   S\)40Sa jjjr* SSSSSSSSSSSSSSSSSSSSSSS&SSSb.S'\\\\
4   \\R>                  S4   S.\\    S/\\    S0\\    S1\\    S2\\    S3\\    S4\\   Sc\\   Sd\\   S_\\   Se\\   Sf\\   Sg\Sh\S(\\   S)\\	\\ 4   \ \\R>                  S4   S*\S+\\   S,\S8\S9\\   S:\S;\\    Si\\   S\+44Sj jjjr, SSSSk.Sl\\	\\
4   \\R>                  4   S'\\\\
4   \\R>                  S4   S<\S+\\   S\-R\                  4
Sm jjjr/   SSSSSSSSS&SSSn.
S'\\\\
4   \\R>                  S4   So\\!\\R>                  S4   S_\\   S<\S(\\   S*\S+\\   S,\S8\S9\\   S:\S;\\    Sp\\	\\
4      S\04Sq jjjr1    SSr\2Ss\SQ\S8\St\\3\\/S4      S;\\    SS4Su jjr4\5\6Rn                  SB\#\   Sv\S\\3\\/S4      4Sw j5       5       r8Sxr9g)r   I   aH  
The constructor method allows model instantiation given either the
Stan program source file or the compiled executable, or both.
This will compile the model if provided a Stan file and no executable,

:param model_name: Model name, used for output file names.
    Optional, default is the base filename of the Stan program file.
    Deprecated: In version 2.0.0, model name cannot be
    specified and will always be taken from executable.

:param stan_file: Path to Stan program file.

:param exe_file: Path to compiled executable file.  Optional, unless
    no Stan program file is specified.  If both the program file and
    the compiled executable file are specified, the base filenames
    must match, (but different directory locations are allowed).

:param force_compile: If ``True``, always compile, even if there
    is an existing executable file for this model.

:param stanc_options: Options for stanc compiler, specified as a Python
    dictionary containing Stanc3 compiler option name, value pairs.
    Optional.

:param cpp_options: Options for C++ compiler, specified as a Python
    dictionary containing C++ compiler option name, value pairs.
    Optional.

:param user_header: A path to a header file to include during C++
    compilation.
    Optional.

:param compile: Whether or not to compile the model.  Default is ``True``.
    If set to the string ``"force"``, it will always compile even if
    an existing executable is found.
    Deprecated: Use ``force_compile`` instead. The ability to instantiate
    a CmdStanModel without an executable will be removed in version 2.0.0.

NF)compile
model_name	stan_fileexe_fileforce_compilestanc_optionscpp_optionsuser_headerr4   forcereturnc                   SU l         SU l        SU l        [        R                  " UUUS9U l        U R
                  R                  5         SU l        Uc  SnO[        5       R                  S5        U(       a  SnUb]  [        5       R                  S5        UR                  5       (       d  [        S	R                  U5      5      eUR                  5       U l         Uc  Uc  [        S
5      eGO[        R                  R                  [        R                  R!                  U5      5      U l        [        R                  R#                  U R                  5      (       d$  [        SR                  U R                  5      5      e[        R                  R%                  U5      u  p['        U
5      S:  d  U
R)                  S5      (       d$  [        SR                  U R                  5      5      eU R                   (       d'  [        R                  R+                  U
5      u  U l         n	[-        U R                  S5       nUR/                  5       nSSS5        SW;   aF  [        R                  R%                  U R                  5      u  pU R
                  R1                  U5        [3        SS5      (       dL  [3        SS5      (       a;   U R5                  5       nSU;   a$  U =R                  ['        US   5      S:H  -  sl        UGbM  [        R                  R                  [        R                  R!                  U5      5      U l        [        R                  R#                  U R                  5      (       d$  [        SR                  U R                  5      5      e[        R                  R%                  U R                  5      u  n	nU R                   (       d(  [        R                  R+                  U5      u  U l         n	OUU R                   [        R                  R+                  U5      S   :w  a%  [        SR                  U R                   U5      5      e[8        R:                  " 5       S:X  a&   [=        SS/SS9  [        5       R7                  S5        U(       a9  U R                  c+  U RO                  [Q        U5      RS                  5       S:H  SS$9  ggg! , (       d  f       GN= f! [         a,  nU(       a  e [        5       R7                  U5         SnAGNSnAff = f! [>         a    [        R@                  RC                  S5      nUc,  [        R                  RE                  [G        5       SSSSS 5      n[        5       R7                  S!U5        S"RE                  [I        [J        RL                  " U/[        R@                  RC                  S#S5      R%                  S"5      -   5      5      5      [        R@                  S#'    GNqf = f)%a*  
Initialize object given constructor args.

:param model_name: Deprecated. Model name, used for output file names.
:param stan_file: Path to Stan program file.
:param exe_file: Path to compiled executable file.
:param force_compile: Whether or not to force recompilation if
    executable file already exists.
:param stanc_options: Options for stanc compiler.
:param cpp_options: Options for C++ compiler.
:param user_header: A path to a header file to include during C++
    compilation.
:param compile: Deprecated. Whether or not to compile the model.
 Nr9   r:   r;   FTzCmdStanModel(compile=...) is deprecated and will be removed in the next major version. The constructor will always ensure a model has a compiled executable.
If you wish to force recompilation, use force_compile=True instead.r<   zYCmdStanModel(model_name=...) is deprecated and will be removed in the next major version.z1Invalid value for argument model name, found "{}"zeMissing model file arguments, you must specify either Stan source or executable program file or both.zno such file {}   z.stanzinvalid stan filename {}rz#include      $   
parametersr   zZName mismatch between Stan file and compiled executable, expecting basename: {} found: {}.Windowsz	where.exeztbb.dll)fd_outzTBB already found in load pathSTAN_TBBstanlib	stan_mathtbbzAdding TBB (%s) to PATH;PATH)r<   	_internal)*_name
_stan_file	_exe_filer   CompilerOptions_compiler_optionsvalidate_fixed_paramr+   warningstrip
ValueErrorformatospathrealpath
expanduserexistssplitlenendswithsplitextopenreadadd_include_pathr)   src_infodebugplatformsystemr*   RuntimeErrorenvirongetjoinr(   listr   fromkeysr4   strlower)selfr5   r6   r7   r8   r9   r:   r;   r4   _filenamefdprogramr]   
model_infoeexenamelibtbbs                     bC:\Users\julio\OneDrive\Documentos\Trabajo\Ideas Frescas\venv\Lib\site-packages\cmdstanpy/model.py__init__CmdStanModel.__init__u   s   4 
!,!<!<'##"

 	'')!?GL   G!L  5 ##%% GNN" 
 $))+DJ M    !gg..rww/A/A)/LMDO77>>$//22 !2!9!9$//!JKK''--	2KA8}q (9(9'(B(B .55dooF  :: " 0 0 :
A doos+r'') ,W$''--8&&77= +1b117M28 8*!%J#z1))SL1I-Ja-OO) WW--bgg.@.@.JKDN77>>$..11 !2!9!9$..!IJJt~~6JAw:: " 0 0 9
A::!1!1'!:1!==$&&,fTZZ&A  ??	)EK3DA" ""#CDt~~-LLs7|113w>$LO .7o ,+ " *L&&q))*.   
3>WW\\${E5F ""#<fE%(XX#,,#Hrzz~~fb'A'G'G'LL&

6"s7   8S :S %T 
S
T'!TTC"W<;W<c                     SR                  U R                  5      nSR                  XR                  5      nSR                  XR                  5      nSR                  XR                  5      nU$ )NzCmdStanModel: name={}z{}
	 stan_file={}z{}
	 exe_file={}z{}
	 compiler_options={})r[   rQ   rR   rS   rU   )rt   reprs     r}   __repr__CmdStanModel.__repr__  sY    &--djj9$++D//B#**4@+2249O9OP    c                     U R                   $ )z
Model name used in output filename templates. Default is basename
of Stan program or exe file, unless specified in call to constructor
via argument ``model_name``.
)rQ   rt   s    r}   nameCmdStanModel.name
  s     zzr   c                     U R                   $ )zFull path to Stan program file.)rR   r   s    r}   r6   CmdStanModel.stan_file  s     r   c                     U R                   $ )zFull path to Stan exe file.)rS   r   s    r}   r7   CmdStanModel.exe_file  s     ~~r   c                    0 nU R                   c  U$  [        5       n[        [        U R                   5      S/US9  UR	                  5       R                  S5      nU HL  nUR                  S5       Vs/ s H  oUR                  5       PM     nn[        U5      S:w  a  MB  US   XS   '   MN     U$ s  snf ! [         a%  n[        5       R                  U5        Us SnA$ SnAff = f)	z
Run model with option 'info'. Parse output statements, which all
have form 'key = value' into a Dict.
If exe file compiled with CmdStan < 2.27, option 'info' isn't
available and the method returns an empty dictionary.
Ninfo)cmdrH   
=rC   r/   r   )r7   r   r*   rr   getvaluera   rY   rb   rl   r+   ri   )rt   resultr   lineslinexkv_pairrz   s           r}   exe_infoCmdStanModel.exe_info  s     "$== M	:DC.7EMMO))$/E.2jjo>o779o>w<1$%,QZqz"	 
 M	 ?
  	Lq!M	s0   A B4 3B/"B4 /B4 4
C#>CC#C#c                     U R                   b  [        SS5      (       a  0 $ [        R                  " [	        U R                   5      U R
                  5      $ )z
Run stanc with option '--info'.

If stanc is older than 2.27 or if the stan
file cannot be found, returns an empty dictionary.
rC   rD   )r6   r)   r   rh   rr   rU   r   s    r}   rh   CmdStanModel.src_info5  sB     >>!%;Ar%B%BI##C$79O9OPPr   T)backupoverwrite_filecanonicalizemax_line_lengthr   c          	          [        5       R                  S5        U R                  c  [        S5      e[        R
                  " U R                  UUUUU R                  S9  g)a  
Deprecated: Use :func:`cmdstanpy.format_stan_file()` instead.

Run stanc's auto-formatter on the model code. Either saves directly
back to the file or prints for inspection


:param overwrite_file: If True, save the updated code to disk, rather
    than printing it. By default False
:param canonicalize: Whether or not the compiler should 'canonicalize'
    the Stan model, removing things like deprecated syntax. Default is
    False. If True, all canonicalizations are run. If it is a list of
    strings, those options are passed to stanc (new in Stan 2.29)
:param max_line_length: Set the wrapping point for the formatter. The
    default value is 78, which wraps most lines by the 80th character.
:param backup: If True, create a stanfile.bak backup before
    writing to the file. Only disable this if you're sure you have other
    copies of the file or are using a version control system like Git.
z|CmdStanModel.format() is deprecated and will be removed in the next major version.
Use cmdstanpy.format_stan_file() instead.Nz"No Stan file found for this module)r   r   r   r   r9   )r+   rX   r6   rZ   r   format_stan_filer9   )rt   r   r   r   r   s        r}   r[   CmdStanModel.formatA  s[    8 	8	
 >>!ABB$$NN)+%,,	
r   c                 .    U R                   R                  $ )zOptions to stanc compilers.)rU   _stanc_optionsr   s    r}   r9   CmdStanModel.stanc_optionso  s     %%444r   c                 .    U R                   R                  $ )zOptions to C++ compilers.)rU   _cpp_optionsr   s    r}   r:   CmdStanModel.cpp_optionst       %%222r   c                 .    U R                   R                  $ )z2The user header file if it exists, otherwise empty)rU   _user_headerr   s    r}   r;   CmdStanModel.user_headery  r   r   c                 0   U R                   (       d  [        S5      eSn [        U R                   S5       nUR                  5       nSSS5        U$ ! , (       d  f       U$ = f! [         a(    [        5       R                  SU R                   5         U$ f = f)z Return Stan program as a string.Please specify source fileNrB   zCannot read file Stan file: %s)rR   rl   re   rf   IOErrorr+   error)rt   coderw   s      r}   r   CmdStanModel.code~  s    ;<<	doos+rwwy ,  ,+ 	  	L0$// 		s.   A# AA# 
A A#  A# #.BB)rP   override_optionsrP   c                R   U(       d  [        5       R                  S5        U R                  (       d  [        S5      eSnUc  Uc  Ubt  [        R
                  " UUUS9nUR                  5         XpR                  :w  a?  SnU R                  c  Xpl        O)U(       a  Xpl        OU R                  R                  U5        [        R                  " [        U R                  5      UU R                  R                  U R                  R                  U R                  R                  S9U l        g)a   
Deprecated: To compile a model, use the :class:`~cmdstanpy.CmdStanModel`
constructor or :func:`cmdstanpy.compile_stan_file()`.

Compile the given Stan program file.  Translates the Stan code to
C++, then calls the C++ compiler.

By default, this function compares the timestamps on the source and
executable files; if the executable is newer than the source file, it
will not recompile the file, unless argument ``force`` is ``True``
or unless the compiler options have been changed.

:param force: When ``True``, always compile, even if the executable file
    is newer than the source file.  Used for Stan models which have
    ``#include`` directives in order to force recompilation when changes
    are made to the included files.

:param stanc_options: Options for stanc compiler.
:param cpp_options: Options for C++ compiler.
:param user_header: A path to a header file to include during C++
    compilation.

:param override_options: When ``True``, override existing option.
    When ``False``, add/replace existing options.  Default is ``False``.
zCmdStanModel.compile() is deprecated and will be removed in the next major version. To compile a model, use the CmdStanModel() constructor or cmdstanpy.compile_stan_file().r   Nr@   T)r<   r9   r:   r;   )r+   rX   rR   rl   r   rT   rV   rU   addcompile_stan_filerr   r6   r9   r:   r;   rS   )rt   r<   r9   r:   r;   r   rP   compiler_optionss           r}   r4   CmdStanModel.compile  s   F L  O ;<<%&&*::+'' 
 %%'#9#99))1-=*%-=***../?@$6600>>..::..::
r   %Y%m%d%H%M%Sdataseedinits
output_dirsig_figssave_profile	algorithm
init_alphatol_objtol_rel_objtol_gradtol_rel_grad	tol_paramhistory_sizeitersave_iterationsrequire_convergedshow_consolerefreshtime_fmttimeoutjacobianc                    [        UUU	U
UUUUUUUS9nU(       a+  [        SSU R                  5       5      (       a  [        S5      e[	        U5       n[        USS9 n[        U R                  U R                  SUUUUUUUUS9nS	n[        US
US9nU R                  UUUUS9  SSS5        SSS5        WR                  5         UR                  5       (       dp  SR                  SR                  UR                  S	5      5      UR!                  5       5      nSU;   a!  U(       d  [#        5       R%                  U5        O['        U5      e[)        U5      nU$ ! , (       d  f       N= f! , (       d  f       N= f)a  
Run the specified CmdStan optimize algorithm to produce a
penalized maximum likelihood estimate of the model parameters.

This function validates the specified configuration, composes a call to
the CmdStan ``optimize`` method and spawns one subprocess to run the
optimizer and waits for it to run to completion.
Unspecified arguments are not included in the call to CmdStan, i.e.,
those arguments will have CmdStan default values.

The :class:`CmdStanMLE` object records the command, the return code,
and the paths to the optimize method output CSV and console files.
The output files are written either to a specified output directory
or to a temporary directory which is deleted upon session exit.

Output files are either written to a temporary directory or to the
specified output directory.  Output filenames correspond to the template
'<model_name>-<YYYYMMDDHHMM>-<chain_id>' plus the file suffix which is
either '.csv' for the CmdStan output or '.txt' for
the console messages, e.g. 'bernoulli-201912081451-1.csv'.
Output files written to the temporary directory contain an additional
8-character random string, e.g. 'bernoulli-201912081451-1-5nm6as7u.csv'.

:param data: Values for all data variables in the model, specified
    either as a dictionary with entries matching the data variables,
    or as the path of a data file in JSON or Rdump format.

:param seed: The seed for random number generator. Must be an integer
    between 0 and 2^32 - 1. If unspecified,
    :func:`numpy.random.default_rng` is used to generate a seed.

:param inits:  Specifies how the sampler initializes parameter values.
    Initialization is either uniform random on a range centered on 0,
    exactly 0, or a dictionary or file of initial values for some or
    all parameters in the model.  The default initialization behavior
    will initialize all parameter values on range [-2, 2] on the
    *unconstrained* support.  If the expected parameter values are
    too far from this range, this option may improve estimation.
    The following value types are allowed:

    * Single number, n > 0 - initialization range is [-n, n].
    * 0 - all parameters are initialized to 0.
    * dictionary - pairs parameter name : initial value.
    * string - pathname to a JSON or Rdump data file.

:param output_dir: Name of the directory to which CmdStan output
    files are written. If unspecified, output files will be written
    to a temporary directory which is deleted upon session exit.

:param sig_figs: Numerical precision used for output CSV and text files.
    Must be an integer between 1 and 18.  If unspecified, the default
    precision for the system file I/O is used; the usual value is 6.
    Introduced in CmdStan-2.25.

:param save_profile: Whether or not to profile auto-diff operations in
    labelled blocks of code.  If ``True``, CSV outputs are written to
    file '<model_name>-<YYYYMMDDHHMM>-profile-<chain_id>'.
    Introduced in CmdStan-2.26.

:param algorithm: Algorithm to use. One of: 'BFGS', 'LBFGS', 'Newton'

:param init_alpha: Line search step size for first iteration

:param tol_obj: Convergence tolerance on changes in objective
    function value

:param tol_rel_obj: Convergence tolerance on relative changes
    in objective function value

:param tol_grad: Convergence tolerance on the norm of the gradient

:param tol_rel_grad: Convergence tolerance on the relative
    norm of the gradient

:param tol_param: Convergence tolerance on changes in parameter value

:param history_size: Size of the history for LBFGS Hessian
    approximation. The value should be less than the dimensionality
    of the parameter space. 5-10 usually sufficient

:param iter: Total number of iterations

:param save_iterations: When ``True``, save intermediate approximations
    to the output CSV file.  Default is ``False``.

:param require_converged: Whether or not to raise an error if Stan
    reports that "The algorithm may not have converged".

:param show_console: If ``True``, stream CmdStan messages sent to
    stdout and stderr to the console.  Default is ``False``.

:param refresh: Specify the number of iterations cmdstan will take
    between progress messages. Default value is 100.

:param time_fmt: A format string passed to
    :meth:`~datetime.datetime.strftime` to decide the file names for
    output CSVs. Defaults to "%Y%m%d%H%M%S"

:param timeout: Duration at which optimization times out in seconds.

:param jacobian: Whether or not to use the Jacobian adjustment for
    constrained variables in optimization. By default this is false,
    meaning optimization yields the Maximum Likehood Estimate (MLE).
    Setting it to true yields the Maximum A Posteriori Estimate (MAP).

:return: CmdStanMLE object
)r   r   r   r   r   r   r   r   r   r   r   rC       zQJacobian adjustment for optimization is only supported in CmdStan 2.32 and above.Fallow_multipleN		chain_idsr   r   r   r   r   r   method_argsr   r   r/   argschainsr   r   r   z2Error during optimization! Command '{}' failed: {} zLine search failed)r   r)   r   rZ   r.   r-   r   rQ   rS   r&   _run_cmdstanraise_for_timeouts_check_retcodesr[   ro   r   get_err_msgsr+   rX   rl   r#   )rt   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   optimize_args_data_initsr   dummy_chain_idrunsetmsgmles                                  r}   optimizeCmdStanModel.optimize  s|   J %!#%%+
 .q"dmmoFF- 
 d#uj%/


%!))D Na(CF)	  %/
#0 	!!#%%''FMMA')<)<)>C $s*3D$$S)"3'' 
G/
 /
##s%   E&AE#E&
E#	E&&
E4)force_one_process_per_chainr   parallel_chainsthreads_per_chainr   iter_warmupiter_samplingsave_warmupthinmax_treedepthmetric	step_sizeadapt_engagedadapt_deltaadapt_init_phaseadapt_metric_windowadapt_step_sizefixed_paramsave_latent_dynamicsshow_progressr   c                ,   Uc  U R                   nUc  SnUS:  a  [        SR                  U5      5      eUc  [        [	        [        5       U5      S5      nOCX2:  a  [        5       R                  SUU5        UnO US:  a  [        SR                  U5      5      eUc  SnUS:  a  [        SR                  U5      5      eUnUn Sn!U R                  5       n"U"R                  S	S
5      R                  5       n#US:X  a  SnUc!  [        SSU"5      (       d  U#S:X  a	  Sn!UU -  n SnUSL aU  [        SSU"5      (       d)  Sn!UU -  n SnU#S
:X  a  [        5       R                  S5        O[        5       R                  SU5        [        U 5      [        R                  S'   Uc  [!        U5       V$s/ s H  n$U$S-   PM
     nn$O[#        U[$        5      (       a?  US:  a  [        SR                  U5      5      e[!        U5       V$s/ s H  n$U$U-   PM
     nn$OU!(       d;  ['        XfSS 5       H)  u  n$n%U$U%S-
  :w  d  M  [        SR                  U5      5      e   [)        U5      U:X  d$  [        SR                  U[)        U5      5      5      eU H#  n&U&S:  d  M  [        SR                  U&5      5      e   [+        U!(       a  SOUUU	U
UUUUUUUUUUS9n'[-        U5       n([/        XvS   S9 n)U!(       a1  [#        U[0        5      (       a  U V$s/ s H  n$U)SS  SU$ S3PM     n*n$OU)n*[3        U R4                  U R6                  UU(UU*UUUUU'US9n+U(       a  SnO7U=(       a    [8        R:                  " 5       n[        5       R                  S5        Sn,U(       aG  Sn-Uc
  U-[<        -  n-OU-U-  n-U	c
  U-[>        -  n-OU-U	-  n-Uc  [@        nU-U-  S-   n-U RC                  UU-S9n,[E        U+UUUU!S9n.[G        US 9 n/[!        U.RH                  5       H"  n$U/RK                  U RL                  U.U$UUU,US!9  M$     SSS5        U(       a  U,b  U," S"S#5        [N        RP                  " S$S%9n0U0b^  U0S   S:  aU  [!        U5       HF  n$[R        RT                  RW                  S&U0S   -  5        [R        RT                  RY                  5         MH     [R        RT                  RW                  S'5        [        5       R                  S(5        U.R[                  5         [        5       R]                  S)[_        U.5      5        [a        U.Rb                  S   S*5       n1U1Re                  5       n2[        5       R]                  S+U25        S,U2;   a1  [        5       R]                  S-5        SU'l3        U'U.Rh                  l5        SSS5        U.Rm                  5       n3U.Ro                  5       (       d(  S.U3 S/[_        U.5       3n4U(       d  U4S0-  n4[q        U45      eU3(       a*  S1U3 3n4U(       d  U4S0-  n4[        5       R                  U45        [s        U.5      n5SSS5        SSS5        W5$ s  sn$f s  sn$f s  sn$f ! , (       d  f       GN/= f! , (       d  f       N= f! , (       d  f       NJ= f! , (       d  f       W5$ = f)2a$  
Run or more chains of the NUTS-HMC sampler to produce a set of draws
from the posterior distribution of a model conditioned on some data.

This function validates the specified configuration, composes a call to
the CmdStan ``sample`` method and spawns one subprocess per chain to run
the sampler and waits for all chains to run to completion.
Unspecified arguments are not included in the call to CmdStan, i.e.,
those arguments will have CmdStan default values.

For each chain, the :class:`CmdStanMCMC` object records the command,
the return code, the sampler output file paths, and the corresponding
console outputs, if any. The output files are written either to a
specified output directory or to a temporary directory which is deleted
upon session exit.

Output files are either written to a temporary directory or to the
specified output directory.  Ouput filenames correspond to the template
'<model_name>-<YYYYMMDDHHMM>-<chain_id>' plus the file suffix which is
either '.csv' for the CmdStan output or '.txt' for
the console messages, e.g. 'bernoulli-201912081451-1.csv'.
Output files written to the temporary directory contain an additional
8-character random string, e.g. 'bernoulli-201912081451-1-5nm6as7u.csv'.

:param data: Values for all data variables in the model, specified
    either as a dictionary with entries matching the data variables,
    or as the path of a data file in JSON or Rdump format.

:param chains: Number of sampler chains, must be a positive integer.

:param parallel_chains: Number of processes to run in parallel. Must be
    a positive integer.  Defaults to :func:`multiprocessing.cpu_count`,
    i.e., it will only run as many chains in parallel as there are
    cores on the machine.   Note that CmdStan 2.28 and higher can run
    all chains in parallel providing that the model was compiled with
    threading support.

:param threads_per_chain: The number of threads to use in parallelized
    sections within an MCMC chain (e.g., when using the Stan functions
    ``reduce_sum()``  or ``map_rect()``).  This will only have an effect
    if the model was compiled with threading support.  For such models,
    CmdStan version 2.28 and higher will run all chains in parallel
    from within a single process.  The total number of threads used
    will be ``parallel_chains * threads_per_chain``, where the default
    value for parallel_chains is the number of cpus, not chains.

:param seed: The seed for random number generator. Must be an integer
    between 0 and 2^32 - 1. If unspecified,
    :func:`numpy.random.default_rng`
    is used to generate a seed which will be used for all chains.
    When the same seed is used across all chains,
    the chain-id is used to advance the RNG to avoid dependent samples.

:param chain_ids: The offset for the random number generator, either
    an integer or a list of unique per-chain offsets.  If unspecified,
    chain ids are numbered sequentially starting from 1.

:param inits: Specifies how the sampler initializes parameter values.
    Initialization is either uniform random on a range centered on 0,
    exactly 0, or a dictionary or file of initial values for some or all
    parameters in the model.  The default initialization behavior will
    initialize all parameter values on range [-2, 2] on the
    *unconstrained* support.  If the expected parameter values are
    too far from this range, this option may improve adaptation.
    The following value types are allowed:

    * Single number n > 0 - initialization range is [-n, n].
    * 0 - all parameters are initialized to 0.
    * dictionary - pairs parameter name : initial value.
    * string - pathname to a JSON or Rdump data file.
    * list of strings - per-chain pathname to data file.
    * list of dictionaries - per-chain initial values.

:param iter_warmup: Number of warmup iterations for each chain.

:param iter_sampling: Number of draws from the posterior for each
    chain.

:param save_warmup: When ``True``, sampler saves warmup draws as part of
    the Stan CSV output file.

:param thin: Period between recorded iterations.  Default is 1, i.e.,
     all iterations are recorded.

:param max_treedepth: Maximum depth of trees evaluated by NUTS sampler
    per iteration.

:param metric: Specification of the mass matrix, either as a
    vector consisting of the diagonal elements of the covariance
    matrix ('diag' or 'diag_e') or the full covariance matrix
    ('dense' or 'dense_e').

    If the value of the metric argument is a string other than
    'diag', 'diag_e', 'dense', or 'dense_e', it must be
    a valid filepath to a JSON or Rdump file which contains an entry
    'inv_metric' whose value is either the diagonal vector or
    the full covariance matrix.

    If the value of the metric argument is a list of paths, its
    length must match the number of chains and all paths must be
    unique.

    If the value of the metric argument is a Python dict object, it
    must contain an entry 'inv_metric' which specifies either the
    diagnoal or dense matrix.

    If the value of the metric argument is a list of Python dicts,
    its length must match the number of chains and all dicts must
    containan entry 'inv_metric' and all 'inv_metric' entries must
    have the same shape.

:param step_size: Initial step size for HMC sampler.  The value is
    either a single number or a list of numbers which will be used
    as the global or per-chain initial step size, respectively.
    The length of the list of step sizes must match the number of
    chains.

:param adapt_engaged: When ``True``, adapt step size and metric.

:param adapt_delta: Adaptation target Metropolis acceptance rate.
    The default value is 0.8.  Increasing this value, which must be
    strictly less than 1, causes adaptation to use smaller step sizes
    which improves the effective sample size, but may increase the time
    per iteration.

:param adapt_init_phase: Iterations for initial phase of adaptation
    during which step size is adjusted so that the chain converges
    towards the typical set.

:param adapt_metric_window: The second phase of adaptation tunes
    the metric and step size in a series of intervals.  This parameter
    specifies the number of iterations used for the first tuning
    interval; window size increases for each subsequent interval.

:param adapt_step_size: Number of iterations given over to adjusting
    the step size given the tuned metric during the final phase of
    adaptation.

:param fixed_param: When ``True``, call CmdStan with argument
    ``algorithm=fixed_param`` which runs the sampler without
    updating the Markov Chain, thus the values of all parameters and
    transformed parameters are constant across all draws and
    only those values in the generated quantities block that are
    produced by RNG functions may change.  This provides
    a way to use Stan programs to generate simulated data via the
    generated quantities block.  Default value is ``False``.

:param output_dir: Name of the directory to which CmdStan output
    files are written. If unspecified, output files will be written
    to a temporary directory which is deleted upon session exit.

:param sig_figs: Numerical precision used for output CSV and text files.
    Must be an integer between 1 and 18.  If unspecified, the default
    precision for the system file I/O is used; the usual value is 6.
    Introduced in CmdStan-2.25.

:param save_latent_dynamics: Whether or not to output the position and
    momentum information for the model parameters (unconstrained).
    If ``True``, CSV outputs are written to an output file
    '<model_name>-<YYYYMMDDHHMM>-diagnostic-<chain_id>',
    e.g. 'bernoulli-201912081451-diagnostic-1.csv', see
    https://mc-stan.org/docs/cmdstan-guide/stan_csv.html,
    section "Diagnostic CSV output file" for details.

:param save_profile: Whether or not to profile auto-diff operations in
    labelled blocks of code.  If ``True``, CSV outputs are written to
    file '<model_name>-<YYYYMMDDHHMM>-profile-<chain_id>'.
    Introduced in CmdStan-2.26, see
    https://mc-stan.org/docs/cmdstan-guide/stan_csv.html,
    section "Profiling CSV output file" for details.

:param show_progress: If ``True``, display progress bar to track
    progress for warmup and sampling iterations.  Default is ``True``,
    unless package tqdm progress bar encounter errors.

:param show_console: If ``True``, stream CmdStan messages sent to stdout
    and stderr to the console.  Default is ``False``.

:param refresh: Specify the number of iterations CmdStan will take
    between progress messages. Default value is 100.

:param time_fmt: A format string passed to
    :meth:`~datetime.datetime.strftime` to decide the file names for
    output CSVs. Defaults to "%Y%m%d%H%M%S"

:param force_one_process_per_chain: If ``True``, run multiple chains in
    distinct processes regardless of model ability to run parallel
    chains (CmdStan 2.28+ feature). If ``False``, always run multiple
    chains in one process (does not check that this is valid).

    If None (Default): Check that CmdStan version is >=2.28, and that
    model was compiled with STAN_THREADS=True, and utilize the
    parallel chain functionality if those conditions are met.

:param timeout: Duration at which sampling times out in seconds.

:return: CmdStanMCMC object
N   r/   z2Chains must be a positive integer value, found {}.zSRequested %u parallel_chains but only %u required, will run all chains in parallel.z>Argument parallel_chains must be a positive integer, found {}.z@Argument threads_per_chain must be a positive integer, found {}.TSTAN_THREADSfalserC      trueFzStan program not compiled for threading, process will run chains sequentially. For multi-chain parallelization, recompile the model with argument "cpp_options={'STAN_THREADS':'TRUE'}.zInstalled version of CmdStan cannot multi-process chains, will run %d processes. Run "install_cmdstan" to upgrade to latest version.STAN_NUM_THREADSz4Chain_id must be a positive integer value, found {}.z8chain_ids must be sequential list of integers, found {}.zVChain_ids must correspond to number of chains specified {} chains, found {} chain_ids.r   z8Chain_id must be a non-negative integer value, found {}.)
num_chainsr   r   r   r   r   r   r   r   r   r   r   r   r   )idru   z.json
r   r   r   r   r   r   r   r   r   r   zCmdStan start processing)r   total)r   r   r   r   one_process_per_chainmax_workers)r   idxr   r   progress_hookr   Done)P      )fallbackr   r   zCmdStan done processing.z	runset
%srB   zChain 1 console:
%szrunning fixed_param samplerzDetected fixed param modelzError during sampling:

Command and output files:
K
Consider re-running with show_console=True if the above output is unclear!z!Non-fatal error during sampling:
):rW   rZ   r[   maxminr   r+   r   r   rn   rs   r)   rX   rr   r\   rm   range
isinstanceintziprb   r   r.   r-   rp   r   rQ   rS   progbarallow_show_progressr   r   r   _wrap_sampler_progress_hookr&   r   	num_procssubmitr   shutilget_terminal_sizesysstdoutwriteflushr   ri   r   re   stdout_filesrf   r   _argsr   r   r   rl   r"   )6rt   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   parallel_procsnum_threadsr  	info_dictstan_threadsijchain_idsampler_argsr   r   cmdstan_initsr   r  
iter_totalr   executor	term_sizerw   console_msgserrorsr   mcmcs6                                                         r}   sampleCmdStanModel.sample  s   b ++K>FA:DKK  "!#ik6":A>O%L3	 %Oq "F?3  $ !q "F#45 
 )' $MMO	 }}^W=CCEQ;*.' (/*1b)<<&$)!)K7KN&%/)!R;;(-%-;!"7*L((D $$J 	 *-[)9

%&(-f61QI6I)S))q=$%%+VI%6  5:&MBMqQ]M	B	, #I} =1A:",!--3VI->#  !> 9~/$DDJF"C	NE  !*H!|())/)9  !* #1qv#'#''#- 3+#
" d#ujl/
$E4)@)@7@!7@!vcr{m1QCu-y  ! !'

##%!%9)(D  % - O'2M2M2O!!"<=BFM
&/1J+-J ("33J-/J?.G'72Q6
 $ @ @'$ !A ! #!&;F $?8v//0AOO))%&3%1&3 ' $  1 @ !:fb) /5.F.F%/	 (Yq\A-="6]

((y|);<

((* + 

  &!!"<=%%'L|T&\: f))!,c2b!wwy""#9<H0L@L&&'CD/3L,/;FLL, 3 ((*F))++.vh 7226v,A  $4C #3'':6(C#4C $$S)v&Dm/
#n O 7 CZ!j @?> 32s/
 /
##n sv   'Y;YZ"!Y3YCY3,<Y(DY3<A"Y"BY3/ZY3
YY3"
Y0,Y33
Z	=Z
Z)mcmc_sampleprevious_fitgq_output_dirr7  c
                &   U
b-  U(       a  [        S5      e[        5       R                  S5        U
n[        U[        [
        [        45      (       a  UnUR                  R                  nOI[        U[        5      (       a)  [        U5      S:  a  [        S5      e Un[        U5      nO[        S5      e[        U[        5      (       aC  UR                  nUR                   nUR"                  (       a  [        5       R                  S	5        O[        U[
        5      (       aL  [%        S
S5      (       a  ['        S5      eSnS/nUR(                  (       a  [        5       R                  S5        O![%        S
S5      (       a  ['        S5      eSnS/n[+        US9nUR-                  U5        [/        U5       n[1        U R2                  U R4                  UUUUUUUS9	n[7        UXUS9n[9        5       n[;        [=        US
-
  U5      S5      n[?        US9 n[A        U5       H   nURC                  U RD                  UUUU	S9  M"     SSS5        URG                  5         URI                  5       nU(       a(  SU S[        U5       3nU(       d  US-  n['        U5      e[K        UUS9nSSS5        U$ ! [          a9  n[        SR                  [        U5      SR                  U5      5      5      UeSnAff = f! , (       d  f       N= f! , (       d  f       W$ = f)a  
Run CmdStan's generate_quantities method which runs the generated
quantities block of a model given an existing sample.

This function takes one of the Stan fit objects
:class:`CmdStanMCMC`, :class:`CmdStanMLE`, or :class:`CmdStanVB`
and the data required for the model and calls to the CmdStan
``generate_quantities`` method to generate additional quantities of
interest.

The :class:`CmdStanGQ` object records the command, the return code,
and the paths to the generate method output CSV and console files.
The output files are written either to a specified output directory
or to a temporary directory which is deleted upon session exit.

Output files are either written to a temporary directory or to the
specified output directory.  Output filenames correspond to the template
'<model_name>-<YYYYMMDDHHMM>-<chain_id>' plus the file suffix which is
either '.csv' for the CmdStan output or '.txt' for
the console messages, e.g. 'bernoulli-201912081451-1.csv'.
Output files written to the temporary directory contain an additional
8-character random string, e.g. 'bernoulli-201912081451-1-5nm6as7u.csv'.

:param data: Values for all data variables in the model, specified
    either as a dictionary with entries matching the data variables,
    or as the path of a data file in JSON or Rdump format.

:param previous_fit: Can be either a :class:`CmdStanMCMC`,
    :class:`CmdStanMLE`, or :class:`CmdStanVB` or a list of
    stan-csv files generated by fitting the model to the data
    using any Stan interface.

:param seed: The seed for random number generator. Must be an integer
    between 0 and 2^32 - 1. If unspecified,
    :func:`numpy.random.default_rng`
    is used to generate a seed which will be used for all chains.
    *NOTE: Specifying the seed will guarantee the same result for
    multiple invocations of this method with the same inputs.  However
    this will not reproduce results from the sample method given
    the same inputs because the RNG will be in a different state.*

:param gq_output_dir:  Name of the directory in which the CmdStan output
    files are saved.  If unspecified, files will be written to a
    temporary directory which is deleted upon session exit.

:param sig_figs: Numerical precision used for output CSV and text files.
    Must be an integer between 1 and 18.  If unspecified, the default
    precision for the system file I/O is used; the usual value is 6.
    Introduced in CmdStan-2.25.

:param show_console: If ``True``, stream CmdStan messages sent to
    stdout and stderr to the console.  Default is ``False``.

:param refresh: Specify the number of iterations CmdStan will take
    between progress messages. Default value is 100.

:param time_fmt: A format string passed to
    :meth:`~datetime.datetime.strftime` to decide the file names for
    output CSVs. Defaults to "%Y%m%d%H%M%S"

:param timeout: Duration at which generation times out in seconds.

:return: CmdStanGQ object
NzGCannot supply both 'previous_fit' and deprecated argument 'mcmc_sample'zKArgument name `mcmc_sample` is deprecated, please rename to `previous_fit`.r/   z2Expecting list of Stan CSV files, found empty listzKInvalid sample from Stan CSV files, error:
	{}
	 while processing files
	{}z
	zTPrevious fit must be either CmdStanPy fit object or list of paths to Stan CSV files.zdSample contains saved warmup draws which will be used to generate additional quantities of interest.rC      zKMethod generate_quantities was not available for non-HMC until CmdStan 2.31z_MLE contains saved iterations which will be used to generate additional quantities of interest.)	csv_files)r   r   r   r   r   r   r   )r   r   r   r   r  r   z"Error during generate_quantities:
r  r  )r   r8  )&rZ   r+   rX   r  r"   r#   r%   r   r<  rp   rb   r'   r[   r   ro   r   r   _save_warmupr)   rl   _save_iterationsr   rV   r.   r   rQ   rS   r&   r   r  r  r   r  r  r   r   r   r    )rt   r   r8  r   r9  r   r   r   r   r   r7  
fit_objectfit_csv_filesrz   r   r   generate_quantities_argsr   r   r   parallel_chains_availr   r0  r*  r3  r   
quantitiess                              r}   generate_quantities CmdStanModel.generate_quantities}  s8   ^ " 8  L  ,
 'Ll[*i$HII%J(//99Md++< 1$ H 	 ,%m4
 7  j+..&&F",,I&&$$E 
J//%a,,"?  FI**$$E
 &a,,"?  FI#9#$
  	!))&1d#u

#(!4
D &F %.K!!#&;a&?"H!LO#@HvAOO))%1 ' $  ' A %%'((*F9& B226v,A  $4C #3''"&zJJS $T q   44:FQ\!:5
 @ A@% $#T s>   J* 2AL0K0?A!L*
K-44K((K-0
K>	:L
L)output_samplesgrad_sampleselbo_sampleseta
adapt_iter	eval_elbodrawsrF  c                   Ub)  Ub  [        S5      e[        5       R                  S5        Un[        UU	U
UUUUUUUS9
n[	        U5       n[        USS9 n[        U R                  U R                  SUUUUUUUUUS9nSn[        US	US
9nU R                  UUUUS9  SSS5        SSS5        WR                  5         UR                  W   n[        R                  " S[        R                  5      n[!        US5       n U R#                  5       n!SSS5        [%        [        R&                  " UW!5      5      S:  a-  U(       a  [)        S5      e[        5       R                  SSS5        UR+                  5       (       d  UR                  U   n[!        US5       n U R#                  5       n!SSS5        [        R                  " S[        R                  5      n[%        [        R&                  " UU!5      5      S:  a  U
c  Sn
SR-                  U
5      n"OSR-                  UR/                  5       5      n"[)        U"5      e[1        U5      n#U#$ ! , (       d  f       GN= f! , (       d  f       GN= f! , (       d  f       GNd= f! , (       d  f       N= f)a  
Run CmdStan's variational inference algorithm to approximate
the posterior distribution of the model conditioned on the data.

This function validates the specified configuration, composes a call to
the CmdStan ``variational`` method and spawns one subprocess to run the
optimizer and waits for it to run to completion.
Unspecified arguments are not included in the call to CmdStan, i.e.,
those arguments will have CmdStan default values.

The :class:`CmdStanVB` object records the command, the return code,
and the paths to the variational method output CSV and console files.
The output files are written either to a specified output directory
or to a temporary directory which is deleted upon session exit.

Output files are either written to a temporary directory or to the
specified output directory.  Output filenames correspond to the template
'<model_name>-<YYYYMMDDHHMM>-<chain_id>' plus the file suffix which is
either '.csv' for the CmdStan output or '.txt' for
the console messages, e.g. 'bernoulli-201912081451-1.csv'.
Output files written to the temporary directory contain an additional
8-character random string, e.g. 'bernoulli-201912081451-1-5nm6as7u.csv'.

:param data: Values for all data variables in the model, specified
    either as a dictionary with entries matching the data variables,
    or as the path of a data file in JSON or Rdump format.

:param seed: The seed for random number generator. Must be an integer
    between 0 and 2^32 - 1. If unspecified,
    :func:`numpy.random.default_rng`
    is used to generate a seed which will be used for all chains.

:param inits:  Specifies how the sampler initializes parameter values.
    Initialization is uniform random on a range centered on 0 with
    default range of 2. Specifying a single number n > 0 changes
    the initialization range to [-n, n].

:param output_dir: Name of the directory to which CmdStan output
    files are written. If unspecified, output files will be written
    to a temporary directory which is deleted upon session exit.

:param sig_figs: Numerical precision used for output CSV and text files.
    Must be an integer between 1 and 18.  If unspecified, the default
    precision for the system file I/O is used; the usual value is 6.
    Introduced in CmdStan-2.25.

:param save_latent_dynamics: Whether or not to save diagnostics.
    If ``True``, CSV outputs are written to output file
    '<model_name>-<YYYYMMDDHHMM>-diagnostic-<chain_id>',
    e.g. 'bernoulli-201912081451-diagnostic-1.csv'.

:param save_profile: Whether or not to profile auto-diff operations in
    labelled blocks of code.  If ``True``, CSV outputs are written to
    file '<model_name>-<YYYYMMDDHHMM>-profile-<chain_id>'.
    Introduced in CmdStan-2.26.

:param algorithm: Algorithm to use. One of: 'meanfield', 'fullrank'.

:param iter: Maximum number of ADVI iterations.

:param grad_samples: Number of MC draws for computing the gradient.
    Default is 10.  If problems arise, try doubling current value.

:param elbo_samples: Number of MC draws for estimate of ELBO.

:param eta: Step size scaling parameter.

:param adapt_engaged: Whether eta adaptation is engaged.

:param adapt_iter: Number of iterations for eta adaptation.

:param tol_rel_obj: Relative tolerance parameter for convergence.

:param eval_elbo: Number of iterations between ELBO evaluations.

:param draws: Number of approximate posterior output draws
    to save.

:param require_converged: Whether or not to raise an error if Stan
    reports that "The algorithm may not have converged".

:param show_console: If ``True``, stream CmdStan messages sent to
    stdout and stderr to the console.  Default is ``False``.

:param refresh: Specify the number of iterations CmdStan will take
    between progress messages. Default value is 100.

:param time_fmt: A format string passed to
    :meth:`~datetime.datetime.strftime` to decide the file names for
    output CSVs. Defaults to "%Y%m%d%H%M%S"

:param timeout: Duration at which variational Bayesian inference times
    out in seconds.

:return: CmdStanVB object
NzCCannot supply both 'draws' and deprecated argument 'output_samples'zGArgument name `output_samples` is deprecated, please rename to `draws`.)
r   r   rG  rH  rI  r   rJ  r   rK  rF  Fr   r  r   r/   r   r   z%The algorithm may not have converged.rB   zsThe algorithm may not have converged.
If you would like to inspect the output, re-call with require_converged=Falsez%s
%sz4Proceeding because require_converged is set to Falsez/stan::variational::normal_meanfield::calc_grad:
   ztVariational algorithm gradient calculation failed. Double the value of argument "grad_samples", current value is {}.z&Error during variational inference: {})rZ   r+   rX   r   r.   r-   r   rQ   rS   r&   r   r   r$  rer4   Mre   rf   rb   findallrl   r   r[   r   r%   )$rt   r   r   r   r   r   r   r   r   r   rG  rH  rI  r   rJ  r   rK  rL  r   r   r   r   r   rF  variational_argsr   r   r   r   r   transcript_filepat
transcriptcontentsr   vbs$                                       r}   variationalCmdStanModel.variational>  s~   x %  '  L  %
 #E*%%'!# 
 d#uj%/


%!%9),D Na(CF)	  )/
#4 	!!# !--n=jjA244H/3':!(H (rzz#x()A- ";  L  7F
 %%''$11.AOos+z%??, ,**BBDDC 2::c8,-1'#%L++16,+?  ?EE'') s##v	I/
 /
##> ('" ,+s=   
IAII=I+I=
I	I
I(+
I:=
J)r   r   r   r   r   r   r   	num_pathsmax_lbfgs_itersrL  num_single_drawsnum_elbo_drawspsis_resamplecalculate_lpr   r   r   r   r   r   r   r   r   r'  rZ  r[  r\  r]  r^  r_  r'  c                   U R                  5       n[        SSU5      (       a  [        S5      eU(       a  U(       d  [        SSU5      (       a  [        S5      eUbQ  US:w  a/  UR                  SS	5      R	                  5       S
:w  a  [        S5      e[        U5      [        R                  S'   U	S:X  a  Uc  UnUb  X:w  a  [        S5      e[        UUUUUUUUU	U
UUUUS9n[        U5       n[        U5       n[        U R                  U R                  SUUUUUUUUS9nSn[        USUS9n U R                  U UUUS9  SSS5        SSS5        W R!                  5         U R#                  5       (       dI  SR%                  SR'                  U R)                  S5      5      U R+                  5       5      n![-        U!5      e[/        U 5      $ ! , (       d  f       N= f! , (       d  f       N= f)uc  
Run CmdStan's Pathfinder variational inference algorithm.

:param data: Values for all data variables in the model, specified
    either as a dictionary with entries matching the data variables,
    or as the path of a data file in JSON or Rdump format.

:param num_paths: Number of single-path Pathfinders to run.
    Default is 4, when the number of paths is 1 then no importance
    sampling is done.

:param draws: Number of approximate draws to return.

:param num_single_draws: Number of draws each single-pathfinder will
    draw.
    If ``num_paths`` is 1, only one of this and ``draws`` should be
    used.

:param max_lbfgs_iters: Maximum number of L-BFGS iterations.

:param num_elbo_draws: Number of Monte Carlo draws to evaluate ELBO.

:param psis_resample: Whether or not to use Pareto Smoothed Importance
    Sampling on the result of the individual Pathfinders. If False, the
    result contains the draws from each path.

:param calculate_lp: Whether or not to calculate the log probability
    for approximate draws. If False, this also implies that
    ``psis_resample`` will be set to False.

:param seed: The seed for random number generator. Must be an integer
    between 0 and 2^32 - 1. If unspecified,
    :func:`numpy.random.default_rng` is used to generate a seed.

:param inits: Specifies how the algorithm initializes parameter values.
    Initialization is either uniform random on a range centered on 0,
    exactly 0, or a dictionary or file of initial values for some or all
    parameters in the model.  The default initialization behavior will
    initialize all parameter values on range [-2, 2] on the
    *unconstrained* support.  If the expected parameter values are
    too far from this range, this option may improve adaptation.
    The following value types are allowed:

    * Single number n > 0 - initialization range is [-n, n].
    * 0 - all parameters are initialized to 0.
    * dictionary - pairs parameter name : initial value.
    * string - pathname to a JSON or Rdump data file.
    * list of strings - per-path pathname to data file.
    * list of dictionaries - per-path initial values.

:param init_alpha: For internal L-BFGS: Line search step size for
    first iteration

:param tol_obj: For internal L-BFGS: Convergence tolerance on changes
    in objective function value

:param tol_rel_obj: For internal L-BFGS: Convergence tolerance on
    relative changes in objective function value

:param tol_grad: For internal L-BFGS: Convergence tolerance on the
    norm of the gradient

:param tol_rel_grad: For internal L-BFGS: Convergence tolerance on
    the relative norm of the gradient

:param tol_param: For internal L-BFGS: Convergence tolerance on changes
    in parameter value

:param history_size: For internal L-BFGS: Size of the history for LBFGS
    Hessian approximation. The value should be less than the
    dimensionality of the parameter space. 5-10 is usually sufficient

:param output_dir: Name of the directory to which CmdStan output
    files are written. If unspecified, output files will be written
    to a temporary directory which is deleted upon session exit.

:param sig_figs: Numerical precision used for output CSV and text files.
    Must be an integer between 1 and 18.  If unspecified, the default
    precision for the system file I/O is used; the usual value is 6.
    Introduced in CmdStan-2.25.

:param save_profile: Whether or not to profile auto-diff operations in
    labelled blocks of code.  If ``True``, CSV outputs are written to
    file '<model_name>-<YYYYMMDDHHMM>-profile-<path_id>'.
    Introduced in CmdStan-2.26, see
    https://mc-stan.org/docs/cmdstan-guide/stan_csv.html,
    section "Profiling CSV output file" for details.

:param show_console: If ``True``, stream CmdStan messages sent to stdout
    and stderr to the console.  Default is ``False``.

:param refresh: Specify the number of iterations CmdStan will take
    between progress messages. Default value is 100.

:param time_fmt: A format string passed to
    :meth:`~datetime.datetime.strftime` to decide the file names for
    output CSVs. Defaults to "%Y%m%d%H%M%S"

:param timeout: Duration at which Pathfinder times
    out in seconds. Defaults to None.

:param num_threads: Number of threads to request for parallel execution.
    A number other than ``1`` requires the model to have been compiled
    with STAN_THREADS=True.

:return: A :class:`CmdStanPathfinder` object

References
----------

Zhang, L., Carpenter, B., Gelman, A., & Vehtari, A. (2022). Pathfinder:
Parallel quasi-Newton variational inference. Journal of Machine Learning
Research, 23(306), 1–49. Retrieved from
http://jmlr.org/papers/v23/21-0889.html
rC   !   zBMethod 'pathfinder' not available for CmdStan versions before 2.33"   zcArguments 'psis_resample' and 'calculate_lp' are only available for CmdStan versions 2.34 and laterNr/   r   r?   r   zMModel must be compiled with 'STAN_THREADS=true' to use 'num_threads' argumentr  zHCannot specify both 'draws' and 'num_single_draws' when 'num_paths' is 1)r   r   r   r   r   r   r   num_psis_drawsrZ  r[  	num_drawsr]  r^  r_  r   r   r   r   z0Error during Pathfinder! Command '{}' failed: {}r   )r   r)   rZ   rn   rs   rr   r\   rm   r   r.   r-   r   rQ   rS   r&   r   r   r   r[   ro   r   r   rl   r$   )"rt   r   r   r   r   r   r   r   r   rZ  r[  rL  r\  r]  r^  r_  r   r   r   r   r   r   r   r   r   r'  r   pathfinder_argsr   r   r   r   r   r   s"                                     r}   
pathfinderCmdStanModel.pathfinder  s   d ==?!!R22 
 \7Mr88
 8
 @ 
 "q LL4::<F .  .1-=BJJ)*>'#(  %5%> - 
 )!#%% +&)'%
" d#uj.?6

%!)+D Na(CF)	  ! /@#, 	!!#%%''DKKA')<)<)>C s## ((; /@.?##s%   ,G8AG?G
G	G
G')r   r   paramsc          	         [        SSU R                  5       5      (       a  [        S5      e[        U5       n[        U5       n[	        U R
                  5      SSU 3S[        U5       3/nUb
  USS	U 3/-  n[        R                  " U R                  [        S
9n[        R                  R                  US5      n	USS	U	 3/-  nUb  UR                  SU 35        [        5       R!                  S[	        U5      5        ["        R$                  " USSSS9n
U
R&                  (       aP  [        5       R)                  SU
R*                  U
R,                  5        [/        S[	        U
R&                  5      -   5      e[0        R2                  " U	SS9nUsSSS5        sSSS5        $ ! , (       d  f       O= fSSS5        g! , (       d  f       g= f)a   
Calculate the log probability and gradient at the given parameter
values.

.. note:: This function is **NOT** an efficient way to evaluate the log
    density of the model. It should be used for diagnostics ONLY.
    Please, do not use this for other purposes such as testing new
    sampling algorithms!

:param params: Values for all parameters in the model, specified
    either as a dictionary with entries matching the parameter
    variables, or as the path of a data file in JSON or Rdump format.

    These should be given on the constrained (natural) scale.

:param data: Values for all data variables in the model, specified
    either as a dictionary with entries matching the data variables,
    or as the path of a data file in JSON or Rdump format.

:param jacobian: Whether or not to enable the Jacobian adjustment
    for constrained parameters. Defaults to ``True``.

:param sig_figs: Numerical precision used for output CSV and text files.
    Must be an integer between 1 and 18.  If unspecified, the default
    precision for the system file I/O is used; the usual value is 6.

:return: A pandas.DataFrame containing columns "lp__" and additional
    columns for the gradient values. These gradients will be for the
    unconstrained parameters of the model.
rC   r;  z@Method 'log_prob' not available for CmdStan versions before 2.31log_probzconstrained_params=z	jacobian=Nr   zfile=)prefixdirz
output.csvoutputz	sig_figs=zCmd: %sTF)capture_outputchecktextz.'log_prob' command failed!
stdout:%s
stderr:%sz*Method 'log_prob' failed with return code #)comment)r)   r   rZ   r.   rr   r7   r  tempfilemkdtempr   r   r\   r]   ro   appendr+   ri   
subprocessrun
returncoder   r!  stderrrl   pdread_csv)rt   rh  r   r   r   r   _paramsr   r   rm  procr   s               r}   rj  CmdStanModel.log_prob  s   N "!R99  d#u.>/
DMM"%gY/CM?+	C  %w00!))HJWW\\*l;FHfX.//C#

Yxj12Ly#c(3>>DDD ""FKKKK
 #@$//*+ 
 [[5FI/
 /
## /
 /
###s$   F;EF!	F;!
F/	+F;;
G	)
r   r   r   r   r   r   r   r   r   opt_argsmoder  c       
            [        SSU R                  5       5      (       a  [        S5      eUb  Ub  [        S5      eUcD  UUUUU	U
UUUS.	nUR                  U=(       d    0 5        SU-   US'    U R                  " SS	U0UD6nO#[        U[        5      (       d  [        U5      nOUnUR                  R                  [        R                  :w  a  [        S5      eUR                  R                  R                  R                   nUU:w  a  [        SU SU 35      e[#        UR                  R$                  S   X45      n['        U5       n[)        U R*                  U R,                  SUUUUUUU
S9
nSn[/        USUS9nU R1                  UUU	US9  SSS5        WR3                  5         [5        UU5      $ ! [
         a  n[        S
5      UeSnAff = f! , (       d  f       NH= f)a  
Run a Laplace approximation around the posterior mode.

:param data: Values for all data variables in the model, specified
    either as a dictionary with entries matching the data variables,
    or as the path of a data file in JSON or Rdump format.

:param mode: The mode around which to place the approximation, either

    * A :class:`CmdStanMLE` object
    * A path to a CSV file containing the output of an optimization run.
    * ``None`` - use default optimizer settings and/or any ``opt_args``.

:param draws: Number of approximate draws to return.
    Defaults to 1000

:param jacobian: Whether or not to enable the Jacobian adjustment
    for constrained parameters. Defaults to ``True``.
    Note: This must match the argument used in the creation of
    ``mode``, if supplied.

:param output_dir: Name of the directory to which CmdStan output
    files are written. If unspecified, output files will be written
    to a temporary directory which is deleted upon session exit.

:param sig_figs: Numerical precision used for output CSV and text files.
    Must be an integer between 1 and 18.  If unspecified, the default
    precision for the system file I/O is used; the usual value is 6.
    Introduced in CmdStan-2.25.

:param save_profile: Whether or not to profile auto-diff operations in
    labelled blocks of code.  If ``True``, CSV outputs are written to
    file '<model_name>-<YYYYMMDDHHMM>-profile-<path_id>'.
    Introduced in CmdStan-2.26, see
    https://mc-stan.org/docs/cmdstan-guide/stan_csv.html,
    section "Profiling CSV output file" for details.

:param show_console: If ``True``, stream CmdStan messages sent to stdout
    and stderr to the console.  Default is ``False``.

:param refresh: Specify the number of iterations CmdStan will take
    between progress messages. Default value is 100.

:param time_fmt: A format string passed to
    :meth:`~datetime.datetime.strftime` to decide the file names for
    output CSVs. Defaults to "%Y%m%d%H%M%S"

:param timeout: Duration at which Pathfinder times
    out in seconds. Defaults to None.

:param opt_args: Dictionary of additional arguments
    which will be passed to :meth:`~CmdStanModel.optimize`

:return: A :class:`CmdStanLaplace` object.
rC   r   zFMethod 'laplace_sample' not available for CmdStan versions before 2.32Nz3Cannot specify both 'opt_args' and 'mode' arguments)	r   r   r   r   r   r   r   r   r   zopt-r   r   zXFailed to run optimizer on model. Consider supplying a mode or additional optimizer argsz6Mode must be a CmdStanMLE or a path to an optimize CSVzTJacobian argument to optimize and laplace must match!
Laplace was run with jacobian=z%,
but optimize was run with jacobian=r   )r   r   r   r   r   r   r   r   r/   r   r    )r)   r   rZ   updater   	Exceptionrl   r  r#   r'   r   methodr   OPTIMIZEr%  r   r   r   r<  r.   r   rQ   rS   r&   r   r   r!   )rt   r   r  rL  r   r   r   r   r   r   r   r   r   r  r   cmdstan_moderz   mode_jacobianlaplace_argsr   r   r   r   s                          r}   laplace_sampleCmdStanModel.laplace_sampleQ  s6   P "!R99  D$4E  <$$ , ,"$"(
M   R0(.(9M*%	+/== ,,#, D*--#D>LL%%8H 
 %%11:: 	 H$119
 ;66C_F  #))!,e
 d#u

%!)(D Na(CF)	   $* 	!!#fl33g  "M : $#s%   /F3 	AG3
G=G		G
Gr   r
  r  c           
      f  ^^^ [        5       R                  ST5        [        5       R                  S[        [        R                  R                  S5      5      5        SnSnTR                  (       a<  SR                  TR                  T   5      nSR                  TR                  T   5      nTR                  T5      n	[        5       R                  SU	5        U(       d  [        5       R                  S	U5         [        TR                  T   S
5      n
[        R                  " U	S[        R                  [        R                   [        R"                  [        R                  SS9mU(       a8  SUUU4S jjn[$        R&                  " Xk5      nSUl        UR+                  5         OSnTR-                  5       c~  TR.                  b^  TR.                  R1                  5       nU
R3                  U5        UR5                  5       nU(       a  [7        U U 35        OUb	  U" UT5        TR-                  5       c  M~  TR9                  5       u  pTR:                  nTR=                  TU5        U(       a  UR?                  5         U(       aA  U
R3                  U5        U(       a)  URA                  S5      nU H  n[7        U U 35        M     U
RC                  5          U
RC                  5         U(       d  [        5       R                  SU5        US:w  aA  [I        U5      nSn [        RJ                  " U5      n[        5       RQ                  SUUU5        gg! [D         a+  nSR                  [        U5      5      n[G        U5      UeSnAff = f! W
RC                  5         f = f! [L        [N        4 a     N}f = f)a  
Helper function which encapsulates call to CmdStan.
Uses subprocess POpen object to run the process.
Records stdout, stderr messages, and process returncode.
Args 'show_progress' and 'show_console' allow use of progress bar,
streaming output to console, respectively.
zidx %dz running CmdStan, num_threads: %sr  CmdStanr?   z
Chain [{}]zChain [{}] zCmdStan args: %sz%s start processingwr/   T)bufsizestdinr!  ry  envuniversal_newlinesNc                  n   > TR                  5       b  g TR                  5         TR                  T S5        g )NT)poll	terminate_set_timeout_flag)r
  r}  r   s   r}   _timer_target0CmdStanModel._run_cmdstan.<locals>._timer_target  s,    yy{.NN$,,S$7r   r   zFailed with error {}
z%s done processingr   z%s error: %s %s)r=   N))r+   ri   rr   r\   rm   rn   r  r[   r   r   r   re   r$  rv  PopenDEVNULLPIPESTDOUT	threadingTimerdaemonstartr  r!  readliner"  rY   printcommunicaterx  _set_retcodecancelra   closeOSErrorrl   r,   strerrorArithmeticErrorrZ   r   )rt   r   r
  r   r   r  r   logger_prefixconsole_prefixr   rH   r  timerr   r!  ru   retcoder   rz   r   retcode_summaryserrorr}  s    ``                   @r}   r   CmdStanModel._run_cmdstan  s     	8S).

123	

 "''(//0@0@0EFM*11&2B2B32GHNjjo-s3L3]C5	&--c2C8F## ((!!((JJ#'D 8 8 "?#))+%;;*;;//1DLL&::<D# 078&2%dC0 ))+% ((*IFooGW-V$"LL.E % 078 !&LLN
 LLNL2MBa<,W5OFW- L!=/6   	+*11#a&9Cs#*	+ LLN $Z0 s>   <D9M 7BM N 
N&N  NN NN0/N0r  c                    ^ ^^^ [         R                  " S5      mT  Vs0 s H  nU[        TSSS0/SU 3SS9_M     snmS[        S	[        S
S4U UUU4S jjnU$ s  snf )z
Sets up tqdm callback for CmdStan sampler console msgs.
CmdStan progress messages start with "Iteration", for single chain
process, "Chain [id] Iteration" for multi-chain processing.
For the latter, manage array of pbars, update accordingly.
zChain \[(\d*)\] (Iteration.*)z,{desc} |{bar}| {elapsed} {postfix[0][value]}valueStatuszchain yellow)r  
bar_formatpostfixdesccolourr   r
  r=   Nc                   > U S:X  aX  TR                  5        HC  nSUR                  S   S'   UR                  TUR                  -
  5        UR	                  5         ME     g TR                  U 5      nU(       a:  [        UR                  S5      5      nUR                  S5      R                  5       nOU R                  S5      (       a  U nTU   nOg SU;   a
  S	TU   l
        TU   R                  S5        UTU   R                  S   S'   g )
Nr  zSampling completedr   r  r/   rC   	IterationSamplingblue)valuesr  r  nr  matchr  grouprY   
startswithr  )	r   r
  pbarr  mliner   rT  pbarsr  s	        r}   r  ?CmdStanModel._wrap_sampler_progress_hook.<locals>.progress_hookh  s    v~!LLND/CDLLOG,KK/JJL +
 		$ekk!n-C!KKN002E__[11 E#C.C&(.E#J%c
!!!$16c
""1%g.r   )rO  r4   r   rr   r  )r   r  r,  r  rT  r  s   ``  @@r}   r  (CmdStanModel._wrap_sampler_progress_hookP  s     jj9: &	"
 & dI!8,-hZ(  &	"
	7 	7# 	7$ 	7 	7* A	"
s   A)rU   rS   rW   rQ   rR   )NNNFNNN)FFN   )FNNNF)NNNNNFNNNNNNNNNFTFNr   NF)NNNNNNNNNFNNNNTNNNNFNNFFTFNr   N)	NNNNNFNr   N)NNNNNFFNNNNNTNNNNTFNr   N)N)NNN)FFNN):__name__
__module____qualname____firstlineno____doc__r   rr   OptionalPathboolr
   r   r   r   r~   r   propertyr   r6   r7   r   rh   r   r  r[   r9   r:   r;   r   r4   r   r\   PathLikefloatr#   r   r   r"   r5  r1   r    rD  r%   rX  r$   rf  rz  	DataFramerj  r!   r  r&   r	   r   staticmethodr  wrap_callbackr  __static_attributes__r  r   r}   r   r   I   sQ   &T %)"&!%#2604$(LP 8<LPSMLP  LP 	LP
 LP  S#X/LP d38n-LP "LP tWW-t34LP 
LP\#  c   <   ,  $sCx. 0	Q$sCx. 	Q  %8=!	,
 ,
,
 D#x}45,
 	,
 ,
 
,
\ 5tCtS#~)>$>? 5 5 3T#uT3Y'7"78 3 3 3S 3 3hsm $ 2604$(!&I
  I
I
  S#X/I
 d38n-	I

 "I
 I
 I
 
I
Z BF"IM#'"&"#'&*#''+$((,%)&*" %"&"!%&#'/|GCH%sBKK=>| sm| WS#X&sBKKEF	|
 !| 3-| | C=| UO| %| e_| 5/| uo| E?| sm|  sm!|" #|$  %|& '|( #)|* +|, %-|. /|2 
3|B BF $)-+/,015 %)'+!"'+ 59"'+*.-1)-!#'"&%*"""!%&#'OcR 7;ScGCH%sBKK=>c c "#	c
 $C=c CcD()c d3i-.c CHIc"#
c  c]!c"  }#c$ %c& sm'c(  })c* c3hcDc3h,@$F
+c0 UT121c2 3c4 e_5c6 #3-7c8 &c]9c: "#;c< =c> !?c@ 3-AcB #CcD EcF GcH IcJ #KcL McN %OcR &.d^ScT 
UcN BF48"&*"&"!%&#' <@GCH%sBKK=> CcD01 sm	
 $ 3-  #  % ;S	478 
3F BF"!%#'"&%*"#'"&*&*#"$('+#'#"&"!%&#'/Z2 )-3ZGCH%sBKK=>Z smZ 	Z
 !Z 3-Z #Z Z C=Z smZ smZ smZ e_Z Z SMZ  e_!Z" C=#Z$ }%Z&  'Z( )Z* #+Z, -Z. %/Z2 !3Z4 
5Z| BFc) '+#''+$((,%)&*#')-#*.(,"!"HL#'"&""!%&#'%)9c)GCH%sBKK=>c) UO	c)
 %c) e_c) 5/c) uoc) E?c) smc) C=c) "#c) }c) #3-c) !c)  !c)" #c)& sm'c)( T#u*%uc2;;DE)c)* !+c), 3--c). /c)0 1c)2 #3c)4 5c)6 %7c)8 c]9c): 
;c)P BFP
 "&Pd38nc2;;67P GCH%sBKK=>P
 P 3-P 
Ph BF:>#	W4 "#'"&""!%&#'-1W4GCH%sBKK=>W4 JR[[$67W4 }	W4 W4 smW4 !W4 3-W4 W4 W4 #W4 W4 %W4 4S>*W4  
!W4z $">B#'dd d 	d
 d  #sT)9 :;d %d 
dL +9++ 
(C:t+,	-+  +r   )Ir  r\   rj   rO  r  rv  r   rs  r  collectionsr   concurrent.futuresr   ior   multiprocessingr   typingr   r	   r
   r   r   r   r   r   r   r   pandasrz  	tqdm.autor   	cmdstanpyr   r   r   r   r   cmdstanpy.cmdstan_argsr   r   r   r   r   r   r   r   cmdstanpy.stanfitr    r!   r"   r#   r$   r%   r&   r'   cmdstanpy.utilsr(   r)   r*   r+   r,   cmdstanpy.utils.filesystemr-   r.   r?   r0   r  rr   r  r  r1   r   r  r   r}   <module>r     s     	  	   
   # 1  %     	 	 		 	 	  D !S"++t+,e[*i8t  t r   