
    %g@^                       d Z ddlZddlZddlZddlZddlZddlZddlZddlZddl	m
Z
 ddlmZ ddlmZ ddlmZ ddlmZmZmZmZmZmZmZmZmZmZ ddlZddlmZ dd	l m!Z!m"Z"m#Z#m$Z$m%Z% dd
l&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z-m.Z. ddl/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z5m6Z6m7Z7 ddl8m9Z9m:Z:m;Z;m<Z<m=Z= ddl>m?Z?m@Z@ ddlAmBZC eeDej                  df   ZF ede2e3e5      ZG G d d       ZHy)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            @       
   e Zd ZdZ	 	 	 	 	 	 	 dwdddee   dededed	eeee	f      d
eeee	f      dede
eed   df   ddfdZdefdZedefd       Zedefd       Zedefd       Zdeeef   fdZdeee	f   fdZ	 	 	 dxdddede
eeee   f   dededdf
dZedeee
eeef   f   fd       Zedeee
eef   f   fd       Zedefd       Zdee   fd Z	 	 	 	 	 dydd!ded	eeee	f      d
eeee	f      ded"ed#eddfd$Z	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dzd&e
eee	f   eej<                  df   d'ee   d(e
eee	f   eeej<                  df   d)ed*ee   d+ed,ee   d-ee   d.ee   d/ee   d0ee   d1ee   d2ee   d3ee   d4ee   d5ed6ed7ed8ee   d9ed:ee   d;ede f.d<Z!	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d{dd=d&e
eee	f   eej<                  df   d>ee   d?ee   d@ee   d'e
ee"e   df   dAe
ee"e   df   d(e
eee	f   eee"e   e"eee	f      df   dBee   dCee   dDedEee   dFee   dGe
eeee	f   e"e   e"eee	f      df   dHe
ee"e   df   dIedJee   dKee   dLee   dMee   dNed)ed*ee   dOed+edPed7ed8ee   d9ed:ee   dQee   de#f>dRZ$	 	 	 	 	 	 	 	 	 d|ddSd&e
eee	f   eej<                  df   dTe
e%e"e   df   d'ee   dUed*ee   d7ed8ee   d9ed:ee   dVe
e#e"e   df   de&e%   fdWZ'	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d}ddXd&e
eee	f   eej<                  df   d'ee   d(ee   d)ed*ee   dOed+ed,ee   d4ee   dYee   dZee   d[ee   dIed\ee   d/ee   d]ee   d^ee   d6ed7ed8ee   d9ed:ee   d_ee   de(f0d`Z)	 d~dddddddddddddddddddddd%dddad&e
eee	f   eej<                  df   d-ee   d.ee   d/ee   d0ee   d1ee   d2ee   d3ee   dbee   dcee   d^ee   ddee   deee   dfedged'ee   d(e
eeef   eeej<                  df   d)ed*ee   d+ed7ed8ee   d9ed:ee   dhee   de*f4diZ+	 d~dddjdke
eee	f   eej<                  f   d&e
eee	f   eej<                  df   d;ed*ee   de,jZ                  f
dlZ.	 	 	 ddddddddd%dddm
d&e
eee	f   eej<                  df   dne
e eej<                  df   d^ee   d;ed'ee   d)ed*ee   d+ed7ed8ee   d9ed:ee   doeeee	f      de/fdpZ0	 	 	 	 ddqe1dredPed7edsee2eegdf      d:ee   ddfdtZ3e4e5jl                  dAe"e   duedee2eegdf      fdv              Z7y)r   a  
    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_headerr3   forcereturnc                t   d| _         d| _        d| _        t        j                  |||      | _        | j
                  j                          d| _        |d}nt               j                  d       |rd}|Xt               j                  d       |j                         st        d	j                  |            |j                         | _         ||t        d
      t        j                  j                  t        j                  j!                  |            | _        t        j                  j#                  | j                        s$t        dj                  | j                              t        j                  j%                  |      \  }	}
