
    %g{                        d Z ddlZddl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 ddlZddlZ	 ddlZdZddlmZmZmZmZ ddlmZmZ dd	lm Z m!Z!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z'm(Z( d
dl)m*Z* d
dl+m,Z,  G d d      Z-y# e$ r dZY Jw xY w)z>
Container for the result of running the sample (MCMC) method
    N)StringIO)	AnyDictHashableListMutableMappingOptionalSequenceTupleUnionTF)_CMDSTAN_SAMPLING_CMDSTAN_THIN_CMDSTAN_WARMUP_TMPDIR)MethodSamplerArgs)		EXTENSIONbuild_xarray_datacheck_sampler_csvcmdstan_pathcmdstan_version_beforecreate_named_text_file
do_commandflatten_chains
get_logger   )InferenceMetadata)RunSetc                      e Zd ZdZdeddfdZdefdZdedej                  fdZ
defd	Zedefd
       Zedee   fd       Zedefd       Zedefd       Zedefd       Zedeedf   fd       Zedee   fd       Zedeej                     fd       Zedeej                     fd       Zedefd       Zedeej                     fd       Zedeej                     fd       Zddddededej                  fdZ de!ee"f   fdZ#d-dZ$d-dZ%	 	 d.de&e   d ede'jP                  fd!Z)dee   fd"Z*	 	 d/d#e+ee   edf   dede'jP                  fd$Z,	 d/d#e+eee   df   dedd%fd&Z-	 d0d'ededej                  fd(Z.de!eej                  f   fd)Z/de!eej                  f   fd*Z0d1d+ee   ddfd,Z1y)2CmdStanMCMCa  
    Container for outputs from CmdStan sampler run.
    Provides methods to summarize and diagnose the model fit
    and accessor methods to access the entire sample or
    individual items. Created by :meth:`CmdStanModel.sample`

    The sample is lazily instantiated on first access of either
    the resulting sample or the HMC tuning parameters, i.e., the
    step size and metric.
    runsetreturnNc                 H   |j                   t        j                  k(  s$t        dj	                  |j                               || _        | j
                  j                  j                  }t        |t              sJ t        | _        |j                  |j                  | _        t        | _        |j                  |j                  | _        t         | _        |j$                  |j$                  | _        |j&                  | _        |j*                  | _        |j                  j.                  | _        t3        j4                  d      | _        t3        j4                  d      | _        t3        j4                  d      | _        t3        j<                  | j
                  j>                  t@              | _!        t3        j<                  | j
                  j>                  t@              | _"        | jG                         }tI        |      | _%        | j(                  s| jM                          yy)zInitialize object.z=Wrong runset method, expecting sample runset, found method {}N dtype)'methodr   SAMPLE
ValueErrorformatr!   _argsmethod_args
isinstancer   r   _iter_samplingiter_samplingr   _iter_warmupiter_warmupr   _thinthinfixed_param_is_fixed_paramsave_warmup_save_warmupsig_figs	_sig_figsnparray_draws_metric
_step_sizezeroschainsint_divergences_max_treedepths_validate_csv_filesr   	_metadata_check_sampler_diagnostics)selfr!   sampler_argsconfigs       S/var/www/dash_apps/app1/venv/lib/python3.12/site-packages/cmdstanpy/stanfit/mcmc.py__init__zCmdStanMCMC.__init__=   s   
 }}-""(&"7   {{((44+
 	
 
 $5%%1"."<"<D!0##/ , 8 8D'
(%**DJ+77".":":.. #%((2,#%88B<&(hhrl(*1C1C3(O+-88KKc,

 ))+,=f,E##++- $    c                    dj                  | j                  j                  | j                  j                  | j                  j                  j
                  j                  dg             }dj                  |dj                  | j                  j                        dj                  | j                  j                              }|S )Nz!CmdStanMCMC: model={} chains={}{}r   )cmdz%{}
 csv_files:
	{}
 output_files:
	{}
	)
r*   r!   modelr@   r+   r,   composejoin	csv_filesstdout_files)rG   reprs     rJ   __repr__zCmdStanMCMC.__repr__k   s    299KKKKKK))11!1<

 =CCKK--.KK001
 rL   attrc                     |j                  d      rt        d|       	 | j                  |      S # t        $ r}t        |j                   d}~ww xY w)z)Synonymous with ``fit.stan_variable(attr)_zUnknown variable name N)
