
    ]he                         S r SSKJr  SSKJrJrJrJrJrJ	r	J
r
JrJrJrJrJr  SSKrSSKr SSKrSrSSKJr  SSKJrJrJr  SS	KJr  S
SK J!r!  S
SK"J#r#  S
SK$J%r%  S
SK&J'r'  S
SK(J)r)  \" S\!\%\)5      r* " S S\\*   5      r+g! \ a    Sr NXf = f)zI
Container for the result of running the
generate quantities (GQ) method
    )Counter)AnyDictGenericHashableListMutableMappingNoReturnOptionalTupleTypeVarUnionoverloadNTF)Method)build_xarray_dataflatten_chains
get_logger)scan_generic_csv   )CmdStanMCMC)InferenceMetadata)
CmdStanMLE)RunSet)	CmdStanVBFitc                   \   \ rS rSrSrS\S\SS4S jrS\4S jr	S	\S\
R                  4S
 jrS\4S jrS\\\4   4S jr\S\4S j5       r\S\\   4S j5       r\S\\S4   4S j5       r\S\4S j5       rSSSSS.S\S\S\S\S\
R                  4
S jjr   S.S\\\   \S4   S\S\S\R>                  4S jjr \!   S.S\S   S\\\\   S4   S\S\S\"4
S jj5       r#\!   S.SSS\\\\   S4   S\S\SS4
S  jj5       r#   S.S\\\\   S4   S\S\SS4S! jjr#S"\S#\S\
R                  4S$ jr$S#\S\\\
R                  4   4S% jr%S/S& jr&S\S\\\4   4S' jr'S\S\
R                  4S( jr(S\\   S\S\R>                  4S) jr)S0S*\*\   SS4S+ jjr+\S\\,\-\.4   4S, j5       r/S-r0g)1	CmdStanGQ.   zr
Container for outputs from CmdStan generate_quantities run.
Created by :meth:`CmdStanModel.generate_quantities`.
runsetprevious_fitreturnNc                    UR                   [        R                  :X  d$  [        SR	                  UR                   5      5      eXl        X l        [        R                  " S5      U l	        U R                  5       n[        U5      U l        g)zInitialize object.zJWrong runset method, expecting generate_quantities runset, found method {} N)methodr   GENERATE_QUANTITIES
ValueErrorformatr   r    nparray_draws_validate_csv_filesr   	_metadata)selfr   r    configs       gC:\Users\julio\OneDrive\Documentos\Trabajo\Ideas Frescas\venv\Lib\site-packages\cmdstanpy/stanfit/gq.py__init__CmdStanGQ.__init__4   sl     }} : ::""(&"7  !-"$((2,))+*62    c           	      r   SR                  U R                  R                  U R                  U R                  R                  R
                  R                  S/ S95      nSR                  USR                  U R                  R                  5      SR                  U R                  R                  5      5      nU$ )NzCmdStanGQ: model={} chains={}{}r   )cmdz%{}
 csv_files:
	{}
 output_files:
	{}z
	)
r'   r   modelchains_argsmethod_argscomposejoin	csv_filesstdout_files)r-   reprs     r/   __repr__CmdStanGQ.__repr__G   s    077KKKKKK))11!1<

 =CCKK--.KK001

 r2   attrc                     UR                  S5      (       a  [        SU 35      e U R                  U5      $ ! [         a  n[        UR                  6 eSnAff = f)z)Synonymous with ``fit.stan_variable(attr)_zUnknown variable name N)
startswithAttributeErrorstan_variabler&   args)r-   r@   es      r/   __getattr__CmdStanGQ.__getattr__T   sY    ??3 #9$!@AA	*%%d++ 	* !&&))	*s   7 
AAAc                 :    U R                  5         U R                  $ N)_assemble_generated_quantities__dict__r-   s    r/   __getstate__CmdStanGQ.__getstate__^   s    
 	++-}}r2   c                 x   0 n[        U R                  5       H  nUS:X  a"  [        U R                  R                  U   S9nM+  [        U R                  R                  U   S9nU HM  nUS;  d  M  X   X4   :w  d  M  [        SR                  U R                  R                  U   UX   X4   5      5      e   M     U$ )z
Checks that Stan CSV output files for all chains are consistent
and returns dict containing config and column names.

Raises exception when inconsistencies detected.
r   )path)idfitted_paramsdiagnostic_filemetric_fileprofile_fileinitseedstart_datetimezFCmdStan config mismatch in Stan CSV file {}: arg {} is {}, expected {})ranger6   r   r   r;   r&   r'   )r-   dzeroidrestkeys        r/   r+   CmdStanGQ._validate_csv_filesf   s     t{{#AAv(..q1 )..q1 !C	 
 "J%*4(88> $ 5 5a 8 # %
 %
	9  ! $B r2   c                 .    U R                   R                  $ )zNumber of chains.)r   r6   rN   s    r/   r6   CmdStanGQ.chains   s     {{!!!r2   c                 .    U R                   R                  $ )z
Chain ids.)r   	chain_idsrN   s    r/   rd   CmdStanGQ.chain_ids   s     {{$$$r2   .c                 4    U R                   R                  S   $ )z,
Names of generated quantities of interest.
column_names)r,   cmdstan_configrN   s    r/   rg   CmdStanGQ.column_names   s    
 ~~,,^<<r2   c                     U R                   $ )z