t'        |
      dk  s|
j)                  d      s$t        dj                  | j                              | j                   s't        j                  j+                  |
      \  | _         }	t-        | j                  d      5 }|j/                         }ddd       dv rGt        j                  j%                  | j                        \  }}	| j
                  j1                  |       t3        dd      sEt3        dd      r9	 | j5                         }d|v r$| xj                  t'        |d         dk(  z  c_        |Bt        j                  j                  t        j                  j!                  |            | _        t        j                  j#                  | j                        s$t        dj                  | j                              t        j                  j%                  | j                        \  }	}| j                   s(t        j                  j+                  |      \  | _         }	nT| j                   t        j                  j+                  |      d   k7  r%t        dj                  | j                   |            t9        j:                         dk(  r)	 t=        ddgd       t               j7                  d       |r;| j                  .| jO                  tQ        |      jS                         dk(  d$       yyy# 1 sw Y   ixY w# t        $ r'}|r t               j7                  |       Y d}~d}~ww xY w# t>        $ r t        j@                  jC                  d      }|,t        j                  jE                  tG               ddddd       }t               j7                  d!|       d"jE                  tI        tK        jL                  |gt        j@                  jC                  d#d      j%                  d"      z                     t        j@                  d#<   Y `w xY w)%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r8   r9   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   fromkeysr3   strlower)selfr4   r5   r6   r7   r8   r9   r:   r3   _filenamefdprogramr\   
model_infoeexenamelibtbbs                     L/var/www/dash_apps/app1/venv/lib/python3.12/site-packages/cmdstanpy/model.py__init__zCmdStanModel.__init__u   s   4 
!,!<!<'##"

 	'')!?GL   G!L  5 ##% GNN" 
 $))+DJ M 
 !gg..rww/A/A)/LMDO77>>$//2 !2!9!9$//!JKK''--	2KAx8}q (9(9'(B .55dooF  :: " 0 0 :
A doos+ $r'')$W$''--8a&&77= +1b17M28*!%J#z1))SL1I-Ja-OO) WW--bgg.@.@.JKDN77>>$..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   R8R! .S R!	S*SSCV76V7c                     dj                  | j                        }dj                  || j                        }dj                  || j                        }dj                  || j                        }|S )NzCmdStanModel: name={}z{}
	 stan_file={}z{}
	 exe_file={}z{}
	 compiler_options={})rZ   rP   rQ   rR   rT   )rs   reprs     r|   __repr__zCmdStanModel.__repr__  s_    &--djj9$++D$//B#**4@+2249O9OP    c                     | j                   S )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``.
        )rP   rs   s    r|   namezCmdStanModel.name
  s     zzr   c                     | j                   S )zFull path to Stan program file.)rQ   r   s    r|   r5   zCmdStanModel.stan_file  s     r   c                     | j                   S )zFull path to Stan exe file.)rR   r   s    r|   r6   zCmdStanModel.exe_file  s     ~~r   c                    i }| j                   |S 	 t               }t        t        | j                         dg|       |j	                         j                  d      }|D ]H  }|j                  d      D cg c]  }|j                          }}t        |      dk7  r>|d   ||d   <   J |S c c}w # t        $ r%}t               j                  |       |cY d}~S d}~ww xY w)	a  
        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)cmdrG   