startswithAttributeErrorstan_variabler)   args)rG   rW   es      rJ   __getattr__zCmdStanMCMC.__getattr__y   sV    ??3 #9$!@AA	*%%d++ 	* !&&))	*s   2 	AAAc                 :    | j                          | j                  S N)_assemble_draws__dict__rG   s    rJ   __getstate__zCmdStanMCMC.__getstate__   s    
 	}}rL   c                 .    | j                   j                  S )zNumber of chains.)r!   r@   rd   s    rJ   r@   zCmdStanMCMC.chains   s     {{!!!rL   c                 .    | j                   j                  S )z
Chain ids.)r!   	chain_idsrd   s    rJ   rh   zCmdStanMCMC.chain_ids   s     {{$$$rL   c                 l    t        t        j                  | j                  | j                  z              S )zBNumber of warmup draws per chain, i.e., thinned warmup iterations.)rA   mathceilr0   r2   rd   s    rJ   num_draws_warmupzCmdStanMCMC.num_draws_warmup   s'     499d//4::=>??rL   c                 l    t        t        j                  | j                  | j                  z              S )zn
        Number of sampling (post-warmup) draws per chain, i.e.,
        thinned sampling iterations.
        )rA   rj   rk   r.   r2   rd   s    rJ   num_draws_samplingzCmdStanMCMC.num_draws_sampling   s'     499d11TZZ?@AArL   c                     | j                   S )z
        Returns object which contains CmdStan configuration as well as
        information about the names and structure of the inference method
        and model output variables.
        )rE   rd   s    rJ   metadatazCmdStanMCMC.metadata   s     ~~rL   .c                 4    | j                   j                  d   S )a9  
        Names of all outputs from the sampler, comprising sampler parameters
        and all components of all model parameters, transformed parameters,
        and quantities of interest. Corresponds to Stan CSV file header row,
        with names munged to array notation, e.g. `beta[1]` not `beta.1`.
        column_names)rE   cmdstan_configrd   s    rJ   rr   zCmdStanMCMC.column_names   s     ~~,,^<<rL   c                 P    | j                   s| j                  j                  d   S dS )z
        Metric type used for adaptation, either 'diag_e' or 'dense_e', according
        to CmdStan arg 'metric'.
        When sampler algorithm 'fixed_param' is specified, metric_type is None.
        metricN)r5   rE   rs   rd   s    rJ   metric_typezCmdStanMCMC.metric_type   s0     '' NN))(3	
 	
rL   c                     | j                   ry| j                  j                  d   dk(  rt               j	                  d       y| j                          | j                  S )z
        Metric used by sampler for each chain.
        When sampler algorithm 'fixed_param' is specified, metric is None.
        Nru   unit_ez8Unit diagnonal metric, inverse mass matrix size unknown.)r5   rE   rs   r   inforb   r=   rd   s    rJ   ru   zCmdStanMCMC.metric   sU     >>((2h>LJ ||rL   c                 V    | j                          | j                  s| j                  S dS )z
        Step size used by sampler for each chain.
        When sampler algorithm 'fixed_param' is specified, step size is None.
        N)rb   r5   r>   rd   s    rJ   	step_sizezCmdStanMCMC.step_size   s'     	&*&:&:tDDrL   c                     | j                   S )zF
        Period between recorded iterations.  (Default is 1).
        )r2   rd   s    rJ   r3   zCmdStanMCMC.thin   s    
 zzrL   c                 6    | j                   s| j                  S dS )z
        Per-chain total number of post-warmup divergent iterations.
        When sampler algorithm 'fixed_param' is specified, returns None.
        N)r5   rB   rd   s    rJ   divergenceszCmdStanMCMC.divergences   s     )-(<(<t  F$FrL   c                 6    | j                   s| j                  S dS )z
        Per-chain total number of post-warmup iterations where the NUTS sampler
        reached the maximum allowed treedepth.
        When sampler algorithm 'fixed_param' is specified, returns None.
        N)r5   rC   rd   s    rJ   max_treedepthszCmdStanMCMC.max_treedepths   s     ,0+?+?t##ITIrL   F
