5#ifndef STOCHTREE_RANDOM_EFFECTS_H_
6#define STOCHTREE_RANDOM_EFFECTS_H_
8#include <stochtree/category_tracker.h>
9#include <stochtree/cutpoint_candidates.h>
10#include <stochtree/data.h>
11#include <stochtree/ensemble.h>
12#include <stochtree/ig_sampler.h>
13#include <stochtree/log.h>
14#include <stochtree/normal_sampler.h>
15#include <stochtree/partition_tracker.h>
16#include <stochtree/prior.h>
17#include <nlohmann/json.hpp>
31class MultivariateRegressionRandomEffectsModel;
32class RandomEffectsContainer;
44 inline int NumCategories() {
return num_categories_; }
45 inline int CategoryNumber(
int category_id) {
return category_sample_tracker_->CategoryNumber(
category_id); }
47 CategorySampleTracker* GetCategorySampleTracker() {
return category_sample_tracker_.get(); }
48 std::vector<data_size_t>::iterator UnsortedNodeBeginIterator(
int category_id);
49 std::vector<data_size_t>::iterator UnsortedNodeEndIterator(
int category_id);
50 std::map<int, int>& GetLabelMap() {
return category_sample_tracker_->GetLabelMap(); }
51 std::vector<int>& GetUniqueGroupIds() {
return category_sample_tracker_->GetUniqueGroupIds(); }
52 std::vector<data_size_t>& NodeIndices(
int category_id) {
return category_sample_tracker_->NodeIndices(
category_id); }
54 double* GetPredictions() {
return rfx_predictions_.data(); }
68 std::unique_ptr<SampleCategoryMapper> sample_category_mapper_;
70 std::unique_ptr<CategorySampleTracker> category_sample_tracker_;
72 std::vector<double> rfx_predictions_;
75 int num_observations_;
87 void LoadFromLabelMap(std::map<int, int>
label_map) {
93 return pos != label_map_.end();
100 label_map_ =
other.Map();
102 void SaveToJsonFile(std::string
filename) {
107 void LoadFromJsonFile(std::string
filename) {
113 std::string DumpJsonString() {
117 void LoadFromJsonString(std::string&
json_string) {
122 std::vector<int>& Keys() {
return keys_; }
123 std::map<int, int>& Map() {
return label_map_; }
128 nlohmann::json to_json();
132 std::map<int, int> label_map_;
133 std::vector<int> keys_;
144 working_parameter_ = Eigen::VectorXd(num_components_);
145 group_parameters_ = Eigen::MatrixXd(num_components_, num_groups_);
146 group_parameter_covariance_ = Eigen::MatrixXd(num_components_, num_components_);
147 working_parameter_covariance_ = Eigen::MatrixXd(num_components_, num_components_);
179 void SetVariancePriorShape(
double value) {
180 variance_prior_shape_ =
value;
182 void SetVariancePriorScale(
double value) {
183 variance_prior_scale_ =
value;
188 return working_parameter_;
190 Eigen::MatrixXd& GetGroupParameters() {
191 return group_parameters_;
193 Eigen::MatrixXd& GetWorkingParameterCovariance() {
194 return working_parameter_covariance_;
196 Eigen::MatrixXd& GetGroupParameterCovariance() {
197 return group_parameter_covariance_;
199 double GetVariancePriorShape() {
200 return variance_prior_shape_;
202 double GetVariancePriorScale() {
203 return variance_prior_scale_;
205 inline int NumComponents() {
return num_components_; }
206 inline int NumGroups() {
return num_groups_; }
208 std::vector<double> Predict(RandomEffectsDataset&
dataset, RandomEffectsTracker&
tracker) {
214 void PredictInplace(RandomEffectsDataset&
dataset, RandomEffectsTracker&
tracker, std::vector<double>&
output) {
215 Eigen::MatrixXd
X =
dataset.GetBasis();
220 Eigen::MatrixXd
alpha_diag = working_parameter_.asDiagonal().toDenseMatrix();
222 for (
int i = 0;
i < n;
i++) {
228 void AddCurrentPredictionToResidual(RandomEffectsDataset&
dataset, RandomEffectsTracker&
tracker, ColumnVector& residual) {
240 void SubtractNewPredictionFromResidual(RandomEffectsDataset&
dataset, RandomEffectsTracker&
tracker, ColumnVector& residual) {
241 Eigen::MatrixXd
X =
dataset.GetBasis();
247 Eigen::MatrixXd
alpha_diag = working_parameter_.asDiagonal().toDenseMatrix();
249 for (
int i = 0;
i < n;
i++) {
283 Eigen::VectorXd working_parameter_;
284 Eigen::MatrixXd group_parameters_;
287 Eigen::MatrixXd group_parameter_covariance_;
290 Eigen::MatrixXd working_parameter_covariance_;
293 double variance_prior_shape_;
294 double variance_prior_scale_;
310 void SaveToJsonFile(std::string
filename) {
315 void LoadFromJsonFile(std::string
filename) {
321 std::string DumpJsonString() {
325 void LoadFromJsonString(std::string&
json_string) {
332 num_samples_ =
other.NumSamples();
333 num_components_ =
other.NumComponents();
334 num_groups_ =
other.NumGroups();
335 beta_ =
other.GetBeta();
336 alpha_ =
other.GetAlpha();
338 sigma_xi_ =
other.GetSigma();
343 inline int NumSamples() {
return num_samples_; }
344 inline int NumComponents() {
return num_components_; }
345 inline int NumGroups() {
return num_groups_; }
346 inline void SetNumSamples(
int num_samples) { num_samples_ = num_samples; }
358 std::vector<double>& GetBeta() {
return beta_; }
359 std::vector<double>& GetAlpha() {
return alpha_; }
360 std::vector<double>& GetXi() {
return xi_; }
361 std::vector<double>& GetSigma() {
return sigma_xi_; }
362 nlohmann::json to_json();
370 std::vector<double> beta_;
371 std::vector<double> alpha_;
372 std::vector<double> xi_;
373 std::vector<double> sigma_xi_;
385 const std::unique_ptr<RandomEffectsContainer>&
src) {
386 if (
src ==
nullptr &&
dst ==
nullptr)
return;
387 if (
src ==
nullptr ||
dst ==
nullptr) {
388 Log::Fatal(
"Cannot merge samples: random effects container present in one chain but not the other");
391 if (
src->NumComponents() !=
dst->NumComponents()) {
392 Log::Fatal(
"Cannot merge samples: random effects container has %d components in one chain but %d in the other",
src->NumComponents(),
dst->NumComponents());
394 if (
src->NumGroups() !=
dst->NumGroups()) {
395 Log::Fatal(
"Cannot merge samples: random effects container has %d groups in one chain but %d in the other",
src->NumGroups(),
dst->NumGroups());
397 dst->SetNumSamples(
dst->NumSamples() +
src->NumSamples());
400 std::vector<double>&
dst_xi =
dst->GetXi();
404 std::vector<double>&
src_xi =
src->GetXi();
Internal wrapper around Eigen::VectorXd interface for univariate floating point data....
Definition data.h:193
Definition ig_sampler.h:10
Standalone container for the map from category IDs to 0-based indices.
Definition random_effects.h:79
Definition normal_sampler.h:26
Posterior computation and sampling and state storage for random effects model with a group-level mult...
Definition random_effects.h:137
double VarianceComponentShape(RandomEffectsDataset &dataset, ColumnVector &residual, RandomEffectsTracker &rfx_tracker, double global_variance, int component_id)
Compute the posterior shape of the group variance component, conditional on the working and group par...
void ResetFromSample(RandomEffectsContainer &rfx_container, int sample_num)
Reconstruction from serialized model parameter samples.
Eigen::VectorXd & GetWorkingParameter()
Getters.
Definition random_effects.h:187
void SampleRandomEffects(RandomEffectsDataset &dataset, ColumnVector &residual, RandomEffectsTracker &tracker, double global_variance, std::mt19937 &gen)
Samplers.
Eigen::VectorXd WorkingParameterMean(RandomEffectsDataset &dataset, ColumnVector &residual, RandomEffectsTracker &rfx_tracker, double global_variance)
Compute the posterior mean of the working parameter, conditional on the group parameters and the vari...
Eigen::VectorXd GroupParameterMean(RandomEffectsDataset &dataset, ColumnVector &residual, RandomEffectsTracker &rfx_tracker, double global_variance, int group_id)
Compute the posterior mean of a group parameter, conditional on the working parameter and the varianc...
Eigen::MatrixXd GroupParameterVariance(RandomEffectsDataset &dataset, ColumnVector &residual, RandomEffectsTracker &rfx_tracker, double global_variance, int group_id)
Compute the posterior covariance of a group parameter, conditional on the working parameter and the v...
Eigen::MatrixXd WorkingParameterVariance(RandomEffectsDataset &dataset, ColumnVector &residual, RandomEffectsTracker &rfx_tracker, double global_variance)
Compute the posterior covariance of the working parameter, conditional on the group parameters and th...
void SetWorkingParameter(Eigen::VectorXd &working_parameter)
Setters.
Definition random_effects.h:161
double VarianceComponentScale(RandomEffectsDataset &dataset, ColumnVector &residual, RandomEffectsTracker &rfx_tracker, double global_variance, int component_id)
Compute the posterior scale of the group variance component, conditional on the working and group par...
Definition random_effects.h:297
API for loading and accessing data used to sample (additive) random effects.
Definition data.h:523
Wrapper around data structures for random effects sampling algorithms.
Definition random_effects.h:35
void RootReset(MultivariateRegressionRandomEffectsModel &rfx_model, RandomEffectsDataset &rfx_dataset, ColumnVector &residual)
Resets RFX tracker to initial default. Assumes tracker already exists in main memory....
void ResetFromSample(MultivariateRegressionRandomEffectsModel &rfx_model, RandomEffectsDataset &rfx_dataset, ColumnVector &residual)
Resets RFX tracker based on a specific sample. Assumes tracker already exists in main memory.
Class storing sample-node map for each tree in an ensemble TODO: Add run-time checks for categories w...
Definition category_tracker.h:41
static void GFRSampleOneIter(TreeEnsemble &active_forest, ForestTracker &tracker, ForestContainer &forests, LeafModel &leaf_model, ForestDataset &dataset, ColumnVector &residual, TreePrior &tree_prior, std::mt19937 &gen, std::vector< double > &variable_weights, std::vector< int > &sweep_update_indices, double global_variance, std::vector< FeatureType > &feature_types, int cutpoint_grid_size, bool keep_forest, bool pre_initialized, bool backfitting, int num_features_subsample, int num_threads, LeafSuffStatConstructorArgs &... leaf_suff_stat_args)
Definition tree_sampler.h:816
A collection of random number generation utilities.
Definition bart.h:15
void AppendRandomEffectsContainerSamples(std::unique_ptr< RandomEffectsContainer > &dst, const std::unique_ptr< RandomEffectsContainer > &src)
Append every retained random effects sample from src onto the end of dst (deep copy)....
Definition random_effects.h:384