""" Container for the result of running a laplace approximation."""fromtypingimport(Any,Dict,Hashable,List,MutableMapping,Optional,Tuple,Union,)importnumpyasnpimportpandasaspdtry:importxarrayasxrXARRAY_INSTALLED=TrueexceptImportError:XARRAY_INSTALLED=Falsefromcmdstanpy.cmdstan_argsimportMethodfromcmdstanpy.utils.data_mungingimportbuild_xarray_datafromcmdstanpy.utils.stancsvimportscan_generic_csvfrom.metadataimportInferenceMetadatafrom.mleimportCmdStanMLEfrom.runsetimportRunSet# TODO list:# - docs and example notebook# - make sure features like standalone GQ are updated/working
[docs]defstan_variable(self,var:str)->np.ndarray:""" Return a numpy.ndarray which contains the estimates for the for the named Stan program variable where the dimensions of the numpy.ndarray match the shape of the Stan program variable. This functionaltiy is also available via a shortcut using ``.`` - writing ``fit.a`` is a synonym for ``fit.stan_variable("a")`` :param var: variable name See Also -------- CmdStanMLE.stan_variables CmdStanMCMC.stan_variable CmdStanPathfinder.stan_variable CmdStanVB.stan_variable CmdStanGQ.stan_variable """self._assemble_draws()try:out:np.ndarray=self._metadata.stan_vars[var].extract_reshape(self._draws)returnoutexceptKeyError:# pylint: disable=raise-missing-fromraiseValueError(f'Unknown variable name: {var}\n''Available variables are '+", ".join(self._metadata.stan_vars.keys()))
[docs]defstan_variables(self)->Dict[str,np.ndarray]:""" Return a dictionary mapping Stan program variables names to the corresponding numpy.ndarray containing the inferred values. :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.stan_variable CmdStanMCMC.stan_variables CmdStanMLE.stan_variables CmdStanPathfinder.stan_variables CmdStanVB.stan_variables """result={}fornameinself._metadata.stan_vars:result[name]=self.stan_variable(name)returnresult
[docs]defmethod_variables(self)->Dict[str,np.ndarray]:""" 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. """self._assemble_draws()return{name:var.extract_reshape(self._draws)forname,varinself._metadata.method_vars.items()}
[docs]defdraws(self)->np.ndarray:""" Return a numpy.ndarray containing the draws from the approximate posterior distribution. This is a 2-D array of shape (draws, parameters). """self._assemble_draws()returnself._draws
[docs]defdraws_xr(self,vars:Union[str,List[str],None]=None,)->"xr.Dataset":""" Returns the sampler draws as a xarray Dataset. :param vars: optional list of variable names. See Also -------- CmdStanMCMC.draws_xr CmdStanGQ.draws_xr """ifnotXARRAY_INSTALLED:raiseRuntimeError('Package "xarray" is not installed, cannot produce draws array.')ifvarsisNone:vars_list=list(self._metadata.stan_vars.keys())elifisinstance(vars,str):vars_list=[vars]else:vars_list=varsself._assemble_draws()meta=self._metadata.cmdstan_configattrs:MutableMapping[Hashable,Any]={"stan_version":f"{meta['stan_version_major']}."f"{meta['stan_version_minor']}.{meta['stan_version_patch']}","model":meta["model"],}data:MutableMapping[Hashable,Any]={}coordinates:MutableMapping[Hashable,Any]={"draw":np.arange(self._draws.shape[0]),}forvarinvars_list:build_xarray_data(data,self._metadata.stan_vars[var],self._draws[:,np.newaxis,:],)return(xr.Dataset(data,coords=coordinates,attrs=attrs).transpose('draw',...).squeeze())
@propertydefmode(self)->CmdStanMLE:""" Return the maximum a posteriori estimate (mode) as a :class:`CmdStanMLE` object. """returnself._mode@propertydefmetadata(self)->InferenceMetadata:""" Returns object which contains CmdStan configuration as well as information about the names and structure of the inference method and model output variables. """returnself._metadatadef__repr__(self)->str:mode='\n'.join(['\t'+lineforlineinrepr(self.mode).splitlines()])[1:]rep='CmdStanLaplace: model={}\nmode=({})\n{}'.format(self._runset.model,mode,self._runset._args.method_args.compose(0,cmd=[]),)rep='{}\n csv_files:\n\t{}\n output_files:\n\t{}'.format(rep,'\n\t'.join(self._runset.csv_files),'\n\t'.join(self._runset.stdout_files),)returnrepdef__getattr__(self,attr:str)->np.ndarray:"""Synonymous with ``fit.stan_variable(attr)"""ifattr.startswith("_"):raiseAttributeError(f"Unknown variable name {attr}")try:returnself.stan_variable(attr)exceptValueErrorase:# pylint: disable=raise-missing-fromraiseAttributeError(*e.args)def__getstate__(self)->dict:# This function returns the mapping of objects to serialize with pickle.# See https://docs.python.org/3/library/pickle.html#object.__getstate__# for details. We call _assemble_draws to ensure posterior samples have# been loaded prior to serialization.self._assemble_draws()returnself.__dict__@propertydefcolumn_names(self)->Tuple[str,...]:""" 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`. """returnself._metadata.cmdstan_config['column_names']# type: ignore
[docs]defsave_csvfiles(self,dir:Optional[str]=None)->None:""" 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 """self._runset.save_csvfiles(dir)