inc_warmupconcat_chainsr   r   c                   | j                          |r%| j                  st               j                  d       d}|s| j                  r| j                  }|r!t        | j                  |dddddf         S | j                  |dddddf   S )a1  
        Returns a numpy.ndarray over all draws from all chains which is
        stored column major so that the values for a parameter are contiguous
        in memory, likewise all draws from a chain are contiguous.
        By default, returns a 3D array arranged (draws, chains, columns);
        parameter ``concat_chains=True`` will return a 2D array where all
        chains are flattened into a single column, preserving chain order,
        so that given M chains of N draws, the first N draws are from chain 1,
        up through the last N draws from chain M.

        :param inc_warmup: When ``True`` and the warmup draws are present in
            the output, i.e., the sampler was run with ``save_warmup=True``,
            then the warmup draws are included.  Default value is ``False``.

        :param concat_chains: When ``True`` return a 2D array flattening all
            all draws from all chains.  Default value is ``False``.

        See Also
        --------
        CmdStanMCMC.draws_pd
        CmdStanMCMC.draws_xr
        CmdStanGQ.draws
        z[Sample doesn't contain draws from warmup iterations, rerun sampler with "save_warmup=True".r   N)rb   r7   r   warningrl   r   r<   )rG   r   r   	start_idxs       rJ   drawszCmdStanMCMC.draws   s    4 	d//L  :
 	d//--I!$++ij!Q.>"?@@{{9:q!+,,rL   c                    i }t        | j                        D ]q  }|dk(  rt        | j                  j                  |   | j
                  | j                  | j                  | j                  | j                        }| j
                  rp|d   | j                  |<   |d   | j                  |<   t        | j                  j                  |   | j
                  | j                  | j                  | j                  | j                        }|D ]L  }|dv s||   ||   k7  st        dj                  | j                  j                  |   |||   ||                | j
                  rN|d   | j                  |<   |d   | j                  |<   t |S )a  
        Checks that Stan CSV output files for all chains are consistent
        and returns dict containing config and column names.

        Tabulates sampling iters which are divergent or at max treedepth
        Raises exception when inconsistencies detected.
        r   )pathis_fixed_paramr/   r1   r6   r3   ct_divergencesct_max_treedepth)
stan_version_majorstan_version_minorstan_version_patchstanc_versionrP   num_samples
num_warmupr6   r3   refreshzFCmdStan config mismatch in Stan CSV file {}: arg {} is {}, expected {})ranger@   r   r!   rS   r5   r.   r0   r7   r2   rB   rC   r)   r*   )rG   dzeroidrestkeys        rJ   rD   zCmdStanMCMC._validate_csv_files  s    t{{# 3	HAAv)..q1#'#7#7"&"5"5 $ 1 1 $ 1 1 +++01A+BD%%a(.34F.GD((+)..q1#'#7#7"&"5"5 $ 1 1 $ 1 1 ! C  "#J%*4(88> $ 5 5a 8 # %c
 %c
	9 %6 +++01A+BD%%a(.34F.GD((+g3	Hh rL   c           
         t        j                  | j                        s t        j                  | j                        rdg}| j                  j
                  d   }t        | j                  j                        D ]  }| j                  |   dkD  r?|j                  d|dz    d| j                  |    d| j                  |   |z  dz  d	d
       | j                  |   dkD  sg|j                  d|dz    d| j                  |    d| j                  |   |z  dz  d	d
        |j                  d       t               j                  dj                  |             yy)zR
        Warn if any iterations ended in divergences or hit maxtreedepth.
        z(Some chains may have failed to converge.r   r   zChain r   z had z divergent transitions (d   z.1fz%)z iterations at max treedepth (zQUse the "diagnose()" method on the CmdStanMCMC object to see further information.rO   N)r:   anyrB   rC   rE   rs   r   r!   _chainsappendr   r   rR   )rG   diagnosticsct_itersr   s       rJ   rF   z&CmdStanMCMC._check_sampler_diagnostics\  sk    66$##$t/C/C(DEFK~~44]CH4;;../ $$Q'!+&& QuT->->q-A,B C"//28;S@#FbJ
 ''*Q.&& QuT-A-A!-D,E F"2215h>CSIM / L  [!9:) )ErL   c           	      H   | j                   j                  dk7  ry| j                  }d}| j                  r|| j                  z  }| j                  }t        j                  || j                  t        | j                        ft        d      | _         t        j                  | j                  t              | _        t        | j                        D ]  }t        | j                  j                  |   d      5 }|j!                         j#                         }t        |      dkD  rO|j%                  d      r>|j!                         j#                         }t        |      dkD  r|j%                  d      r>| j&                  sx| j                  rtt        | j                        D ]\  }|j!                         j#                         }|j)                  d	      }|D cg c]  }t        |       c}| j                   ||ddf<   ^ |j!                         j#                         }|d
