
    %ge                        d 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mZmZ ddlZddlZ	 ddlZdZddlmZ ddlmZmZm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' d
dl(m)Z)  ede!e%e)      Z* G d dee*         Z+y# e$ r dZY Ww xY w)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                      e Zd ZdZde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deeef   fdZedefd       Zedee   fd       Zedeedf   fd       Zedefd       Zddddddedededede	j                  f
dZ	 	 	 d,deee   edf   dededej<                  fdZe 	 	 	 d,ded   deeee   df   dedede!f
d       Z"e 	 	 	 d,dddeeee   df   dededdf
d       Z"	 	 	 d,deeee   df   dededdfd Z"d!ed"ede	j                  fd#Z#d"edeee	j                  f   fd$Z$d-d%Z%dedeeef   fd&Z&dede	j                  fd'Z'dee   dedej<                  fd(Z(d.d)e)e   ddfd*Z*edee+e,e-f   fd+       Z.y)/	CmdStanGQz~
    Container for outputs from CmdStan generate_quantities run.
    Created by :meth:`CmdStanModel.generate_quantities`.
    runsetprevious_fitreturnNc                    |j                   t        j                  k(  s$t        dj	                  |j                               || _        || _        t        j                  d      | _	        | j                         }t        |      | _        y)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       Q/var/www/dash_apps/app1/venv/lib/python3.12/site-packages/cmdstanpy/stanfit/gq.py__init__zCmdStanGQ.__init__4   sp     }} : ::""(&"7  !-"$((2,))+*62    c                 x   dj                  | j                  j                  | j                  | j                  j                  j
                  j                  dg             }dj                  |dj                  | j                  j                        dj                  | j                  j                              }|S )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__zCmdStanGQ.__repr__G   s    077KKKKKK))11!1<

 =CCKK--.KK001

 r0   attrc                     |j                  d      rt        d|       	 | j                  |      S # t        $ r}t        |j                   d}~ww xY w)z)Synonymous with ``fit.stan_variable(attr)_zUnknown variable name N)
startswithAttributeErrorstan_variabler%   args)r,   r=   es      r.   __getattr__zCmdStanGQ.__getattr__T   sV    ??3 #9$!@AA	*%%d++ 	* !&&))	*s   2 	AAAc                 :    | j                          | j                  S N)_assemble_generated_quantities__dict__r,   s    r.   __getstate__zCmdStanGQ.__getstate__^   s    
 	++-}}r0   c                 x   i }t        | j                        D ]  }|dk(  r$t        | j                  j                  |         },t        | j                  j                  |         }|D ]L  }|dvs||   ||   k7  st        dj                  | j                  j                  |   |||   ||                 |S )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 {})ranger4   r   r   r9   r%   r&   )r,   dzeroidrestkeys        r.   r*   zCmdStanGQ._validate_csv_filesf   s     t{{#  	AAv(..q1 )..q1 ! C	 
 "#J%*4(88> $ 5 5a 8 # %c
 %c
	9  	B r0   c                 .    | j                   j                  S )zNumber of chains.)r   r4   rJ   s    r.   r4   zCmdStanGQ.chains   s     {{!!!r0   c                 .    | j                   j                  S )z
Chain ids.)r   	chain_idsrJ   s    r.   r]   zCmdStanGQ.chain_ids   s     {{$$$r0   .c                 4    | j                   j                  d   S )z<
        Names of generated quantities of interest.
        column_names)r+   cmdstan_configrJ   s    r.   r_   zCmdStanGQ.column_names   s    
 ~~,,^<<r0   c                     | j                   S )z
        Returns object which contains CmdStan configuration as well as
        information about the names and structure of the inference method
        and model output variables.
        )r+   rJ   s    r.   metadatazCmdStanGQ.metadata   s     ~~r0   F)
inc_warmupinc_iterationsconcat_chains
inc_samplerc   rd   re   rf   c          	         | j                          ||z  }|rt        | j                  t              r0| j                  j                  st               j                  d       n}t        | j                  t              r0| j                  j                  st               j                  d       n3t        | j                  t              rt               j                  d       |r| j                  j                  }| j                  }t        ||z         j                         D cg c]  \  }}|dkD  r| }	}}g }
|	D ]B  }|
j                  | j                  j                  j                  |   j!                                D | j#                  |      \  }}| j%                  d      }|rN|rLt'        t)        j*                  t)        j,                  |
d      | j.                  f      |dddddf         S |r!t'        | j.                  |dddddf         S |rCt)        j*                  t)        j,                  |
d      | j.                  f      |dddddf   S | j.                  |dddddf   S c c}}w )aC  
        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)rH   