Returns object which contains CmdStan configuration as well as
information about the names and structure of the inference method
and model output variables.
)r,   rN   s    r/   metadataCmdStanGQ.metadata   s     ~~r2   F)
inc_warmupinc_iterationsconcat_chains
inc_samplerm   rn   ro   rp   c          
      f   U R                  5         X-  nU(       a  [        U R                  [        5      (       a5  U R                  R                  (       d  [        5       R                  S5        O[        U R                  [        5      (       a5  U R                  R                  (       d  [        5       R                  S5        O8[        U R                  [        5      (       a  [        5       R                  S5        U(       a  U R                  R                  nU R                  n[        XV-   5      R                  5        VVs/ s H  u  pxUS:  d  M  UPM     n	nn/ n
U	 HC  nU
R                  U R                  R                  R                  U   R!                  5       5        ME     U R#                  U5      u  pU R%                  S5      nU(       aR  U(       aK  ['        [(        R*                  " [(        R,                  " UW
SS9U R.                  45      US2SS2SS24   5      $ U(       a!  ['        U R.                  US2SS2SS24   5      $ U(       aB  [(        R*                  " [(        R,                  " UW
SS9U R.                  45      US2SS2SS24   $ U R.                  US2SS2SS24   $ s  snnf )a  
Returns a numpy.ndarray over the generated quantities 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, ..., and the the last N draws
are 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``.

:param inc_sample: When ``True`` include all columns in the previous_fit
    draws array as well, excepting columns for variables already present
    in the generated quantities drawset. Default value is ``False``.

See Also
--------
CmdStanGQ.draws_pd
CmdStanGQ.draws_xr
CmdStanMCMC.draws
[Sample doesn't contain draws from warmup iterations, rerun sampler with "save_warmup=True".jMLE doesn't contain draws from pre-convergence iterations, rerun optimization with "save_iterations=True".BVariational fit doesn't make sense with argument "inc_warmup=True"r   TaxisN)rL   
isinstancer    r   _save_warmupr   warningr   _save_iterationsr   rg   r   itemsextendr,   	stan_varscolumns_draws_start_previous_drawsr   r(   dstackdeleter*   )r-   rm   rn   ro   rp   cols_1cols_2itemcountdups	drop_colsdup	start_idxrB   previous_drawss                  r/   drawsCmdStanGQ.draws   sJ   H 	++-$
4,,k::))66$$>
 4,,j99))::$$G D--y99$$(
 &&33F&&F $+6?#;#A#A#C#CKD19 #C  
 $&I  %%//99#>FFH 
 ((4	--d3Z!				.)!D
 *a"$  !$++ij!Q.>"?@@99IInia@KK
 j!Q    {{9:q!+,,?s   J-J-varsc                 8	   Ub9  [        U[        5      (       a  U/nOUn[        [        R	                  U5      5      nU(       a  [        U R
                  [        5      (       a5  U R
                  R                  (       d  [        5       R                  S5        O[        U R
                  [        5      (       a5  U R
                  R                  (       d  [        5       R                  S5        O8[        U R
                  [        5      (       a  [        5       R                  S5        U R                  5         / SQ[        U R                  5      -   n/ n/ nUGb.  W GH&  nXR                  R                   ;   aM  U R                  R                   U   n	UR#                  U R                  U	R$                  U	R&                   5        Mj  U(       a  XR
                  R                  R                   ;   aa  U R
                  R                  R                   U   n	UR#                  U R
                  R                  U	R$                  U	R&                   5        M  US;   a  UR)                  U5        GM  [+        SR-                  U5      5      e   OUnUnU R/                  Xr5      n
U R1                  US9nUR2                  u  pn[4        R6                  " [4        R8                  " SUS-   5      U5      R;                  SX5      R<                  n[4        R>                  " [4        R8                  " SUS-   5      U5      R;                  SX5      R<                  n[4        R8                  " SX-  S-   5      R;                  SX5      R<                  n[4        R@                  " UUUU/SS	9n[B        RD                  " [G        U5      US
9nU(       a-  U(       a&  U(       a  [B        RH                  " U
UU   /SS	9U   $ U
$ U(       a  Uc  [        U
RJ                  5      n[        URJ                  5      n[M        UU-   5      RO                  5        VVs/ s H  u  nnUS:  d  M  UPM     nnn[B        RH                  " U
RQ                  US9RS                  SS9U/SS	9$ U(       a  UU   $ U$ s  snnf )a]  
Returns the generated quantities 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
--------
CmdStanGQ.draws
CmdStanGQ.draws_xr
CmdStanMCMC.draws_pd
rr   rs   rt   )chain__iter__draw__Unknown variable: {}rm   r      ru   )datar~   r~   )r~   T)drop)*rw   strlistdictfromkeysr    r   rx   r   ry   r   rz   r   rL   rg   r,   r}   r|   r   end_idxappendr&   r'   _previous_draws_pdr   shaper(   repeatarangereshapeTtileconcatenatepd	DataFramer   concatr~   r   r{   r   reset_index)r-   r   rm   rp   	vars_listall_columnsgq_cols	mcmc_varsvarinfoprevious_draws_pdr   n_drawsn_chainsrB   
chains_coliter_coldraw_coldraws_pdr   r   r   r   r   s                           r/   r   CmdStanGQ.draws_pd  s   2 $$$!F	 	T]]956I4,,k::))66$$>
 4,,j99))::$$G D--y99$$(
 	++-5T=N=N8OO!	 ..222>>33C8DNN))$..4<<H 3*;*;*E*E*O*O#O,,66@@ED$$))66 NNT\\
 ;;NN3'$%;%B%B3%GHH% !( "GI 33IJ

j
1${{1IIbii8a<0':WQ*Q 	 GGBIIa1-x8WQ*Q 	 IIa',12WQ*Q 	
 
HhFQO<<&

 )yy) ) #   )(DL+334F(**+F $+6F?#;#A#A#C#CKD%19 #C  
 99%**4*8DD$DO   G$$s   =RRr-   )zCmdStanGQ[CmdStanMLE]zCmdStanGQ[CmdStanVB]c                     g rK   r#   r-   r   rm   rp   s       r/   draws_xrCmdStanGQ.draws_xr       	r2   zCmdStanGQ[CmdStanMCMC]z
xr.Datasetc                     g rK   r#   r   s       r/   r   r     r   r2   c           	         [         (       d  [        S5      e[        U R                  [        5      (       d  [        S5      e/ n/ nUb  [        U[
        5      (       a  U/nOUnU H  nXpR                  R                  ;  d  M  U(       aG  XpR                  R                  R                  ;   a$  UR                  U5        UR                  U5        Ml  [        SR                  U5      5      e   O[        U R                  R                  R                  5       5      nU(       aT  U R                  R                  R                  R                  5        H"  nXv;  d  M
  Xt;  d  M  UR                  U5        M$     U H  nUR                  U5        M     U R                  5         U R                  R                  nU R                  R                  R                   n	U	S    SU	S    SU	S    3U	S   US	.n
U(       a;  U	S
   (       a1  XR                  R"                  -  nU R                  R"                  U
S'   0 nU R$                  [&        R(                  " U5      S.nU H4  n[+        UU R                  R                  U   U R-                  US95        M6     U(       aN  U HH  n[+        UU R                  R                  R                  U   U R                  R-                  US95        MJ     [.        R0                  " XU
S9R3                  SSS5      $ )a  
Returns the generated quantities draws as a xarray Dataset.

This method can only be called when the underlying fit was made
through sampling, it cannot be used on MLE or VB outputs.

:param vars: optional list of variable names.

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

See Also
--------
CmdStanGQ.draws
CmdStanGQ.draws_pd
CmdStanMCMC.draws_xr
z>Package "xarray" is not installed, cannot produce draws array.zKMethod "draws_xr" is only available when original fit is done via Sampling.r   stan_version_major.stan_version_minorstan_version_patchr5   )stan_versionr5   num_draws_samplingsave_warmupnum_draws_warmup)chaindrawr   )coordsattrsr   r   .)XARRAY_INSTALLEDRuntimeErrorrw   r    r   r   r,   r}   r   r&   r'   r   keysremoverL   r   rh   r   rd   r(   r   r   r   xrDataset	transpose)r-   r   rm   rp   mcmc_vars_listdup_varsr   r   	num_drawssample_configr   r   coordinatess                r/   r   r     s   0  P  $++[995  $$$!F	 	 nn666!00::DDD&--c2 ,()?)F)Fs)KLL ! T^^55::<=I,,66@@EEGC+0I&--c2 H CS!  	++-%%88	))33BB,-ABC112311235 #7+"+0
 -6**;;;I(,(9(9(J(JE$%.0^^IIi(6

 C((-

j
1  %!%%//99#>%%++z+B & zz$%@JJVS
 	
r2   r   kwargsc                    U R                   R                  R                  R                  5       nU R                  R                  R                  5       nX;   d(  X;   d#  [	        SU S3SR                  X4-  5      -   5      eX;  a1  [        R                  " U R                   R                  " U40 UD65      $ U R                  5         U R                  UR                  SS5      =(       d    UR                  SS5      S9u  pV[        U R                  US 5      nU R                  R                  U   R                  U5      nU$ )	aQ  
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 in the sample.
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 kwargs: Additional keyword arguments are passed to the underlying
    fit's ``stan_variable`` method if the variable is not a generated
    quantity.

See Also
--------
CmdStanGQ.stan_variables
CmdStanMCMC.stan_variable
CmdStanMLE.stan_variable
CmdStanPathfinder.stan_variable
CmdStanVB.stan_variable
CmdStanLaplace.stan_variable
zUnknown variable name: z
Available variables are z, rm   Frn   r   N)r    r,   r}   r   r&   r:   r(   
atleast_1drE   rL   r   getr   r*   extract_reshape)	r-   r   r   model_var_namesgq_var_namesdraw1rB   r   outs	            r/   rE   CmdStanGQ.stan_variable  s.   X ++55??DDF~~//446&#*=)# /+ +))O:;< 
 "==!!//>v> 
 	++-$$zz,6 3zz*E2 % 
 t{{5623..2237GGN
r2   c                 4   0 nU R                   R                  R                  R                  5       nU R                  R                  R                  5       nU H  nU R                  " U40 UD6X%'   M     U H  nXT;  d  M
  U R                  " U40 UD6X%'   M!     U$ )a  
Return a dictionary mapping Stan program variables names
to the corresponding numpy.ndarray containing the inferred values.

:param kwargs: Additional keyword arguments are passed to the underlying
    fit's ``stan_variable`` method if the variable is not a generated
    quantity.

See Also
--------
CmdStanGQ.stan_variable
CmdStanMCMC.stan_variables
CmdStanMLE.stan_variables
CmdStanPathfinder.stan_variables
CmdStanVB.stan_variables
CmdStanLaplace.stan_variables
)r    r,   r}   r   rE   )r-   r   resultsample_var_namesr   names         r/   stan_variablesCmdStanGQ.stan_variablesT  s    $ ,,66@@EEG~~//446 D--d=f=FL !$D'#11$A&A % r2   c           
          U R                   R                  S:w  a  g U R                  SS9u  p[        R                  " X R
                  [        U R                  5      4[        SS9n[        U R
                  5       Hh  n[        U R                  R                  U   S5       nS U 5       n[        R                  " U[        R                  SS	S
S9US S 2US S 24'   S S S 5        Mj     X0l         g ! , (       d  f       M  = f)N)r   Tr   F)dtypeorderrc              3   T   #    U  H  oR                  S 5      (       a  M  Uv   M      g7f)#N)rC   ).0lines     r/   	<genexpr>;CmdStanGQ._assemble_generated_quantities.<locals>.<genexpr>}  s     I"$OOC4H"s   (	(r   r   ,)r   ndminskiprows	delimiter)r*   r   r   r(   emptyr6   lenrg   floatr[   openr   r;   loadtxtndarray)r-   rB   r   	gq_sampler   fdliness          r/   rL   (CmdStanGQ._assemble_generated_quantitiesp  s    ;;$((D(9 "S):):%;<!
	
 4;;'Edkk++E2C8BI"I)+1qC*	!UA+& 98 (   98s   !:C..
C=	c                    SnU R                   n[        U[        5      (       aD  UR                  nUR                  (       a$  U(       a  XCR
                  -  nX$4$ UR
                  nX$4$ [        U[        5      (       a<  SnUR                  (       a&  [        UR                  5      nU(       a  UnX$4$ US-
  nX$4$ SnUR                  R                  S   nU(       a  US-  nX$4$ )Nr   r   )r    rw   r   r   rx   r   r   rz   r   optimized_iterations_npvariational_sampler   )r-   rm   r   p_fitr   	opt_iterss         r/   r   CmdStanGQ._draws_start  s    !!e[))00I!!!7!77I$ ! "22E   z**I%% = =>	 )I  &ME  E0066q9IQ	r2   c                    U R                   n[        U[        5      (       a  UR                  US9$ [        U[        5      (       aR  U(       a$  UR
                  (       a  UR                  SS2S4   $ [        R                  " UR                  5      SS2S4   $ U(       a3  [        R                  " UR                  UR                  /5      SS2S4   $ UR                  SS2S4   $ )z@
Extract the draws from self.previous_fit.
Return is always 3-d
r   N)r    rw   r   r   r   rz   r  r(   
atleast_2doptimized_params_npvstackvariational_params_npr  )r-   rm   r  s      r/   r   CmdStanGQ._previous_draws  s    
 !!e[));;*;55z**e4444QW====))g  yy00%2J2JKT'  ++AtG44r2   c                 V   U(       a  UnO[        S S 5      nU R                  n[        U[        5      (       a  UR	                  U=(       d    S US9$ [        U[
        5      (       a6  U(       a   UR                  (       a  UR                  U   $ UR                  U   $ UR                  U   $ )Nr   )
slicer    rw   r   r   r   rz   optimized_iterations_pdoptimized_params_pdvariational_sample_pd)r-   r   rm   selr  s        r/   r   CmdStanGQ._previous_draws_pd  s     +/Cd#C!!e[))>>$,$:>FFz**e4444S990055..s33r2   dirc                 :    U R                   R                  U5        g)a/  
Move output CSV files to specified directory.  If files were
written to the temporary session directory, clean filename.
E.g., save 'bernoulli-201912081451-1-5nm6as7u.csv' as
'bernoulli-201912081451-1.csv'.

:param dir: directory path

See Also
--------
stanfit.RunSet.save_csvfiles
cmdstanpy.from_csv
N)r   save_csvfiles)r-   r  s     r/   r  CmdStanGQ.save_csvfiles  s     	!!#&r2   c                 L    [        5       R                  S5        U R                  $ )Nz@Property `mcmc_sample` is deprecated, use `previous_fit` instead)r   ry   r    rN   s    r/   mcmc_sampleCmdStanGQ.mcmc_sample  s#    N	
    r2   )r*   r,   r    r   )NFF)r!   NrK   )1__name__
__module____qualname____firstlineno____doc__r   r   r0   r   r>   r(   r   rH   r   rO   r   r   r+   propertyintr6   r   rd   r   rg   r   rk   boolr   r   r   r   r   r   r
   r   rE   r   rL   r   r   r   r   r  r   r   r   r  __static_attributes__r#   r2   r/   r   r   .   sn   
33 3 
	3&# * *

 *d )T#s(^ )V " " " %49 % % =eCHo = = +   !$# _- _- 	_-
 _- _- 
_-F -1  	NDIsD()N N 	N
 
N`  -1  	CDCcD()  	
 
   -1  	&CcD()  	
 
  -1  	_
CcD()_
 _
 	_

 
_
BC C C CJt S"**_0E 8 & t  c3h  65$ 52:: 5,4I4+/4	4('# '$ '" !U;
I#EF ! !r2   r   ),r  collectionsr   typingr   r   r   r   r   r	   r
   r   r   r   r   r   numpyr(   pandasr   xarrayr   r   ImportErrorcmdstanpy.cmdstan_argsr   cmdstanpy.utilsr   r   r   cmdstanpy.utils.stancsvr   mcmcr   rk   r   mler   r   r   vbr   r   r   r#   r2   r/   <module>r/     s   
       
 * I I 4  '   e[*i8p
! p
!#  s   B BB