k7  r)|d
k7  r$|j!                         j#                         }|d
k7  r$|j!                         j#                         }|j)                  d      \  }	}
t        |
j#                               | j                  |<   | j*                  j,                  d   dk7  r|j!                         j#                         }|j!                         j/                  d      j1                         }t        |j)                  d	            }|dk(  ri| j2                  dk(  r-t        j                  | j                  |ft              | _        n-t        j                  | j                  ||ft              | _        |ra| j2                  dk(  r=|j)                  d	      }|D cg c]  }t        |       c}| j4                  |ddf<   n|j#                         j)                  d	      }|D cg c]  }t        |       c}| j4                  |dddf<   t        d|      D ]k  }|j!                         j/                  d      j1                         }|j)                  d	      }|D cg c]  }t        |       c}| j4                  ||ddf<   m nP|j7                         }|j!                         j#                         }|j%                  d      s|j9                  |       t        ||      D ]\  }|j!                         j#                         }|j)                  d	      }|D cg c]  }t        |       c}| j                   ||ddf<   ^ 	 ddd        | j                   J yc c}w c c}w c c}w c c}w c c}w # 1 sw Y   xY w)z
        Allocates and populates the step size, metric, and sample arrays
        by parsing the validated stan_csv files.
        )r   Nr   F)r&   orderr%   r#,z# Adaptation terminated=ru   rx   z #	diag_er   )r<   shapern   r7   rl   r:   emptyr@   lenrr   floatr>   r   openr!   rS   readlinestriprZ   r5   splitrE   rs   lstriprstriprv   r=   tellseek)rG   	num_drawssampling_iter_startchainfdliner   xsxrY   r{   num_unconstrained_paramsposs                rJ   rb   zCmdStanMCMC._assemble_drawsv  s   
 ;;$++	...I"&"7"7hhS):):%;<

 ((4;;e<4;;' A	FEdkk++E2C8 @FB{{}**,$i!m(<;;=..0D $i!m(<++((!&t'<'<!= NA#%;;=#6#6#8D!%CBJL7MQa7MDKK5!4N ;;=..0D88"&??#%;;=#6#6#8D #&?? ;;=..0D#'::c?LAy-29??3D-EDOOE*~~44X>(J!{{}224!{{}33F;BBD36tzz#3G0 A:#//8;/1xx%)[[2J$K*/0"
 02xx(,(@(@%&
 +00"  #//8;%)ZZ_LN9Oq%(9OUAX 6%)ZZ\%7%7%<68="12E!H="UAq[ 9 */q2J)K !&A+-;;=+?+?+G+N+N+PD)-CB:<A&56aA&DLL1$=!& !ggi!{{}224#s3GGCL 2I> FA;;=..0DCBBD/EQa/EDKK5!,F{@F @FA	FD {{&&&m 8N> :P="A& 0FA@F @Fs`   7A;V3A$VU>
)A"VE/V;V9VVA&V>V
B*V:V
V>VV!	percentilesr8   c           	         t        |      dk(  rt        d      d}|D ]  }|dkD  s||kD  st        d      |} ddj                  d |D               }t        |t              r
|dk  s|d	kD  rt        d
j                  |            | j                  xs d}||kD  rt               j                  d||       d| }t        j                  j                  t               ddt        z         }dj                  | j                  j                  j                        }	t!        t"        |	dd      }
dj                  |
      }t%        dd      rdj                  |
      }||||g| j                  j&                  z   }t)        |d       t+        |
d      5 }t-        j.                  |ddddd      }ddd       | j0                  r*j2                  D cg c]  }|j5                  d        c}n0j2                  D cg c]  }|dk(  xs |j5                  d        c}}d|j2                  _        ||   S # 1 sw Y   xY wc c}w c c}w ) aN  
        Run cmdstan/bin/stansummary over all output CSV files, assemble
        summary into DataFrame object.  The first row contains statistics
        for the total joint log probability `lp__`, but is omitted when the
        Stan model has no parameters.  The remaining rows contain summary
        statistics for all parameters, transformed parameters, and generated
        quantities variables, in program declaration order.

        :param percentiles: Ordered non-empty sequence of percentiles to report.
            Must be integers from (1, 99), inclusive. Defaults to
            ``(5, 50, 95)``

        :param sig_figs: Number of significant figures to report.
            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.
            If precision above 6 is requested, sample must have been produced
            by CmdStan version 2.25 or later and sampler output precision
            must equal to or greater than the requested summary precision.

        :return: pandas.DataFrame
        r   zUInvalid percentiles argument, must be ordered non-empty list from (1, 99), inclusive.c   zQInvalid percentiles spec, must be ordered non-empty list from (1, 99), inclusive.z--percentiles= r   c              3   2   K   | ]  }t        |        y wra   )str).0r   s     rJ   	<genexpr>z&CmdStanMCMC.summary.<locals>.<genexpr>  s     &C!s1v&Cs   r      z@Keyword "sig_figs" must be an integer between 1 and 18, found {}   z[Requesting %d significant digits of output, but CSV files only have %d digits of precision.z--sig_figs=binstansummaryzstansummary-{}-z.csvT)dirprefixsuffix	name_onlyz--csv_filename={}      z--csv_file={}N)fd_outrbr   high)	delimiterheader	index_colcommentfloat_precision__lp__)r   r)   rR   r-   rA   r*   r9   r   r   osr   r   r   r!   r+   
model_namer   r   r   rS   r   r   pdread_csvr5   indexendswithname)rG   r   r8   cur_pctpctpercentiles_strcsv_sig_figssig_figs_strcmd_pathtmp_csv_filetmp_csv_pathcsv_strrN   r   summary_datar   masks                    rJ   summaryzCmdStanMCMC.summary  st   4 {q ;   	CRxsW} ?  G	 chh&C{&CCDE 	 (C(HqLHrM"F8,  ~~*l"L  5	 %XJ/77<<NE=9#<
 )//0A0A0L0LM-Vt
 &,,\:!!R(%,,\:G	

 KK!!" 	3t$,% 	;; &L	 ## ,8+=+=>aD!!> >J=O=O89V31::d#333 	 #'D!!#	 	 ?s   H5I< I5H>c                     t         j                  j                  t               ddt        z         }|g| j
                  j                  z   }t               }t        ||       |j                         S )a  
        Run cmdstan/bin/diagnose over all output CSV files,
        return console output.

        The diagnose utility reads the outputs of all chains
        and checks for the following potential problems:

        + Transitions that hit the maximum treedepth
        + Divergent transitions
        + Low E-BFMI values (sampler transitions HMC potential energy)
        + Low effective sample sizes
        + High R-hat values
        r   diagnose)rN   r   )
r   r   rR   r   r   r!   rS   r   r   getvalue)rG   r   rN   results       rJ   r   zCmdStanMCMC.diagnose*  sU     77<<zI7MNj4;;000s6*  rL   varsc                    |t        |t              r|g}n|}|r%| j                  st               j	                  d       | j                          g }|t        j                        D ]  }|| j                  j                  v r|j                  |       -|| j                  j                  v rL| j                  j                  |   }|j                  | j                  |j                  |j                          |dv r|j                  |       t!        d|        ng dt#        | j                        z   }| j%                  |      }|j&                  \  }}	}
t)        j*                  t)        j,                  d|	dz         |      j/                  d|	|      j0                  }t)        j2                  t)        j,                  d|dz         |	      j/                  d|	|      j0                  }t)        j,                  d||	z  dz         j/                  d|	|      j0                  }t)        j4                  ||||gd      }t7        j8                  t;        |      g dt#        | j                        z         |   S )	a  
        Returns the sample draws as a pandas DataFrame.
        Flattens all chains into single column.  Container variables
        (array, vector, matrix) will span multiple columns, one column
        per element. E.g. variable 'matrix[2,2] foo' spans 4 columns:
        'foo[1,1], ... foo[2,2]'.

        :param vars: optional list of variable names.

        :param inc_warmup: When ``True`` and the warmup draws are present in
            the output, i.e., the sampler was run with ``save_warmup=True``,
            then the warmup draws are included.  Default value is ``False``.

        See Also
        --------
        CmdStanMCMC.draws
        CmdStanMCMC.draws_xr
        CmdStanGQ.draws_pd
        UDraws from warmup iterations not available, must run sampler with "save_warmup=True".)chain__iter__draw__zUnknown variable: r   r   r   )axis)datacolumns)r-   r   r7   r   r   rb   dictfromkeysrE   method_varsr   	stan_varsextendrr   r   end_idxr)   listr   r   r:   repeatarangereshapeTtileconcatenater   	DataFramer   )rG   r   r   	vars_listcolsvarry   r   n_drawsn_chainsrY   
chains_coliter_coldraw_cols                 rJ   draws_pdzCmdStanMCMC.draws_pd>  s+   0 $$!F	 	d//L  =
 	}}Y/ A$..444KK$DNN444>>33C8DKK))$..4<<H ;;KK$$'9#%?@@A 3T$:K:K5LLD

j
1${{1IIbii8a<0':WQ'*Q 	 GGBIIa1-x8WQ'*Q 	 IIa'H,12WQ'*Q 	
 
HhFQO||&3d4;L;L6MM
  	rL   z
xr.Datasetc                    t         st        d      |r%| j                  st               j	                  d       |.t        | j                  j                  j                               }nt        |t              r|g}n|}| j                          | j                  }| j                  j                  }|d    d|d    d|d    |d   |d}|r*| j                  r|| j                  z  }| j                  |d	<   i }| j                  t!        j"                  |      d
}|D ]6  }	t%        || j                  j                  |	   | j'                  |             8 t)        j*                  |||      j-                  ddd      S )a  
        Returns the sampler draws as a xarray Dataset.

        :param vars: optional list of variable names.

        :param inc_warmup: When ``True`` and the warmup draws are present in
            the output, i.e., the sampler was run with ``save_warmup=True``,
            then the warmup draws are included.  Default value is ``False``.

        See Also
        --------
        CmdStanMCMC.draws
        CmdStanMCMC.draws_pd
        CmdStanGQ.draws_xr
        z>Package "xarray" is not installed, cannot produce draws array.r   r   .r   r   rP   )stan_versionrP   rn   rl   )r   drawr   )coordsattrsr   r  .)XARRAY_INSTALLEDRuntimeErrorr7   r   r   r   rE   r   keysr-   r   rb   rn   rs   rl   rh   r:   r  r   r   xrDataset	transpose)
rG   r   r   r  r   metar  r   coordinatesr	  s
             rJ   draws_xrzCmdStanMCMC.draws_xr  s   $  P  d//L  = <T^^55::<=Ic"II++	~~,,#$89:!()*!D1E,F+GI']"+	0
 $++...I(,(=(=E$%.0^^IIi(6

  	C((-

j
1	 zz${%@JJVS
 	
rL   r	  c                    	 | j                  |d      }| j                  j                  |   j                  |      }|S # t        $ rD t        d| ddj                  | j                  j                  j                               z         w xY w)a  
        Return a numpy.ndarray which contains the set of draws
        for the named Stan program variable.  Flattens the chains,
        leaving the draws in chain order.  The first array dimension,
        corresponds to number of draws or post-warmup draws in the sample,
        per argument ``inc_warmup``.  The remaining dimensions correspond to
        the shape of the Stan program variable.

        Underlyingly draws are in chain order, i.e., for a sample with
        N chains of M draws each, the first M array elements are from chain 1,
        the next M are from chain 2, and the last M elements are from chain N.

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

        For example, if the Stan program variable ``theta`` is a 3x3 matrix,
        and the sample consists of 4 chains with 1000 post-warmup draws,
        this function will return a numpy.ndarray with shape (4000,3,3).

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

        :param var: variable name

        :param inc_warmup: When ``True`` and the warmup draws are present in
            the output, i.e., the sampler was run with ``save_warmup=True``,
            then the warmup draws are included.  Default value is ``False``.

        See Also
        --------
        CmdStanMCMC.stan_variables
        CmdStanMLE.stan_variable
        CmdStanPathfinder.stan_variable
        CmdStanVB.stan_variable
        CmdStanGQ.stan_variable
        CmdStanLaplace.stan_variable
        Tr   zUnknown variable name: z
Available variables are z, )r   rE   r   extract_reshapeKeyErrorr)   rR   r  )rG   r	  r   r   outs        rJ   r\   zCmdStanMCMC.stan_variable  s    `	JJ*DJIE"nn66s;KKC J 	)# /+ +))DNN4499;<= 	s
   <? ABc                 h    i }| j                   j                  D ]  }| j                  |      ||<    |S )a  
        Return a dictionary mapping Stan program variables names
        to the corresponding numpy.ndarray containing the inferred values.

        See Also
        --------
        CmdStanMCMC.stan_variable
        CmdStanMLE.stan_variables
        CmdStanPathfinder.stan_variables
        CmdStanVB.stan_variables
        CmdStanGQ.stan_variables
        CmdStanLaplace.stan_variables
        )rE   r   r\   )rG   r   r   s      rJ   stan_variableszCmdStanMCMC.stan_variables  s;     NN,, 	4D--d3F4L	4rL   c                     | j                          | j                  j                  j                         D ci c]!  \  }}||j	                  | j
                        # c}}S c c}}w )aH  
        Returns a dictionary of all sampler variables, i.e., all
        output column names ending in `__`.  Assumes that all variables
        are scalar variables where column name is variable name.
        Maps each column name to a numpy.ndarray (draws x chains x 1)
        containing per-draw diagnostic values.
        )rb   rE   r   itemsr   r<   )rG   r   r	  s      rJ   method_variableszCmdStanMCMC.method_variables  s]     	 "^^77==?