isinstancer   r   _save_warmupr   warningr   _save_iterationsr   r_   r   itemsextendr+   	stan_varscolumns_draws_start_previous_drawsr   r'   dstackdeleter)   )r,   rc   rd   re   rf   cols_1cols_2itemcountdups	drop_colsdup	start_idxr?   previous_drawss                  r.   drawszCmdStanGQ.draws   sK   H 	++-n$
4,,k:))66$$>
 4,,j9))::$$G D--y9$$(
 &&33F&&F $+6F?#;#A#A#CD%19 D 
 $&I   %%//99#>FFH
 ((4	1--d3Z!				.)!D
 *a"$  !$++ij!Q.>"?@@99IInia@KK
 j!Q    {{9:q!+,,?s   "I4varsc                    |4t        |t              r|g}n|}t        t        j	                  |            }|rt        | j
                  t              r0| j
                  j                  st               j                  d       n}t        | j
                  t              r0| j
                  j                  st               j                  d       n3t        | j
                  t              rt               j                  d       | j                          g dt        | j                        z   }g }g }|!D ]  }|| j                  j                   v rL| j                  j                   |   }	|j#                  | j                  |	j$                  |	j&                          h|r|| j
                  j                  j                   v r`| j
                  j                  j                   |   }	|j#                  | j
                  j                  |	j$                  |	j&                          |dv r|j)                  |       t+        dj-                  |             n|}|}| j/                  ||      }
| j1                  |      }|j2                  \  }}}t5        j6                  t5        j8                  d|dz         |      j;                  d||      j<                  }t5        j>                  t5        j8                  d|dz         |      j;                  d||      j<                  }t5        j8                  d||z  dz         j;                  d||      j<                  }t5        j@                  ||||gd	      }tC        jD                  tG        |      |
      }|r%|r#|rtC        jH                  |
||   gd	      |   S |
S |r|t        |
jJ                        }t        |jJ                        }tM        ||z         jO                         D cg c]  \  }}|dkD  r| }}}tC        jH                  |
jQ                  |      jS                  d      |gd	      S |r||   S |S c c}}w )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
        rh   ri   rj   )chain__iter__draw__Unknown variable: {}rc   r      rk   )datart   rt   )rt   T)drop)*rm   strlistdictfromkeysr   r   rn   r   ro   r   rp   r   rH   r_   r+   rs   rr   r   end_idxappendr%   r&   _previous_draws_pdr   shaper'   repeatarangereshapeTtileconcatenatepd	DataFramer   concatrt   r   rq   r   reset_index)r,   r   rc   rf   	vars_listall_columnsgq_cols	mcmc_varsvarinfoprevious_draws_pdr   n_drawsn_chainsr?   
chains_coliter_coldraw_coldraws_pdry   rz   r{   r|   r}   s                           r.   r   zCmdStanGQ.draws_pd  s   2 $$!F	 	T]]956I4,,k:))66$$>
 4,,j9))::$$G D--y9$$(
 	++-5T=N=N8OO!	  I$..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%I( "GI 33IzJ

j
1${{1IIbii8a<0':WQ'*Q 	 GGBIIa1-x8WQ'*Q 	 IIa'H,12WQ'*Q 	
 
HhFQO<<&

 )yy) ) #   )(DL+334F(**+F $+6F?#;#A#A#CD%19 D 
 99%**4*8DD$DO   G$$s    Qr,   )zCmdStanGQ[CmdStanMLE]zCmdStanGQ[CmdStanVB]c                      y rG   r"   r,   r   rc   rf   s       r.   draws_xrzCmdStanGQ.draws_xr       	r0   zCmdStanGQ[CmdStanMCMC]z
xr.Datasetc                      y rG   r"   r   s       r.   r   zCmdStanGQ.draws_xr  r   r0   c                    t         st        d      t        | j                  t              st        d      g }g }|t        |t
              r|g}n|}|D ]{  }|| j                  j                  vs|rE|| j                  j                  j                  v r#|j                  |       |j                  |       ct        dj                  |             n}t        | j                  j                  j                               }|rN| j                  j                  j                  j                         D ]  }||vs||vs|j                  |        |D ]  }|j                  |        | j                          | j                  j                  }| j                  j                  j                   }	|	d    d|	d    d|	d    |	d   |d	}
|r7|	d
   r2|| j                  j"                  z  }| j                  j"                  |
d<   i }| j$                  t'        j(                  |      d}|D ]6  }t+        || j                  j                  |   | j-                  |             8 |rO|D ]J  }t+        || j                  j                  j                  |   | j                  j-                  |             L t/        j0                  |||
      j3                  ddd      S )a9  
        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_patchr3   )stan_versionr3   num_draws_samplingsave_warmupnum_draws_warmup)chaindrawr   )coordsattrsr   r   .)XARRAY_INSTALLEDRuntimeErrorrm   r   r   r   r+   rs   r   r%   r&   r   keysremoverH   r   r`   r   r]   r'   r   r   r   xrDataset	transpose)r,   r   rc   rf   mcmc_vars_listdup_varsr   r   	num_drawssample_configr   r   coordinatess                r.   r   zCmdStanGQ.draws_xr  s   0  P  $++[95  $$!F	 	  Mdnn666!t00::DDD&--c2 ,()?)F)Fs)KLLM T^^55::<=I,,66@@EEG 3C)+>0I&--c23  	"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
 	
r0   r   kwargsc                 |   | j                   j                  j                  j                         }| j                  j                  j                         }||v s(||v s$t	        d| ddj                  ||z        z         ||vr0t        j                   | j                   j                  |fi |      S | j                          | j                  |j                  dd      xs |j                  dd            \  }}t        | j                  |d       }| j                  j                  |   j                  |      }|S )	ai  
        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, rc   Frd   r   N)r   r+   rs   r   r%   r8   r'   