=rB   r/   r   )r6   r   r*   rq   getvaluer`   rX   ra   rk   r+   rh   )rs   resultr   lineslinexkv_pairry   s           r|   exe_infozCmdStanModel.exe_info  s     "$== M	:DC.7EMMO))$/E 0.2jjo>1779>>w<1$%,QZwqz"	0
 M	 ?
  	Lq!M	s0   A#B1 5B,B1 ,B1 1	C:CCCc                     | j                   t        dd      ri S t        j                  t	        | j                         | j
                        S )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.
        rB   rC   )r5   r)   r   rg   rq   rT   r   s    r|   rg   zCmdStanModel.src_info5  s?     >>!%;Ar%BI##C$79O9OPPr   T)backupoverwrite_filecanonicalizemax_line_lengthr   c                    t               j                  d       | j                  t        d      t	        j
                  | j                  ||||| j                         y)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   r8   )r+   rW   r5   rY   r   format_stan_filer8   )rs   r   r   r   r   s        r|   rZ   zCmdStanModel.formatA  s[    8 	8	
 >>!ABB$$NN)+%,,	
r   c                 .    | j                   j                  S )zOptions to stanc compilers.)rT   _stanc_optionsr   s    r|   r8   zCmdStanModel.stanc_optionso  s     %%444r   c                 .    | j                   j                  S )zOptions to C++ compilers.)rT   _cpp_optionsr   s    r|   r9   zCmdStanModel.cpp_optionst       %%222r   c                 .    | j                   j                  S )z2The user header file if it exists, otherwise empty)rT   _user_headerr   s    r|   r:   zCmdStanModel.user_headery  r   r   c                    | j                   st        d      d}	 t        | j                   d      5 }|j                         }ddd       |S # 1 sw Y   |S xY w# t        $ r( t               j                  d| j                          Y |S w xY w)z Return Stan program as a string.Please specify source fileNrA   zCannot read file Stan file: %s)rQ   rk   rd   re   IOErrorr+   error)rs   coderv   s      r|   r   zCmdStanModel.code~  s    ;<<	doos+ !rwwy! ! 	  	L0$// 		s.   A AA AA A -B
	B
)rO   override_optionsrO   c                8   |st               j                  d       | j                  st        d      d}|||rt	        j
                  |||      }|j                          || j                  k7  r;d}| j                  || _        n%|r|| _        n| j                  j                  |       t	        j                  t        | j                        || j                  j                  | j                  j                  | j                  j                        | _        y)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;   r8   r9   r:   )r+   rW   rQ   rk   r   rS   rU   rT   addcompile_stan_filerq   r5   r8   r9   r:   rR   )rs   r;   r8   r9   r:   r   rO   compiler_optionss           r|   r3   zCmdStanModel.compile  s   F L  O ;<<%&&*::+'' 
 %%'4#9#99))1-=D*%-=D***../?@$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                    t        |||	|
|||||||      }|r&t        dd| j                               rt        d      t	        |      5 }t        |d      5 }t        | j                  | j                  d||||||||      }d	}t        |d
|      }| j                  ||||       ddd       ddd       j                          |j                         sidj                  dj                  |j                  d	            |j!                               }d|v r|st#               j%                  |       nt'        |      t)        |      }|S # 1 sw Y   xY w# 1 sw Y   xY w)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   rB       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   rY   r.   r-   r   rP   rR   r&   _run_cmdstanraise_for_timeouts_check_retcodesrZ   rn   r   get_err_msgsr+   rW   rk   r#   )rs   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|   optimizezCmdStanModel.optimize  s   J %!#%%+
 .q"dmmo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E#)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                L   || j                   }|d}|dk  rt        dj                  |            |t        t	        t               |      d      }nB||kD  rt               j                  d||       |}n|dk  rt        dj                  |            |d}|dk  rt        dj                  |            |}|} d}!| j                         }"|"j                  d	d
      j                         }#|dk(  rd}|t        dd|"      s|#dk(  r	d}!|| z  } d}|du rOt        dd|"      s(d}!|| z  } d}|#d
k(  r4t               j                  d       nt               j                  d|       t        |       t        j                  d<   |t!        |      D $cg c]  }$|$dz   	 }}$nt#        |t$              r;|dk  rt        dj                  |            t!        |      D $cg c]  }$|$|z   	 }}$n|!s9t'        ||dd       D ]'  \  }$}%|$|%dz
  k7  st        dj                  |             t)        |      |k(  s$t        dj                  |t)        |                  |D ]!  }&|&dk  s	t        dj                  |&             t+        |!rdn|||	|
||||||||||      }'t-        |      5 }(t/        ||d         5 })|!r)t#        |t0              r|D $cg c]  }$|)dd  d|$ d }*}$n|)}*t3        | j4                  | j6                  ||(||*|||||'|      }+|rd}n1|xr t9        j:                         }t               j                  d       d},|rGd}-|
|-t<        z  }-n|-|z  }-|	
|-t>        z  }-n|-|	z  }-|t@        }|-|z  dz   }-| jC                  ||-      },tE        |+||||!      }.tG        |       5 }/t!        |.jH                        D ]$  }$|/jK                  | jL                  |.|$|||,|!       & 	 ddd       |r|, |,d"d#       tO        jP                  d$%      }0|0[|0d   dkD  rSt!        |      D ]E  }$tR        jT                  jW                  d&|0d   z         tR        jT                  jY                          G tR        jT                  jW                  d'       t               j                  d(       |.j[                          t               j]                  d)t_        |.             ta        |.jb                  d   d*      5 }1|1je                         }2t               j]                  d+|2       d,|2v r1t               j]                  d-       d|'_3        |'|.jh                  _5        ddd       |.jm                         }3|.jo                         s#d.|3 d/t_        |.       }4|s|4d0z  }4tq        |4      |3r%d1|3 }4|s|4d0z  }4t               j                  |4       ts        |.      }5ddd       ddd       5S c c}$w c c}$w c c}$w # 1 sw Y   xY w# 1 sw Y   xY w# 1 sw Y   ;xY w# 1 sw Y   5S xY w)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falserB      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   )idrt   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
%srA   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:
):rV   rY   rZ   maxminr   r+   r   r   rm   rr   r)   rW   rq   r[   rl   range
isinstanceintzipra   r   r.   r-   ro   r   rP   rR   progbarallow_show_progressr   r   r   _wrap_sampler_progress_hookr&   r   	num_procssubmitr   shutilget_terminal_sizesysstdoutwriteflushr   rh   r   rd   stdout_filesre   r   _argsr   r   r   rk   r"   )6rs   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_sizerv   console_msgserrorsr   mcmcs6                                                         r|   samplezCmdStanModel.sample  s
   b ++K>FA:DKK  "!#ik6":A>Ov%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61Q6I6)S)q=$%%+VI%6  5:&MBqQ]B	B, #Iy} = 1A:",!--3VI->#  9~/$DDJF"C	NE  !* H!|())/)9  #1qv#'#''#- 3+#
" d# v	'ujil/
 v	'$E4)@7@!23vcr{m1QCu-! ! !'

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

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

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

  &!!"<=%%'L|T&\: f))!,c2 <b!wwy""#9<H0L@L&&'CD/3L,/;FLL,< ((*F))+.vh 7226v,A  $4C #3'':6(C#4C $$S)v&Dmv	' v	'n O 7 CZ!j
 
>< <sv	' v	' v	'n sv   W%W*%X6XW/CX,=W4*DX6A XA=XX/X4W>9XX
XX	XX#)mcmc_sampleprevious_fitgq_output_dirr'  c
                   |
(|rt        d      t               j                  d       |
}t        |t        t
        t        f      r|}|j                  j                  }nCt        |t              r(t        |      dk  rt        d      	 |}t        |      }nt        d      t        |t              r>|j                  }|j                   }|j"                  rt               j                  d	       nnt        |t
              rBt%        d
d      rt'        d      d}dg}|j(                  r6t               j                  d       nt%        d
d      rt'        d      d}dg}t+        |      }|j-                  |       t/        |      5 }t1        | j2                  | j4                  |||||||	      }t7        ||||      }t9               }t;        t=        |d
z
  |      d      }t?        |      5 }tA        |      D ]"  }|jC                  | jD                  ||||	       $ 	 ddd       |jG                          |jI                         }|r#d| dt        |       }|s|dz  }t'        |      tK        ||      }ddd       |S # t         $ r9}t        dj                  t        |      dj                  |                  |d}~ww xY w# 1 sw Y   xY w# 1 sw Y   S xY w)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.rB      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   r(  )&rY   r+   rW   r  r"   r#   r%   r   r,  ro   ra   r'   rZ   r   rn   r   r   _save_warmupr)   rk   _save_iterationsr   rU   r.   r   rP   rR   r&   r   r  r  r   r  r  r   r   r   r    )rs   r   r(  r   r)  r   r   r   r   r   r'  
fit_objectfit_csv_filesry   r   r   generate_quantities_argsr   r   r   parallel_chains_availr   r!  r  r$  r   
quantitiess                              r|   generate_quantitiesz CmdStanModel.generate_quantities}  s5   ^ " 8  L  ,
 'Ll[*i$H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# )	Ku

#(!4
D &IF %.K!!#&;a&?"H!LO#@ Hv AOO))%1 ' $  %%'((*F9& B226v,A  $4C #3''"&zJJS)	KT q   44:FQ\!:5
 @ %)	KT s>   	J A'K-1KAK	K4K  KK	KK)output_samplesgrad_sampleselbo_sampleseta
adapt_iter	eval_elbodrawsr5  c                    |(|t        d      t               j                  d       |}t        ||	|
|||||||
      }t	        |      5 }t        |d      5 }t        | j                  | j                  d|||||||||      }d}t        |d	|
      }| j                  ||||       ddd       ddd       j                          |j                     }t        j                  dt        j                        }t!        |d      5 } | j#                         }!ddd       t%        t        j&                  |!            dkD  r(|rt)        d      t               j                  ddd       |j+                         s|j                  |   }t!        |d      5 } | j#                         }!ddd       t        j                  dt        j                        }t%        t        j&                  ||!            dkD  r |
d}
dj-                  |
      }"t)        |"      dj-                  |j/                               }"t)        |"      t1        |      }#|#S # 1 sw Y   xY w# 1 sw Y   xY w# 1 sw Y   OxY w# 1 sw Y   xY w)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   r6  r7  r8  r   r9  r   r:  r5  Fr   r   r   r/   r   r   z%The algorithm may not have converged.rA   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: {})rY   r+   rW   r   r.   r-   r   rP   rR   r&   r   r   r  rer3   Mrd   re   ra   findallrk   r   rZ   r   r%   )$rs   r   r   r   r   r   r   r   r   r   r6  r7  r8  r   r9  r   r:  r;  r   r   r   r   r   r5  variational_argsr   r   r   r   r   transcript_filepat
transcriptcontentsr   vbs$                                       r|   variationalz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,+?  s## ?EE'') s##v	I	 	 	 	>	) 	)"- -s=   IAI*I	I'I4I	II$'I14I=)r   r   r   r   r   r   r   	num_pathsmax_lbfgs_itersr;  num_single_drawsnum_elbo_drawspsis_resamplecalculate_lpr   r   r   r   r   r   r   r   r   r  rH  rI  rJ  rK  rL  rM  r  c                   | j                         }t        dd|      rt        d      |r|st        dd|      rt        d      |O|dk7  r.|j                  dd	      j	                         d
k7  rt        d      t        |      t        j                  d<   |	dk(  r||}|||k7  rt        d      t        |||||||||	|
||||      }t        |      5 }t        |      5 }t        | j                  | j                  d||||||||      }d}t        |d|      } | j                  | |||       ddd       ddd        j!                          | j#                         sIdj%                  dj'                  | j)                  d            | j+                               }!t-        |!      t/        |       S # 1 sw Y   xY w# 1 sw Y   xY w)u  
        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
        rB   !   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_drawsrH  rI  	num_drawsrK  rL  rM  r   r   r   r   z0Error during Pathfinder! Command '{}' failed: {}r   )r   r)   rY   rm   rr   rq   r[   rl   r   r.   r-   r   rP   rR   r&   r   r   r   rZ   rn   r   r   rk   r$   )"rs   r   r   r   r   r   r   r   r   rH  rI  r;  rJ  rK  rL  rM  r   r   r   r   r   r   r   r   r   r  r   pathfinder_argsr   r   r   r   r   r   s"                                     r|   
pathfinderzCmdStanModel.pathfinder  s   d ==?!!R2 
 \7Mr88
 @ 
 "q LL4::<F .  .1-=BJJ)*>'#(  %5%> - 
 )!#%% +&)'%
" d# 	uj.? 	6

%!)+D Na(CF)	  !	 	, 	!!#%%'DKKA')<)<)>C s## ((;	 	 	 	s%   G!AF51G5F>	:GG
)r   r   paramsc          	      x   t        dd| j                               rt        d      t        |      5 }t        |      5 }t	        | j
                        dd| dt        |       g}|
|dd	| gz  }t        j                  | j                  t        
      }t        j                  j                  |d      }	|dd	|	 gz  }||j                  d|        t               j!                  dt	        |             t#        j$                  |ddd      }
|
j&                  rPt               j)                  d|
j*                  |
j,                         t/        dt	        |
j&                        z         t1        j2                  |	d      }|cddd       cddd       S # 1 sw Y   nxY wddd       y# 1 sw Y   yxY w)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.
        rB   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   rY   r.   rq   r6   r  tempfilemkdtempr   r   r[   r\   rn   appendr+   rh   
subprocessrun
returncoder   r  stderrrk   pdread_csv)rs   rU  r   r   r   r   _paramsr   r   rZ  procr   s               r|   rW  zCmdStanModel.log_prob  s   N "!R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#   F0E
F	F0F$	 F00F9)
r   r   r   r   r   r   r   r   r   opt_argsmoderk  c       
            t        dd| j                               rt        d      ||t        d      |?|||||	|
|||d	}|j                  |xs i        d|z   |d<   	  | j                  dd	|i|}nt        |t              st        |      }n|}|j                  j                  t        j                  k7  rt        d      |j                  j                  j                  j                   }||k7  rt        d| d|       t#        |j                  j$                  d   ||      }t'        |      5 }t)        | j*                  | j,                  d|||||||

      }d}t/        |d|      }| j1                  |||	|       ddd       j3                          t5        ||      S # t
        $ r}t        d
      |d}~ww xY w# 1 sw Y   BxY w)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.
        rB   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   rY   updater   	Exceptionrk   r  r#   r'   r   methodr   OPTIMIZEr  r   r   r   r,  r.   r   rP   rR   r&   r   r   r!   )rs   r   rl  r;  r   r   r   r   r   r   r   r   r   rk  r   cmdstan_modery   mode_jacobianlaplace_argsr   r   r   r   s                          r|   laplace_samplezCmdStanModel.laplace_sampleQ  s;   P "!R9  D$4E  <$$ , ,"$"(
M   R0(.(9M*%	+84== ,,#, D*-#D>LL%%8H 
 %%11:: 	 H$119
 ;66C_F  #))!,eX
 d# 	u

%!)(D Na(CF)	  	* 	!!#fl33g  "M :	 	s%   "F) 6AG)	G2F>>GGr   r   r   c           	         t               j                  d       t               j                  dt        t        j                  j                  d                   d}d}j                  r<dj                  j                           }dj                  j                           }j                        }	t               j                  d|	       |st               j                  d	|       	 t        j                     d
      }
t        j                  |	dt        j                  t        j                   t        j"                  t        j                  d      |r6dfd}t%        j&                  ||      }d|_        |j+                          nd}j-                         uj.                  Xj.                  j1                         }|
j3                  |       |j5                         }|rt7        | |        n|	 ||       j-                         uj9                         \  }}j:                  }j=                  |       |r|j?                          |r:|
j3                  |       |r'|jA                  d      }|D ]  }t7        | |         |
jC                          	 |
jC                          |st               j                  d|       |dk7  r@tI        |      }d}	 t        jJ                  |      }t               jQ                  d|||       yy# tD        $ r+}dj                  t        |            }tG        |      |d}~ww xY w# 
jC                          w xY w# tL        tN        f$ r Y {w xY w)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  rf  envuniversal_newlinesNc                  l    j                         y j                          j                   d       y )NT)poll	terminate_set_timeout_flag)r   rj  r   s   r|   _timer_targetz0CmdStanModel._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+   rh   rq   r[   rl   rm   r   rZ   r   r   r   rd   r  rc  PopenDEVNULLPIPESTDOUT	threadingTimerdaemonstartr  r  readliner  rX   printcommunicatere  _set_retcodecancelr`   closeOSErrorrk   r,   strerrorArithmeticErrorrY   r   )rs   r   r   r   r   r   r   logger_prefixconsole_prefixr   rG   r  timerr   r  rt   retcoder   ry   r   retcode_summaryserrorrj  s    ``                   @r|   r   z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 "?#))+%;;*;;//1DLL&::<D# 078&2%dC0 ))+% ((*IFAooGW-V$"LL.E % 9 0789LLN
 LLNL2MBa<,W5OFW- L!=/6   	+*11#a&9Cs#*	+ LLN $Z0 s>   2D+L  BL  -M,  	M)&MMM M),M>=M>r   c                      t        j                  d       D ci c]  }|t        dddigd| d       c}dt        d	t        d