c #%%dkk22
 	
 
s   &A"r   c                 :    | j                   j                  |       y)a  
        Move output CSV files to specified directory.  If files were
        written to the temporary session directory, clean filename.
        E.g., save 'bernoulli-201912081451-1-5nm6as7u.csv' as
        'bernoulli-201912081451-1.csv'.

        :param dir: directory path

        See Also
        --------
        stanfit.RunSet.save_csvfiles
        cmdstanpy.from_csv
        N)r!   save_csvfiles)rG   r   s     rJ   r)  zCmdStanMCMC.save_csvfiles,  s     	!!#&rL   )r"   N))   2   _   r   )NF)Fra   )2__name__
__module____qualname____doc__r   rK   r   rV   r:   ndarrayr_   r   re   propertyrA   r@   r   rh   rl   rn   r   rp   r   rr   r	   rv   ru   r{   r3   r~   r   boolr   r   r   rD   rF   rb   r
   r   r  r   r   r   r  r  r\   r$  r'  r)  r$   rL   rJ   r    r    0   sQ   	,.,. 
,.\# * *

 *d  " " " %49 % % @# @ @ BC B B +   =eCHo = = 

Xc] 

 

 ,   E8BJJ/ E E c   GXbjj1 G G J 4 J J %*(-!(-:>(-	(-T=T#s(^ =~;4T'p &1\"c]\" \" 
	\"|!(3- !, -1 MDIsD()M M 
	M` LQ>
#tCy$./>
DH>
	>
F !<< < 
	<|S"**_ 5 &
$sBJJ"7 
'# '$ 'rL   r    ).r0  rj   r   ior   typingr   r   r   r   r   r	   r
   r   r   numpyr:   pandasr   xarrayr  r  ImportError	cmdstanpyr   r   r   r   cmdstanpy.cmdstan_argsr   r   cmdstanpy.utilsr   r   r   r   r   r   r   r   r   rp   r   r!   r   r    r$   rL   rJ   <module>r=     s     	 
 
 
   Q P 6
 
 
 ( J' J'+  s   A7 7B B