atleast_1drB   rH   ru   getr   r)   extract_reshape)	r,   r   r   model_var_namesgq_var_namesdraw1r?   r   outs	            r.   rB   zCmdStanGQ.stan_variable  s:   X ++55??DDF~~//446&#*=)# /+ +))Ol:;< 
 l"==/!!//>v> 
 	++-$$zz,6 3zz*E2 % 
q t{{5623..2237GGN
r0   c                 ,   i }| j                   j                  j                  j                         }| j                  j                  j                         }|D ]  } | j                  |fi |||<    |D ]  }||vs | j                  |fi |||<    |S )aC  
        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+   rs   r   rB   )r,   r   resultsample_var_namesr   names         r.   stan_variableszCmdStanGQ.stan_variablesT  s    $ ,,66@@EEG~~//446  	>D-4--d=f=F4L	>$ 	BD<'1t11$A&At	B r0   c           	         | j                   j                  dk7  ry | j                  d      \  }}t        j                  || j
                  t        | j                        ft        d      }t        | j
                        D ]i  }t        | j                  j                  |   d      5 }d |D        }t        j                  |t        j                  dd	d
      |d d |d d f<   d d d        k || _         y # 1 sw Y   }xY w)N)r   Tr   F)dtypeorderrc              3   D   K   | ]  }|j                  d       r|  yw)#N)r@   ).0lines     r.   	<genexpr>z;CmdStanGQ._assemble_generated_quantities.<locals>.<genexpr>}  s     I$DOOC4HIs     r   r   ,)r   ndminskiprows	delimiter)r)   r   ru   r'   emptyr4   lenr_   floatrV   openr   r9   loadtxtndarray)r,   r?   r   	gq_sampler   fdliness          r.   rH   z(CmdStanGQ._assemble_generated_quantitiesp  s    ;;$((D(99 "S):):%;<!
	
 4;;' 	Edkk++E2C8 BI"I)+1qC*	!UA+& 	   s   '<C55C>	c                    d}| j                   }t        |t              r=|j                  }|j                  r!|r||j
                  z  }||fS |j
                  }||fS t        |t              r4d}|j                  r"t        |j                        }|r|}||fS |dz
  }||fS d}|j                  j                  d   }|r|dz  }||fS )Nr   r   )r   rm   r   r   rn   r   r   rp   r   optimized_iterations_npvariational_sampler   )r,   rc   r   p_fitr   	opt_iterss         r.   ru   zCmdStanGQ._draws_start  s    !!e[)00I!!!7!77I$ i! "22E  i z*I%% = =>	 )I i &ME i E0066q9IQ	ir0   c                    | j                   }t        |t              r|j                  |      S t        |t              rG|r|j
                  r|j                  dddf   S t        j                  |j                        dddf   S |r2t        j                  |j                  |j                  g      dddf   S |j                  dddf   S )zX
        Extract the draws from self.previous_fit.
        Return is always 3-d
        r   N)r   rm   r   r   r   rp   r   r'   
atleast_2doptimized_params_npvstackvariational_params_npr   )r,   rc   r   s      r.   rv   zCmdStanGQ._previous_draws  s    
 !!e[);;*;55z*e4444QW====))g  yy00%2J2JKT'  ++AtG44r0   c                     |r|}nt        d d       }| j                  }t        |t              r|j	                  |xs d |      S t        |t
              r,|r|j                  r|j                  |   S |j                  |   S |j                  |   S )Nr   )
slicer   rm   r   r   r   rp   optimized_iterations_pdoptimized_params_pdvariational_sample_pd)r,   r   rc   selr   s        r.   r   z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3r0   dirc                 :    | j                   j                  |       y)a  
        Move output CSV files to specified directory.  If files were
        written to the temporary session directory, clean filename.
        E.g., save 'bernoulli-201912081451-1-5nm6as7u.csv' as
        'bernoulli-201912081451-1.csv'.

        :param dir: directory path

        See Also
        --------
        stanfit.RunSet.save_csvfiles
        cmdstanpy.from_csv
        N)r   save_csvfiles)r,   r   s     r.   r  zCmdStanGQ.save_csvfiles  s     	!!#&r0   c                 L    t               j                  d       | j                  S )Nz@Property `mcmc_sample` is deprecated, use `previous_fit` instead)r   ro   r   rJ   s    r.   mcmc_samplezCmdStanGQ.mcmc_sample  s#    N	
    r0   )NFF)r    NrG   )/__name__
__module____qualname____doc__r   r   r/   r   r<   r'   r   rE   r   rK   r   r   r*   propertyintr4   r   r]   r   r_   r   rb   boolr   r   r   r   r   r   r
   r   rB   r   rH   ru   rv   r   r   r  r   r   r   r  r"   r0   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 ! !r0   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   rb   r   mler   r   r   vbr   r   r   r"   r0   r.   <module>r     s   
       
 * I I 4  '   e[*i8p
! p
!#  s   B BB