df fd}|S c c}w )a  
        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                    | dk(  rVj                         D ]B  }d|j                  d   d<   |j                  |j                  z
         |j	                          D y j                  |       }|r:t        |j                  d            }|j                  d      j                         }n| j                  d      r| }|   }ny d|v r
d	|   _
        |   j                  d       ||   j                  d   d<   y )
Nr   zSampling completedr   r  r/   rB   	IterationSamplingblue)valuesr  ro  nr  matchr  grouprX   
startswithr  )	r   r   pbarr  mliner   rC  pbarsr   s	        r|   r   z?CmdStanModel._wrap_sampler_progress_hook.<locals>.progress_hookh  s    v~!LLN !D/CDLLOG,KK/JJL!
 		$ekk!n-C!KKN002E__[1 E#C.C&(.E#J%c
!!!$16c
""1%g.r   )r>  r3   r   rq   r  )r   r   r  r   rC  r  s   ``  @@r|   r  z(CmdStanModel._wrap_sampler_progress_hookP  s     jj9: &	"
  dI!8,-hZ( 	"
	7 	7# 	7$ 	7 	7* A	"
s   A)NNNFNNN)FFN   )FNNNF)NNNNNFNNNNNNNNNFTFNr   NF)NNNNNNNNNFNNNNTNNNNFNNFFTFNr   N)	NNNNNFNr   N)NNNNNFFNNNNNTNNNNTFNr   N)N)NNN)FFNN)8__name__
__module____qualname____doc__r   rq   OptionalPathboolr
   r   r   r   r}   r   propertyr   r5   r6   r   rg   r   r  rZ   r8   r9   r:   r   r3   r   r[   PathLikefloatr#   r   r   r"   r&  r1   r    r4  r%   rG  r$   rT  rg  	DataFramerW  r!   rv  r&   r	   r   staticmethodr
  wrap_callbackr  rn  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[   ri   r>  r  rc  r  r`  r  collectionsr   concurrent.futuresr   ior   multiprocessingr   typingr   r	   r
   r   r   r   r   r   r   r   pandasrg  	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
  rq   r  r  r1   r   rn  r   r|   <module>r     s     	  	   
   # 1  %     	 	 		 	 	  D !S"++t+,e[*i8t  t r   